three.cjs 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968
  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 = '144dev';
  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; // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  161. const NoColorSpace = '';
  162. const SRGBColorSpace = 'srgb';
  163. const LinearSRGBColorSpace = 'srgb-linear';
  164. const ZeroStencilOp = 0;
  165. const KeepStencilOp = 7680;
  166. const ReplaceStencilOp = 7681;
  167. const IncrementStencilOp = 7682;
  168. const DecrementStencilOp = 7683;
  169. const IncrementWrapStencilOp = 34055;
  170. const DecrementWrapStencilOp = 34056;
  171. const InvertStencilOp = 5386;
  172. const NeverStencilFunc = 512;
  173. const LessStencilFunc = 513;
  174. const EqualStencilFunc = 514;
  175. const LessEqualStencilFunc = 515;
  176. const GreaterStencilFunc = 516;
  177. const NotEqualStencilFunc = 517;
  178. const GreaterEqualStencilFunc = 518;
  179. const AlwaysStencilFunc = 519;
  180. const StaticDrawUsage = 35044;
  181. const DynamicDrawUsage = 35048;
  182. const StreamDrawUsage = 35040;
  183. const StaticReadUsage = 35045;
  184. const DynamicReadUsage = 35049;
  185. const StreamReadUsage = 35041;
  186. const StaticCopyUsage = 35046;
  187. const DynamicCopyUsage = 35050;
  188. const StreamCopyUsage = 35042;
  189. const GLSL1 = '100';
  190. const GLSL3 = '300 es';
  191. const _SRGBAFormat = 1035; // fallback for WebGL 1
  192. /**
  193. * https://github.com/mrdoob/eventdispatcher.js/
  194. */
  195. class EventDispatcher {
  196. addEventListener(type, listener) {
  197. if (this._listeners === undefined) this._listeners = {};
  198. const listeners = this._listeners;
  199. if (listeners[type] === undefined) {
  200. listeners[type] = [];
  201. }
  202. if (listeners[type].indexOf(listener) === -1) {
  203. listeners[type].push(listener);
  204. }
  205. }
  206. hasEventListener(type, listener) {
  207. if (this._listeners === undefined) return false;
  208. const listeners = this._listeners;
  209. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  210. }
  211. removeEventListener(type, listener) {
  212. if (this._listeners === undefined) return;
  213. const listeners = this._listeners;
  214. const listenerArray = listeners[type];
  215. if (listenerArray !== undefined) {
  216. const index = listenerArray.indexOf(listener);
  217. if (index !== -1) {
  218. listenerArray.splice(index, 1);
  219. }
  220. }
  221. }
  222. dispatchEvent(event) {
  223. if (this._listeners === undefined) return;
  224. const listeners = this._listeners;
  225. const listenerArray = listeners[event.type];
  226. if (listenerArray !== undefined) {
  227. event.target = this; // Make a copy, in case listeners are removed while iterating.
  228. const array = listenerArray.slice(0);
  229. for (let i = 0, l = array.length; i < l; i++) {
  230. array[i].call(this, event);
  231. }
  232. event.target = null;
  233. }
  234. }
  235. }
  236. 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'];
  237. let _seed = 1234567;
  238. const DEG2RAD = Math.PI / 180;
  239. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  240. function generateUUID() {
  241. const d0 = Math.random() * 0xffffffff | 0;
  242. const d1 = Math.random() * 0xffffffff | 0;
  243. const d2 = Math.random() * 0xffffffff | 0;
  244. const d3 = Math.random() * 0xffffffff | 0;
  245. 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]; // .toLowerCase() here flattens concatenated strings to save heap memory space.
  246. return uuid.toLowerCase();
  247. }
  248. function clamp(value, min, max) {
  249. return Math.max(min, Math.min(max, value));
  250. } // compute euclidean modulo of m % n
  251. // https://en.wikipedia.org/wiki/Modulo_operation
  252. function euclideanModulo(n, m) {
  253. return (n % m + m) % m;
  254. } // Linear mapping from range <a1, a2> to range <b1, b2>
  255. function mapLinear(x, a1, a2, b1, b2) {
  256. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  257. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  258. function inverseLerp(x, y, value) {
  259. if (x !== y) {
  260. return (value - x) / (y - x);
  261. } else {
  262. return 0;
  263. }
  264. } // https://en.wikipedia.org/wiki/Linear_interpolation
  265. function lerp(x, y, t) {
  266. return (1 - t) * x + t * y;
  267. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  268. function damp(x, y, lambda, dt) {
  269. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  270. } // https://www.desmos.com/calculator/vcsjnyz7x4
  271. function pingpong(x, length = 1) {
  272. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  273. } // http://en.wikipedia.org/wiki/Smoothstep
  274. function smoothstep(x, min, max) {
  275. if (x <= min) return 0;
  276. if (x >= max) return 1;
  277. x = (x - min) / (max - min);
  278. return x * x * (3 - 2 * x);
  279. }
  280. function smootherstep(x, min, max) {
  281. if (x <= min) return 0;
  282. if (x >= max) return 1;
  283. x = (x - min) / (max - min);
  284. return x * x * x * (x * (x * 6 - 15) + 10);
  285. } // Random integer from <low, high> interval
  286. function randInt(low, high) {
  287. return low + Math.floor(Math.random() * (high - low + 1));
  288. } // Random float from <low, high> interval
  289. function randFloat(low, high) {
  290. return low + Math.random() * (high - low);
  291. } // Random float from <-range/2, range/2> interval
  292. function randFloatSpread(range) {
  293. return range * (0.5 - Math.random());
  294. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  295. function seededRandom(s) {
  296. if (s !== undefined) _seed = s; // Mulberry32 generator
  297. let t = _seed += 0x6D2B79F5;
  298. t = Math.imul(t ^ t >>> 15, t | 1);
  299. t ^= t + Math.imul(t ^ t >>> 7, t | 61);
  300. return ((t ^ t >>> 14) >>> 0) / 4294967296;
  301. }
  302. function degToRad(degrees) {
  303. return degrees * DEG2RAD;
  304. }
  305. function radToDeg(radians) {
  306. return radians * RAD2DEG;
  307. }
  308. function isPowerOfTwo(value) {
  309. return (value & value - 1) === 0 && value !== 0;
  310. }
  311. function ceilPowerOfTwo(value) {
  312. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  313. }
  314. function floorPowerOfTwo(value) {
  315. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  316. }
  317. function setQuaternionFromProperEuler(q, a, b, c, order) {
  318. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  319. // rotations are applied to the axes in the order specified by 'order'
  320. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  321. // angles are in radians
  322. const cos = Math.cos;
  323. const sin = Math.sin;
  324. const c2 = cos(b / 2);
  325. const s2 = sin(b / 2);
  326. const c13 = cos((a + c) / 2);
  327. const s13 = sin((a + c) / 2);
  328. const c1_3 = cos((a - c) / 2);
  329. const s1_3 = sin((a - c) / 2);
  330. const c3_1 = cos((c - a) / 2);
  331. const s3_1 = sin((c - a) / 2);
  332. switch (order) {
  333. case 'XYX':
  334. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  335. break;
  336. case 'YZY':
  337. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  338. break;
  339. case 'ZXZ':
  340. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  341. break;
  342. case 'XZX':
  343. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  344. break;
  345. case 'YXY':
  346. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  347. break;
  348. case 'ZYZ':
  349. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  350. break;
  351. default:
  352. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  353. }
  354. }
  355. function denormalize(value, array) {
  356. switch (array.constructor) {
  357. case Float32Array:
  358. return value;
  359. case Uint16Array:
  360. return value / 65535.0;
  361. case Uint8Array:
  362. return value / 255.0;
  363. case Int16Array:
  364. return Math.max(value / 32767.0, -1.0);
  365. case Int8Array:
  366. return Math.max(value / 127.0, -1.0);
  367. default:
  368. throw new Error('Invalid component type.');
  369. }
  370. }
  371. function normalize(value, array) {
  372. switch (array.constructor) {
  373. case Float32Array:
  374. return value;
  375. case Uint16Array:
  376. return Math.round(value * 65535.0);
  377. case Uint8Array:
  378. return Math.round(value * 255.0);
  379. case Int16Array:
  380. return Math.round(value * 32767.0);
  381. case Int8Array:
  382. return Math.round(value * 127.0);
  383. default:
  384. throw new Error('Invalid component type.');
  385. }
  386. }
  387. var MathUtils = /*#__PURE__*/Object.freeze({
  388. __proto__: null,
  389. DEG2RAD: DEG2RAD,
  390. RAD2DEG: RAD2DEG,
  391. generateUUID: generateUUID,
  392. clamp: clamp,
  393. euclideanModulo: euclideanModulo,
  394. mapLinear: mapLinear,
  395. inverseLerp: inverseLerp,
  396. lerp: lerp,
  397. damp: damp,
  398. pingpong: pingpong,
  399. smoothstep: smoothstep,
  400. smootherstep: smootherstep,
  401. randInt: randInt,
  402. randFloat: randFloat,
  403. randFloatSpread: randFloatSpread,
  404. seededRandom: seededRandom,
  405. degToRad: degToRad,
  406. radToDeg: radToDeg,
  407. isPowerOfTwo: isPowerOfTwo,
  408. ceilPowerOfTwo: ceilPowerOfTwo,
  409. floorPowerOfTwo: floorPowerOfTwo,
  410. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  411. normalize: normalize,
  412. denormalize: denormalize
  413. });
  414. class Vector2 {
  415. constructor(x = 0, y = 0) {
  416. Vector2.prototype.isVector2 = true;
  417. this.x = x;
  418. this.y = y;
  419. }
  420. get width() {
  421. return this.x;
  422. }
  423. set width(value) {
  424. this.x = value;
  425. }
  426. get height() {
  427. return this.y;
  428. }
  429. set height(value) {
  430. this.y = value;
  431. }
  432. set(x, y) {
  433. this.x = x;
  434. this.y = y;
  435. return this;
  436. }
  437. setScalar(scalar) {
  438. this.x = scalar;
  439. this.y = scalar;
  440. return this;
  441. }
  442. setX(x) {
  443. this.x = x;
  444. return this;
  445. }
  446. setY(y) {
  447. this.y = y;
  448. return this;
  449. }
  450. setComponent(index, value) {
  451. switch (index) {
  452. case 0:
  453. this.x = value;
  454. break;
  455. case 1:
  456. this.y = value;
  457. break;
  458. default:
  459. throw new Error('index is out of range: ' + index);
  460. }
  461. return this;
  462. }
  463. getComponent(index) {
  464. switch (index) {
  465. case 0:
  466. return this.x;
  467. case 1:
  468. return this.y;
  469. default:
  470. throw new Error('index is out of range: ' + index);
  471. }
  472. }
  473. clone() {
  474. return new this.constructor(this.x, this.y);
  475. }
  476. copy(v) {
  477. this.x = v.x;
  478. this.y = v.y;
  479. return this;
  480. }
  481. add(v) {
  482. this.x += v.x;
  483. this.y += v.y;
  484. return this;
  485. }
  486. addScalar(s) {
  487. this.x += s;
  488. this.y += s;
  489. return this;
  490. }
  491. addVectors(a, b) {
  492. this.x = a.x + b.x;
  493. this.y = a.y + b.y;
  494. return this;
  495. }
  496. addScaledVector(v, s) {
  497. this.x += v.x * s;
  498. this.y += v.y * s;
  499. return this;
  500. }
  501. sub(v) {
  502. this.x -= v.x;
  503. this.y -= v.y;
  504. return this;
  505. }
  506. subScalar(s) {
  507. this.x -= s;
  508. this.y -= s;
  509. return this;
  510. }
  511. subVectors(a, b) {
  512. this.x = a.x - b.x;
  513. this.y = a.y - b.y;
  514. return this;
  515. }
  516. multiply(v) {
  517. this.x *= v.x;
  518. this.y *= v.y;
  519. return this;
  520. }
  521. multiplyScalar(scalar) {
  522. this.x *= scalar;
  523. this.y *= scalar;
  524. return this;
  525. }
  526. divide(v) {
  527. this.x /= v.x;
  528. this.y /= v.y;
  529. return this;
  530. }
  531. divideScalar(scalar) {
  532. return this.multiplyScalar(1 / scalar);
  533. }
  534. applyMatrix3(m) {
  535. const x = this.x,
  536. y = this.y;
  537. const e = m.elements;
  538. this.x = e[0] * x + e[3] * y + e[6];
  539. this.y = e[1] * x + e[4] * y + e[7];
  540. return this;
  541. }
  542. min(v) {
  543. this.x = Math.min(this.x, v.x);
  544. this.y = Math.min(this.y, v.y);
  545. return this;
  546. }
  547. max(v) {
  548. this.x = Math.max(this.x, v.x);
  549. this.y = Math.max(this.y, v.y);
  550. return this;
  551. }
  552. clamp(min, max) {
  553. // assumes min < max, componentwise
  554. this.x = Math.max(min.x, Math.min(max.x, this.x));
  555. this.y = Math.max(min.y, Math.min(max.y, this.y));
  556. return this;
  557. }
  558. clampScalar(minVal, maxVal) {
  559. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  560. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  561. return this;
  562. }
  563. clampLength(min, max) {
  564. const length = this.length();
  565. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  566. }
  567. floor() {
  568. this.x = Math.floor(this.x);
  569. this.y = Math.floor(this.y);
  570. return this;
  571. }
  572. ceil() {
  573. this.x = Math.ceil(this.x);
  574. this.y = Math.ceil(this.y);
  575. return this;
  576. }
  577. round() {
  578. this.x = Math.round(this.x);
  579. this.y = Math.round(this.y);
  580. return this;
  581. }
  582. roundToZero() {
  583. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  584. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  585. return this;
  586. }
  587. negate() {
  588. this.x = -this.x;
  589. this.y = -this.y;
  590. return this;
  591. }
  592. dot(v) {
  593. return this.x * v.x + this.y * v.y;
  594. }
  595. cross(v) {
  596. return this.x * v.y - this.y * v.x;
  597. }
  598. lengthSq() {
  599. return this.x * this.x + this.y * this.y;
  600. }
  601. length() {
  602. return Math.sqrt(this.x * this.x + this.y * this.y);
  603. }
  604. manhattanLength() {
  605. return Math.abs(this.x) + Math.abs(this.y);
  606. }
  607. normalize() {
  608. return this.divideScalar(this.length() || 1);
  609. }
  610. angle() {
  611. // computes the angle in radians with respect to the positive x-axis
  612. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  613. return angle;
  614. }
  615. distanceTo(v) {
  616. return Math.sqrt(this.distanceToSquared(v));
  617. }
  618. distanceToSquared(v) {
  619. const dx = this.x - v.x,
  620. dy = this.y - v.y;
  621. return dx * dx + dy * dy;
  622. }
  623. manhattanDistanceTo(v) {
  624. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  625. }
  626. setLength(length) {
  627. return this.normalize().multiplyScalar(length);
  628. }
  629. lerp(v, alpha) {
  630. this.x += (v.x - this.x) * alpha;
  631. this.y += (v.y - this.y) * alpha;
  632. return this;
  633. }
  634. lerpVectors(v1, v2, alpha) {
  635. this.x = v1.x + (v2.x - v1.x) * alpha;
  636. this.y = v1.y + (v2.y - v1.y) * alpha;
  637. return this;
  638. }
  639. equals(v) {
  640. return v.x === this.x && v.y === this.y;
  641. }
  642. fromArray(array, offset = 0) {
  643. this.x = array[offset];
  644. this.y = array[offset + 1];
  645. return this;
  646. }
  647. toArray(array = [], offset = 0) {
  648. array[offset] = this.x;
  649. array[offset + 1] = this.y;
  650. return array;
  651. }
  652. fromBufferAttribute(attribute, index) {
  653. this.x = attribute.getX(index);
  654. this.y = attribute.getY(index);
  655. return this;
  656. }
  657. rotateAround(center, angle) {
  658. const c = Math.cos(angle),
  659. s = Math.sin(angle);
  660. const x = this.x - center.x;
  661. const y = this.y - center.y;
  662. this.x = x * c - y * s + center.x;
  663. this.y = x * s + y * c + center.y;
  664. return this;
  665. }
  666. random() {
  667. this.x = Math.random();
  668. this.y = Math.random();
  669. return this;
  670. }
  671. *[Symbol.iterator]() {
  672. yield this.x;
  673. yield this.y;
  674. }
  675. }
  676. class Matrix3 {
  677. constructor() {
  678. Matrix3.prototype.isMatrix3 = true;
  679. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  680. }
  681. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  682. const te = this.elements;
  683. te[0] = n11;
  684. te[1] = n21;
  685. te[2] = n31;
  686. te[3] = n12;
  687. te[4] = n22;
  688. te[5] = n32;
  689. te[6] = n13;
  690. te[7] = n23;
  691. te[8] = n33;
  692. return this;
  693. }
  694. identity() {
  695. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  696. return this;
  697. }
  698. copy(m) {
  699. const te = this.elements;
  700. const me = m.elements;
  701. te[0] = me[0];
  702. te[1] = me[1];
  703. te[2] = me[2];
  704. te[3] = me[3];
  705. te[4] = me[4];
  706. te[5] = me[5];
  707. te[6] = me[6];
  708. te[7] = me[7];
  709. te[8] = me[8];
  710. return this;
  711. }
  712. extractBasis(xAxis, yAxis, zAxis) {
  713. xAxis.setFromMatrix3Column(this, 0);
  714. yAxis.setFromMatrix3Column(this, 1);
  715. zAxis.setFromMatrix3Column(this, 2);
  716. return this;
  717. }
  718. setFromMatrix4(m) {
  719. const me = m.elements;
  720. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  721. return this;
  722. }
  723. multiply(m) {
  724. return this.multiplyMatrices(this, m);
  725. }
  726. premultiply(m) {
  727. return this.multiplyMatrices(m, this);
  728. }
  729. multiplyMatrices(a, b) {
  730. const ae = a.elements;
  731. const be = b.elements;
  732. const te = this.elements;
  733. const a11 = ae[0],
  734. a12 = ae[3],
  735. a13 = ae[6];
  736. const a21 = ae[1],
  737. a22 = ae[4],
  738. a23 = ae[7];
  739. const a31 = ae[2],
  740. a32 = ae[5],
  741. a33 = ae[8];
  742. const b11 = be[0],
  743. b12 = be[3],
  744. b13 = be[6];
  745. const b21 = be[1],
  746. b22 = be[4],
  747. b23 = be[7];
  748. const b31 = be[2],
  749. b32 = be[5],
  750. b33 = be[8];
  751. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  752. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  753. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  754. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  755. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  756. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  757. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  758. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  759. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  760. return this;
  761. }
  762. multiplyScalar(s) {
  763. const te = this.elements;
  764. te[0] *= s;
  765. te[3] *= s;
  766. te[6] *= s;
  767. te[1] *= s;
  768. te[4] *= s;
  769. te[7] *= s;
  770. te[2] *= s;
  771. te[5] *= s;
  772. te[8] *= s;
  773. return this;
  774. }
  775. determinant() {
  776. const te = this.elements;
  777. const a = te[0],
  778. b = te[1],
  779. c = te[2],
  780. d = te[3],
  781. e = te[4],
  782. f = te[5],
  783. g = te[6],
  784. h = te[7],
  785. i = te[8];
  786. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  787. }
  788. invert() {
  789. const te = this.elements,
  790. n11 = te[0],
  791. n21 = te[1],
  792. n31 = te[2],
  793. n12 = te[3],
  794. n22 = te[4],
  795. n32 = te[5],
  796. n13 = te[6],
  797. n23 = te[7],
  798. n33 = te[8],
  799. t11 = n33 * n22 - n32 * n23,
  800. t12 = n32 * n13 - n33 * n12,
  801. t13 = n23 * n12 - n22 * n13,
  802. det = n11 * t11 + n21 * t12 + n31 * t13;
  803. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  804. const detInv = 1 / det;
  805. te[0] = t11 * detInv;
  806. te[1] = (n31 * n23 - n33 * n21) * detInv;
  807. te[2] = (n32 * n21 - n31 * n22) * detInv;
  808. te[3] = t12 * detInv;
  809. te[4] = (n33 * n11 - n31 * n13) * detInv;
  810. te[5] = (n31 * n12 - n32 * n11) * detInv;
  811. te[6] = t13 * detInv;
  812. te[7] = (n21 * n13 - n23 * n11) * detInv;
  813. te[8] = (n22 * n11 - n21 * n12) * detInv;
  814. return this;
  815. }
  816. transpose() {
  817. let tmp;
  818. const m = this.elements;
  819. tmp = m[1];
  820. m[1] = m[3];
  821. m[3] = tmp;
  822. tmp = m[2];
  823. m[2] = m[6];
  824. m[6] = tmp;
  825. tmp = m[5];
  826. m[5] = m[7];
  827. m[7] = tmp;
  828. return this;
  829. }
  830. getNormalMatrix(matrix4) {
  831. return this.setFromMatrix4(matrix4).invert().transpose();
  832. }
  833. transposeIntoArray(r) {
  834. const m = this.elements;
  835. r[0] = m[0];
  836. r[1] = m[3];
  837. r[2] = m[6];
  838. r[3] = m[1];
  839. r[4] = m[4];
  840. r[5] = m[7];
  841. r[6] = m[2];
  842. r[7] = m[5];
  843. r[8] = m[8];
  844. return this;
  845. }
  846. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  847. const c = Math.cos(rotation);
  848. const s = Math.sin(rotation);
  849. 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);
  850. return this;
  851. }
  852. scale(sx, sy) {
  853. const te = this.elements;
  854. te[0] *= sx;
  855. te[3] *= sx;
  856. te[6] *= sx;
  857. te[1] *= sy;
  858. te[4] *= sy;
  859. te[7] *= sy;
  860. return this;
  861. }
  862. rotate(theta) {
  863. const c = Math.cos(theta);
  864. const s = Math.sin(theta);
  865. const te = this.elements;
  866. const a11 = te[0],
  867. a12 = te[3],
  868. a13 = te[6];
  869. const a21 = te[1],
  870. a22 = te[4],
  871. a23 = te[7];
  872. te[0] = c * a11 + s * a21;
  873. te[3] = c * a12 + s * a22;
  874. te[6] = c * a13 + s * a23;
  875. te[1] = -s * a11 + c * a21;
  876. te[4] = -s * a12 + c * a22;
  877. te[7] = -s * a13 + c * a23;
  878. return this;
  879. }
  880. translate(tx, ty) {
  881. const te = this.elements;
  882. te[0] += tx * te[2];
  883. te[3] += tx * te[5];
  884. te[6] += tx * te[8];
  885. te[1] += ty * te[2];
  886. te[4] += ty * te[5];
  887. te[7] += ty * te[8];
  888. return this;
  889. }
  890. equals(matrix) {
  891. const te = this.elements;
  892. const me = matrix.elements;
  893. for (let i = 0; i < 9; i++) {
  894. if (te[i] !== me[i]) return false;
  895. }
  896. return true;
  897. }
  898. fromArray(array, offset = 0) {
  899. for (let i = 0; i < 9; i++) {
  900. this.elements[i] = array[i + offset];
  901. }
  902. return this;
  903. }
  904. toArray(array = [], offset = 0) {
  905. const te = this.elements;
  906. array[offset] = te[0];
  907. array[offset + 1] = te[1];
  908. array[offset + 2] = te[2];
  909. array[offset + 3] = te[3];
  910. array[offset + 4] = te[4];
  911. array[offset + 5] = te[5];
  912. array[offset + 6] = te[6];
  913. array[offset + 7] = te[7];
  914. array[offset + 8] = te[8];
  915. return array;
  916. }
  917. clone() {
  918. return new this.constructor().fromArray(this.elements);
  919. }
  920. }
  921. function arrayNeedsUint32(array) {
  922. // assumes larger values usually on last
  923. for (let i = array.length - 1; i >= 0; --i) {
  924. if (array[i] > 65535) return true;
  925. }
  926. return false;
  927. }
  928. const TYPED_ARRAYS = {
  929. Int8Array: Int8Array,
  930. Uint8Array: Uint8Array,
  931. Uint8ClampedArray: Uint8ClampedArray,
  932. Int16Array: Int16Array,
  933. Uint16Array: Uint16Array,
  934. Int32Array: Int32Array,
  935. Uint32Array: Uint32Array,
  936. Float32Array: Float32Array,
  937. Float64Array: Float64Array
  938. };
  939. function getTypedArray(type, buffer) {
  940. return new TYPED_ARRAYS[type](buffer);
  941. }
  942. function createElementNS(name) {
  943. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  944. }
  945. function SRGBToLinear(c) {
  946. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  947. }
  948. function LinearToSRGB(c) {
  949. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  950. } // JavaScript RGB-to-RGB transforms, defined as
  951. // FN[InputColorSpace][OutputColorSpace] callback functions.
  952. const FN = {
  953. [SRGBColorSpace]: {
  954. [LinearSRGBColorSpace]: SRGBToLinear
  955. },
  956. [LinearSRGBColorSpace]: {
  957. [SRGBColorSpace]: LinearToSRGB
  958. }
  959. };
  960. const ColorManagement = {
  961. legacyMode: true,
  962. get workingColorSpace() {
  963. return LinearSRGBColorSpace;
  964. },
  965. set workingColorSpace(colorSpace) {
  966. console.warn('THREE.ColorManagement: .workingColorSpace is readonly.');
  967. },
  968. convert: function (color, sourceColorSpace, targetColorSpace) {
  969. if (this.legacyMode || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) {
  970. return color;
  971. }
  972. if (FN[sourceColorSpace] && FN[sourceColorSpace][targetColorSpace] !== undefined) {
  973. const fn = FN[sourceColorSpace][targetColorSpace];
  974. color.r = fn(color.r);
  975. color.g = fn(color.g);
  976. color.b = fn(color.b);
  977. return color;
  978. }
  979. throw new Error('Unsupported color space conversion.');
  980. },
  981. fromWorkingColorSpace: function (color, targetColorSpace) {
  982. return this.convert(color, this.workingColorSpace, targetColorSpace);
  983. },
  984. toWorkingColorSpace: function (color, sourceColorSpace) {
  985. return this.convert(color, sourceColorSpace, this.workingColorSpace);
  986. }
  987. };
  988. const _colorKeywords = {
  989. 'aliceblue': 0xF0F8FF,
  990. 'antiquewhite': 0xFAEBD7,
  991. 'aqua': 0x00FFFF,
  992. 'aquamarine': 0x7FFFD4,
  993. 'azure': 0xF0FFFF,
  994. 'beige': 0xF5F5DC,
  995. 'bisque': 0xFFE4C4,
  996. 'black': 0x000000,
  997. 'blanchedalmond': 0xFFEBCD,
  998. 'blue': 0x0000FF,
  999. 'blueviolet': 0x8A2BE2,
  1000. 'brown': 0xA52A2A,
  1001. 'burlywood': 0xDEB887,
  1002. 'cadetblue': 0x5F9EA0,
  1003. 'chartreuse': 0x7FFF00,
  1004. 'chocolate': 0xD2691E,
  1005. 'coral': 0xFF7F50,
  1006. 'cornflowerblue': 0x6495ED,
  1007. 'cornsilk': 0xFFF8DC,
  1008. 'crimson': 0xDC143C,
  1009. 'cyan': 0x00FFFF,
  1010. 'darkblue': 0x00008B,
  1011. 'darkcyan': 0x008B8B,
  1012. 'darkgoldenrod': 0xB8860B,
  1013. 'darkgray': 0xA9A9A9,
  1014. 'darkgreen': 0x006400,
  1015. 'darkgrey': 0xA9A9A9,
  1016. 'darkkhaki': 0xBDB76B,
  1017. 'darkmagenta': 0x8B008B,
  1018. 'darkolivegreen': 0x556B2F,
  1019. 'darkorange': 0xFF8C00,
  1020. 'darkorchid': 0x9932CC,
  1021. 'darkred': 0x8B0000,
  1022. 'darksalmon': 0xE9967A,
  1023. 'darkseagreen': 0x8FBC8F,
  1024. 'darkslateblue': 0x483D8B,
  1025. 'darkslategray': 0x2F4F4F,
  1026. 'darkslategrey': 0x2F4F4F,
  1027. 'darkturquoise': 0x00CED1,
  1028. 'darkviolet': 0x9400D3,
  1029. 'deeppink': 0xFF1493,
  1030. 'deepskyblue': 0x00BFFF,
  1031. 'dimgray': 0x696969,
  1032. 'dimgrey': 0x696969,
  1033. 'dodgerblue': 0x1E90FF,
  1034. 'firebrick': 0xB22222,
  1035. 'floralwhite': 0xFFFAF0,
  1036. 'forestgreen': 0x228B22,
  1037. 'fuchsia': 0xFF00FF,
  1038. 'gainsboro': 0xDCDCDC,
  1039. 'ghostwhite': 0xF8F8FF,
  1040. 'gold': 0xFFD700,
  1041. 'goldenrod': 0xDAA520,
  1042. 'gray': 0x808080,
  1043. 'green': 0x008000,
  1044. 'greenyellow': 0xADFF2F,
  1045. 'grey': 0x808080,
  1046. 'honeydew': 0xF0FFF0,
  1047. 'hotpink': 0xFF69B4,
  1048. 'indianred': 0xCD5C5C,
  1049. 'indigo': 0x4B0082,
  1050. 'ivory': 0xFFFFF0,
  1051. 'khaki': 0xF0E68C,
  1052. 'lavender': 0xE6E6FA,
  1053. 'lavenderblush': 0xFFF0F5,
  1054. 'lawngreen': 0x7CFC00,
  1055. 'lemonchiffon': 0xFFFACD,
  1056. 'lightblue': 0xADD8E6,
  1057. 'lightcoral': 0xF08080,
  1058. 'lightcyan': 0xE0FFFF,
  1059. 'lightgoldenrodyellow': 0xFAFAD2,
  1060. 'lightgray': 0xD3D3D3,
  1061. 'lightgreen': 0x90EE90,
  1062. 'lightgrey': 0xD3D3D3,
  1063. 'lightpink': 0xFFB6C1,
  1064. 'lightsalmon': 0xFFA07A,
  1065. 'lightseagreen': 0x20B2AA,
  1066. 'lightskyblue': 0x87CEFA,
  1067. 'lightslategray': 0x778899,
  1068. 'lightslategrey': 0x778899,
  1069. 'lightsteelblue': 0xB0C4DE,
  1070. 'lightyellow': 0xFFFFE0,
  1071. 'lime': 0x00FF00,
  1072. 'limegreen': 0x32CD32,
  1073. 'linen': 0xFAF0E6,
  1074. 'magenta': 0xFF00FF,
  1075. 'maroon': 0x800000,
  1076. 'mediumaquamarine': 0x66CDAA,
  1077. 'mediumblue': 0x0000CD,
  1078. 'mediumorchid': 0xBA55D3,
  1079. 'mediumpurple': 0x9370DB,
  1080. 'mediumseagreen': 0x3CB371,
  1081. 'mediumslateblue': 0x7B68EE,
  1082. 'mediumspringgreen': 0x00FA9A,
  1083. 'mediumturquoise': 0x48D1CC,
  1084. 'mediumvioletred': 0xC71585,
  1085. 'midnightblue': 0x191970,
  1086. 'mintcream': 0xF5FFFA,
  1087. 'mistyrose': 0xFFE4E1,
  1088. 'moccasin': 0xFFE4B5,
  1089. 'navajowhite': 0xFFDEAD,
  1090. 'navy': 0x000080,
  1091. 'oldlace': 0xFDF5E6,
  1092. 'olive': 0x808000,
  1093. 'olivedrab': 0x6B8E23,
  1094. 'orange': 0xFFA500,
  1095. 'orangered': 0xFF4500,
  1096. 'orchid': 0xDA70D6,
  1097. 'palegoldenrod': 0xEEE8AA,
  1098. 'palegreen': 0x98FB98,
  1099. 'paleturquoise': 0xAFEEEE,
  1100. 'palevioletred': 0xDB7093,
  1101. 'papayawhip': 0xFFEFD5,
  1102. 'peachpuff': 0xFFDAB9,
  1103. 'peru': 0xCD853F,
  1104. 'pink': 0xFFC0CB,
  1105. 'plum': 0xDDA0DD,
  1106. 'powderblue': 0xB0E0E6,
  1107. 'purple': 0x800080,
  1108. 'rebeccapurple': 0x663399,
  1109. 'red': 0xFF0000,
  1110. 'rosybrown': 0xBC8F8F,
  1111. 'royalblue': 0x4169E1,
  1112. 'saddlebrown': 0x8B4513,
  1113. 'salmon': 0xFA8072,
  1114. 'sandybrown': 0xF4A460,
  1115. 'seagreen': 0x2E8B57,
  1116. 'seashell': 0xFFF5EE,
  1117. 'sienna': 0xA0522D,
  1118. 'silver': 0xC0C0C0,
  1119. 'skyblue': 0x87CEEB,
  1120. 'slateblue': 0x6A5ACD,
  1121. 'slategray': 0x708090,
  1122. 'slategrey': 0x708090,
  1123. 'snow': 0xFFFAFA,
  1124. 'springgreen': 0x00FF7F,
  1125. 'steelblue': 0x4682B4,
  1126. 'tan': 0xD2B48C,
  1127. 'teal': 0x008080,
  1128. 'thistle': 0xD8BFD8,
  1129. 'tomato': 0xFF6347,
  1130. 'turquoise': 0x40E0D0,
  1131. 'violet': 0xEE82EE,
  1132. 'wheat': 0xF5DEB3,
  1133. 'white': 0xFFFFFF,
  1134. 'whitesmoke': 0xF5F5F5,
  1135. 'yellow': 0xFFFF00,
  1136. 'yellowgreen': 0x9ACD32
  1137. };
  1138. const _rgb = {
  1139. r: 0,
  1140. g: 0,
  1141. b: 0
  1142. };
  1143. const _hslA = {
  1144. h: 0,
  1145. s: 0,
  1146. l: 0
  1147. };
  1148. const _hslB = {
  1149. h: 0,
  1150. s: 0,
  1151. l: 0
  1152. };
  1153. function hue2rgb(p, q, t) {
  1154. if (t < 0) t += 1;
  1155. if (t > 1) t -= 1;
  1156. if (t < 1 / 6) return p + (q - p) * 6 * t;
  1157. if (t < 1 / 2) return q;
  1158. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  1159. return p;
  1160. }
  1161. function toComponents(source, target) {
  1162. target.r = source.r;
  1163. target.g = source.g;
  1164. target.b = source.b;
  1165. return target;
  1166. }
  1167. class Color {
  1168. constructor(r, g, b) {
  1169. this.isColor = true;
  1170. this.r = 1;
  1171. this.g = 1;
  1172. this.b = 1;
  1173. if (g === undefined && b === undefined) {
  1174. // r is THREE.Color, hex or string
  1175. return this.set(r);
  1176. }
  1177. return this.setRGB(r, g, b);
  1178. }
  1179. set(value) {
  1180. if (value && value.isColor) {
  1181. this.copy(value);
  1182. } else if (typeof value === 'number') {
  1183. this.setHex(value);
  1184. } else if (typeof value === 'string') {
  1185. this.setStyle(value);
  1186. }
  1187. return this;
  1188. }
  1189. setScalar(scalar) {
  1190. this.r = scalar;
  1191. this.g = scalar;
  1192. this.b = scalar;
  1193. return this;
  1194. }
  1195. setHex(hex, colorSpace = SRGBColorSpace) {
  1196. hex = Math.floor(hex);
  1197. this.r = (hex >> 16 & 255) / 255;
  1198. this.g = (hex >> 8 & 255) / 255;
  1199. this.b = (hex & 255) / 255;
  1200. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1201. return this;
  1202. }
  1203. setRGB(r, g, b, colorSpace = LinearSRGBColorSpace) {
  1204. this.r = r;
  1205. this.g = g;
  1206. this.b = b;
  1207. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1208. return this;
  1209. }
  1210. setHSL(h, s, l, colorSpace = LinearSRGBColorSpace) {
  1211. // h,s,l ranges are in 0.0 - 1.0
  1212. h = euclideanModulo(h, 1);
  1213. s = clamp(s, 0, 1);
  1214. l = clamp(l, 0, 1);
  1215. if (s === 0) {
  1216. this.r = this.g = this.b = l;
  1217. } else {
  1218. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  1219. const q = 2 * l - p;
  1220. this.r = hue2rgb(q, p, h + 1 / 3);
  1221. this.g = hue2rgb(q, p, h);
  1222. this.b = hue2rgb(q, p, h - 1 / 3);
  1223. }
  1224. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1225. return this;
  1226. }
  1227. setStyle(style, colorSpace = SRGBColorSpace) {
  1228. function handleAlpha(string) {
  1229. if (string === undefined) return;
  1230. if (parseFloat(string) < 1) {
  1231. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  1232. }
  1233. }
  1234. let m;
  1235. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  1236. // rgb / hsl
  1237. let color;
  1238. const name = m[1];
  1239. const components = m[2];
  1240. switch (name) {
  1241. case 'rgb':
  1242. case 'rgba':
  1243. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1244. // rgb(255,0,0) rgba(255,0,0,0.5)
  1245. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  1246. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  1247. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  1248. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1249. handleAlpha(color[4]);
  1250. return this;
  1251. }
  1252. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1253. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1254. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  1255. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  1256. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  1257. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1258. handleAlpha(color[4]);
  1259. return this;
  1260. }
  1261. break;
  1262. case 'hsl':
  1263. case 'hsla':
  1264. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1265. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1266. const h = parseFloat(color[1]) / 360;
  1267. const s = parseFloat(color[2]) / 100;
  1268. const l = parseFloat(color[3]) / 100;
  1269. handleAlpha(color[4]);
  1270. return this.setHSL(h, s, l, colorSpace);
  1271. }
  1272. break;
  1273. }
  1274. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  1275. // hex color
  1276. const hex = m[1];
  1277. const size = hex.length;
  1278. if (size === 3) {
  1279. // #ff0
  1280. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  1281. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  1282. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  1283. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1284. return this;
  1285. } else if (size === 6) {
  1286. // #ff0000
  1287. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  1288. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  1289. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  1290. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1291. return this;
  1292. }
  1293. }
  1294. if (style && style.length > 0) {
  1295. return this.setColorName(style, colorSpace);
  1296. }
  1297. return this;
  1298. }
  1299. setColorName(style, colorSpace = SRGBColorSpace) {
  1300. // color keywords
  1301. const hex = _colorKeywords[style.toLowerCase()];
  1302. if (hex !== undefined) {
  1303. // red
  1304. this.setHex(hex, colorSpace);
  1305. } else {
  1306. // unknown color
  1307. console.warn('THREE.Color: Unknown color ' + style);
  1308. }
  1309. return this;
  1310. }
  1311. clone() {
  1312. return new this.constructor(this.r, this.g, this.b);
  1313. }
  1314. copy(color) {
  1315. this.r = color.r;
  1316. this.g = color.g;
  1317. this.b = color.b;
  1318. return this;
  1319. }
  1320. copySRGBToLinear(color) {
  1321. this.r = SRGBToLinear(color.r);
  1322. this.g = SRGBToLinear(color.g);
  1323. this.b = SRGBToLinear(color.b);
  1324. return this;
  1325. }
  1326. copyLinearToSRGB(color) {
  1327. this.r = LinearToSRGB(color.r);
  1328. this.g = LinearToSRGB(color.g);
  1329. this.b = LinearToSRGB(color.b);
  1330. return this;
  1331. }
  1332. convertSRGBToLinear() {
  1333. this.copySRGBToLinear(this);
  1334. return this;
  1335. }
  1336. convertLinearToSRGB() {
  1337. this.copyLinearToSRGB(this);
  1338. return this;
  1339. }
  1340. getHex(colorSpace = SRGBColorSpace) {
  1341. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1342. return clamp(_rgb.r * 255, 0, 255) << 16 ^ clamp(_rgb.g * 255, 0, 255) << 8 ^ clamp(_rgb.b * 255, 0, 255) << 0;
  1343. }
  1344. getHexString(colorSpace = SRGBColorSpace) {
  1345. return ('000000' + this.getHex(colorSpace).toString(16)).slice(-6);
  1346. }
  1347. getHSL(target, colorSpace = LinearSRGBColorSpace) {
  1348. // h,s,l ranges are in 0.0 - 1.0
  1349. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1350. const r = _rgb.r,
  1351. g = _rgb.g,
  1352. b = _rgb.b;
  1353. const max = Math.max(r, g, b);
  1354. const min = Math.min(r, g, b);
  1355. let hue, saturation;
  1356. const lightness = (min + max) / 2.0;
  1357. if (min === max) {
  1358. hue = 0;
  1359. saturation = 0;
  1360. } else {
  1361. const delta = max - min;
  1362. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  1363. switch (max) {
  1364. case r:
  1365. hue = (g - b) / delta + (g < b ? 6 : 0);
  1366. break;
  1367. case g:
  1368. hue = (b - r) / delta + 2;
  1369. break;
  1370. case b:
  1371. hue = (r - g) / delta + 4;
  1372. break;
  1373. }
  1374. hue /= 6;
  1375. }
  1376. target.h = hue;
  1377. target.s = saturation;
  1378. target.l = lightness;
  1379. return target;
  1380. }
  1381. getRGB(target, colorSpace = LinearSRGBColorSpace) {
  1382. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1383. target.r = _rgb.r;
  1384. target.g = _rgb.g;
  1385. target.b = _rgb.b;
  1386. return target;
  1387. }
  1388. getStyle(colorSpace = SRGBColorSpace) {
  1389. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1390. if (colorSpace !== SRGBColorSpace) {
  1391. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1392. return `color(${colorSpace} ${_rgb.r} ${_rgb.g} ${_rgb.b})`;
  1393. }
  1394. return `rgb(${_rgb.r * 255 | 0},${_rgb.g * 255 | 0},${_rgb.b * 255 | 0})`;
  1395. }
  1396. offsetHSL(h, s, l) {
  1397. this.getHSL(_hslA);
  1398. _hslA.h += h;
  1399. _hslA.s += s;
  1400. _hslA.l += l;
  1401. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  1402. return this;
  1403. }
  1404. add(color) {
  1405. this.r += color.r;
  1406. this.g += color.g;
  1407. this.b += color.b;
  1408. return this;
  1409. }
  1410. addColors(color1, color2) {
  1411. this.r = color1.r + color2.r;
  1412. this.g = color1.g + color2.g;
  1413. this.b = color1.b + color2.b;
  1414. return this;
  1415. }
  1416. addScalar(s) {
  1417. this.r += s;
  1418. this.g += s;
  1419. this.b += s;
  1420. return this;
  1421. }
  1422. sub(color) {
  1423. this.r = Math.max(0, this.r - color.r);
  1424. this.g = Math.max(0, this.g - color.g);
  1425. this.b = Math.max(0, this.b - color.b);
  1426. return this;
  1427. }
  1428. multiply(color) {
  1429. this.r *= color.r;
  1430. this.g *= color.g;
  1431. this.b *= color.b;
  1432. return this;
  1433. }
  1434. multiplyScalar(s) {
  1435. this.r *= s;
  1436. this.g *= s;
  1437. this.b *= s;
  1438. return this;
  1439. }
  1440. lerp(color, alpha) {
  1441. this.r += (color.r - this.r) * alpha;
  1442. this.g += (color.g - this.g) * alpha;
  1443. this.b += (color.b - this.b) * alpha;
  1444. return this;
  1445. }
  1446. lerpColors(color1, color2, alpha) {
  1447. this.r = color1.r + (color2.r - color1.r) * alpha;
  1448. this.g = color1.g + (color2.g - color1.g) * alpha;
  1449. this.b = color1.b + (color2.b - color1.b) * alpha;
  1450. return this;
  1451. }
  1452. lerpHSL(color, alpha) {
  1453. this.getHSL(_hslA);
  1454. color.getHSL(_hslB);
  1455. const h = lerp(_hslA.h, _hslB.h, alpha);
  1456. const s = lerp(_hslA.s, _hslB.s, alpha);
  1457. const l = lerp(_hslA.l, _hslB.l, alpha);
  1458. this.setHSL(h, s, l);
  1459. return this;
  1460. }
  1461. equals(c) {
  1462. return c.r === this.r && c.g === this.g && c.b === this.b;
  1463. }
  1464. fromArray(array, offset = 0) {
  1465. this.r = array[offset];
  1466. this.g = array[offset + 1];
  1467. this.b = array[offset + 2];
  1468. return this;
  1469. }
  1470. toArray(array = [], offset = 0) {
  1471. array[offset] = this.r;
  1472. array[offset + 1] = this.g;
  1473. array[offset + 2] = this.b;
  1474. return array;
  1475. }
  1476. fromBufferAttribute(attribute, index) {
  1477. this.r = attribute.getX(index);
  1478. this.g = attribute.getY(index);
  1479. this.b = attribute.getZ(index);
  1480. return this;
  1481. }
  1482. toJSON() {
  1483. return this.getHex();
  1484. }
  1485. *[Symbol.iterator]() {
  1486. yield this.r;
  1487. yield this.g;
  1488. yield this.b;
  1489. }
  1490. }
  1491. Color.NAMES = _colorKeywords;
  1492. let _canvas;
  1493. class ImageUtils {
  1494. static getDataURL(image) {
  1495. if (/^data:/i.test(image.src)) {
  1496. return image.src;
  1497. }
  1498. if (typeof HTMLCanvasElement == 'undefined') {
  1499. return image.src;
  1500. }
  1501. let canvas;
  1502. if (image instanceof HTMLCanvasElement) {
  1503. canvas = image;
  1504. } else {
  1505. if (_canvas === undefined) _canvas = createElementNS('canvas');
  1506. _canvas.width = image.width;
  1507. _canvas.height = image.height;
  1508. const context = _canvas.getContext('2d');
  1509. if (image instanceof ImageData) {
  1510. context.putImageData(image, 0, 0);
  1511. } else {
  1512. context.drawImage(image, 0, 0, image.width, image.height);
  1513. }
  1514. canvas = _canvas;
  1515. }
  1516. if (canvas.width > 2048 || canvas.height > 2048) {
  1517. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  1518. return canvas.toDataURL('image/jpeg', 0.6);
  1519. } else {
  1520. return canvas.toDataURL('image/png');
  1521. }
  1522. }
  1523. static sRGBToLinear(image) {
  1524. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1525. const canvas = createElementNS('canvas');
  1526. canvas.width = image.width;
  1527. canvas.height = image.height;
  1528. const context = canvas.getContext('2d');
  1529. context.drawImage(image, 0, 0, image.width, image.height);
  1530. const imageData = context.getImageData(0, 0, image.width, image.height);
  1531. const data = imageData.data;
  1532. for (let i = 0; i < data.length; i++) {
  1533. data[i] = SRGBToLinear(data[i] / 255) * 255;
  1534. }
  1535. context.putImageData(imageData, 0, 0);
  1536. return canvas;
  1537. } else if (image.data) {
  1538. const data = image.data.slice(0);
  1539. for (let i = 0; i < data.length; i++) {
  1540. if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
  1541. data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255);
  1542. } else {
  1543. // assuming float
  1544. data[i] = SRGBToLinear(data[i]);
  1545. }
  1546. }
  1547. return {
  1548. data: data,
  1549. width: image.width,
  1550. height: image.height
  1551. };
  1552. } else {
  1553. console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.');
  1554. return image;
  1555. }
  1556. }
  1557. }
  1558. class Source {
  1559. constructor(data = null) {
  1560. this.isSource = true;
  1561. this.uuid = generateUUID();
  1562. this.data = data;
  1563. this.version = 0;
  1564. }
  1565. set needsUpdate(value) {
  1566. if (value === true) this.version++;
  1567. }
  1568. toJSON(meta) {
  1569. const isRootObject = meta === undefined || typeof meta === 'string';
  1570. if (!isRootObject && meta.images[this.uuid] !== undefined) {
  1571. return meta.images[this.uuid];
  1572. }
  1573. const output = {
  1574. uuid: this.uuid,
  1575. url: ''
  1576. };
  1577. const data = this.data;
  1578. if (data !== null) {
  1579. let url;
  1580. if (Array.isArray(data)) {
  1581. // cube texture
  1582. url = [];
  1583. for (let i = 0, l = data.length; i < l; i++) {
  1584. if (data[i].isDataTexture) {
  1585. url.push(serializeImage(data[i].image));
  1586. } else {
  1587. url.push(serializeImage(data[i]));
  1588. }
  1589. }
  1590. } else {
  1591. // texture
  1592. url = serializeImage(data);
  1593. }
  1594. output.url = url;
  1595. }
  1596. if (!isRootObject) {
  1597. meta.images[this.uuid] = output;
  1598. }
  1599. return output;
  1600. }
  1601. }
  1602. function serializeImage(image) {
  1603. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1604. // default images
  1605. return ImageUtils.getDataURL(image);
  1606. } else {
  1607. if (image.data) {
  1608. // images of DataTexture
  1609. return {
  1610. data: Array.from(image.data),
  1611. width: image.width,
  1612. height: image.height,
  1613. type: image.data.constructor.name
  1614. };
  1615. } else {
  1616. console.warn('THREE.Texture: Unable to serialize Texture.');
  1617. return {};
  1618. }
  1619. }
  1620. }
  1621. let textureId = 0;
  1622. class Texture extends EventDispatcher {
  1623. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  1624. super();
  1625. this.isTexture = true;
  1626. Object.defineProperty(this, 'id', {
  1627. value: textureId++
  1628. });
  1629. this.uuid = generateUUID();
  1630. this.name = '';
  1631. this.source = new Source(image);
  1632. this.mipmaps = [];
  1633. this.mapping = mapping;
  1634. this.wrapS = wrapS;
  1635. this.wrapT = wrapT;
  1636. this.magFilter = magFilter;
  1637. this.minFilter = minFilter;
  1638. this.anisotropy = anisotropy;
  1639. this.format = format;
  1640. this.internalFormat = null;
  1641. this.type = type;
  1642. this.offset = new Vector2(0, 0);
  1643. this.repeat = new Vector2(1, 1);
  1644. this.center = new Vector2(0, 0);
  1645. this.rotation = 0;
  1646. this.matrixAutoUpdate = true;
  1647. this.matrix = new Matrix3();
  1648. this.generateMipmaps = true;
  1649. this.premultiplyAlpha = false;
  1650. this.flipY = true;
  1651. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1652. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1653. //
  1654. // Also changing the encoding after already used by a Material will not automatically make the Material
  1655. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1656. this.encoding = encoding;
  1657. this.userData = {};
  1658. this.version = 0;
  1659. this.onUpdate = null;
  1660. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1661. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1662. }
  1663. get image() {
  1664. return this.source.data;
  1665. }
  1666. set image(value) {
  1667. this.source.data = value;
  1668. }
  1669. updateMatrix() {
  1670. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1671. }
  1672. clone() {
  1673. return new this.constructor().copy(this);
  1674. }
  1675. copy(source) {
  1676. this.name = source.name;
  1677. this.source = source.source;
  1678. this.mipmaps = source.mipmaps.slice(0);
  1679. this.mapping = source.mapping;
  1680. this.wrapS = source.wrapS;
  1681. this.wrapT = source.wrapT;
  1682. this.magFilter = source.magFilter;
  1683. this.minFilter = source.minFilter;
  1684. this.anisotropy = source.anisotropy;
  1685. this.format = source.format;
  1686. this.internalFormat = source.internalFormat;
  1687. this.type = source.type;
  1688. this.offset.copy(source.offset);
  1689. this.repeat.copy(source.repeat);
  1690. this.center.copy(source.center);
  1691. this.rotation = source.rotation;
  1692. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1693. this.matrix.copy(source.matrix);
  1694. this.generateMipmaps = source.generateMipmaps;
  1695. this.premultiplyAlpha = source.premultiplyAlpha;
  1696. this.flipY = source.flipY;
  1697. this.unpackAlignment = source.unpackAlignment;
  1698. this.encoding = source.encoding;
  1699. this.userData = JSON.parse(JSON.stringify(source.userData));
  1700. this.needsUpdate = true;
  1701. return this;
  1702. }
  1703. toJSON(meta) {
  1704. const isRootObject = meta === undefined || typeof meta === 'string';
  1705. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1706. return meta.textures[this.uuid];
  1707. }
  1708. const output = {
  1709. metadata: {
  1710. version: 4.5,
  1711. type: 'Texture',
  1712. generator: 'Texture.toJSON'
  1713. },
  1714. uuid: this.uuid,
  1715. name: this.name,
  1716. image: this.source.toJSON(meta).uuid,
  1717. mapping: this.mapping,
  1718. repeat: [this.repeat.x, this.repeat.y],
  1719. offset: [this.offset.x, this.offset.y],
  1720. center: [this.center.x, this.center.y],
  1721. rotation: this.rotation,
  1722. wrap: [this.wrapS, this.wrapT],
  1723. format: this.format,
  1724. type: this.type,
  1725. encoding: this.encoding,
  1726. minFilter: this.minFilter,
  1727. magFilter: this.magFilter,
  1728. anisotropy: this.anisotropy,
  1729. flipY: this.flipY,
  1730. premultiplyAlpha: this.premultiplyAlpha,
  1731. unpackAlignment: this.unpackAlignment
  1732. };
  1733. if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
  1734. if (!isRootObject) {
  1735. meta.textures[this.uuid] = output;
  1736. }
  1737. return output;
  1738. }
  1739. dispose() {
  1740. this.dispatchEvent({
  1741. type: 'dispose'
  1742. });
  1743. }
  1744. transformUv(uv) {
  1745. if (this.mapping !== UVMapping) return uv;
  1746. uv.applyMatrix3(this.matrix);
  1747. if (uv.x < 0 || uv.x > 1) {
  1748. switch (this.wrapS) {
  1749. case RepeatWrapping:
  1750. uv.x = uv.x - Math.floor(uv.x);
  1751. break;
  1752. case ClampToEdgeWrapping:
  1753. uv.x = uv.x < 0 ? 0 : 1;
  1754. break;
  1755. case MirroredRepeatWrapping:
  1756. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1757. uv.x = Math.ceil(uv.x) - uv.x;
  1758. } else {
  1759. uv.x = uv.x - Math.floor(uv.x);
  1760. }
  1761. break;
  1762. }
  1763. }
  1764. if (uv.y < 0 || uv.y > 1) {
  1765. switch (this.wrapT) {
  1766. case RepeatWrapping:
  1767. uv.y = uv.y - Math.floor(uv.y);
  1768. break;
  1769. case ClampToEdgeWrapping:
  1770. uv.y = uv.y < 0 ? 0 : 1;
  1771. break;
  1772. case MirroredRepeatWrapping:
  1773. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1774. uv.y = Math.ceil(uv.y) - uv.y;
  1775. } else {
  1776. uv.y = uv.y - Math.floor(uv.y);
  1777. }
  1778. break;
  1779. }
  1780. }
  1781. if (this.flipY) {
  1782. uv.y = 1 - uv.y;
  1783. }
  1784. return uv;
  1785. }
  1786. set needsUpdate(value) {
  1787. if (value === true) {
  1788. this.version++;
  1789. this.source.needsUpdate = true;
  1790. }
  1791. }
  1792. }
  1793. Texture.DEFAULT_IMAGE = null;
  1794. Texture.DEFAULT_MAPPING = UVMapping;
  1795. class Vector4 {
  1796. constructor(x = 0, y = 0, z = 0, w = 1) {
  1797. Vector4.prototype.isVector4 = true;
  1798. this.x = x;
  1799. this.y = y;
  1800. this.z = z;
  1801. this.w = w;
  1802. }
  1803. get width() {
  1804. return this.z;
  1805. }
  1806. set width(value) {
  1807. this.z = value;
  1808. }
  1809. get height() {
  1810. return this.w;
  1811. }
  1812. set height(value) {
  1813. this.w = value;
  1814. }
  1815. set(x, y, z, w) {
  1816. this.x = x;
  1817. this.y = y;
  1818. this.z = z;
  1819. this.w = w;
  1820. return this;
  1821. }
  1822. setScalar(scalar) {
  1823. this.x = scalar;
  1824. this.y = scalar;
  1825. this.z = scalar;
  1826. this.w = scalar;
  1827. return this;
  1828. }
  1829. setX(x) {
  1830. this.x = x;
  1831. return this;
  1832. }
  1833. setY(y) {
  1834. this.y = y;
  1835. return this;
  1836. }
  1837. setZ(z) {
  1838. this.z = z;
  1839. return this;
  1840. }
  1841. setW(w) {
  1842. this.w = w;
  1843. return this;
  1844. }
  1845. setComponent(index, value) {
  1846. switch (index) {
  1847. case 0:
  1848. this.x = value;
  1849. break;
  1850. case 1:
  1851. this.y = value;
  1852. break;
  1853. case 2:
  1854. this.z = value;
  1855. break;
  1856. case 3:
  1857. this.w = value;
  1858. break;
  1859. default:
  1860. throw new Error('index is out of range: ' + index);
  1861. }
  1862. return this;
  1863. }
  1864. getComponent(index) {
  1865. switch (index) {
  1866. case 0:
  1867. return this.x;
  1868. case 1:
  1869. return this.y;
  1870. case 2:
  1871. return this.z;
  1872. case 3:
  1873. return this.w;
  1874. default:
  1875. throw new Error('index is out of range: ' + index);
  1876. }
  1877. }
  1878. clone() {
  1879. return new this.constructor(this.x, this.y, this.z, this.w);
  1880. }
  1881. copy(v) {
  1882. this.x = v.x;
  1883. this.y = v.y;
  1884. this.z = v.z;
  1885. this.w = v.w !== undefined ? v.w : 1;
  1886. return this;
  1887. }
  1888. add(v) {
  1889. this.x += v.x;
  1890. this.y += v.y;
  1891. this.z += v.z;
  1892. this.w += v.w;
  1893. return this;
  1894. }
  1895. addScalar(s) {
  1896. this.x += s;
  1897. this.y += s;
  1898. this.z += s;
  1899. this.w += s;
  1900. return this;
  1901. }
  1902. addVectors(a, b) {
  1903. this.x = a.x + b.x;
  1904. this.y = a.y + b.y;
  1905. this.z = a.z + b.z;
  1906. this.w = a.w + b.w;
  1907. return this;
  1908. }
  1909. addScaledVector(v, s) {
  1910. this.x += v.x * s;
  1911. this.y += v.y * s;
  1912. this.z += v.z * s;
  1913. this.w += v.w * s;
  1914. return this;
  1915. }
  1916. sub(v) {
  1917. this.x -= v.x;
  1918. this.y -= v.y;
  1919. this.z -= v.z;
  1920. this.w -= v.w;
  1921. return this;
  1922. }
  1923. subScalar(s) {
  1924. this.x -= s;
  1925. this.y -= s;
  1926. this.z -= s;
  1927. this.w -= s;
  1928. return this;
  1929. }
  1930. subVectors(a, b) {
  1931. this.x = a.x - b.x;
  1932. this.y = a.y - b.y;
  1933. this.z = a.z - b.z;
  1934. this.w = a.w - b.w;
  1935. return this;
  1936. }
  1937. multiply(v) {
  1938. this.x *= v.x;
  1939. this.y *= v.y;
  1940. this.z *= v.z;
  1941. this.w *= v.w;
  1942. return this;
  1943. }
  1944. multiplyScalar(scalar) {
  1945. this.x *= scalar;
  1946. this.y *= scalar;
  1947. this.z *= scalar;
  1948. this.w *= scalar;
  1949. return this;
  1950. }
  1951. applyMatrix4(m) {
  1952. const x = this.x,
  1953. y = this.y,
  1954. z = this.z,
  1955. w = this.w;
  1956. const e = m.elements;
  1957. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1958. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1959. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1960. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1961. return this;
  1962. }
  1963. divideScalar(scalar) {
  1964. return this.multiplyScalar(1 / scalar);
  1965. }
  1966. setAxisAngleFromQuaternion(q) {
  1967. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1968. // q is assumed to be normalized
  1969. this.w = 2 * Math.acos(q.w);
  1970. const s = Math.sqrt(1 - q.w * q.w);
  1971. if (s < 0.0001) {
  1972. this.x = 1;
  1973. this.y = 0;
  1974. this.z = 0;
  1975. } else {
  1976. this.x = q.x / s;
  1977. this.y = q.y / s;
  1978. this.z = q.z / s;
  1979. }
  1980. return this;
  1981. }
  1982. setAxisAngleFromRotationMatrix(m) {
  1983. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1984. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1985. let angle, x, y, z; // variables for result
  1986. const epsilon = 0.01,
  1987. // margin to allow for rounding errors
  1988. epsilon2 = 0.1,
  1989. // margin to distinguish between 0 and 180 degrees
  1990. te = m.elements,
  1991. m11 = te[0],
  1992. m12 = te[4],
  1993. m13 = te[8],
  1994. m21 = te[1],
  1995. m22 = te[5],
  1996. m23 = te[9],
  1997. m31 = te[2],
  1998. m32 = te[6],
  1999. m33 = te[10];
  2000. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  2001. // singularity found
  2002. // first check for identity matrix which must have +1 for all terms
  2003. // in leading diagonal and zero in other terms
  2004. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  2005. // this singularity is identity matrix so angle = 0
  2006. this.set(1, 0, 0, 0);
  2007. return this; // zero angle, arbitrary axis
  2008. } // otherwise this singularity is angle = 180
  2009. angle = Math.PI;
  2010. const xx = (m11 + 1) / 2;
  2011. const yy = (m22 + 1) / 2;
  2012. const zz = (m33 + 1) / 2;
  2013. const xy = (m12 + m21) / 4;
  2014. const xz = (m13 + m31) / 4;
  2015. const yz = (m23 + m32) / 4;
  2016. if (xx > yy && xx > zz) {
  2017. // m11 is the largest diagonal term
  2018. if (xx < epsilon) {
  2019. x = 0;
  2020. y = 0.707106781;
  2021. z = 0.707106781;
  2022. } else {
  2023. x = Math.sqrt(xx);
  2024. y = xy / x;
  2025. z = xz / x;
  2026. }
  2027. } else if (yy > zz) {
  2028. // m22 is the largest diagonal term
  2029. if (yy < epsilon) {
  2030. x = 0.707106781;
  2031. y = 0;
  2032. z = 0.707106781;
  2033. } else {
  2034. y = Math.sqrt(yy);
  2035. x = xy / y;
  2036. z = yz / y;
  2037. }
  2038. } else {
  2039. // m33 is the largest diagonal term so base result on this
  2040. if (zz < epsilon) {
  2041. x = 0.707106781;
  2042. y = 0.707106781;
  2043. z = 0;
  2044. } else {
  2045. z = Math.sqrt(zz);
  2046. x = xz / z;
  2047. y = yz / z;
  2048. }
  2049. }
  2050. this.set(x, y, z, angle);
  2051. return this; // return 180 deg rotation
  2052. } // as we have reached here there are no singularities so we can handle normally
  2053. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  2054. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2055. // caught by singularity test above, but I've left it in just in case
  2056. this.x = (m32 - m23) / s;
  2057. this.y = (m13 - m31) / s;
  2058. this.z = (m21 - m12) / s;
  2059. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2060. return this;
  2061. }
  2062. min(v) {
  2063. this.x = Math.min(this.x, v.x);
  2064. this.y = Math.min(this.y, v.y);
  2065. this.z = Math.min(this.z, v.z);
  2066. this.w = Math.min(this.w, v.w);
  2067. return this;
  2068. }
  2069. max(v) {
  2070. this.x = Math.max(this.x, v.x);
  2071. this.y = Math.max(this.y, v.y);
  2072. this.z = Math.max(this.z, v.z);
  2073. this.w = Math.max(this.w, v.w);
  2074. return this;
  2075. }
  2076. clamp(min, max) {
  2077. // assumes min < max, componentwise
  2078. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2079. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2080. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2081. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2082. return this;
  2083. }
  2084. clampScalar(minVal, maxVal) {
  2085. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2086. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2087. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2088. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2089. return this;
  2090. }
  2091. clampLength(min, max) {
  2092. const length = this.length();
  2093. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2094. }
  2095. floor() {
  2096. this.x = Math.floor(this.x);
  2097. this.y = Math.floor(this.y);
  2098. this.z = Math.floor(this.z);
  2099. this.w = Math.floor(this.w);
  2100. return this;
  2101. }
  2102. ceil() {
  2103. this.x = Math.ceil(this.x);
  2104. this.y = Math.ceil(this.y);
  2105. this.z = Math.ceil(this.z);
  2106. this.w = Math.ceil(this.w);
  2107. return this;
  2108. }
  2109. round() {
  2110. this.x = Math.round(this.x);
  2111. this.y = Math.round(this.y);
  2112. this.z = Math.round(this.z);
  2113. this.w = Math.round(this.w);
  2114. return this;
  2115. }
  2116. roundToZero() {
  2117. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2118. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2119. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2120. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2121. return this;
  2122. }
  2123. negate() {
  2124. this.x = -this.x;
  2125. this.y = -this.y;
  2126. this.z = -this.z;
  2127. this.w = -this.w;
  2128. return this;
  2129. }
  2130. dot(v) {
  2131. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2132. }
  2133. lengthSq() {
  2134. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2135. }
  2136. length() {
  2137. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2138. }
  2139. manhattanLength() {
  2140. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2141. }
  2142. normalize() {
  2143. return this.divideScalar(this.length() || 1);
  2144. }
  2145. setLength(length) {
  2146. return this.normalize().multiplyScalar(length);
  2147. }
  2148. lerp(v, alpha) {
  2149. this.x += (v.x - this.x) * alpha;
  2150. this.y += (v.y - this.y) * alpha;
  2151. this.z += (v.z - this.z) * alpha;
  2152. this.w += (v.w - this.w) * alpha;
  2153. return this;
  2154. }
  2155. lerpVectors(v1, v2, alpha) {
  2156. this.x = v1.x + (v2.x - v1.x) * alpha;
  2157. this.y = v1.y + (v2.y - v1.y) * alpha;
  2158. this.z = v1.z + (v2.z - v1.z) * alpha;
  2159. this.w = v1.w + (v2.w - v1.w) * alpha;
  2160. return this;
  2161. }
  2162. equals(v) {
  2163. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2164. }
  2165. fromArray(array, offset = 0) {
  2166. this.x = array[offset];
  2167. this.y = array[offset + 1];
  2168. this.z = array[offset + 2];
  2169. this.w = array[offset + 3];
  2170. return this;
  2171. }
  2172. toArray(array = [], offset = 0) {
  2173. array[offset] = this.x;
  2174. array[offset + 1] = this.y;
  2175. array[offset + 2] = this.z;
  2176. array[offset + 3] = this.w;
  2177. return array;
  2178. }
  2179. fromBufferAttribute(attribute, index) {
  2180. this.x = attribute.getX(index);
  2181. this.y = attribute.getY(index);
  2182. this.z = attribute.getZ(index);
  2183. this.w = attribute.getW(index);
  2184. return this;
  2185. }
  2186. random() {
  2187. this.x = Math.random();
  2188. this.y = Math.random();
  2189. this.z = Math.random();
  2190. this.w = Math.random();
  2191. return this;
  2192. }
  2193. *[Symbol.iterator]() {
  2194. yield this.x;
  2195. yield this.y;
  2196. yield this.z;
  2197. yield this.w;
  2198. }
  2199. }
  2200. /*
  2201. In options, we can specify:
  2202. * Texture parameters for an auto-generated target texture
  2203. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2204. */
  2205. class WebGLRenderTarget extends EventDispatcher {
  2206. constructor(width, height, options = {}) {
  2207. super();
  2208. this.isWebGLRenderTarget = true;
  2209. this.width = width;
  2210. this.height = height;
  2211. this.depth = 1;
  2212. this.scissor = new Vector4(0, 0, width, height);
  2213. this.scissorTest = false;
  2214. this.viewport = new Vector4(0, 0, width, height);
  2215. const image = {
  2216. width: width,
  2217. height: height,
  2218. depth: 1
  2219. };
  2220. this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2221. this.texture.isRenderTargetTexture = true;
  2222. this.texture.flipY = false;
  2223. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2224. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2225. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2226. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2227. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2228. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2229. this.samples = options.samples !== undefined ? options.samples : 0;
  2230. }
  2231. setSize(width, height, depth = 1) {
  2232. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2233. this.width = width;
  2234. this.height = height;
  2235. this.depth = depth;
  2236. this.texture.image.width = width;
  2237. this.texture.image.height = height;
  2238. this.texture.image.depth = depth;
  2239. this.dispose();
  2240. }
  2241. this.viewport.set(0, 0, width, height);
  2242. this.scissor.set(0, 0, width, height);
  2243. }
  2244. clone() {
  2245. return new this.constructor().copy(this);
  2246. }
  2247. copy(source) {
  2248. this.width = source.width;
  2249. this.height = source.height;
  2250. this.depth = source.depth;
  2251. this.viewport.copy(source.viewport);
  2252. this.texture = source.texture.clone();
  2253. this.texture.isRenderTargetTexture = true; // ensure image object is not shared, see #20328
  2254. const image = Object.assign({}, source.texture.image);
  2255. this.texture.source = new Source(image);
  2256. this.depthBuffer = source.depthBuffer;
  2257. this.stencilBuffer = source.stencilBuffer;
  2258. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2259. this.samples = source.samples;
  2260. return this;
  2261. }
  2262. dispose() {
  2263. this.dispatchEvent({
  2264. type: 'dispose'
  2265. });
  2266. }
  2267. }
  2268. class DataArrayTexture extends Texture {
  2269. constructor(data = null, width = 1, height = 1, depth = 1) {
  2270. super(null);
  2271. this.isDataArrayTexture = true;
  2272. this.image = {
  2273. data,
  2274. width,
  2275. height,
  2276. depth
  2277. };
  2278. this.magFilter = NearestFilter;
  2279. this.minFilter = NearestFilter;
  2280. this.wrapR = ClampToEdgeWrapping;
  2281. this.generateMipmaps = false;
  2282. this.flipY = false;
  2283. this.unpackAlignment = 1;
  2284. }
  2285. }
  2286. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2287. constructor(width, height, depth) {
  2288. super(width, height);
  2289. this.isWebGLArrayRenderTarget = true;
  2290. this.depth = depth;
  2291. this.texture = new DataArrayTexture(null, width, height, depth);
  2292. this.texture.isRenderTargetTexture = true;
  2293. }
  2294. }
  2295. class Data3DTexture extends Texture {
  2296. constructor(data = null, width = 1, height = 1, depth = 1) {
  2297. // We're going to add .setXXX() methods for setting properties later.
  2298. // Users can still set in DataTexture3D directly.
  2299. //
  2300. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2301. // texture.anisotropy = 16;
  2302. //
  2303. // See #14839
  2304. super(null);
  2305. this.isData3DTexture = true;
  2306. this.image = {
  2307. data,
  2308. width,
  2309. height,
  2310. depth
  2311. };
  2312. this.magFilter = NearestFilter;
  2313. this.minFilter = NearestFilter;
  2314. this.wrapR = ClampToEdgeWrapping;
  2315. this.generateMipmaps = false;
  2316. this.flipY = false;
  2317. this.unpackAlignment = 1;
  2318. }
  2319. }
  2320. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2321. constructor(width, height, depth) {
  2322. super(width, height);
  2323. this.isWebGL3DRenderTarget = true;
  2324. this.depth = depth;
  2325. this.texture = new Data3DTexture(null, width, height, depth);
  2326. this.texture.isRenderTargetTexture = true;
  2327. }
  2328. }
  2329. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2330. constructor(width, height, count, options = {}) {
  2331. super(width, height, options);
  2332. this.isWebGLMultipleRenderTargets = true;
  2333. const texture = this.texture;
  2334. this.texture = [];
  2335. for (let i = 0; i < count; i++) {
  2336. this.texture[i] = texture.clone();
  2337. this.texture[i].isRenderTargetTexture = true;
  2338. }
  2339. }
  2340. setSize(width, height, depth = 1) {
  2341. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2342. this.width = width;
  2343. this.height = height;
  2344. this.depth = depth;
  2345. for (let i = 0, il = this.texture.length; i < il; i++) {
  2346. this.texture[i].image.width = width;
  2347. this.texture[i].image.height = height;
  2348. this.texture[i].image.depth = depth;
  2349. }
  2350. this.dispose();
  2351. }
  2352. this.viewport.set(0, 0, width, height);
  2353. this.scissor.set(0, 0, width, height);
  2354. return this;
  2355. }
  2356. copy(source) {
  2357. this.dispose();
  2358. this.width = source.width;
  2359. this.height = source.height;
  2360. this.depth = source.depth;
  2361. this.viewport.set(0, 0, this.width, this.height);
  2362. this.scissor.set(0, 0, this.width, this.height);
  2363. this.depthBuffer = source.depthBuffer;
  2364. this.stencilBuffer = source.stencilBuffer;
  2365. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2366. this.texture.length = 0;
  2367. for (let i = 0, il = source.texture.length; i < il; i++) {
  2368. this.texture[i] = source.texture[i].clone();
  2369. this.texture[i].isRenderTargetTexture = true;
  2370. }
  2371. return this;
  2372. }
  2373. }
  2374. class Quaternion {
  2375. constructor(x = 0, y = 0, z = 0, w = 1) {
  2376. this.isQuaternion = true;
  2377. this._x = x;
  2378. this._y = y;
  2379. this._z = z;
  2380. this._w = w;
  2381. }
  2382. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2383. // fuzz-free, array-based Quaternion SLERP operation
  2384. let x0 = src0[srcOffset0 + 0],
  2385. y0 = src0[srcOffset0 + 1],
  2386. z0 = src0[srcOffset0 + 2],
  2387. w0 = src0[srcOffset0 + 3];
  2388. const x1 = src1[srcOffset1 + 0],
  2389. y1 = src1[srcOffset1 + 1],
  2390. z1 = src1[srcOffset1 + 2],
  2391. w1 = src1[srcOffset1 + 3];
  2392. if (t === 0) {
  2393. dst[dstOffset + 0] = x0;
  2394. dst[dstOffset + 1] = y0;
  2395. dst[dstOffset + 2] = z0;
  2396. dst[dstOffset + 3] = w0;
  2397. return;
  2398. }
  2399. if (t === 1) {
  2400. dst[dstOffset + 0] = x1;
  2401. dst[dstOffset + 1] = y1;
  2402. dst[dstOffset + 2] = z1;
  2403. dst[dstOffset + 3] = w1;
  2404. return;
  2405. }
  2406. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2407. let s = 1 - t;
  2408. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2409. dir = cos >= 0 ? 1 : -1,
  2410. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2411. if (sqrSin > Number.EPSILON) {
  2412. const sin = Math.sqrt(sqrSin),
  2413. len = Math.atan2(sin, cos * dir);
  2414. s = Math.sin(s * len) / sin;
  2415. t = Math.sin(t * len) / sin;
  2416. }
  2417. const tDir = t * dir;
  2418. x0 = x0 * s + x1 * tDir;
  2419. y0 = y0 * s + y1 * tDir;
  2420. z0 = z0 * s + z1 * tDir;
  2421. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2422. if (s === 1 - t) {
  2423. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2424. x0 *= f;
  2425. y0 *= f;
  2426. z0 *= f;
  2427. w0 *= f;
  2428. }
  2429. }
  2430. dst[dstOffset] = x0;
  2431. dst[dstOffset + 1] = y0;
  2432. dst[dstOffset + 2] = z0;
  2433. dst[dstOffset + 3] = w0;
  2434. }
  2435. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2436. const x0 = src0[srcOffset0];
  2437. const y0 = src0[srcOffset0 + 1];
  2438. const z0 = src0[srcOffset0 + 2];
  2439. const w0 = src0[srcOffset0 + 3];
  2440. const x1 = src1[srcOffset1];
  2441. const y1 = src1[srcOffset1 + 1];
  2442. const z1 = src1[srcOffset1 + 2];
  2443. const w1 = src1[srcOffset1 + 3];
  2444. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2445. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2446. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2447. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2448. return dst;
  2449. }
  2450. get x() {
  2451. return this._x;
  2452. }
  2453. set x(value) {
  2454. this._x = value;
  2455. this._onChangeCallback();
  2456. }
  2457. get y() {
  2458. return this._y;
  2459. }
  2460. set y(value) {
  2461. this._y = value;
  2462. this._onChangeCallback();
  2463. }
  2464. get z() {
  2465. return this._z;
  2466. }
  2467. set z(value) {
  2468. this._z = value;
  2469. this._onChangeCallback();
  2470. }
  2471. get w() {
  2472. return this._w;
  2473. }
  2474. set w(value) {
  2475. this._w = value;
  2476. this._onChangeCallback();
  2477. }
  2478. set(x, y, z, w) {
  2479. this._x = x;
  2480. this._y = y;
  2481. this._z = z;
  2482. this._w = w;
  2483. this._onChangeCallback();
  2484. return this;
  2485. }
  2486. clone() {
  2487. return new this.constructor(this._x, this._y, this._z, this._w);
  2488. }
  2489. copy(quaternion) {
  2490. this._x = quaternion.x;
  2491. this._y = quaternion.y;
  2492. this._z = quaternion.z;
  2493. this._w = quaternion.w;
  2494. this._onChangeCallback();
  2495. return this;
  2496. }
  2497. setFromEuler(euler, update) {
  2498. const x = euler._x,
  2499. y = euler._y,
  2500. z = euler._z,
  2501. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2502. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2503. // content/SpinCalc.m
  2504. const cos = Math.cos;
  2505. const sin = Math.sin;
  2506. const c1 = cos(x / 2);
  2507. const c2 = cos(y / 2);
  2508. const c3 = cos(z / 2);
  2509. const s1 = sin(x / 2);
  2510. const s2 = sin(y / 2);
  2511. const s3 = sin(z / 2);
  2512. switch (order) {
  2513. case 'XYZ':
  2514. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2515. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2516. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2517. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2518. break;
  2519. case 'YXZ':
  2520. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2521. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2522. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2523. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2524. break;
  2525. case 'ZXY':
  2526. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2527. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2528. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2529. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2530. break;
  2531. case 'ZYX':
  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 'YZX':
  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 'XZY':
  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. default:
  2550. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2551. }
  2552. if (update !== false) this._onChangeCallback();
  2553. return this;
  2554. }
  2555. setFromAxisAngle(axis, angle) {
  2556. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2557. // assumes axis is normalized
  2558. const halfAngle = angle / 2,
  2559. s = Math.sin(halfAngle);
  2560. this._x = axis.x * s;
  2561. this._y = axis.y * s;
  2562. this._z = axis.z * s;
  2563. this._w = Math.cos(halfAngle);
  2564. this._onChangeCallback();
  2565. return this;
  2566. }
  2567. setFromRotationMatrix(m) {
  2568. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2569. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2570. const te = m.elements,
  2571. m11 = te[0],
  2572. m12 = te[4],
  2573. m13 = te[8],
  2574. m21 = te[1],
  2575. m22 = te[5],
  2576. m23 = te[9],
  2577. m31 = te[2],
  2578. m32 = te[6],
  2579. m33 = te[10],
  2580. trace = m11 + m22 + m33;
  2581. if (trace > 0) {
  2582. const s = 0.5 / Math.sqrt(trace + 1.0);
  2583. this._w = 0.25 / s;
  2584. this._x = (m32 - m23) * s;
  2585. this._y = (m13 - m31) * s;
  2586. this._z = (m21 - m12) * s;
  2587. } else if (m11 > m22 && m11 > m33) {
  2588. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2589. this._w = (m32 - m23) / s;
  2590. this._x = 0.25 * s;
  2591. this._y = (m12 + m21) / s;
  2592. this._z = (m13 + m31) / s;
  2593. } else if (m22 > m33) {
  2594. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2595. this._w = (m13 - m31) / s;
  2596. this._x = (m12 + m21) / s;
  2597. this._y = 0.25 * s;
  2598. this._z = (m23 + m32) / s;
  2599. } else {
  2600. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2601. this._w = (m21 - m12) / s;
  2602. this._x = (m13 + m31) / s;
  2603. this._y = (m23 + m32) / s;
  2604. this._z = 0.25 * s;
  2605. }
  2606. this._onChangeCallback();
  2607. return this;
  2608. }
  2609. setFromUnitVectors(vFrom, vTo) {
  2610. // assumes direction vectors vFrom and vTo are normalized
  2611. let r = vFrom.dot(vTo) + 1;
  2612. if (r < Number.EPSILON) {
  2613. // vFrom and vTo point in opposite directions
  2614. r = 0;
  2615. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2616. this._x = -vFrom.y;
  2617. this._y = vFrom.x;
  2618. this._z = 0;
  2619. this._w = r;
  2620. } else {
  2621. this._x = 0;
  2622. this._y = -vFrom.z;
  2623. this._z = vFrom.y;
  2624. this._w = r;
  2625. }
  2626. } else {
  2627. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2628. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2629. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2630. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2631. this._w = r;
  2632. }
  2633. return this.normalize();
  2634. }
  2635. angleTo(q) {
  2636. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2637. }
  2638. rotateTowards(q, step) {
  2639. const angle = this.angleTo(q);
  2640. if (angle === 0) return this;
  2641. const t = Math.min(1, step / angle);
  2642. this.slerp(q, t);
  2643. return this;
  2644. }
  2645. identity() {
  2646. return this.set(0, 0, 0, 1);
  2647. }
  2648. invert() {
  2649. // quaternion is assumed to have unit length
  2650. return this.conjugate();
  2651. }
  2652. conjugate() {
  2653. this._x *= -1;
  2654. this._y *= -1;
  2655. this._z *= -1;
  2656. this._onChangeCallback();
  2657. return this;
  2658. }
  2659. dot(v) {
  2660. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2661. }
  2662. lengthSq() {
  2663. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2664. }
  2665. length() {
  2666. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2667. }
  2668. normalize() {
  2669. let l = this.length();
  2670. if (l === 0) {
  2671. this._x = 0;
  2672. this._y = 0;
  2673. this._z = 0;
  2674. this._w = 1;
  2675. } else {
  2676. l = 1 / l;
  2677. this._x = this._x * l;
  2678. this._y = this._y * l;
  2679. this._z = this._z * l;
  2680. this._w = this._w * l;
  2681. }
  2682. this._onChangeCallback();
  2683. return this;
  2684. }
  2685. multiply(q) {
  2686. return this.multiplyQuaternions(this, q);
  2687. }
  2688. premultiply(q) {
  2689. return this.multiplyQuaternions(q, this);
  2690. }
  2691. multiplyQuaternions(a, b) {
  2692. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2693. const qax = a._x,
  2694. qay = a._y,
  2695. qaz = a._z,
  2696. qaw = a._w;
  2697. const qbx = b._x,
  2698. qby = b._y,
  2699. qbz = b._z,
  2700. qbw = b._w;
  2701. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2702. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2703. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2704. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2705. this._onChangeCallback();
  2706. return this;
  2707. }
  2708. slerp(qb, t) {
  2709. if (t === 0) return this;
  2710. if (t === 1) return this.copy(qb);
  2711. const x = this._x,
  2712. y = this._y,
  2713. z = this._z,
  2714. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2715. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2716. if (cosHalfTheta < 0) {
  2717. this._w = -qb._w;
  2718. this._x = -qb._x;
  2719. this._y = -qb._y;
  2720. this._z = -qb._z;
  2721. cosHalfTheta = -cosHalfTheta;
  2722. } else {
  2723. this.copy(qb);
  2724. }
  2725. if (cosHalfTheta >= 1.0) {
  2726. this._w = w;
  2727. this._x = x;
  2728. this._y = y;
  2729. this._z = z;
  2730. return this;
  2731. }
  2732. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2733. if (sqrSinHalfTheta <= Number.EPSILON) {
  2734. const s = 1 - t;
  2735. this._w = s * w + t * this._w;
  2736. this._x = s * x + t * this._x;
  2737. this._y = s * y + t * this._y;
  2738. this._z = s * z + t * this._z;
  2739. this.normalize();
  2740. this._onChangeCallback();
  2741. return this;
  2742. }
  2743. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2744. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2745. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2746. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2747. this._w = w * ratioA + this._w * ratioB;
  2748. this._x = x * ratioA + this._x * ratioB;
  2749. this._y = y * ratioA + this._y * ratioB;
  2750. this._z = z * ratioA + this._z * ratioB;
  2751. this._onChangeCallback();
  2752. return this;
  2753. }
  2754. slerpQuaternions(qa, qb, t) {
  2755. return this.copy(qa).slerp(qb, t);
  2756. }
  2757. random() {
  2758. // Derived from http://planning.cs.uiuc.edu/node198.html
  2759. // Note, this source uses w, x, y, z ordering,
  2760. // so we swap the order below.
  2761. const u1 = Math.random();
  2762. const sqrt1u1 = Math.sqrt(1 - u1);
  2763. const sqrtu1 = Math.sqrt(u1);
  2764. const u2 = 2 * Math.PI * Math.random();
  2765. const u3 = 2 * Math.PI * Math.random();
  2766. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2767. }
  2768. equals(quaternion) {
  2769. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2770. }
  2771. fromArray(array, offset = 0) {
  2772. this._x = array[offset];
  2773. this._y = array[offset + 1];
  2774. this._z = array[offset + 2];
  2775. this._w = array[offset + 3];
  2776. this._onChangeCallback();
  2777. return this;
  2778. }
  2779. toArray(array = [], offset = 0) {
  2780. array[offset] = this._x;
  2781. array[offset + 1] = this._y;
  2782. array[offset + 2] = this._z;
  2783. array[offset + 3] = this._w;
  2784. return array;
  2785. }
  2786. fromBufferAttribute(attribute, index) {
  2787. this._x = attribute.getX(index);
  2788. this._y = attribute.getY(index);
  2789. this._z = attribute.getZ(index);
  2790. this._w = attribute.getW(index);
  2791. return this;
  2792. }
  2793. _onChange(callback) {
  2794. this._onChangeCallback = callback;
  2795. return this;
  2796. }
  2797. _onChangeCallback() {}
  2798. *[Symbol.iterator]() {
  2799. yield this._x;
  2800. yield this._y;
  2801. yield this._z;
  2802. yield this._w;
  2803. }
  2804. }
  2805. class Vector3 {
  2806. constructor(x = 0, y = 0, z = 0) {
  2807. Vector3.prototype.isVector3 = true;
  2808. this.x = x;
  2809. this.y = y;
  2810. this.z = z;
  2811. }
  2812. set(x, y, z) {
  2813. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2814. this.x = x;
  2815. this.y = y;
  2816. this.z = z;
  2817. return this;
  2818. }
  2819. setScalar(scalar) {
  2820. this.x = scalar;
  2821. this.y = scalar;
  2822. this.z = scalar;
  2823. return this;
  2824. }
  2825. setX(x) {
  2826. this.x = x;
  2827. return this;
  2828. }
  2829. setY(y) {
  2830. this.y = y;
  2831. return this;
  2832. }
  2833. setZ(z) {
  2834. this.z = z;
  2835. return this;
  2836. }
  2837. setComponent(index, value) {
  2838. switch (index) {
  2839. case 0:
  2840. this.x = value;
  2841. break;
  2842. case 1:
  2843. this.y = value;
  2844. break;
  2845. case 2:
  2846. this.z = value;
  2847. break;
  2848. default:
  2849. throw new Error('index is out of range: ' + index);
  2850. }
  2851. return this;
  2852. }
  2853. getComponent(index) {
  2854. switch (index) {
  2855. case 0:
  2856. return this.x;
  2857. case 1:
  2858. return this.y;
  2859. case 2:
  2860. return this.z;
  2861. default:
  2862. throw new Error('index is out of range: ' + index);
  2863. }
  2864. }
  2865. clone() {
  2866. return new this.constructor(this.x, this.y, this.z);
  2867. }
  2868. copy(v) {
  2869. this.x = v.x;
  2870. this.y = v.y;
  2871. this.z = v.z;
  2872. return this;
  2873. }
  2874. add(v) {
  2875. this.x += v.x;
  2876. this.y += v.y;
  2877. this.z += v.z;
  2878. return this;
  2879. }
  2880. addScalar(s) {
  2881. this.x += s;
  2882. this.y += s;
  2883. this.z += s;
  2884. return this;
  2885. }
  2886. addVectors(a, b) {
  2887. this.x = a.x + b.x;
  2888. this.y = a.y + b.y;
  2889. this.z = a.z + b.z;
  2890. return this;
  2891. }
  2892. addScaledVector(v, s) {
  2893. this.x += v.x * s;
  2894. this.y += v.y * s;
  2895. this.z += v.z * s;
  2896. return this;
  2897. }
  2898. sub(v) {
  2899. this.x -= v.x;
  2900. this.y -= v.y;
  2901. this.z -= v.z;
  2902. return this;
  2903. }
  2904. subScalar(s) {
  2905. this.x -= s;
  2906. this.y -= s;
  2907. this.z -= s;
  2908. return this;
  2909. }
  2910. subVectors(a, b) {
  2911. this.x = a.x - b.x;
  2912. this.y = a.y - b.y;
  2913. this.z = a.z - b.z;
  2914. return this;
  2915. }
  2916. multiply(v) {
  2917. this.x *= v.x;
  2918. this.y *= v.y;
  2919. this.z *= v.z;
  2920. return this;
  2921. }
  2922. multiplyScalar(scalar) {
  2923. this.x *= scalar;
  2924. this.y *= scalar;
  2925. this.z *= scalar;
  2926. return this;
  2927. }
  2928. multiplyVectors(a, b) {
  2929. this.x = a.x * b.x;
  2930. this.y = a.y * b.y;
  2931. this.z = a.z * b.z;
  2932. return this;
  2933. }
  2934. applyEuler(euler) {
  2935. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2936. }
  2937. applyAxisAngle(axis, angle) {
  2938. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2939. }
  2940. applyMatrix3(m) {
  2941. const x = this.x,
  2942. y = this.y,
  2943. z = this.z;
  2944. const e = m.elements;
  2945. this.x = e[0] * x + e[3] * y + e[6] * z;
  2946. this.y = e[1] * x + e[4] * y + e[7] * z;
  2947. this.z = e[2] * x + e[5] * y + e[8] * z;
  2948. return this;
  2949. }
  2950. applyNormalMatrix(m) {
  2951. return this.applyMatrix3(m).normalize();
  2952. }
  2953. applyMatrix4(m) {
  2954. const x = this.x,
  2955. y = this.y,
  2956. z = this.z;
  2957. const e = m.elements;
  2958. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2959. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2960. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2961. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2962. return this;
  2963. }
  2964. applyQuaternion(q) {
  2965. const x = this.x,
  2966. y = this.y,
  2967. z = this.z;
  2968. const qx = q.x,
  2969. qy = q.y,
  2970. qz = q.z,
  2971. qw = q.w; // calculate quat * vector
  2972. const ix = qw * x + qy * z - qz * y;
  2973. const iy = qw * y + qz * x - qx * z;
  2974. const iz = qw * z + qx * y - qy * x;
  2975. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2976. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2977. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2978. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2979. return this;
  2980. }
  2981. project(camera) {
  2982. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2983. }
  2984. unproject(camera) {
  2985. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2986. }
  2987. transformDirection(m) {
  2988. // input: THREE.Matrix4 affine matrix
  2989. // vector interpreted as a direction
  2990. const x = this.x,
  2991. y = this.y,
  2992. z = this.z;
  2993. const e = m.elements;
  2994. this.x = e[0] * x + e[4] * y + e[8] * z;
  2995. this.y = e[1] * x + e[5] * y + e[9] * z;
  2996. this.z = e[2] * x + e[6] * y + e[10] * z;
  2997. return this.normalize();
  2998. }
  2999. divide(v) {
  3000. this.x /= v.x;
  3001. this.y /= v.y;
  3002. this.z /= v.z;
  3003. return this;
  3004. }
  3005. divideScalar(scalar) {
  3006. return this.multiplyScalar(1 / scalar);
  3007. }
  3008. min(v) {
  3009. this.x = Math.min(this.x, v.x);
  3010. this.y = Math.min(this.y, v.y);
  3011. this.z = Math.min(this.z, v.z);
  3012. return this;
  3013. }
  3014. max(v) {
  3015. this.x = Math.max(this.x, v.x);
  3016. this.y = Math.max(this.y, v.y);
  3017. this.z = Math.max(this.z, v.z);
  3018. return this;
  3019. }
  3020. clamp(min, max) {
  3021. // assumes min < max, componentwise
  3022. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3023. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3024. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3025. return this;
  3026. }
  3027. clampScalar(minVal, maxVal) {
  3028. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3029. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3030. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3031. return this;
  3032. }
  3033. clampLength(min, max) {
  3034. const length = this.length();
  3035. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3036. }
  3037. floor() {
  3038. this.x = Math.floor(this.x);
  3039. this.y = Math.floor(this.y);
  3040. this.z = Math.floor(this.z);
  3041. return this;
  3042. }
  3043. ceil() {
  3044. this.x = Math.ceil(this.x);
  3045. this.y = Math.ceil(this.y);
  3046. this.z = Math.ceil(this.z);
  3047. return this;
  3048. }
  3049. round() {
  3050. this.x = Math.round(this.x);
  3051. this.y = Math.round(this.y);
  3052. this.z = Math.round(this.z);
  3053. return this;
  3054. }
  3055. roundToZero() {
  3056. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3057. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3058. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3059. return this;
  3060. }
  3061. negate() {
  3062. this.x = -this.x;
  3063. this.y = -this.y;
  3064. this.z = -this.z;
  3065. return this;
  3066. }
  3067. dot(v) {
  3068. return this.x * v.x + this.y * v.y + this.z * v.z;
  3069. } // TODO lengthSquared?
  3070. lengthSq() {
  3071. return this.x * this.x + this.y * this.y + this.z * this.z;
  3072. }
  3073. length() {
  3074. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3075. }
  3076. manhattanLength() {
  3077. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  3078. }
  3079. normalize() {
  3080. return this.divideScalar(this.length() || 1);
  3081. }
  3082. setLength(length) {
  3083. return this.normalize().multiplyScalar(length);
  3084. }
  3085. lerp(v, alpha) {
  3086. this.x += (v.x - this.x) * alpha;
  3087. this.y += (v.y - this.y) * alpha;
  3088. this.z += (v.z - this.z) * alpha;
  3089. return this;
  3090. }
  3091. lerpVectors(v1, v2, alpha) {
  3092. this.x = v1.x + (v2.x - v1.x) * alpha;
  3093. this.y = v1.y + (v2.y - v1.y) * alpha;
  3094. this.z = v1.z + (v2.z - v1.z) * alpha;
  3095. return this;
  3096. }
  3097. cross(v) {
  3098. return this.crossVectors(this, v);
  3099. }
  3100. crossVectors(a, b) {
  3101. const ax = a.x,
  3102. ay = a.y,
  3103. az = a.z;
  3104. const bx = b.x,
  3105. by = b.y,
  3106. bz = b.z;
  3107. this.x = ay * bz - az * by;
  3108. this.y = az * bx - ax * bz;
  3109. this.z = ax * by - ay * bx;
  3110. return this;
  3111. }
  3112. projectOnVector(v) {
  3113. const denominator = v.lengthSq();
  3114. if (denominator === 0) return this.set(0, 0, 0);
  3115. const scalar = v.dot(this) / denominator;
  3116. return this.copy(v).multiplyScalar(scalar);
  3117. }
  3118. projectOnPlane(planeNormal) {
  3119. _vector$c.copy(this).projectOnVector(planeNormal);
  3120. return this.sub(_vector$c);
  3121. }
  3122. reflect(normal) {
  3123. // reflect incident vector off plane orthogonal to normal
  3124. // normal is assumed to have unit length
  3125. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  3126. }
  3127. angleTo(v) {
  3128. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  3129. if (denominator === 0) return Math.PI / 2;
  3130. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  3131. return Math.acos(clamp(theta, -1, 1));
  3132. }
  3133. distanceTo(v) {
  3134. return Math.sqrt(this.distanceToSquared(v));
  3135. }
  3136. distanceToSquared(v) {
  3137. const dx = this.x - v.x,
  3138. dy = this.y - v.y,
  3139. dz = this.z - v.z;
  3140. return dx * dx + dy * dy + dz * dz;
  3141. }
  3142. manhattanDistanceTo(v) {
  3143. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  3144. }
  3145. setFromSpherical(s) {
  3146. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3147. }
  3148. setFromSphericalCoords(radius, phi, theta) {
  3149. const sinPhiRadius = Math.sin(phi) * radius;
  3150. this.x = sinPhiRadius * Math.sin(theta);
  3151. this.y = Math.cos(phi) * radius;
  3152. this.z = sinPhiRadius * Math.cos(theta);
  3153. return this;
  3154. }
  3155. setFromCylindrical(c) {
  3156. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3157. }
  3158. setFromCylindricalCoords(radius, theta, y) {
  3159. this.x = radius * Math.sin(theta);
  3160. this.y = y;
  3161. this.z = radius * Math.cos(theta);
  3162. return this;
  3163. }
  3164. setFromMatrixPosition(m) {
  3165. const e = m.elements;
  3166. this.x = e[12];
  3167. this.y = e[13];
  3168. this.z = e[14];
  3169. return this;
  3170. }
  3171. setFromMatrixScale(m) {
  3172. const sx = this.setFromMatrixColumn(m, 0).length();
  3173. const sy = this.setFromMatrixColumn(m, 1).length();
  3174. const sz = this.setFromMatrixColumn(m, 2).length();
  3175. this.x = sx;
  3176. this.y = sy;
  3177. this.z = sz;
  3178. return this;
  3179. }
  3180. setFromMatrixColumn(m, index) {
  3181. return this.fromArray(m.elements, index * 4);
  3182. }
  3183. setFromMatrix3Column(m, index) {
  3184. return this.fromArray(m.elements, index * 3);
  3185. }
  3186. setFromEuler(e) {
  3187. this.x = e._x;
  3188. this.y = e._y;
  3189. this.z = e._z;
  3190. return this;
  3191. }
  3192. equals(v) {
  3193. return v.x === this.x && v.y === this.y && v.z === this.z;
  3194. }
  3195. fromArray(array, offset = 0) {
  3196. this.x = array[offset];
  3197. this.y = array[offset + 1];
  3198. this.z = array[offset + 2];
  3199. return this;
  3200. }
  3201. toArray(array = [], offset = 0) {
  3202. array[offset] = this.x;
  3203. array[offset + 1] = this.y;
  3204. array[offset + 2] = this.z;
  3205. return array;
  3206. }
  3207. fromBufferAttribute(attribute, index) {
  3208. this.x = attribute.getX(index);
  3209. this.y = attribute.getY(index);
  3210. this.z = attribute.getZ(index);
  3211. return this;
  3212. }
  3213. random() {
  3214. this.x = Math.random();
  3215. this.y = Math.random();
  3216. this.z = Math.random();
  3217. return this;
  3218. }
  3219. randomDirection() {
  3220. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  3221. const u = (Math.random() - 0.5) * 2;
  3222. const t = Math.random() * Math.PI * 2;
  3223. const f = Math.sqrt(1 - u ** 2);
  3224. this.x = f * Math.cos(t);
  3225. this.y = f * Math.sin(t);
  3226. this.z = u;
  3227. return this;
  3228. }
  3229. *[Symbol.iterator]() {
  3230. yield this.x;
  3231. yield this.y;
  3232. yield this.z;
  3233. }
  3234. }
  3235. const _vector$c = /*@__PURE__*/new Vector3();
  3236. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  3237. class Box3 {
  3238. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  3239. this.isBox3 = true;
  3240. this.min = min;
  3241. this.max = max;
  3242. }
  3243. set(min, max) {
  3244. this.min.copy(min);
  3245. this.max.copy(max);
  3246. return this;
  3247. }
  3248. setFromArray(array) {
  3249. let minX = +Infinity;
  3250. let minY = +Infinity;
  3251. let minZ = +Infinity;
  3252. let maxX = -Infinity;
  3253. let maxY = -Infinity;
  3254. let maxZ = -Infinity;
  3255. for (let i = 0, l = array.length; i < l; i += 3) {
  3256. const x = array[i];
  3257. const y = array[i + 1];
  3258. const z = array[i + 2];
  3259. if (x < minX) minX = x;
  3260. if (y < minY) minY = y;
  3261. if (z < minZ) minZ = z;
  3262. if (x > maxX) maxX = x;
  3263. if (y > maxY) maxY = y;
  3264. if (z > maxZ) maxZ = z;
  3265. }
  3266. this.min.set(minX, minY, minZ);
  3267. this.max.set(maxX, maxY, maxZ);
  3268. return this;
  3269. }
  3270. setFromBufferAttribute(attribute) {
  3271. let minX = +Infinity;
  3272. let minY = +Infinity;
  3273. let minZ = +Infinity;
  3274. let maxX = -Infinity;
  3275. let maxY = -Infinity;
  3276. let maxZ = -Infinity;
  3277. for (let i = 0, l = attribute.count; i < l; i++) {
  3278. const x = attribute.getX(i);
  3279. const y = attribute.getY(i);
  3280. const z = attribute.getZ(i);
  3281. if (x < minX) minX = x;
  3282. if (y < minY) minY = y;
  3283. if (z < minZ) minZ = z;
  3284. if (x > maxX) maxX = x;
  3285. if (y > maxY) maxY = y;
  3286. if (z > maxZ) maxZ = z;
  3287. }
  3288. this.min.set(minX, minY, minZ);
  3289. this.max.set(maxX, maxY, maxZ);
  3290. return this;
  3291. }
  3292. setFromPoints(points) {
  3293. this.makeEmpty();
  3294. for (let i = 0, il = points.length; i < il; i++) {
  3295. this.expandByPoint(points[i]);
  3296. }
  3297. return this;
  3298. }
  3299. setFromCenterAndSize(center, size) {
  3300. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  3301. this.min.copy(center).sub(halfSize);
  3302. this.max.copy(center).add(halfSize);
  3303. return this;
  3304. }
  3305. setFromObject(object, precise = false) {
  3306. this.makeEmpty();
  3307. return this.expandByObject(object, precise);
  3308. }
  3309. clone() {
  3310. return new this.constructor().copy(this);
  3311. }
  3312. copy(box) {
  3313. this.min.copy(box.min);
  3314. this.max.copy(box.max);
  3315. return this;
  3316. }
  3317. makeEmpty() {
  3318. this.min.x = this.min.y = this.min.z = +Infinity;
  3319. this.max.x = this.max.y = this.max.z = -Infinity;
  3320. return this;
  3321. }
  3322. isEmpty() {
  3323. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3324. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3325. }
  3326. getCenter(target) {
  3327. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3328. }
  3329. getSize(target) {
  3330. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3331. }
  3332. expandByPoint(point) {
  3333. this.min.min(point);
  3334. this.max.max(point);
  3335. return this;
  3336. }
  3337. expandByVector(vector) {
  3338. this.min.sub(vector);
  3339. this.max.add(vector);
  3340. return this;
  3341. }
  3342. expandByScalar(scalar) {
  3343. this.min.addScalar(-scalar);
  3344. this.max.addScalar(scalar);
  3345. return this;
  3346. }
  3347. expandByObject(object, precise = false) {
  3348. // Computes the world-axis-aligned bounding box of an object (including its children),
  3349. // accounting for both the object's, and children's, world transforms
  3350. object.updateWorldMatrix(false, false);
  3351. const geometry = object.geometry;
  3352. if (geometry !== undefined) {
  3353. if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) {
  3354. const position = geometry.attributes.position;
  3355. for (let i = 0, l = position.count; i < l; i++) {
  3356. _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
  3357. this.expandByPoint(_vector$b);
  3358. }
  3359. } else {
  3360. if (geometry.boundingBox === null) {
  3361. geometry.computeBoundingBox();
  3362. }
  3363. _box$3.copy(geometry.boundingBox);
  3364. _box$3.applyMatrix4(object.matrixWorld);
  3365. this.union(_box$3);
  3366. }
  3367. }
  3368. const children = object.children;
  3369. for (let i = 0, l = children.length; i < l; i++) {
  3370. this.expandByObject(children[i], precise);
  3371. }
  3372. return this;
  3373. }
  3374. containsPoint(point) {
  3375. 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;
  3376. }
  3377. containsBox(box) {
  3378. 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;
  3379. }
  3380. getParameter(point, target) {
  3381. // This can potentially have a divide by zero if the box
  3382. // has a size dimension of 0.
  3383. 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));
  3384. }
  3385. intersectsBox(box) {
  3386. // using 6 splitting planes to rule out intersections.
  3387. 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;
  3388. }
  3389. intersectsSphere(sphere) {
  3390. // Find the point on the AABB closest to the sphere center.
  3391. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  3392. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3393. }
  3394. intersectsPlane(plane) {
  3395. // We compute the minimum and maximum dot product values. If those values
  3396. // are on the same side (back or front) of the plane, then there is no intersection.
  3397. let min, max;
  3398. if (plane.normal.x > 0) {
  3399. min = plane.normal.x * this.min.x;
  3400. max = plane.normal.x * this.max.x;
  3401. } else {
  3402. min = plane.normal.x * this.max.x;
  3403. max = plane.normal.x * this.min.x;
  3404. }
  3405. if (plane.normal.y > 0) {
  3406. min += plane.normal.y * this.min.y;
  3407. max += plane.normal.y * this.max.y;
  3408. } else {
  3409. min += plane.normal.y * this.max.y;
  3410. max += plane.normal.y * this.min.y;
  3411. }
  3412. if (plane.normal.z > 0) {
  3413. min += plane.normal.z * this.min.z;
  3414. max += plane.normal.z * this.max.z;
  3415. } else {
  3416. min += plane.normal.z * this.max.z;
  3417. max += plane.normal.z * this.min.z;
  3418. }
  3419. return min <= -plane.constant && max >= -plane.constant;
  3420. }
  3421. intersectsTriangle(triangle) {
  3422. if (this.isEmpty()) {
  3423. return false;
  3424. } // compute box center and extents
  3425. this.getCenter(_center);
  3426. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  3427. _v0$2.subVectors(triangle.a, _center);
  3428. _v1$7.subVectors(triangle.b, _center);
  3429. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  3430. _f0.subVectors(_v1$7, _v0$2);
  3431. _f1.subVectors(_v2$3, _v1$7);
  3432. _f2.subVectors(_v0$2, _v2$3); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3433. // 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
  3434. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3435. 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];
  3436. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  3437. return false;
  3438. } // test 3 face normals from the aabb
  3439. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3440. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  3441. return false;
  3442. } // finally testing the face normal of the triangle
  3443. // use already existing triangle edge vectors here
  3444. _triangleNormal.crossVectors(_f0, _f1);
  3445. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3446. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  3447. }
  3448. clampPoint(point, target) {
  3449. return target.copy(point).clamp(this.min, this.max);
  3450. }
  3451. distanceToPoint(point) {
  3452. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  3453. return clampedPoint.sub(point).length();
  3454. }
  3455. getBoundingSphere(target) {
  3456. this.getCenter(target.center);
  3457. target.radius = this.getSize(_vector$b).length() * 0.5;
  3458. return target;
  3459. }
  3460. intersect(box) {
  3461. this.min.max(box.min);
  3462. this.max.min(box.max); // 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.
  3463. if (this.isEmpty()) this.makeEmpty();
  3464. return this;
  3465. }
  3466. union(box) {
  3467. this.min.min(box.min);
  3468. this.max.max(box.max);
  3469. return this;
  3470. }
  3471. applyMatrix4(matrix) {
  3472. // transform of empty box is an empty box.
  3473. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3474. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3475. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3476. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3477. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3478. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3479. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3480. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3481. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3482. this.setFromPoints(_points);
  3483. return this;
  3484. }
  3485. translate(offset) {
  3486. this.min.add(offset);
  3487. this.max.add(offset);
  3488. return this;
  3489. }
  3490. equals(box) {
  3491. return box.min.equals(this.min) && box.max.equals(this.max);
  3492. }
  3493. }
  3494. 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()];
  3495. const _vector$b = /*@__PURE__*/new Vector3();
  3496. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  3497. const _v0$2 = /*@__PURE__*/new Vector3();
  3498. const _v1$7 = /*@__PURE__*/new Vector3();
  3499. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  3500. const _f0 = /*@__PURE__*/new Vector3();
  3501. const _f1 = /*@__PURE__*/new Vector3();
  3502. const _f2 = /*@__PURE__*/new Vector3();
  3503. const _center = /*@__PURE__*/new Vector3();
  3504. const _extents = /*@__PURE__*/new Vector3();
  3505. const _triangleNormal = /*@__PURE__*/new Vector3();
  3506. const _testAxis = /*@__PURE__*/new Vector3();
  3507. function satForAxes(axes, v0, v1, v2, extents) {
  3508. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3509. _testAxis.fromArray(axes, i); // project the aabb onto the separating axis
  3510. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the separating axis
  3511. const p0 = v0.dot(_testAxis);
  3512. const p1 = v1.dot(_testAxis);
  3513. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  3514. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3515. // points of the projected triangle are outside the projected half-length of the aabb
  3516. // the axis is separating and we can exit
  3517. return false;
  3518. }
  3519. }
  3520. return true;
  3521. }
  3522. const _box$2 = /*@__PURE__*/new Box3();
  3523. const _v1$6 = /*@__PURE__*/new Vector3();
  3524. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  3525. const _toPoint = /*@__PURE__*/new Vector3();
  3526. class Sphere {
  3527. constructor(center = new Vector3(), radius = -1) {
  3528. this.center = center;
  3529. this.radius = radius;
  3530. }
  3531. set(center, radius) {
  3532. this.center.copy(center);
  3533. this.radius = radius;
  3534. return this;
  3535. }
  3536. setFromPoints(points, optionalCenter) {
  3537. const center = this.center;
  3538. if (optionalCenter !== undefined) {
  3539. center.copy(optionalCenter);
  3540. } else {
  3541. _box$2.setFromPoints(points).getCenter(center);
  3542. }
  3543. let maxRadiusSq = 0;
  3544. for (let i = 0, il = points.length; i < il; i++) {
  3545. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3546. }
  3547. this.radius = Math.sqrt(maxRadiusSq);
  3548. return this;
  3549. }
  3550. copy(sphere) {
  3551. this.center.copy(sphere.center);
  3552. this.radius = sphere.radius;
  3553. return this;
  3554. }
  3555. isEmpty() {
  3556. return this.radius < 0;
  3557. }
  3558. makeEmpty() {
  3559. this.center.set(0, 0, 0);
  3560. this.radius = -1;
  3561. return this;
  3562. }
  3563. containsPoint(point) {
  3564. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3565. }
  3566. distanceToPoint(point) {
  3567. return point.distanceTo(this.center) - this.radius;
  3568. }
  3569. intersectsSphere(sphere) {
  3570. const radiusSum = this.radius + sphere.radius;
  3571. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3572. }
  3573. intersectsBox(box) {
  3574. return box.intersectsSphere(this);
  3575. }
  3576. intersectsPlane(plane) {
  3577. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3578. }
  3579. clampPoint(point, target) {
  3580. const deltaLengthSq = this.center.distanceToSquared(point);
  3581. target.copy(point);
  3582. if (deltaLengthSq > this.radius * this.radius) {
  3583. target.sub(this.center).normalize();
  3584. target.multiplyScalar(this.radius).add(this.center);
  3585. }
  3586. return target;
  3587. }
  3588. getBoundingBox(target) {
  3589. if (this.isEmpty()) {
  3590. // Empty sphere produces empty bounding box
  3591. target.makeEmpty();
  3592. return target;
  3593. }
  3594. target.set(this.center, this.center);
  3595. target.expandByScalar(this.radius);
  3596. return target;
  3597. }
  3598. applyMatrix4(matrix) {
  3599. this.center.applyMatrix4(matrix);
  3600. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3601. return this;
  3602. }
  3603. translate(offset) {
  3604. this.center.add(offset);
  3605. return this;
  3606. }
  3607. expandByPoint(point) {
  3608. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3609. _toPoint.subVectors(point, this.center);
  3610. const lengthSq = _toPoint.lengthSq();
  3611. if (lengthSq > this.radius * this.radius) {
  3612. const length = Math.sqrt(lengthSq);
  3613. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3614. // and the other half to position. This gives a tighter enclosure, instead of if
  3615. // the whole missing distance were just added to radius.
  3616. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  3617. this.radius += missingRadiusHalf;
  3618. }
  3619. return this;
  3620. }
  3621. union(sphere) {
  3622. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3623. // To enclose another sphere into this sphere, we only need to enclose two points:
  3624. // 1) Enclose the farthest point on the other sphere into this sphere.
  3625. // 2) Enclose the opposite point of the farthest point into this sphere.
  3626. if (this.center.equals(sphere.center) === true) {
  3627. _toFarthestPoint.set(0, 0, 1).multiplyScalar(sphere.radius);
  3628. } else {
  3629. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  3630. }
  3631. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  3632. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  3633. return this;
  3634. }
  3635. equals(sphere) {
  3636. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3637. }
  3638. clone() {
  3639. return new this.constructor().copy(this);
  3640. }
  3641. }
  3642. const _vector$a = /*@__PURE__*/new Vector3();
  3643. const _segCenter = /*@__PURE__*/new Vector3();
  3644. const _segDir = /*@__PURE__*/new Vector3();
  3645. const _diff = /*@__PURE__*/new Vector3();
  3646. const _edge1 = /*@__PURE__*/new Vector3();
  3647. const _edge2 = /*@__PURE__*/new Vector3();
  3648. const _normal$1 = /*@__PURE__*/new Vector3();
  3649. class Ray {
  3650. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3651. this.origin = origin;
  3652. this.direction = direction;
  3653. }
  3654. set(origin, direction) {
  3655. this.origin.copy(origin);
  3656. this.direction.copy(direction);
  3657. return this;
  3658. }
  3659. copy(ray) {
  3660. this.origin.copy(ray.origin);
  3661. this.direction.copy(ray.direction);
  3662. return this;
  3663. }
  3664. at(t, target) {
  3665. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3666. }
  3667. lookAt(v) {
  3668. this.direction.copy(v).sub(this.origin).normalize();
  3669. return this;
  3670. }
  3671. recast(t) {
  3672. this.origin.copy(this.at(t, _vector$a));
  3673. return this;
  3674. }
  3675. closestPointToPoint(point, target) {
  3676. target.subVectors(point, this.origin);
  3677. const directionDistance = target.dot(this.direction);
  3678. if (directionDistance < 0) {
  3679. return target.copy(this.origin);
  3680. }
  3681. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3682. }
  3683. distanceToPoint(point) {
  3684. return Math.sqrt(this.distanceSqToPoint(point));
  3685. }
  3686. distanceSqToPoint(point) {
  3687. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3688. if (directionDistance < 0) {
  3689. return this.origin.distanceToSquared(point);
  3690. }
  3691. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3692. return _vector$a.distanceToSquared(point);
  3693. }
  3694. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3695. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3696. // It returns the min distance between the ray and the segment
  3697. // defined by v0 and v1
  3698. // It can also set two optional targets :
  3699. // - The closest point on the ray
  3700. // - The closest point on the segment
  3701. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3702. _segDir.copy(v1).sub(v0).normalize();
  3703. _diff.copy(this.origin).sub(_segCenter);
  3704. const segExtent = v0.distanceTo(v1) * 0.5;
  3705. const a01 = -this.direction.dot(_segDir);
  3706. const b0 = _diff.dot(this.direction);
  3707. const b1 = -_diff.dot(_segDir);
  3708. const c = _diff.lengthSq();
  3709. const det = Math.abs(1 - a01 * a01);
  3710. let s0, s1, sqrDist, extDet;
  3711. if (det > 0) {
  3712. // The ray and segment are not parallel.
  3713. s0 = a01 * b1 - b0;
  3714. s1 = a01 * b0 - b1;
  3715. extDet = segExtent * det;
  3716. if (s0 >= 0) {
  3717. if (s1 >= -extDet) {
  3718. if (s1 <= extDet) {
  3719. // region 0
  3720. // Minimum at interior points of ray and segment.
  3721. const invDet = 1 / det;
  3722. s0 *= invDet;
  3723. s1 *= invDet;
  3724. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3725. } else {
  3726. // region 1
  3727. s1 = segExtent;
  3728. s0 = Math.max(0, -(a01 * s1 + b0));
  3729. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3730. }
  3731. } else {
  3732. // region 5
  3733. s1 = -segExtent;
  3734. s0 = Math.max(0, -(a01 * s1 + b0));
  3735. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3736. }
  3737. } else {
  3738. if (s1 <= -extDet) {
  3739. // region 4
  3740. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3741. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3742. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3743. } else if (s1 <= extDet) {
  3744. // region 3
  3745. s0 = 0;
  3746. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3747. sqrDist = s1 * (s1 + 2 * b1) + c;
  3748. } else {
  3749. // region 2
  3750. s0 = Math.max(0, -(a01 * segExtent + b0));
  3751. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3752. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3753. }
  3754. }
  3755. } else {
  3756. // Ray and segment are parallel.
  3757. s1 = a01 > 0 ? -segExtent : segExtent;
  3758. s0 = Math.max(0, -(a01 * s1 + b0));
  3759. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3760. }
  3761. if (optionalPointOnRay) {
  3762. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3763. }
  3764. if (optionalPointOnSegment) {
  3765. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3766. }
  3767. return sqrDist;
  3768. }
  3769. intersectSphere(sphere, target) {
  3770. _vector$a.subVectors(sphere.center, this.origin);
  3771. const tca = _vector$a.dot(this.direction);
  3772. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3773. const radius2 = sphere.radius * sphere.radius;
  3774. if (d2 > radius2) return null;
  3775. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3776. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3777. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3778. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3779. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3780. // in order to always return an intersect point that is in front of the ray.
  3781. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  3782. return this.at(t0, target);
  3783. }
  3784. intersectsSphere(sphere) {
  3785. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3786. }
  3787. distanceToPlane(plane) {
  3788. const denominator = plane.normal.dot(this.direction);
  3789. if (denominator === 0) {
  3790. // line is coplanar, return origin
  3791. if (plane.distanceToPoint(this.origin) === 0) {
  3792. return 0;
  3793. } // Null is preferable to undefined since undefined means.... it is undefined
  3794. return null;
  3795. }
  3796. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3797. return t >= 0 ? t : null;
  3798. }
  3799. intersectPlane(plane, target) {
  3800. const t = this.distanceToPlane(plane);
  3801. if (t === null) {
  3802. return null;
  3803. }
  3804. return this.at(t, target);
  3805. }
  3806. intersectsPlane(plane) {
  3807. // check if the ray lies on the plane first
  3808. const distToPoint = plane.distanceToPoint(this.origin);
  3809. if (distToPoint === 0) {
  3810. return true;
  3811. }
  3812. const denominator = plane.normal.dot(this.direction);
  3813. if (denominator * distToPoint < 0) {
  3814. return true;
  3815. } // ray origin is behind the plane (and is pointing behind it)
  3816. return false;
  3817. }
  3818. intersectBox(box, target) {
  3819. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3820. const invdirx = 1 / this.direction.x,
  3821. invdiry = 1 / this.direction.y,
  3822. invdirz = 1 / this.direction.z;
  3823. const origin = this.origin;
  3824. if (invdirx >= 0) {
  3825. tmin = (box.min.x - origin.x) * invdirx;
  3826. tmax = (box.max.x - origin.x) * invdirx;
  3827. } else {
  3828. tmin = (box.max.x - origin.x) * invdirx;
  3829. tmax = (box.min.x - origin.x) * invdirx;
  3830. }
  3831. if (invdiry >= 0) {
  3832. tymin = (box.min.y - origin.y) * invdiry;
  3833. tymax = (box.max.y - origin.y) * invdiry;
  3834. } else {
  3835. tymin = (box.max.y - origin.y) * invdiry;
  3836. tymax = (box.min.y - origin.y) * invdiry;
  3837. }
  3838. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3839. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3840. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3841. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3842. if (invdirz >= 0) {
  3843. tzmin = (box.min.z - origin.z) * invdirz;
  3844. tzmax = (box.max.z - origin.z) * invdirz;
  3845. } else {
  3846. tzmin = (box.max.z - origin.z) * invdirz;
  3847. tzmax = (box.min.z - origin.z) * invdirz;
  3848. }
  3849. if (tmin > tzmax || tzmin > tmax) return null;
  3850. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3851. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3852. if (tmax < 0) return null;
  3853. return this.at(tmin >= 0 ? tmin : tmax, target);
  3854. }
  3855. intersectsBox(box) {
  3856. return this.intersectBox(box, _vector$a) !== null;
  3857. }
  3858. intersectTriangle(a, b, c, backfaceCulling, target) {
  3859. // Compute the offset origin, edges, and normal.
  3860. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3861. _edge1.subVectors(b, a);
  3862. _edge2.subVectors(c, a);
  3863. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3864. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3865. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3866. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3867. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3868. let DdN = this.direction.dot(_normal$1);
  3869. let sign;
  3870. if (DdN > 0) {
  3871. if (backfaceCulling) return null;
  3872. sign = 1;
  3873. } else if (DdN < 0) {
  3874. sign = -1;
  3875. DdN = -DdN;
  3876. } else {
  3877. return null;
  3878. }
  3879. _diff.subVectors(this.origin, a);
  3880. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3881. if (DdQxE2 < 0) {
  3882. return null;
  3883. }
  3884. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3885. if (DdE1xQ < 0) {
  3886. return null;
  3887. } // b1+b2 > 1, no intersection
  3888. if (DdQxE2 + DdE1xQ > DdN) {
  3889. return null;
  3890. } // Line intersects triangle, check if ray does.
  3891. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3892. if (QdN < 0) {
  3893. return null;
  3894. } // Ray intersects triangle.
  3895. return this.at(QdN / DdN, target);
  3896. }
  3897. applyMatrix4(matrix4) {
  3898. this.origin.applyMatrix4(matrix4);
  3899. this.direction.transformDirection(matrix4);
  3900. return this;
  3901. }
  3902. equals(ray) {
  3903. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3904. }
  3905. clone() {
  3906. return new this.constructor().copy(this);
  3907. }
  3908. }
  3909. class Matrix4 {
  3910. constructor() {
  3911. Matrix4.prototype.isMatrix4 = true;
  3912. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3913. }
  3914. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3915. const te = this.elements;
  3916. te[0] = n11;
  3917. te[4] = n12;
  3918. te[8] = n13;
  3919. te[12] = n14;
  3920. te[1] = n21;
  3921. te[5] = n22;
  3922. te[9] = n23;
  3923. te[13] = n24;
  3924. te[2] = n31;
  3925. te[6] = n32;
  3926. te[10] = n33;
  3927. te[14] = n34;
  3928. te[3] = n41;
  3929. te[7] = n42;
  3930. te[11] = n43;
  3931. te[15] = n44;
  3932. return this;
  3933. }
  3934. identity() {
  3935. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3936. return this;
  3937. }
  3938. clone() {
  3939. return new Matrix4().fromArray(this.elements);
  3940. }
  3941. copy(m) {
  3942. const te = this.elements;
  3943. const me = m.elements;
  3944. te[0] = me[0];
  3945. te[1] = me[1];
  3946. te[2] = me[2];
  3947. te[3] = me[3];
  3948. te[4] = me[4];
  3949. te[5] = me[5];
  3950. te[6] = me[6];
  3951. te[7] = me[7];
  3952. te[8] = me[8];
  3953. te[9] = me[9];
  3954. te[10] = me[10];
  3955. te[11] = me[11];
  3956. te[12] = me[12];
  3957. te[13] = me[13];
  3958. te[14] = me[14];
  3959. te[15] = me[15];
  3960. return this;
  3961. }
  3962. copyPosition(m) {
  3963. const te = this.elements,
  3964. me = m.elements;
  3965. te[12] = me[12];
  3966. te[13] = me[13];
  3967. te[14] = me[14];
  3968. return this;
  3969. }
  3970. setFromMatrix3(m) {
  3971. const me = m.elements;
  3972. 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);
  3973. return this;
  3974. }
  3975. extractBasis(xAxis, yAxis, zAxis) {
  3976. xAxis.setFromMatrixColumn(this, 0);
  3977. yAxis.setFromMatrixColumn(this, 1);
  3978. zAxis.setFromMatrixColumn(this, 2);
  3979. return this;
  3980. }
  3981. makeBasis(xAxis, yAxis, zAxis) {
  3982. 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);
  3983. return this;
  3984. }
  3985. extractRotation(m) {
  3986. // this method does not support reflection matrices
  3987. const te = this.elements;
  3988. const me = m.elements;
  3989. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3990. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3991. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3992. te[0] = me[0] * scaleX;
  3993. te[1] = me[1] * scaleX;
  3994. te[2] = me[2] * scaleX;
  3995. te[3] = 0;
  3996. te[4] = me[4] * scaleY;
  3997. te[5] = me[5] * scaleY;
  3998. te[6] = me[6] * scaleY;
  3999. te[7] = 0;
  4000. te[8] = me[8] * scaleZ;
  4001. te[9] = me[9] * scaleZ;
  4002. te[10] = me[10] * scaleZ;
  4003. te[11] = 0;
  4004. te[12] = 0;
  4005. te[13] = 0;
  4006. te[14] = 0;
  4007. te[15] = 1;
  4008. return this;
  4009. }
  4010. makeRotationFromEuler(euler) {
  4011. const te = this.elements;
  4012. const x = euler.x,
  4013. y = euler.y,
  4014. z = euler.z;
  4015. const a = Math.cos(x),
  4016. b = Math.sin(x);
  4017. const c = Math.cos(y),
  4018. d = Math.sin(y);
  4019. const e = Math.cos(z),
  4020. f = Math.sin(z);
  4021. if (euler.order === 'XYZ') {
  4022. const ae = a * e,
  4023. af = a * f,
  4024. be = b * e,
  4025. bf = b * f;
  4026. te[0] = c * e;
  4027. te[4] = -c * f;
  4028. te[8] = d;
  4029. te[1] = af + be * d;
  4030. te[5] = ae - bf * d;
  4031. te[9] = -b * c;
  4032. te[2] = bf - ae * d;
  4033. te[6] = be + af * d;
  4034. te[10] = a * c;
  4035. } else if (euler.order === 'YXZ') {
  4036. const ce = c * e,
  4037. cf = c * f,
  4038. de = d * e,
  4039. df = d * f;
  4040. te[0] = ce + df * b;
  4041. te[4] = de * b - cf;
  4042. te[8] = a * d;
  4043. te[1] = a * f;
  4044. te[5] = a * e;
  4045. te[9] = -b;
  4046. te[2] = cf * b - de;
  4047. te[6] = df + ce * b;
  4048. te[10] = a * c;
  4049. } else if (euler.order === 'ZXY') {
  4050. const ce = c * e,
  4051. cf = c * f,
  4052. de = d * e,
  4053. df = d * f;
  4054. te[0] = ce - df * b;
  4055. te[4] = -a * f;
  4056. te[8] = de + cf * b;
  4057. te[1] = cf + de * b;
  4058. te[5] = a * e;
  4059. te[9] = df - ce * b;
  4060. te[2] = -a * d;
  4061. te[6] = b;
  4062. te[10] = a * c;
  4063. } else if (euler.order === 'ZYX') {
  4064. const ae = a * e,
  4065. af = a * f,
  4066. be = b * e,
  4067. bf = b * f;
  4068. te[0] = c * e;
  4069. te[4] = be * d - af;
  4070. te[8] = ae * d + bf;
  4071. te[1] = c * f;
  4072. te[5] = bf * d + ae;
  4073. te[9] = af * d - be;
  4074. te[2] = -d;
  4075. te[6] = b * c;
  4076. te[10] = a * c;
  4077. } else if (euler.order === 'YZX') {
  4078. const ac = a * c,
  4079. ad = a * d,
  4080. bc = b * c,
  4081. bd = b * d;
  4082. te[0] = c * e;
  4083. te[4] = bd - ac * f;
  4084. te[8] = bc * f + ad;
  4085. te[1] = f;
  4086. te[5] = a * e;
  4087. te[9] = -b * e;
  4088. te[2] = -d * e;
  4089. te[6] = ad * f + bc;
  4090. te[10] = ac - bd * f;
  4091. } else if (euler.order === 'XZY') {
  4092. const ac = a * c,
  4093. ad = a * d,
  4094. bc = b * c,
  4095. bd = b * d;
  4096. te[0] = c * e;
  4097. te[4] = -f;
  4098. te[8] = d * e;
  4099. te[1] = ac * f + bd;
  4100. te[5] = a * e;
  4101. te[9] = ad * f - bc;
  4102. te[2] = bc * f - ad;
  4103. te[6] = b * e;
  4104. te[10] = bd * f + ac;
  4105. } // bottom row
  4106. te[3] = 0;
  4107. te[7] = 0;
  4108. te[11] = 0; // last column
  4109. te[12] = 0;
  4110. te[13] = 0;
  4111. te[14] = 0;
  4112. te[15] = 1;
  4113. return this;
  4114. }
  4115. makeRotationFromQuaternion(q) {
  4116. return this.compose(_zero, q, _one);
  4117. }
  4118. lookAt(eye, target, up) {
  4119. const te = this.elements;
  4120. _z.subVectors(eye, target);
  4121. if (_z.lengthSq() === 0) {
  4122. // eye and target are in the same position
  4123. _z.z = 1;
  4124. }
  4125. _z.normalize();
  4126. _x.crossVectors(up, _z);
  4127. if (_x.lengthSq() === 0) {
  4128. // up and z are parallel
  4129. if (Math.abs(up.z) === 1) {
  4130. _z.x += 0.0001;
  4131. } else {
  4132. _z.z += 0.0001;
  4133. }
  4134. _z.normalize();
  4135. _x.crossVectors(up, _z);
  4136. }
  4137. _x.normalize();
  4138. _y.crossVectors(_z, _x);
  4139. te[0] = _x.x;
  4140. te[4] = _y.x;
  4141. te[8] = _z.x;
  4142. te[1] = _x.y;
  4143. te[5] = _y.y;
  4144. te[9] = _z.y;
  4145. te[2] = _x.z;
  4146. te[6] = _y.z;
  4147. te[10] = _z.z;
  4148. return this;
  4149. }
  4150. multiply(m) {
  4151. return this.multiplyMatrices(this, m);
  4152. }
  4153. premultiply(m) {
  4154. return this.multiplyMatrices(m, this);
  4155. }
  4156. multiplyMatrices(a, b) {
  4157. const ae = a.elements;
  4158. const be = b.elements;
  4159. const te = this.elements;
  4160. const a11 = ae[0],
  4161. a12 = ae[4],
  4162. a13 = ae[8],
  4163. a14 = ae[12];
  4164. const a21 = ae[1],
  4165. a22 = ae[5],
  4166. a23 = ae[9],
  4167. a24 = ae[13];
  4168. const a31 = ae[2],
  4169. a32 = ae[6],
  4170. a33 = ae[10],
  4171. a34 = ae[14];
  4172. const a41 = ae[3],
  4173. a42 = ae[7],
  4174. a43 = ae[11],
  4175. a44 = ae[15];
  4176. const b11 = be[0],
  4177. b12 = be[4],
  4178. b13 = be[8],
  4179. b14 = be[12];
  4180. const b21 = be[1],
  4181. b22 = be[5],
  4182. b23 = be[9],
  4183. b24 = be[13];
  4184. const b31 = be[2],
  4185. b32 = be[6],
  4186. b33 = be[10],
  4187. b34 = be[14];
  4188. const b41 = be[3],
  4189. b42 = be[7],
  4190. b43 = be[11],
  4191. b44 = be[15];
  4192. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4193. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4194. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4195. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4196. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4197. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4198. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4199. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4200. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4201. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4202. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4203. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4204. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4205. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4206. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4207. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4208. return this;
  4209. }
  4210. multiplyScalar(s) {
  4211. const te = this.elements;
  4212. te[0] *= s;
  4213. te[4] *= s;
  4214. te[8] *= s;
  4215. te[12] *= s;
  4216. te[1] *= s;
  4217. te[5] *= s;
  4218. te[9] *= s;
  4219. te[13] *= s;
  4220. te[2] *= s;
  4221. te[6] *= s;
  4222. te[10] *= s;
  4223. te[14] *= s;
  4224. te[3] *= s;
  4225. te[7] *= s;
  4226. te[11] *= s;
  4227. te[15] *= s;
  4228. return this;
  4229. }
  4230. determinant() {
  4231. const te = this.elements;
  4232. const n11 = te[0],
  4233. n12 = te[4],
  4234. n13 = te[8],
  4235. n14 = te[12];
  4236. const n21 = te[1],
  4237. n22 = te[5],
  4238. n23 = te[9],
  4239. n24 = te[13];
  4240. const n31 = te[2],
  4241. n32 = te[6],
  4242. n33 = te[10],
  4243. n34 = te[14];
  4244. const n41 = te[3],
  4245. n42 = te[7],
  4246. n43 = te[11],
  4247. n44 = te[15]; //TODO: make this more efficient
  4248. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4249. 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);
  4250. }
  4251. transpose() {
  4252. const te = this.elements;
  4253. let tmp;
  4254. tmp = te[1];
  4255. te[1] = te[4];
  4256. te[4] = tmp;
  4257. tmp = te[2];
  4258. te[2] = te[8];
  4259. te[8] = tmp;
  4260. tmp = te[6];
  4261. te[6] = te[9];
  4262. te[9] = tmp;
  4263. tmp = te[3];
  4264. te[3] = te[12];
  4265. te[12] = tmp;
  4266. tmp = te[7];
  4267. te[7] = te[13];
  4268. te[13] = tmp;
  4269. tmp = te[11];
  4270. te[11] = te[14];
  4271. te[14] = tmp;
  4272. return this;
  4273. }
  4274. setPosition(x, y, z) {
  4275. const te = this.elements;
  4276. if (x.isVector3) {
  4277. te[12] = x.x;
  4278. te[13] = x.y;
  4279. te[14] = x.z;
  4280. } else {
  4281. te[12] = x;
  4282. te[13] = y;
  4283. te[14] = z;
  4284. }
  4285. return this;
  4286. }
  4287. invert() {
  4288. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4289. const te = this.elements,
  4290. n11 = te[0],
  4291. n21 = te[1],
  4292. n31 = te[2],
  4293. n41 = te[3],
  4294. n12 = te[4],
  4295. n22 = te[5],
  4296. n32 = te[6],
  4297. n42 = te[7],
  4298. n13 = te[8],
  4299. n23 = te[9],
  4300. n33 = te[10],
  4301. n43 = te[11],
  4302. n14 = te[12],
  4303. n24 = te[13],
  4304. n34 = te[14],
  4305. n44 = te[15],
  4306. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4307. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4308. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4309. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4310. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4311. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4312. const detInv = 1 / det;
  4313. te[0] = t11 * detInv;
  4314. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4315. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4316. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4317. te[4] = t12 * detInv;
  4318. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4319. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4320. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4321. te[8] = t13 * detInv;
  4322. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4323. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4324. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4325. te[12] = t14 * detInv;
  4326. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4327. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4328. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4329. return this;
  4330. }
  4331. scale(v) {
  4332. const te = this.elements;
  4333. const x = v.x,
  4334. y = v.y,
  4335. z = v.z;
  4336. te[0] *= x;
  4337. te[4] *= y;
  4338. te[8] *= z;
  4339. te[1] *= x;
  4340. te[5] *= y;
  4341. te[9] *= z;
  4342. te[2] *= x;
  4343. te[6] *= y;
  4344. te[10] *= z;
  4345. te[3] *= x;
  4346. te[7] *= y;
  4347. te[11] *= z;
  4348. return this;
  4349. }
  4350. getMaxScaleOnAxis() {
  4351. const te = this.elements;
  4352. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4353. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4354. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4355. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4356. }
  4357. makeTranslation(x, y, z) {
  4358. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4359. return this;
  4360. }
  4361. makeRotationX(theta) {
  4362. const c = Math.cos(theta),
  4363. s = Math.sin(theta);
  4364. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4365. return this;
  4366. }
  4367. makeRotationY(theta) {
  4368. const c = Math.cos(theta),
  4369. s = Math.sin(theta);
  4370. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4371. return this;
  4372. }
  4373. makeRotationZ(theta) {
  4374. const c = Math.cos(theta),
  4375. s = Math.sin(theta);
  4376. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4377. return this;
  4378. }
  4379. makeRotationAxis(axis, angle) {
  4380. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4381. const c = Math.cos(angle);
  4382. const s = Math.sin(angle);
  4383. const t = 1 - c;
  4384. const x = axis.x,
  4385. y = axis.y,
  4386. z = axis.z;
  4387. const tx = t * x,
  4388. ty = t * y;
  4389. 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);
  4390. return this;
  4391. }
  4392. makeScale(x, y, z) {
  4393. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4394. return this;
  4395. }
  4396. makeShear(xy, xz, yx, yz, zx, zy) {
  4397. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  4398. return this;
  4399. }
  4400. compose(position, quaternion, scale) {
  4401. const te = this.elements;
  4402. const x = quaternion._x,
  4403. y = quaternion._y,
  4404. z = quaternion._z,
  4405. w = quaternion._w;
  4406. const x2 = x + x,
  4407. y2 = y + y,
  4408. z2 = z + z;
  4409. const xx = x * x2,
  4410. xy = x * y2,
  4411. xz = x * z2;
  4412. const yy = y * y2,
  4413. yz = y * z2,
  4414. zz = z * z2;
  4415. const wx = w * x2,
  4416. wy = w * y2,
  4417. wz = w * z2;
  4418. const sx = scale.x,
  4419. sy = scale.y,
  4420. sz = scale.z;
  4421. te[0] = (1 - (yy + zz)) * sx;
  4422. te[1] = (xy + wz) * sx;
  4423. te[2] = (xz - wy) * sx;
  4424. te[3] = 0;
  4425. te[4] = (xy - wz) * sy;
  4426. te[5] = (1 - (xx + zz)) * sy;
  4427. te[6] = (yz + wx) * sy;
  4428. te[7] = 0;
  4429. te[8] = (xz + wy) * sz;
  4430. te[9] = (yz - wx) * sz;
  4431. te[10] = (1 - (xx + yy)) * sz;
  4432. te[11] = 0;
  4433. te[12] = position.x;
  4434. te[13] = position.y;
  4435. te[14] = position.z;
  4436. te[15] = 1;
  4437. return this;
  4438. }
  4439. decompose(position, quaternion, scale) {
  4440. const te = this.elements;
  4441. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  4442. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  4443. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4444. const det = this.determinant();
  4445. if (det < 0) sx = -sx;
  4446. position.x = te[12];
  4447. position.y = te[13];
  4448. position.z = te[14]; // scale the rotation part
  4449. _m1$2.copy(this);
  4450. const invSX = 1 / sx;
  4451. const invSY = 1 / sy;
  4452. const invSZ = 1 / sz;
  4453. _m1$2.elements[0] *= invSX;
  4454. _m1$2.elements[1] *= invSX;
  4455. _m1$2.elements[2] *= invSX;
  4456. _m1$2.elements[4] *= invSY;
  4457. _m1$2.elements[5] *= invSY;
  4458. _m1$2.elements[6] *= invSY;
  4459. _m1$2.elements[8] *= invSZ;
  4460. _m1$2.elements[9] *= invSZ;
  4461. _m1$2.elements[10] *= invSZ;
  4462. quaternion.setFromRotationMatrix(_m1$2);
  4463. scale.x = sx;
  4464. scale.y = sy;
  4465. scale.z = sz;
  4466. return this;
  4467. }
  4468. makePerspective(left, right, top, bottom, near, far) {
  4469. const te = this.elements;
  4470. const x = 2 * near / (right - left);
  4471. const y = 2 * near / (top - bottom);
  4472. const a = (right + left) / (right - left);
  4473. const b = (top + bottom) / (top - bottom);
  4474. const c = -(far + near) / (far - near);
  4475. const d = -2 * far * near / (far - near);
  4476. te[0] = x;
  4477. te[4] = 0;
  4478. te[8] = a;
  4479. te[12] = 0;
  4480. te[1] = 0;
  4481. te[5] = y;
  4482. te[9] = b;
  4483. te[13] = 0;
  4484. te[2] = 0;
  4485. te[6] = 0;
  4486. te[10] = c;
  4487. te[14] = d;
  4488. te[3] = 0;
  4489. te[7] = 0;
  4490. te[11] = -1;
  4491. te[15] = 0;
  4492. return this;
  4493. }
  4494. makeOrthographic(left, right, top, bottom, near, far) {
  4495. const te = this.elements;
  4496. const w = 1.0 / (right - left);
  4497. const h = 1.0 / (top - bottom);
  4498. const p = 1.0 / (far - near);
  4499. const x = (right + left) * w;
  4500. const y = (top + bottom) * h;
  4501. const z = (far + near) * p;
  4502. te[0] = 2 * w;
  4503. te[4] = 0;
  4504. te[8] = 0;
  4505. te[12] = -x;
  4506. te[1] = 0;
  4507. te[5] = 2 * h;
  4508. te[9] = 0;
  4509. te[13] = -y;
  4510. te[2] = 0;
  4511. te[6] = 0;
  4512. te[10] = -2 * p;
  4513. te[14] = -z;
  4514. te[3] = 0;
  4515. te[7] = 0;
  4516. te[11] = 0;
  4517. te[15] = 1;
  4518. return this;
  4519. }
  4520. equals(matrix) {
  4521. const te = this.elements;
  4522. const me = matrix.elements;
  4523. for (let i = 0; i < 16; i++) {
  4524. if (te[i] !== me[i]) return false;
  4525. }
  4526. return true;
  4527. }
  4528. fromArray(array, offset = 0) {
  4529. for (let i = 0; i < 16; i++) {
  4530. this.elements[i] = array[i + offset];
  4531. }
  4532. return this;
  4533. }
  4534. toArray(array = [], offset = 0) {
  4535. const te = this.elements;
  4536. array[offset] = te[0];
  4537. array[offset + 1] = te[1];
  4538. array[offset + 2] = te[2];
  4539. array[offset + 3] = te[3];
  4540. array[offset + 4] = te[4];
  4541. array[offset + 5] = te[5];
  4542. array[offset + 6] = te[6];
  4543. array[offset + 7] = te[7];
  4544. array[offset + 8] = te[8];
  4545. array[offset + 9] = te[9];
  4546. array[offset + 10] = te[10];
  4547. array[offset + 11] = te[11];
  4548. array[offset + 12] = te[12];
  4549. array[offset + 13] = te[13];
  4550. array[offset + 14] = te[14];
  4551. array[offset + 15] = te[15];
  4552. return array;
  4553. }
  4554. }
  4555. const _v1$5 = /*@__PURE__*/new Vector3();
  4556. const _m1$2 = /*@__PURE__*/new Matrix4();
  4557. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  4558. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  4559. const _x = /*@__PURE__*/new Vector3();
  4560. const _y = /*@__PURE__*/new Vector3();
  4561. const _z = /*@__PURE__*/new Vector3();
  4562. const _matrix$1 = /*@__PURE__*/new Matrix4();
  4563. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  4564. class Euler {
  4565. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4566. this.isEuler = true;
  4567. this._x = x;
  4568. this._y = y;
  4569. this._z = z;
  4570. this._order = order;
  4571. }
  4572. get x() {
  4573. return this._x;
  4574. }
  4575. set x(value) {
  4576. this._x = value;
  4577. this._onChangeCallback();
  4578. }
  4579. get y() {
  4580. return this._y;
  4581. }
  4582. set y(value) {
  4583. this._y = value;
  4584. this._onChangeCallback();
  4585. }
  4586. get z() {
  4587. return this._z;
  4588. }
  4589. set z(value) {
  4590. this._z = value;
  4591. this._onChangeCallback();
  4592. }
  4593. get order() {
  4594. return this._order;
  4595. }
  4596. set order(value) {
  4597. this._order = value;
  4598. this._onChangeCallback();
  4599. }
  4600. set(x, y, z, order = this._order) {
  4601. this._x = x;
  4602. this._y = y;
  4603. this._z = z;
  4604. this._order = order;
  4605. this._onChangeCallback();
  4606. return this;
  4607. }
  4608. clone() {
  4609. return new this.constructor(this._x, this._y, this._z, this._order);
  4610. }
  4611. copy(euler) {
  4612. this._x = euler._x;
  4613. this._y = euler._y;
  4614. this._z = euler._z;
  4615. this._order = euler._order;
  4616. this._onChangeCallback();
  4617. return this;
  4618. }
  4619. setFromRotationMatrix(m, order = this._order, update = true) {
  4620. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4621. const te = m.elements;
  4622. const m11 = te[0],
  4623. m12 = te[4],
  4624. m13 = te[8];
  4625. const m21 = te[1],
  4626. m22 = te[5],
  4627. m23 = te[9];
  4628. const m31 = te[2],
  4629. m32 = te[6],
  4630. m33 = te[10];
  4631. switch (order) {
  4632. case 'XYZ':
  4633. this._y = Math.asin(clamp(m13, -1, 1));
  4634. if (Math.abs(m13) < 0.9999999) {
  4635. this._x = Math.atan2(-m23, m33);
  4636. this._z = Math.atan2(-m12, m11);
  4637. } else {
  4638. this._x = Math.atan2(m32, m22);
  4639. this._z = 0;
  4640. }
  4641. break;
  4642. case 'YXZ':
  4643. this._x = Math.asin(-clamp(m23, -1, 1));
  4644. if (Math.abs(m23) < 0.9999999) {
  4645. this._y = Math.atan2(m13, m33);
  4646. this._z = Math.atan2(m21, m22);
  4647. } else {
  4648. this._y = Math.atan2(-m31, m11);
  4649. this._z = 0;
  4650. }
  4651. break;
  4652. case 'ZXY':
  4653. this._x = Math.asin(clamp(m32, -1, 1));
  4654. if (Math.abs(m32) < 0.9999999) {
  4655. this._y = Math.atan2(-m31, m33);
  4656. this._z = Math.atan2(-m12, m22);
  4657. } else {
  4658. this._y = 0;
  4659. this._z = Math.atan2(m21, m11);
  4660. }
  4661. break;
  4662. case 'ZYX':
  4663. this._y = Math.asin(-clamp(m31, -1, 1));
  4664. if (Math.abs(m31) < 0.9999999) {
  4665. this._x = Math.atan2(m32, m33);
  4666. this._z = Math.atan2(m21, m11);
  4667. } else {
  4668. this._x = 0;
  4669. this._z = Math.atan2(-m12, m22);
  4670. }
  4671. break;
  4672. case 'YZX':
  4673. this._z = Math.asin(clamp(m21, -1, 1));
  4674. if (Math.abs(m21) < 0.9999999) {
  4675. this._x = Math.atan2(-m23, m22);
  4676. this._y = Math.atan2(-m31, m11);
  4677. } else {
  4678. this._x = 0;
  4679. this._y = Math.atan2(m13, m33);
  4680. }
  4681. break;
  4682. case 'XZY':
  4683. this._z = Math.asin(-clamp(m12, -1, 1));
  4684. if (Math.abs(m12) < 0.9999999) {
  4685. this._x = Math.atan2(m32, m22);
  4686. this._y = Math.atan2(m13, m11);
  4687. } else {
  4688. this._x = Math.atan2(-m23, m33);
  4689. this._y = 0;
  4690. }
  4691. break;
  4692. default:
  4693. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4694. }
  4695. this._order = order;
  4696. if (update === true) this._onChangeCallback();
  4697. return this;
  4698. }
  4699. setFromQuaternion(q, order, update) {
  4700. _matrix$1.makeRotationFromQuaternion(q);
  4701. return this.setFromRotationMatrix(_matrix$1, order, update);
  4702. }
  4703. setFromVector3(v, order = this._order) {
  4704. return this.set(v.x, v.y, v.z, order);
  4705. }
  4706. reorder(newOrder) {
  4707. // WARNING: this discards revolution information -bhouston
  4708. _quaternion$3.setFromEuler(this);
  4709. return this.setFromQuaternion(_quaternion$3, newOrder);
  4710. }
  4711. equals(euler) {
  4712. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4713. }
  4714. fromArray(array) {
  4715. this._x = array[0];
  4716. this._y = array[1];
  4717. this._z = array[2];
  4718. if (array[3] !== undefined) this._order = array[3];
  4719. this._onChangeCallback();
  4720. return this;
  4721. }
  4722. toArray(array = [], offset = 0) {
  4723. array[offset] = this._x;
  4724. array[offset + 1] = this._y;
  4725. array[offset + 2] = this._z;
  4726. array[offset + 3] = this._order;
  4727. return array;
  4728. }
  4729. _onChange(callback) {
  4730. this._onChangeCallback = callback;
  4731. return this;
  4732. }
  4733. _onChangeCallback() {}
  4734. *[Symbol.iterator]() {
  4735. yield this._x;
  4736. yield this._y;
  4737. yield this._z;
  4738. yield this._order;
  4739. } // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4740. toVector3() {
  4741. console.error('THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead');
  4742. }
  4743. }
  4744. Euler.DefaultOrder = 'XYZ';
  4745. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4746. class Layers {
  4747. constructor() {
  4748. this.mask = 1 | 0;
  4749. }
  4750. set(channel) {
  4751. this.mask = (1 << channel | 0) >>> 0;
  4752. }
  4753. enable(channel) {
  4754. this.mask |= 1 << channel | 0;
  4755. }
  4756. enableAll() {
  4757. this.mask = 0xffffffff | 0;
  4758. }
  4759. toggle(channel) {
  4760. this.mask ^= 1 << channel | 0;
  4761. }
  4762. disable(channel) {
  4763. this.mask &= ~(1 << channel | 0);
  4764. }
  4765. disableAll() {
  4766. this.mask = 0;
  4767. }
  4768. test(layers) {
  4769. return (this.mask & layers.mask) !== 0;
  4770. }
  4771. isEnabled(channel) {
  4772. return (this.mask & (1 << channel | 0)) !== 0;
  4773. }
  4774. }
  4775. let _object3DId = 0;
  4776. const _v1$4 = /*@__PURE__*/new Vector3();
  4777. const _q1 = /*@__PURE__*/new Quaternion();
  4778. const _m1$1 = /*@__PURE__*/new Matrix4();
  4779. const _target = /*@__PURE__*/new Vector3();
  4780. const _position$3 = /*@__PURE__*/new Vector3();
  4781. const _scale$2 = /*@__PURE__*/new Vector3();
  4782. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4783. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4784. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4785. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4786. const _addedEvent = {
  4787. type: 'added'
  4788. };
  4789. const _removedEvent = {
  4790. type: 'removed'
  4791. };
  4792. class Object3D extends EventDispatcher {
  4793. constructor() {
  4794. super();
  4795. this.isObject3D = true;
  4796. Object.defineProperty(this, 'id', {
  4797. value: _object3DId++
  4798. });
  4799. this.uuid = generateUUID();
  4800. this.name = '';
  4801. this.type = 'Object3D';
  4802. this.parent = null;
  4803. this.children = [];
  4804. this.up = Object3D.DefaultUp.clone();
  4805. const position = new Vector3();
  4806. const rotation = new Euler();
  4807. const quaternion = new Quaternion();
  4808. const scale = new Vector3(1, 1, 1);
  4809. function onRotationChange() {
  4810. quaternion.setFromEuler(rotation, false);
  4811. }
  4812. function onQuaternionChange() {
  4813. rotation.setFromQuaternion(quaternion, undefined, false);
  4814. }
  4815. rotation._onChange(onRotationChange);
  4816. quaternion._onChange(onQuaternionChange);
  4817. Object.defineProperties(this, {
  4818. position: {
  4819. configurable: true,
  4820. enumerable: true,
  4821. value: position
  4822. },
  4823. rotation: {
  4824. configurable: true,
  4825. enumerable: true,
  4826. value: rotation
  4827. },
  4828. quaternion: {
  4829. configurable: true,
  4830. enumerable: true,
  4831. value: quaternion
  4832. },
  4833. scale: {
  4834. configurable: true,
  4835. enumerable: true,
  4836. value: scale
  4837. },
  4838. modelViewMatrix: {
  4839. value: new Matrix4()
  4840. },
  4841. normalMatrix: {
  4842. value: new Matrix3()
  4843. }
  4844. });
  4845. this.matrix = new Matrix4();
  4846. this.matrixWorld = new Matrix4();
  4847. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4848. this.matrixWorldNeedsUpdate = false;
  4849. this.layers = new Layers();
  4850. this.visible = true;
  4851. this.castShadow = false;
  4852. this.receiveShadow = false;
  4853. this.frustumCulled = true;
  4854. this.renderOrder = 0;
  4855. this.animations = [];
  4856. this.userData = {};
  4857. }
  4858. onBeforeRender() {}
  4859. onAfterRender() {}
  4860. applyMatrix4(matrix) {
  4861. if (this.matrixAutoUpdate) this.updateMatrix();
  4862. this.matrix.premultiply(matrix);
  4863. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4864. }
  4865. applyQuaternion(q) {
  4866. this.quaternion.premultiply(q);
  4867. return this;
  4868. }
  4869. setRotationFromAxisAngle(axis, angle) {
  4870. // assumes axis is normalized
  4871. this.quaternion.setFromAxisAngle(axis, angle);
  4872. }
  4873. setRotationFromEuler(euler) {
  4874. this.quaternion.setFromEuler(euler, true);
  4875. }
  4876. setRotationFromMatrix(m) {
  4877. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4878. this.quaternion.setFromRotationMatrix(m);
  4879. }
  4880. setRotationFromQuaternion(q) {
  4881. // assumes q is normalized
  4882. this.quaternion.copy(q);
  4883. }
  4884. rotateOnAxis(axis, angle) {
  4885. // rotate object on axis in object space
  4886. // axis is assumed to be normalized
  4887. _q1.setFromAxisAngle(axis, angle);
  4888. this.quaternion.multiply(_q1);
  4889. return this;
  4890. }
  4891. rotateOnWorldAxis(axis, angle) {
  4892. // rotate object on axis in world space
  4893. // axis is assumed to be normalized
  4894. // method assumes no rotated parent
  4895. _q1.setFromAxisAngle(axis, angle);
  4896. this.quaternion.premultiply(_q1);
  4897. return this;
  4898. }
  4899. rotateX(angle) {
  4900. return this.rotateOnAxis(_xAxis, angle);
  4901. }
  4902. rotateY(angle) {
  4903. return this.rotateOnAxis(_yAxis, angle);
  4904. }
  4905. rotateZ(angle) {
  4906. return this.rotateOnAxis(_zAxis, angle);
  4907. }
  4908. translateOnAxis(axis, distance) {
  4909. // translate object by distance along axis in object space
  4910. // axis is assumed to be normalized
  4911. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4912. this.position.add(_v1$4.multiplyScalar(distance));
  4913. return this;
  4914. }
  4915. translateX(distance) {
  4916. return this.translateOnAxis(_xAxis, distance);
  4917. }
  4918. translateY(distance) {
  4919. return this.translateOnAxis(_yAxis, distance);
  4920. }
  4921. translateZ(distance) {
  4922. return this.translateOnAxis(_zAxis, distance);
  4923. }
  4924. localToWorld(vector) {
  4925. return vector.applyMatrix4(this.matrixWorld);
  4926. }
  4927. worldToLocal(vector) {
  4928. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4929. }
  4930. lookAt(x, y, z) {
  4931. // This method does not support objects having non-uniformly-scaled parent(s)
  4932. if (x.isVector3) {
  4933. _target.copy(x);
  4934. } else {
  4935. _target.set(x, y, z);
  4936. }
  4937. const parent = this.parent;
  4938. this.updateWorldMatrix(true, false);
  4939. _position$3.setFromMatrixPosition(this.matrixWorld);
  4940. if (this.isCamera || this.isLight) {
  4941. _m1$1.lookAt(_position$3, _target, this.up);
  4942. } else {
  4943. _m1$1.lookAt(_target, _position$3, this.up);
  4944. }
  4945. this.quaternion.setFromRotationMatrix(_m1$1);
  4946. if (parent) {
  4947. _m1$1.extractRotation(parent.matrixWorld);
  4948. _q1.setFromRotationMatrix(_m1$1);
  4949. this.quaternion.premultiply(_q1.invert());
  4950. }
  4951. }
  4952. add(object) {
  4953. if (arguments.length > 1) {
  4954. for (let i = 0; i < arguments.length; i++) {
  4955. this.add(arguments[i]);
  4956. }
  4957. return this;
  4958. }
  4959. if (object === this) {
  4960. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4961. return this;
  4962. }
  4963. if (object && object.isObject3D) {
  4964. if (object.parent !== null) {
  4965. object.parent.remove(object);
  4966. }
  4967. object.parent = this;
  4968. this.children.push(object);
  4969. object.dispatchEvent(_addedEvent);
  4970. } else {
  4971. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4972. }
  4973. return this;
  4974. }
  4975. remove(object) {
  4976. if (arguments.length > 1) {
  4977. for (let i = 0; i < arguments.length; i++) {
  4978. this.remove(arguments[i]);
  4979. }
  4980. return this;
  4981. }
  4982. const index = this.children.indexOf(object);
  4983. if (index !== -1) {
  4984. object.parent = null;
  4985. this.children.splice(index, 1);
  4986. object.dispatchEvent(_removedEvent);
  4987. }
  4988. return this;
  4989. }
  4990. removeFromParent() {
  4991. const parent = this.parent;
  4992. if (parent !== null) {
  4993. parent.remove(this);
  4994. }
  4995. return this;
  4996. }
  4997. clear() {
  4998. for (let i = 0; i < this.children.length; i++) {
  4999. const object = this.children[i];
  5000. object.parent = null;
  5001. object.dispatchEvent(_removedEvent);
  5002. }
  5003. this.children.length = 0;
  5004. return this;
  5005. }
  5006. attach(object) {
  5007. // adds object as a child of this, while maintaining the object's world transform
  5008. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  5009. this.updateWorldMatrix(true, false);
  5010. _m1$1.copy(this.matrixWorld).invert();
  5011. if (object.parent !== null) {
  5012. object.parent.updateWorldMatrix(true, false);
  5013. _m1$1.multiply(object.parent.matrixWorld);
  5014. }
  5015. object.applyMatrix4(_m1$1);
  5016. this.add(object);
  5017. object.updateWorldMatrix(false, true);
  5018. return this;
  5019. }
  5020. getObjectById(id) {
  5021. return this.getObjectByProperty('id', id);
  5022. }
  5023. getObjectByName(name) {
  5024. return this.getObjectByProperty('name', name);
  5025. }
  5026. getObjectByProperty(name, value) {
  5027. if (this[name] === value) return this;
  5028. for (let i = 0, l = this.children.length; i < l; i++) {
  5029. const child = this.children[i];
  5030. const object = child.getObjectByProperty(name, value);
  5031. if (object !== undefined) {
  5032. return object;
  5033. }
  5034. }
  5035. return undefined;
  5036. }
  5037. getWorldPosition(target) {
  5038. this.updateWorldMatrix(true, false);
  5039. return target.setFromMatrixPosition(this.matrixWorld);
  5040. }
  5041. getWorldQuaternion(target) {
  5042. this.updateWorldMatrix(true, false);
  5043. this.matrixWorld.decompose(_position$3, target, _scale$2);
  5044. return target;
  5045. }
  5046. getWorldScale(target) {
  5047. this.updateWorldMatrix(true, false);
  5048. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  5049. return target;
  5050. }
  5051. getWorldDirection(target) {
  5052. this.updateWorldMatrix(true, false);
  5053. const e = this.matrixWorld.elements;
  5054. return target.set(e[8], e[9], e[10]).normalize();
  5055. }
  5056. raycast() {}
  5057. traverse(callback) {
  5058. callback(this);
  5059. const children = this.children;
  5060. for (let i = 0, l = children.length; i < l; i++) {
  5061. children[i].traverse(callback);
  5062. }
  5063. }
  5064. traverseVisible(callback) {
  5065. if (this.visible === false) return;
  5066. callback(this);
  5067. const children = this.children;
  5068. for (let i = 0, l = children.length; i < l; i++) {
  5069. children[i].traverseVisible(callback);
  5070. }
  5071. }
  5072. traverseAncestors(callback) {
  5073. const parent = this.parent;
  5074. if (parent !== null) {
  5075. callback(parent);
  5076. parent.traverseAncestors(callback);
  5077. }
  5078. }
  5079. updateMatrix() {
  5080. this.matrix.compose(this.position, this.quaternion, this.scale);
  5081. this.matrixWorldNeedsUpdate = true;
  5082. }
  5083. updateMatrixWorld(force) {
  5084. if (this.matrixAutoUpdate) this.updateMatrix();
  5085. if (this.matrixWorldNeedsUpdate || force) {
  5086. if (this.parent === null) {
  5087. this.matrixWorld.copy(this.matrix);
  5088. } else {
  5089. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5090. }
  5091. this.matrixWorldNeedsUpdate = false;
  5092. force = true;
  5093. } // update children
  5094. const children = this.children;
  5095. for (let i = 0, l = children.length; i < l; i++) {
  5096. children[i].updateMatrixWorld(force);
  5097. }
  5098. }
  5099. updateWorldMatrix(updateParents, updateChildren) {
  5100. const parent = this.parent;
  5101. if (updateParents === true && parent !== null) {
  5102. parent.updateWorldMatrix(true, false);
  5103. }
  5104. if (this.matrixAutoUpdate) this.updateMatrix();
  5105. if (this.parent === null) {
  5106. this.matrixWorld.copy(this.matrix);
  5107. } else {
  5108. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5109. } // update children
  5110. if (updateChildren === true) {
  5111. const children = this.children;
  5112. for (let i = 0, l = children.length; i < l; i++) {
  5113. children[i].updateWorldMatrix(false, true);
  5114. }
  5115. }
  5116. }
  5117. toJSON(meta) {
  5118. // meta is a string when called from JSON.stringify
  5119. const isRootObject = meta === undefined || typeof meta === 'string';
  5120. const output = {}; // meta is a hash used to collect geometries, materials.
  5121. // not providing it implies that this is the root object
  5122. // being serialized.
  5123. if (isRootObject) {
  5124. // initialize meta obj
  5125. meta = {
  5126. geometries: {},
  5127. materials: {},
  5128. textures: {},
  5129. images: {},
  5130. shapes: {},
  5131. skeletons: {},
  5132. animations: {},
  5133. nodes: {}
  5134. };
  5135. output.metadata = {
  5136. version: 4.5,
  5137. type: 'Object',
  5138. generator: 'Object3D.toJSON'
  5139. };
  5140. } // standard Object3D serialization
  5141. const object = {};
  5142. object.uuid = this.uuid;
  5143. object.type = this.type;
  5144. if (this.name !== '') object.name = this.name;
  5145. if (this.castShadow === true) object.castShadow = true;
  5146. if (this.receiveShadow === true) object.receiveShadow = true;
  5147. if (this.visible === false) object.visible = false;
  5148. if (this.frustumCulled === false) object.frustumCulled = false;
  5149. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5150. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5151. object.layers = this.layers.mask;
  5152. object.matrix = this.matrix.toArray();
  5153. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5154. if (this.isInstancedMesh) {
  5155. object.type = 'InstancedMesh';
  5156. object.count = this.count;
  5157. object.instanceMatrix = this.instanceMatrix.toJSON();
  5158. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  5159. } //
  5160. function serialize(library, element) {
  5161. if (library[element.uuid] === undefined) {
  5162. library[element.uuid] = element.toJSON(meta);
  5163. }
  5164. return element.uuid;
  5165. }
  5166. if (this.isScene) {
  5167. if (this.background) {
  5168. if (this.background.isColor) {
  5169. object.background = this.background.toJSON();
  5170. } else if (this.background.isTexture) {
  5171. object.background = this.background.toJSON(meta).uuid;
  5172. }
  5173. }
  5174. if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) {
  5175. object.environment = this.environment.toJSON(meta).uuid;
  5176. }
  5177. } else if (this.isMesh || this.isLine || this.isPoints) {
  5178. object.geometry = serialize(meta.geometries, this.geometry);
  5179. const parameters = this.geometry.parameters;
  5180. if (parameters !== undefined && parameters.shapes !== undefined) {
  5181. const shapes = parameters.shapes;
  5182. if (Array.isArray(shapes)) {
  5183. for (let i = 0, l = shapes.length; i < l; i++) {
  5184. const shape = shapes[i];
  5185. serialize(meta.shapes, shape);
  5186. }
  5187. } else {
  5188. serialize(meta.shapes, shapes);
  5189. }
  5190. }
  5191. }
  5192. if (this.isSkinnedMesh) {
  5193. object.bindMode = this.bindMode;
  5194. object.bindMatrix = this.bindMatrix.toArray();
  5195. if (this.skeleton !== undefined) {
  5196. serialize(meta.skeletons, this.skeleton);
  5197. object.skeleton = this.skeleton.uuid;
  5198. }
  5199. }
  5200. if (this.material !== undefined) {
  5201. if (Array.isArray(this.material)) {
  5202. const uuids = [];
  5203. for (let i = 0, l = this.material.length; i < l; i++) {
  5204. uuids.push(serialize(meta.materials, this.material[i]));
  5205. }
  5206. object.material = uuids;
  5207. } else {
  5208. object.material = serialize(meta.materials, this.material);
  5209. }
  5210. } //
  5211. if (this.children.length > 0) {
  5212. object.children = [];
  5213. for (let i = 0; i < this.children.length; i++) {
  5214. object.children.push(this.children[i].toJSON(meta).object);
  5215. }
  5216. } //
  5217. if (this.animations.length > 0) {
  5218. object.animations = [];
  5219. for (let i = 0; i < this.animations.length; i++) {
  5220. const animation = this.animations[i];
  5221. object.animations.push(serialize(meta.animations, animation));
  5222. }
  5223. }
  5224. if (isRootObject) {
  5225. const geometries = extractFromCache(meta.geometries);
  5226. const materials = extractFromCache(meta.materials);
  5227. const textures = extractFromCache(meta.textures);
  5228. const images = extractFromCache(meta.images);
  5229. const shapes = extractFromCache(meta.shapes);
  5230. const skeletons = extractFromCache(meta.skeletons);
  5231. const animations = extractFromCache(meta.animations);
  5232. const nodes = extractFromCache(meta.nodes);
  5233. if (geometries.length > 0) output.geometries = geometries;
  5234. if (materials.length > 0) output.materials = materials;
  5235. if (textures.length > 0) output.textures = textures;
  5236. if (images.length > 0) output.images = images;
  5237. if (shapes.length > 0) output.shapes = shapes;
  5238. if (skeletons.length > 0) output.skeletons = skeletons;
  5239. if (animations.length > 0) output.animations = animations;
  5240. if (nodes.length > 0) output.nodes = nodes;
  5241. }
  5242. output.object = object;
  5243. return output; // extract data from the cache hash
  5244. // remove metadata on each item
  5245. // and return as array
  5246. function extractFromCache(cache) {
  5247. const values = [];
  5248. for (const key in cache) {
  5249. const data = cache[key];
  5250. delete data.metadata;
  5251. values.push(data);
  5252. }
  5253. return values;
  5254. }
  5255. }
  5256. clone(recursive) {
  5257. return new this.constructor().copy(this, recursive);
  5258. }
  5259. copy(source, recursive = true) {
  5260. this.name = source.name;
  5261. this.up.copy(source.up);
  5262. this.position.copy(source.position);
  5263. this.rotation.order = source.rotation.order;
  5264. this.quaternion.copy(source.quaternion);
  5265. this.scale.copy(source.scale);
  5266. this.matrix.copy(source.matrix);
  5267. this.matrixWorld.copy(source.matrixWorld);
  5268. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5269. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5270. this.layers.mask = source.layers.mask;
  5271. this.visible = source.visible;
  5272. this.castShadow = source.castShadow;
  5273. this.receiveShadow = source.receiveShadow;
  5274. this.frustumCulled = source.frustumCulled;
  5275. this.renderOrder = source.renderOrder;
  5276. this.userData = JSON.parse(JSON.stringify(source.userData));
  5277. if (recursive === true) {
  5278. for (let i = 0; i < source.children.length; i++) {
  5279. const child = source.children[i];
  5280. this.add(child.clone());
  5281. }
  5282. }
  5283. return this;
  5284. }
  5285. }
  5286. Object3D.DefaultUp = /*@__PURE__*/new Vector3(0, 1, 0);
  5287. Object3D.DefaultMatrixAutoUpdate = true;
  5288. const _v0$1 = /*@__PURE__*/new Vector3();
  5289. const _v1$3 = /*@__PURE__*/new Vector3();
  5290. const _v2$2 = /*@__PURE__*/new Vector3();
  5291. const _v3$1 = /*@__PURE__*/new Vector3();
  5292. const _vab = /*@__PURE__*/new Vector3();
  5293. const _vac = /*@__PURE__*/new Vector3();
  5294. const _vbc = /*@__PURE__*/new Vector3();
  5295. const _vap = /*@__PURE__*/new Vector3();
  5296. const _vbp = /*@__PURE__*/new Vector3();
  5297. const _vcp = /*@__PURE__*/new Vector3();
  5298. class Triangle {
  5299. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  5300. this.a = a;
  5301. this.b = b;
  5302. this.c = c;
  5303. }
  5304. static getNormal(a, b, c, target) {
  5305. target.subVectors(c, b);
  5306. _v0$1.subVectors(a, b);
  5307. target.cross(_v0$1);
  5308. const targetLengthSq = target.lengthSq();
  5309. if (targetLengthSq > 0) {
  5310. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5311. }
  5312. return target.set(0, 0, 0);
  5313. } // static/instance method to calculate barycentric coordinates
  5314. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5315. static getBarycoord(point, a, b, c, target) {
  5316. _v0$1.subVectors(c, a);
  5317. _v1$3.subVectors(b, a);
  5318. _v2$2.subVectors(point, a);
  5319. const dot00 = _v0$1.dot(_v0$1);
  5320. const dot01 = _v0$1.dot(_v1$3);
  5321. const dot02 = _v0$1.dot(_v2$2);
  5322. const dot11 = _v1$3.dot(_v1$3);
  5323. const dot12 = _v1$3.dot(_v2$2);
  5324. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  5325. if (denom === 0) {
  5326. // arbitrary location outside of triangle?
  5327. // not sure if this is the best idea, maybe should be returning undefined
  5328. return target.set(-2, -1, -1);
  5329. }
  5330. const invDenom = 1 / denom;
  5331. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5332. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5333. return target.set(1 - u - v, v, u);
  5334. }
  5335. static containsPoint(point, a, b, c) {
  5336. this.getBarycoord(point, a, b, c, _v3$1);
  5337. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  5338. }
  5339. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5340. this.getBarycoord(point, p1, p2, p3, _v3$1);
  5341. target.set(0, 0);
  5342. target.addScaledVector(uv1, _v3$1.x);
  5343. target.addScaledVector(uv2, _v3$1.y);
  5344. target.addScaledVector(uv3, _v3$1.z);
  5345. return target;
  5346. }
  5347. static isFrontFacing(a, b, c, direction) {
  5348. _v0$1.subVectors(c, b);
  5349. _v1$3.subVectors(a, b); // strictly front facing
  5350. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5351. }
  5352. set(a, b, c) {
  5353. this.a.copy(a);
  5354. this.b.copy(b);
  5355. this.c.copy(c);
  5356. return this;
  5357. }
  5358. setFromPointsAndIndices(points, i0, i1, i2) {
  5359. this.a.copy(points[i0]);
  5360. this.b.copy(points[i1]);
  5361. this.c.copy(points[i2]);
  5362. return this;
  5363. }
  5364. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  5365. this.a.fromBufferAttribute(attribute, i0);
  5366. this.b.fromBufferAttribute(attribute, i1);
  5367. this.c.fromBufferAttribute(attribute, i2);
  5368. return this;
  5369. }
  5370. clone() {
  5371. return new this.constructor().copy(this);
  5372. }
  5373. copy(triangle) {
  5374. this.a.copy(triangle.a);
  5375. this.b.copy(triangle.b);
  5376. this.c.copy(triangle.c);
  5377. return this;
  5378. }
  5379. getArea() {
  5380. _v0$1.subVectors(this.c, this.b);
  5381. _v1$3.subVectors(this.a, this.b);
  5382. return _v0$1.cross(_v1$3).length() * 0.5;
  5383. }
  5384. getMidpoint(target) {
  5385. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5386. }
  5387. getNormal(target) {
  5388. return Triangle.getNormal(this.a, this.b, this.c, target);
  5389. }
  5390. getPlane(target) {
  5391. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5392. }
  5393. getBarycoord(point, target) {
  5394. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5395. }
  5396. getUV(point, uv1, uv2, uv3, target) {
  5397. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5398. }
  5399. containsPoint(point) {
  5400. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5401. }
  5402. isFrontFacing(direction) {
  5403. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5404. }
  5405. intersectsBox(box) {
  5406. return box.intersectsTriangle(this);
  5407. }
  5408. closestPointToPoint(p, target) {
  5409. const a = this.a,
  5410. b = this.b,
  5411. c = this.c;
  5412. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5413. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5414. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5415. // basically, we're distinguishing which of the voronoi regions of the triangle
  5416. // the point lies in with the minimum amount of redundant computation.
  5417. _vab.subVectors(b, a);
  5418. _vac.subVectors(c, a);
  5419. _vap.subVectors(p, a);
  5420. const d1 = _vab.dot(_vap);
  5421. const d2 = _vac.dot(_vap);
  5422. if (d1 <= 0 && d2 <= 0) {
  5423. // vertex region of A; barycentric coords (1, 0, 0)
  5424. return target.copy(a);
  5425. }
  5426. _vbp.subVectors(p, b);
  5427. const d3 = _vab.dot(_vbp);
  5428. const d4 = _vac.dot(_vbp);
  5429. if (d3 >= 0 && d4 <= d3) {
  5430. // vertex region of B; barycentric coords (0, 1, 0)
  5431. return target.copy(b);
  5432. }
  5433. const vc = d1 * d4 - d3 * d2;
  5434. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5435. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5436. return target.copy(a).addScaledVector(_vab, v);
  5437. }
  5438. _vcp.subVectors(p, c);
  5439. const d5 = _vab.dot(_vcp);
  5440. const d6 = _vac.dot(_vcp);
  5441. if (d6 >= 0 && d5 <= d6) {
  5442. // vertex region of C; barycentric coords (0, 0, 1)
  5443. return target.copy(c);
  5444. }
  5445. const vb = d5 * d2 - d1 * d6;
  5446. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5447. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5448. return target.copy(a).addScaledVector(_vac, w);
  5449. }
  5450. const va = d3 * d6 - d5 * d4;
  5451. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5452. _vbc.subVectors(c, b);
  5453. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5454. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5455. } // face region
  5456. const denom = 1 / (va + vb + vc); // u = va * denom
  5457. v = vb * denom;
  5458. w = vc * denom;
  5459. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5460. }
  5461. equals(triangle) {
  5462. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5463. }
  5464. }
  5465. let materialId = 0;
  5466. class Material extends EventDispatcher {
  5467. constructor() {
  5468. super();
  5469. this.isMaterial = true;
  5470. Object.defineProperty(this, 'id', {
  5471. value: materialId++
  5472. });
  5473. this.uuid = generateUUID();
  5474. this.name = '';
  5475. this.type = 'Material';
  5476. this.blending = NormalBlending;
  5477. this.side = FrontSide;
  5478. this.vertexColors = false;
  5479. this.opacity = 1;
  5480. this.transparent = false;
  5481. this.blendSrc = SrcAlphaFactor;
  5482. this.blendDst = OneMinusSrcAlphaFactor;
  5483. this.blendEquation = AddEquation;
  5484. this.blendSrcAlpha = null;
  5485. this.blendDstAlpha = null;
  5486. this.blendEquationAlpha = null;
  5487. this.depthFunc = LessEqualDepth;
  5488. this.depthTest = true;
  5489. this.depthWrite = true;
  5490. this.stencilWriteMask = 0xff;
  5491. this.stencilFunc = AlwaysStencilFunc;
  5492. this.stencilRef = 0;
  5493. this.stencilFuncMask = 0xff;
  5494. this.stencilFail = KeepStencilOp;
  5495. this.stencilZFail = KeepStencilOp;
  5496. this.stencilZPass = KeepStencilOp;
  5497. this.stencilWrite = false;
  5498. this.clippingPlanes = null;
  5499. this.clipIntersection = false;
  5500. this.clipShadows = false;
  5501. this.shadowSide = null;
  5502. this.colorWrite = true;
  5503. this.precision = null; // override the renderer's default precision for this material
  5504. this.polygonOffset = false;
  5505. this.polygonOffsetFactor = 0;
  5506. this.polygonOffsetUnits = 0;
  5507. this.dithering = false;
  5508. this.alphaToCoverage = false;
  5509. this.premultipliedAlpha = false;
  5510. this.visible = true;
  5511. this.toneMapped = true;
  5512. this.userData = {};
  5513. this.version = 0;
  5514. this._alphaTest = 0;
  5515. }
  5516. get alphaTest() {
  5517. return this._alphaTest;
  5518. }
  5519. set alphaTest(value) {
  5520. if (this._alphaTest > 0 !== value > 0) {
  5521. this.version++;
  5522. }
  5523. this._alphaTest = value;
  5524. }
  5525. onBuild() {}
  5526. onBeforeRender() {}
  5527. onBeforeCompile() {}
  5528. customProgramCacheKey() {
  5529. return this.onBeforeCompile.toString();
  5530. }
  5531. setValues(values) {
  5532. if (values === undefined) return;
  5533. for (const key in values) {
  5534. const newValue = values[key];
  5535. if (newValue === undefined) {
  5536. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5537. continue;
  5538. }
  5539. const currentValue = this[key];
  5540. if (currentValue === undefined) {
  5541. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5542. continue;
  5543. }
  5544. if (currentValue && currentValue.isColor) {
  5545. currentValue.set(newValue);
  5546. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5547. currentValue.copy(newValue);
  5548. } else {
  5549. this[key] = newValue;
  5550. }
  5551. }
  5552. }
  5553. toJSON(meta) {
  5554. const isRootObject = meta === undefined || typeof meta === 'string';
  5555. if (isRootObject) {
  5556. meta = {
  5557. textures: {},
  5558. images: {}
  5559. };
  5560. }
  5561. const data = {
  5562. metadata: {
  5563. version: 4.5,
  5564. type: 'Material',
  5565. generator: 'Material.toJSON'
  5566. }
  5567. }; // standard Material serialization
  5568. data.uuid = this.uuid;
  5569. data.type = this.type;
  5570. if (this.name !== '') data.name = this.name;
  5571. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5572. if (this.roughness !== undefined) data.roughness = this.roughness;
  5573. if (this.metalness !== undefined) data.metalness = this.metalness;
  5574. if (this.sheen !== undefined) data.sheen = this.sheen;
  5575. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  5576. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  5577. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5578. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5579. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5580. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  5581. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  5582. if (this.shininess !== undefined) data.shininess = this.shininess;
  5583. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5584. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5585. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5586. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5587. }
  5588. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5589. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5590. }
  5591. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5592. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5593. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5594. }
  5595. if (this.iridescence !== undefined) data.iridescence = this.iridescence;
  5596. if (this.iridescenceIOR !== undefined) data.iridescenceIOR = this.iridescenceIOR;
  5597. if (this.iridescenceThicknessRange !== undefined) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5598. if (this.iridescenceMap && this.iridescenceMap.isTexture) {
  5599. data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid;
  5600. }
  5601. if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) {
  5602. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid;
  5603. }
  5604. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5605. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5606. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5607. if (this.lightMap && this.lightMap.isTexture) {
  5608. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5609. data.lightMapIntensity = this.lightMapIntensity;
  5610. }
  5611. if (this.aoMap && this.aoMap.isTexture) {
  5612. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5613. data.aoMapIntensity = this.aoMapIntensity;
  5614. }
  5615. if (this.bumpMap && this.bumpMap.isTexture) {
  5616. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5617. data.bumpScale = this.bumpScale;
  5618. }
  5619. if (this.normalMap && this.normalMap.isTexture) {
  5620. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5621. data.normalMapType = this.normalMapType;
  5622. data.normalScale = this.normalScale.toArray();
  5623. }
  5624. if (this.displacementMap && this.displacementMap.isTexture) {
  5625. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5626. data.displacementScale = this.displacementScale;
  5627. data.displacementBias = this.displacementBias;
  5628. }
  5629. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5630. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5631. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5632. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5633. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5634. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5635. if (this.envMap && this.envMap.isTexture) {
  5636. data.envMap = this.envMap.toJSON(meta).uuid;
  5637. if (this.combine !== undefined) data.combine = this.combine;
  5638. }
  5639. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5640. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5641. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5642. if (this.gradientMap && this.gradientMap.isTexture) {
  5643. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5644. }
  5645. if (this.transmission !== undefined) data.transmission = this.transmission;
  5646. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5647. if (this.thickness !== undefined) data.thickness = this.thickness;
  5648. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5649. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5650. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5651. if (this.size !== undefined) data.size = this.size;
  5652. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5653. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5654. if (this.blending !== NormalBlending) data.blending = this.blending;
  5655. if (this.side !== FrontSide) data.side = this.side;
  5656. if (this.vertexColors) data.vertexColors = true;
  5657. if (this.opacity < 1) data.opacity = this.opacity;
  5658. if (this.transparent === true) data.transparent = this.transparent;
  5659. data.depthFunc = this.depthFunc;
  5660. data.depthTest = this.depthTest;
  5661. data.depthWrite = this.depthWrite;
  5662. data.colorWrite = this.colorWrite;
  5663. data.stencilWrite = this.stencilWrite;
  5664. data.stencilWriteMask = this.stencilWriteMask;
  5665. data.stencilFunc = this.stencilFunc;
  5666. data.stencilRef = this.stencilRef;
  5667. data.stencilFuncMask = this.stencilFuncMask;
  5668. data.stencilFail = this.stencilFail;
  5669. data.stencilZFail = this.stencilZFail;
  5670. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5671. if (this.rotation !== undefined && this.rotation !== 0) data.rotation = this.rotation;
  5672. if (this.polygonOffset === true) data.polygonOffset = true;
  5673. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5674. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5675. if (this.linewidth !== undefined && this.linewidth !== 1) data.linewidth = this.linewidth;
  5676. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5677. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5678. if (this.scale !== undefined) data.scale = this.scale;
  5679. if (this.dithering === true) data.dithering = true;
  5680. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5681. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5682. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5683. if (this.wireframe === true) data.wireframe = this.wireframe;
  5684. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5685. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5686. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5687. if (this.flatShading === true) data.flatShading = this.flatShading;
  5688. if (this.visible === false) data.visible = false;
  5689. if (this.toneMapped === false) data.toneMapped = false;
  5690. if (this.fog === false) data.fog = false;
  5691. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5692. function extractFromCache(cache) {
  5693. const values = [];
  5694. for (const key in cache) {
  5695. const data = cache[key];
  5696. delete data.metadata;
  5697. values.push(data);
  5698. }
  5699. return values;
  5700. }
  5701. if (isRootObject) {
  5702. const textures = extractFromCache(meta.textures);
  5703. const images = extractFromCache(meta.images);
  5704. if (textures.length > 0) data.textures = textures;
  5705. if (images.length > 0) data.images = images;
  5706. }
  5707. return data;
  5708. }
  5709. clone() {
  5710. return new this.constructor().copy(this);
  5711. }
  5712. copy(source) {
  5713. this.name = source.name;
  5714. this.blending = source.blending;
  5715. this.side = source.side;
  5716. this.vertexColors = source.vertexColors;
  5717. this.opacity = source.opacity;
  5718. this.transparent = source.transparent;
  5719. this.blendSrc = source.blendSrc;
  5720. this.blendDst = source.blendDst;
  5721. this.blendEquation = source.blendEquation;
  5722. this.blendSrcAlpha = source.blendSrcAlpha;
  5723. this.blendDstAlpha = source.blendDstAlpha;
  5724. this.blendEquationAlpha = source.blendEquationAlpha;
  5725. this.depthFunc = source.depthFunc;
  5726. this.depthTest = source.depthTest;
  5727. this.depthWrite = source.depthWrite;
  5728. this.stencilWriteMask = source.stencilWriteMask;
  5729. this.stencilFunc = source.stencilFunc;
  5730. this.stencilRef = source.stencilRef;
  5731. this.stencilFuncMask = source.stencilFuncMask;
  5732. this.stencilFail = source.stencilFail;
  5733. this.stencilZFail = source.stencilZFail;
  5734. this.stencilZPass = source.stencilZPass;
  5735. this.stencilWrite = source.stencilWrite;
  5736. const srcPlanes = source.clippingPlanes;
  5737. let dstPlanes = null;
  5738. if (srcPlanes !== null) {
  5739. const n = srcPlanes.length;
  5740. dstPlanes = new Array(n);
  5741. for (let i = 0; i !== n; ++i) {
  5742. dstPlanes[i] = srcPlanes[i].clone();
  5743. }
  5744. }
  5745. this.clippingPlanes = dstPlanes;
  5746. this.clipIntersection = source.clipIntersection;
  5747. this.clipShadows = source.clipShadows;
  5748. this.shadowSide = source.shadowSide;
  5749. this.colorWrite = source.colorWrite;
  5750. this.precision = source.precision;
  5751. this.polygonOffset = source.polygonOffset;
  5752. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5753. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5754. this.dithering = source.dithering;
  5755. this.alphaTest = source.alphaTest;
  5756. this.alphaToCoverage = source.alphaToCoverage;
  5757. this.premultipliedAlpha = source.premultipliedAlpha;
  5758. this.visible = source.visible;
  5759. this.toneMapped = source.toneMapped;
  5760. this.userData = JSON.parse(JSON.stringify(source.userData));
  5761. return this;
  5762. }
  5763. dispose() {
  5764. this.dispatchEvent({
  5765. type: 'dispose'
  5766. });
  5767. }
  5768. set needsUpdate(value) {
  5769. if (value === true) this.version++;
  5770. }
  5771. }
  5772. class MeshBasicMaterial extends Material {
  5773. constructor(parameters) {
  5774. super();
  5775. this.isMeshBasicMaterial = true;
  5776. this.type = 'MeshBasicMaterial';
  5777. this.color = new Color(0xffffff); // emissive
  5778. this.map = null;
  5779. this.lightMap = null;
  5780. this.lightMapIntensity = 1.0;
  5781. this.aoMap = null;
  5782. this.aoMapIntensity = 1.0;
  5783. this.specularMap = null;
  5784. this.alphaMap = null;
  5785. this.envMap = null;
  5786. this.combine = MultiplyOperation;
  5787. this.reflectivity = 1;
  5788. this.refractionRatio = 0.98;
  5789. this.wireframe = false;
  5790. this.wireframeLinewidth = 1;
  5791. this.wireframeLinecap = 'round';
  5792. this.wireframeLinejoin = 'round';
  5793. this.fog = true;
  5794. this.setValues(parameters);
  5795. }
  5796. copy(source) {
  5797. super.copy(source);
  5798. this.color.copy(source.color);
  5799. this.map = source.map;
  5800. this.lightMap = source.lightMap;
  5801. this.lightMapIntensity = source.lightMapIntensity;
  5802. this.aoMap = source.aoMap;
  5803. this.aoMapIntensity = source.aoMapIntensity;
  5804. this.specularMap = source.specularMap;
  5805. this.alphaMap = source.alphaMap;
  5806. this.envMap = source.envMap;
  5807. this.combine = source.combine;
  5808. this.reflectivity = source.reflectivity;
  5809. this.refractionRatio = source.refractionRatio;
  5810. this.wireframe = source.wireframe;
  5811. this.wireframeLinewidth = source.wireframeLinewidth;
  5812. this.wireframeLinecap = source.wireframeLinecap;
  5813. this.wireframeLinejoin = source.wireframeLinejoin;
  5814. this.fog = source.fog;
  5815. return this;
  5816. }
  5817. }
  5818. const _vector$9 = /*@__PURE__*/new Vector3();
  5819. const _vector2$1 = /*@__PURE__*/new Vector2();
  5820. class BufferAttribute {
  5821. constructor(array, itemSize, normalized) {
  5822. if (Array.isArray(array)) {
  5823. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5824. }
  5825. this.isBufferAttribute = true;
  5826. this.name = '';
  5827. this.array = array;
  5828. this.itemSize = itemSize;
  5829. this.count = array !== undefined ? array.length / itemSize : 0;
  5830. this.normalized = normalized === true;
  5831. this.usage = StaticDrawUsage;
  5832. this.updateRange = {
  5833. offset: 0,
  5834. count: -1
  5835. };
  5836. this.version = 0;
  5837. }
  5838. onUploadCallback() {}
  5839. set needsUpdate(value) {
  5840. if (value === true) this.version++;
  5841. }
  5842. setUsage(value) {
  5843. this.usage = value;
  5844. return this;
  5845. }
  5846. copy(source) {
  5847. this.name = source.name;
  5848. this.array = new source.array.constructor(source.array);
  5849. this.itemSize = source.itemSize;
  5850. this.count = source.count;
  5851. this.normalized = source.normalized;
  5852. this.usage = source.usage;
  5853. return this;
  5854. }
  5855. copyAt(index1, attribute, index2) {
  5856. index1 *= this.itemSize;
  5857. index2 *= attribute.itemSize;
  5858. for (let i = 0, l = this.itemSize; i < l; i++) {
  5859. this.array[index1 + i] = attribute.array[index2 + i];
  5860. }
  5861. return this;
  5862. }
  5863. copyArray(array) {
  5864. this.array.set(array);
  5865. return this;
  5866. }
  5867. copyColorsArray(colors) {
  5868. const array = this.array;
  5869. let offset = 0;
  5870. for (let i = 0, l = colors.length; i < l; i++) {
  5871. let color = colors[i];
  5872. if (color === undefined) {
  5873. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5874. color = new Color();
  5875. }
  5876. if (this.normalized) {
  5877. array[offset++] = normalize(color.r, array);
  5878. array[offset++] = normalize(color.g, array);
  5879. array[offset++] = normalize(color.b, array);
  5880. } else {
  5881. array[offset++] = color.r;
  5882. array[offset++] = color.g;
  5883. array[offset++] = color.b;
  5884. }
  5885. }
  5886. return this;
  5887. }
  5888. copyVector2sArray(vectors) {
  5889. const array = this.array;
  5890. let offset = 0;
  5891. for (let i = 0, l = vectors.length; i < l; i++) {
  5892. let vector = vectors[i];
  5893. if (vector === undefined) {
  5894. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5895. vector = new Vector2();
  5896. }
  5897. if (this.normalized) {
  5898. array[offset++] = normalize(vector.x, array);
  5899. array[offset++] = normalize(vector.y, array);
  5900. } else {
  5901. array[offset++] = vector.x;
  5902. array[offset++] = vector.y;
  5903. }
  5904. }
  5905. return this;
  5906. }
  5907. copyVector3sArray(vectors) {
  5908. const array = this.array;
  5909. let offset = 0;
  5910. for (let i = 0, l = vectors.length; i < l; i++) {
  5911. let vector = vectors[i];
  5912. if (vector === undefined) {
  5913. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5914. vector = new Vector3();
  5915. }
  5916. if (this.normalized) {
  5917. array[offset++] = normalize(vector.x, array);
  5918. array[offset++] = normalize(vector.y, array);
  5919. array[offset++] = normalize(vector.z, array);
  5920. } else {
  5921. array[offset++] = vector.x;
  5922. array[offset++] = vector.y;
  5923. array[offset++] = vector.z;
  5924. }
  5925. }
  5926. return this;
  5927. }
  5928. copyVector4sArray(vectors) {
  5929. const array = this.array;
  5930. let offset = 0;
  5931. for (let i = 0, l = vectors.length; i < l; i++) {
  5932. let vector = vectors[i];
  5933. if (vector === undefined) {
  5934. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5935. vector = new Vector4();
  5936. }
  5937. if (this.normalized) {
  5938. array[offset++] = normalize(vector.x, array);
  5939. array[offset++] = normalize(vector.y, array);
  5940. array[offset++] = normalize(vector.z, array);
  5941. array[offset++] = normalize(vector.w, array);
  5942. } else {
  5943. array[offset++] = vector.x;
  5944. array[offset++] = vector.y;
  5945. array[offset++] = vector.z;
  5946. array[offset++] = vector.w;
  5947. }
  5948. }
  5949. return this;
  5950. }
  5951. applyMatrix3(m) {
  5952. if (this.itemSize === 2) {
  5953. for (let i = 0, l = this.count; i < l; i++) {
  5954. _vector2$1.fromBufferAttribute(this, i);
  5955. _vector2$1.applyMatrix3(m);
  5956. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5957. }
  5958. } else if (this.itemSize === 3) {
  5959. for (let i = 0, l = this.count; i < l; i++) {
  5960. _vector$9.fromBufferAttribute(this, i);
  5961. _vector$9.applyMatrix3(m);
  5962. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5963. }
  5964. }
  5965. return this;
  5966. }
  5967. applyMatrix4(m) {
  5968. for (let i = 0, l = this.count; i < l; i++) {
  5969. _vector$9.fromBufferAttribute(this, i);
  5970. _vector$9.applyMatrix4(m);
  5971. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5972. }
  5973. return this;
  5974. }
  5975. applyNormalMatrix(m) {
  5976. for (let i = 0, l = this.count; i < l; i++) {
  5977. _vector$9.fromBufferAttribute(this, i);
  5978. _vector$9.applyNormalMatrix(m);
  5979. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5980. }
  5981. return this;
  5982. }
  5983. transformDirection(m) {
  5984. for (let i = 0, l = this.count; i < l; i++) {
  5985. _vector$9.fromBufferAttribute(this, i);
  5986. _vector$9.transformDirection(m);
  5987. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5988. }
  5989. return this;
  5990. }
  5991. set(value, offset = 0) {
  5992. const array = this.array;
  5993. const normalized = this.normalized;
  5994. if (normalized) value = value.map(v => normalize(v, array));
  5995. array.set(value, offset);
  5996. return this;
  5997. }
  5998. getX(index) {
  5999. let x = this.array[index * this.itemSize];
  6000. if (this.normalized) x = denormalize(x, this.array);
  6001. return x;
  6002. }
  6003. setX(index, x) {
  6004. if (this.normalized) x = normalize(x, this.array);
  6005. this.array[index * this.itemSize] = x;
  6006. return this;
  6007. }
  6008. getY(index) {
  6009. let y = this.array[index * this.itemSize + 1];
  6010. if (this.normalized) y = denormalize(y, this.array);
  6011. return y;
  6012. }
  6013. setY(index, y) {
  6014. if (this.normalized) y = normalize(y, this.array);
  6015. this.array[index * this.itemSize + 1] = y;
  6016. return this;
  6017. }
  6018. getZ(index) {
  6019. let z = this.array[index * this.itemSize + 2];
  6020. if (this.normalized) z = denormalize(z, this.array);
  6021. return z;
  6022. }
  6023. setZ(index, z) {
  6024. if (this.normalized) z = normalize(z, this.array);
  6025. this.array[index * this.itemSize + 2] = z;
  6026. return this;
  6027. }
  6028. getW(index) {
  6029. let w = this.array[index * this.itemSize + 3];
  6030. if (this.normalized) w = denormalize(w, this.array);
  6031. return w;
  6032. }
  6033. setW(index, w) {
  6034. if (this.normalized) w = normalize(w, this.array);
  6035. this.array[index * this.itemSize + 3] = w;
  6036. return this;
  6037. }
  6038. setXY(index, x, y) {
  6039. index *= this.itemSize;
  6040. if (this.normalized) {
  6041. x = normalize(x, this.array);
  6042. y = normalize(y, this.array);
  6043. }
  6044. this.array[index + 0] = x;
  6045. this.array[index + 1] = y;
  6046. return this;
  6047. }
  6048. setXYZ(index, x, y, z) {
  6049. index *= this.itemSize;
  6050. if (this.normalized) {
  6051. x = normalize(x, this.array);
  6052. y = normalize(y, this.array);
  6053. z = normalize(z, this.array);
  6054. }
  6055. this.array[index + 0] = x;
  6056. this.array[index + 1] = y;
  6057. this.array[index + 2] = z;
  6058. return this;
  6059. }
  6060. setXYZW(index, x, y, z, w) {
  6061. index *= this.itemSize;
  6062. if (this.normalized) {
  6063. x = normalize(x, this.array);
  6064. y = normalize(y, this.array);
  6065. z = normalize(z, this.array);
  6066. w = normalize(w, this.array);
  6067. }
  6068. this.array[index + 0] = x;
  6069. this.array[index + 1] = y;
  6070. this.array[index + 2] = z;
  6071. this.array[index + 3] = w;
  6072. return this;
  6073. }
  6074. onUpload(callback) {
  6075. this.onUploadCallback = callback;
  6076. return this;
  6077. }
  6078. clone() {
  6079. return new this.constructor(this.array, this.itemSize).copy(this);
  6080. }
  6081. toJSON() {
  6082. const data = {
  6083. itemSize: this.itemSize,
  6084. type: this.array.constructor.name,
  6085. array: Array.from(this.array),
  6086. normalized: this.normalized
  6087. };
  6088. if (this.name !== '') data.name = this.name;
  6089. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6090. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6091. return data;
  6092. }
  6093. } //
  6094. class Int8BufferAttribute extends BufferAttribute {
  6095. constructor(array, itemSize, normalized) {
  6096. super(new Int8Array(array), itemSize, normalized);
  6097. }
  6098. }
  6099. class Uint8BufferAttribute extends BufferAttribute {
  6100. constructor(array, itemSize, normalized) {
  6101. super(new Uint8Array(array), itemSize, normalized);
  6102. }
  6103. }
  6104. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6105. constructor(array, itemSize, normalized) {
  6106. super(new Uint8ClampedArray(array), itemSize, normalized);
  6107. }
  6108. }
  6109. class Int16BufferAttribute extends BufferAttribute {
  6110. constructor(array, itemSize, normalized) {
  6111. super(new Int16Array(array), itemSize, normalized);
  6112. }
  6113. }
  6114. class Uint16BufferAttribute extends BufferAttribute {
  6115. constructor(array, itemSize, normalized) {
  6116. super(new Uint16Array(array), itemSize, normalized);
  6117. }
  6118. }
  6119. class Int32BufferAttribute extends BufferAttribute {
  6120. constructor(array, itemSize, normalized) {
  6121. super(new Int32Array(array), itemSize, normalized);
  6122. }
  6123. }
  6124. class Uint32BufferAttribute extends BufferAttribute {
  6125. constructor(array, itemSize, normalized) {
  6126. super(new Uint32Array(array), itemSize, normalized);
  6127. }
  6128. }
  6129. class Float16BufferAttribute extends BufferAttribute {
  6130. constructor(array, itemSize, normalized) {
  6131. super(new Uint16Array(array), itemSize, normalized);
  6132. this.isFloat16BufferAttribute = true;
  6133. }
  6134. }
  6135. class Float32BufferAttribute extends BufferAttribute {
  6136. constructor(array, itemSize, normalized) {
  6137. super(new Float32Array(array), itemSize, normalized);
  6138. }
  6139. }
  6140. class Float64BufferAttribute extends BufferAttribute {
  6141. constructor(array, itemSize, normalized) {
  6142. super(new Float64Array(array), itemSize, normalized);
  6143. }
  6144. } //
  6145. let _id$1 = 0;
  6146. const _m1 = /*@__PURE__*/new Matrix4();
  6147. const _obj = /*@__PURE__*/new Object3D();
  6148. const _offset = /*@__PURE__*/new Vector3();
  6149. const _box$1 = /*@__PURE__*/new Box3();
  6150. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6151. const _vector$8 = /*@__PURE__*/new Vector3();
  6152. class BufferGeometry extends EventDispatcher {
  6153. constructor() {
  6154. super();
  6155. this.isBufferGeometry = true;
  6156. Object.defineProperty(this, 'id', {
  6157. value: _id$1++
  6158. });
  6159. this.uuid = generateUUID();
  6160. this.name = '';
  6161. this.type = 'BufferGeometry';
  6162. this.index = null;
  6163. this.attributes = {};
  6164. this.morphAttributes = {};
  6165. this.morphTargetsRelative = false;
  6166. this.groups = [];
  6167. this.boundingBox = null;
  6168. this.boundingSphere = null;
  6169. this.drawRange = {
  6170. start: 0,
  6171. count: Infinity
  6172. };
  6173. this.userData = {};
  6174. }
  6175. getIndex() {
  6176. return this.index;
  6177. }
  6178. setIndex(index) {
  6179. if (Array.isArray(index)) {
  6180. this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6181. } else {
  6182. this.index = index;
  6183. }
  6184. return this;
  6185. }
  6186. getAttribute(name) {
  6187. return this.attributes[name];
  6188. }
  6189. setAttribute(name, attribute) {
  6190. this.attributes[name] = attribute;
  6191. return this;
  6192. }
  6193. deleteAttribute(name) {
  6194. delete this.attributes[name];
  6195. return this;
  6196. }
  6197. hasAttribute(name) {
  6198. return this.attributes[name] !== undefined;
  6199. }
  6200. addGroup(start, count, materialIndex = 0) {
  6201. this.groups.push({
  6202. start: start,
  6203. count: count,
  6204. materialIndex: materialIndex
  6205. });
  6206. }
  6207. clearGroups() {
  6208. this.groups = [];
  6209. }
  6210. setDrawRange(start, count) {
  6211. this.drawRange.start = start;
  6212. this.drawRange.count = count;
  6213. }
  6214. applyMatrix4(matrix) {
  6215. const position = this.attributes.position;
  6216. if (position !== undefined) {
  6217. position.applyMatrix4(matrix);
  6218. position.needsUpdate = true;
  6219. }
  6220. const normal = this.attributes.normal;
  6221. if (normal !== undefined) {
  6222. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6223. normal.applyNormalMatrix(normalMatrix);
  6224. normal.needsUpdate = true;
  6225. }
  6226. const tangent = this.attributes.tangent;
  6227. if (tangent !== undefined) {
  6228. tangent.transformDirection(matrix);
  6229. tangent.needsUpdate = true;
  6230. }
  6231. if (this.boundingBox !== null) {
  6232. this.computeBoundingBox();
  6233. }
  6234. if (this.boundingSphere !== null) {
  6235. this.computeBoundingSphere();
  6236. }
  6237. return this;
  6238. }
  6239. applyQuaternion(q) {
  6240. _m1.makeRotationFromQuaternion(q);
  6241. this.applyMatrix4(_m1);
  6242. return this;
  6243. }
  6244. rotateX(angle) {
  6245. // rotate geometry around world x-axis
  6246. _m1.makeRotationX(angle);
  6247. this.applyMatrix4(_m1);
  6248. return this;
  6249. }
  6250. rotateY(angle) {
  6251. // rotate geometry around world y-axis
  6252. _m1.makeRotationY(angle);
  6253. this.applyMatrix4(_m1);
  6254. return this;
  6255. }
  6256. rotateZ(angle) {
  6257. // rotate geometry around world z-axis
  6258. _m1.makeRotationZ(angle);
  6259. this.applyMatrix4(_m1);
  6260. return this;
  6261. }
  6262. translate(x, y, z) {
  6263. // translate geometry
  6264. _m1.makeTranslation(x, y, z);
  6265. this.applyMatrix4(_m1);
  6266. return this;
  6267. }
  6268. scale(x, y, z) {
  6269. // scale geometry
  6270. _m1.makeScale(x, y, z);
  6271. this.applyMatrix4(_m1);
  6272. return this;
  6273. }
  6274. lookAt(vector) {
  6275. _obj.lookAt(vector);
  6276. _obj.updateMatrix();
  6277. this.applyMatrix4(_obj.matrix);
  6278. return this;
  6279. }
  6280. center() {
  6281. this.computeBoundingBox();
  6282. this.boundingBox.getCenter(_offset).negate();
  6283. this.translate(_offset.x, _offset.y, _offset.z);
  6284. return this;
  6285. }
  6286. setFromPoints(points) {
  6287. const position = [];
  6288. for (let i = 0, l = points.length; i < l; i++) {
  6289. const point = points[i];
  6290. position.push(point.x, point.y, point.z || 0);
  6291. }
  6292. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6293. return this;
  6294. }
  6295. computeBoundingBox() {
  6296. if (this.boundingBox === null) {
  6297. this.boundingBox = new Box3();
  6298. }
  6299. const position = this.attributes.position;
  6300. const morphAttributesPosition = this.morphAttributes.position;
  6301. if (position && position.isGLBufferAttribute) {
  6302. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6303. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6304. return;
  6305. }
  6306. if (position !== undefined) {
  6307. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6308. if (morphAttributesPosition) {
  6309. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6310. const morphAttribute = morphAttributesPosition[i];
  6311. _box$1.setFromBufferAttribute(morphAttribute);
  6312. if (this.morphTargetsRelative) {
  6313. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6314. this.boundingBox.expandByPoint(_vector$8);
  6315. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6316. this.boundingBox.expandByPoint(_vector$8);
  6317. } else {
  6318. this.boundingBox.expandByPoint(_box$1.min);
  6319. this.boundingBox.expandByPoint(_box$1.max);
  6320. }
  6321. }
  6322. }
  6323. } else {
  6324. this.boundingBox.makeEmpty();
  6325. }
  6326. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6327. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6328. }
  6329. }
  6330. computeBoundingSphere() {
  6331. if (this.boundingSphere === null) {
  6332. this.boundingSphere = new Sphere();
  6333. }
  6334. const position = this.attributes.position;
  6335. const morphAttributesPosition = this.morphAttributes.position;
  6336. if (position && position.isGLBufferAttribute) {
  6337. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6338. this.boundingSphere.set(new Vector3(), Infinity);
  6339. return;
  6340. }
  6341. if (position) {
  6342. // first, find the center of the bounding sphere
  6343. const center = this.boundingSphere.center;
  6344. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6345. if (morphAttributesPosition) {
  6346. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6347. const morphAttribute = morphAttributesPosition[i];
  6348. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6349. if (this.morphTargetsRelative) {
  6350. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6351. _box$1.expandByPoint(_vector$8);
  6352. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6353. _box$1.expandByPoint(_vector$8);
  6354. } else {
  6355. _box$1.expandByPoint(_boxMorphTargets.min);
  6356. _box$1.expandByPoint(_boxMorphTargets.max);
  6357. }
  6358. }
  6359. }
  6360. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6361. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6362. let maxRadiusSq = 0;
  6363. for (let i = 0, il = position.count; i < il; i++) {
  6364. _vector$8.fromBufferAttribute(position, i);
  6365. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6366. } // process morph attributes if present
  6367. if (morphAttributesPosition) {
  6368. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6369. const morphAttribute = morphAttributesPosition[i];
  6370. const morphTargetsRelative = this.morphTargetsRelative;
  6371. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6372. _vector$8.fromBufferAttribute(morphAttribute, j);
  6373. if (morphTargetsRelative) {
  6374. _offset.fromBufferAttribute(position, j);
  6375. _vector$8.add(_offset);
  6376. }
  6377. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6378. }
  6379. }
  6380. }
  6381. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6382. if (isNaN(this.boundingSphere.radius)) {
  6383. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6384. }
  6385. }
  6386. }
  6387. computeTangents() {
  6388. const index = this.index;
  6389. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6390. // (per vertex tangents)
  6391. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6392. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6393. return;
  6394. }
  6395. const indices = index.array;
  6396. const positions = attributes.position.array;
  6397. const normals = attributes.normal.array;
  6398. const uvs = attributes.uv.array;
  6399. const nVertices = positions.length / 3;
  6400. if (this.hasAttribute('tangent') === false) {
  6401. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6402. }
  6403. const tangents = this.getAttribute('tangent').array;
  6404. const tan1 = [],
  6405. tan2 = [];
  6406. for (let i = 0; i < nVertices; i++) {
  6407. tan1[i] = new Vector3();
  6408. tan2[i] = new Vector3();
  6409. }
  6410. const vA = new Vector3(),
  6411. vB = new Vector3(),
  6412. vC = new Vector3(),
  6413. uvA = new Vector2(),
  6414. uvB = new Vector2(),
  6415. uvC = new Vector2(),
  6416. sdir = new Vector3(),
  6417. tdir = new Vector3();
  6418. function handleTriangle(a, b, c) {
  6419. vA.fromArray(positions, a * 3);
  6420. vB.fromArray(positions, b * 3);
  6421. vC.fromArray(positions, c * 3);
  6422. uvA.fromArray(uvs, a * 2);
  6423. uvB.fromArray(uvs, b * 2);
  6424. uvC.fromArray(uvs, c * 2);
  6425. vB.sub(vA);
  6426. vC.sub(vA);
  6427. uvB.sub(uvA);
  6428. uvC.sub(uvA);
  6429. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6430. if (!isFinite(r)) return;
  6431. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6432. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6433. tan1[a].add(sdir);
  6434. tan1[b].add(sdir);
  6435. tan1[c].add(sdir);
  6436. tan2[a].add(tdir);
  6437. tan2[b].add(tdir);
  6438. tan2[c].add(tdir);
  6439. }
  6440. let groups = this.groups;
  6441. if (groups.length === 0) {
  6442. groups = [{
  6443. start: 0,
  6444. count: indices.length
  6445. }];
  6446. }
  6447. for (let i = 0, il = groups.length; i < il; ++i) {
  6448. const group = groups[i];
  6449. const start = group.start;
  6450. const count = group.count;
  6451. for (let j = start, jl = start + count; j < jl; j += 3) {
  6452. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6453. }
  6454. }
  6455. const tmp = new Vector3(),
  6456. tmp2 = new Vector3();
  6457. const n = new Vector3(),
  6458. n2 = new Vector3();
  6459. function handleVertex(v) {
  6460. n.fromArray(normals, v * 3);
  6461. n2.copy(n);
  6462. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6463. tmp.copy(t);
  6464. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6465. tmp2.crossVectors(n2, t);
  6466. const test = tmp2.dot(tan2[v]);
  6467. const w = test < 0.0 ? -1.0 : 1.0;
  6468. tangents[v * 4] = tmp.x;
  6469. tangents[v * 4 + 1] = tmp.y;
  6470. tangents[v * 4 + 2] = tmp.z;
  6471. tangents[v * 4 + 3] = w;
  6472. }
  6473. for (let i = 0, il = groups.length; i < il; ++i) {
  6474. const group = groups[i];
  6475. const start = group.start;
  6476. const count = group.count;
  6477. for (let j = start, jl = start + count; j < jl; j += 3) {
  6478. handleVertex(indices[j + 0]);
  6479. handleVertex(indices[j + 1]);
  6480. handleVertex(indices[j + 2]);
  6481. }
  6482. }
  6483. }
  6484. computeVertexNormals() {
  6485. const index = this.index;
  6486. const positionAttribute = this.getAttribute('position');
  6487. if (positionAttribute !== undefined) {
  6488. let normalAttribute = this.getAttribute('normal');
  6489. if (normalAttribute === undefined) {
  6490. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6491. this.setAttribute('normal', normalAttribute);
  6492. } else {
  6493. // reset existing normals to zero
  6494. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6495. normalAttribute.setXYZ(i, 0, 0, 0);
  6496. }
  6497. }
  6498. const pA = new Vector3(),
  6499. pB = new Vector3(),
  6500. pC = new Vector3();
  6501. const nA = new Vector3(),
  6502. nB = new Vector3(),
  6503. nC = new Vector3();
  6504. const cb = new Vector3(),
  6505. ab = new Vector3(); // indexed elements
  6506. if (index) {
  6507. for (let i = 0, il = index.count; i < il; i += 3) {
  6508. const vA = index.getX(i + 0);
  6509. const vB = index.getX(i + 1);
  6510. const vC = index.getX(i + 2);
  6511. pA.fromBufferAttribute(positionAttribute, vA);
  6512. pB.fromBufferAttribute(positionAttribute, vB);
  6513. pC.fromBufferAttribute(positionAttribute, vC);
  6514. cb.subVectors(pC, pB);
  6515. ab.subVectors(pA, pB);
  6516. cb.cross(ab);
  6517. nA.fromBufferAttribute(normalAttribute, vA);
  6518. nB.fromBufferAttribute(normalAttribute, vB);
  6519. nC.fromBufferAttribute(normalAttribute, vC);
  6520. nA.add(cb);
  6521. nB.add(cb);
  6522. nC.add(cb);
  6523. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6524. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6525. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6526. }
  6527. } else {
  6528. // non-indexed elements (unconnected triangle soup)
  6529. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6530. pA.fromBufferAttribute(positionAttribute, i + 0);
  6531. pB.fromBufferAttribute(positionAttribute, i + 1);
  6532. pC.fromBufferAttribute(positionAttribute, i + 2);
  6533. cb.subVectors(pC, pB);
  6534. ab.subVectors(pA, pB);
  6535. cb.cross(ab);
  6536. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6537. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6538. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6539. }
  6540. }
  6541. this.normalizeNormals();
  6542. normalAttribute.needsUpdate = true;
  6543. }
  6544. } // @deprecated since r144
  6545. merge() {
  6546. console.error('THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.');
  6547. return this;
  6548. }
  6549. normalizeNormals() {
  6550. const normals = this.attributes.normal;
  6551. for (let i = 0, il = normals.count; i < il; i++) {
  6552. _vector$8.fromBufferAttribute(normals, i);
  6553. _vector$8.normalize();
  6554. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6555. }
  6556. }
  6557. toNonIndexed() {
  6558. function convertBufferAttribute(attribute, indices) {
  6559. const array = attribute.array;
  6560. const itemSize = attribute.itemSize;
  6561. const normalized = attribute.normalized;
  6562. const array2 = new array.constructor(indices.length * itemSize);
  6563. let index = 0,
  6564. index2 = 0;
  6565. for (let i = 0, l = indices.length; i < l; i++) {
  6566. if (attribute.isInterleavedBufferAttribute) {
  6567. index = indices[i] * attribute.data.stride + attribute.offset;
  6568. } else {
  6569. index = indices[i] * itemSize;
  6570. }
  6571. for (let j = 0; j < itemSize; j++) {
  6572. array2[index2++] = array[index++];
  6573. }
  6574. }
  6575. return new BufferAttribute(array2, itemSize, normalized);
  6576. } //
  6577. if (this.index === null) {
  6578. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6579. return this;
  6580. }
  6581. const geometry2 = new BufferGeometry();
  6582. const indices = this.index.array;
  6583. const attributes = this.attributes; // attributes
  6584. for (const name in attributes) {
  6585. const attribute = attributes[name];
  6586. const newAttribute = convertBufferAttribute(attribute, indices);
  6587. geometry2.setAttribute(name, newAttribute);
  6588. } // morph attributes
  6589. const morphAttributes = this.morphAttributes;
  6590. for (const name in morphAttributes) {
  6591. const morphArray = [];
  6592. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6593. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6594. const attribute = morphAttribute[i];
  6595. const newAttribute = convertBufferAttribute(attribute, indices);
  6596. morphArray.push(newAttribute);
  6597. }
  6598. geometry2.morphAttributes[name] = morphArray;
  6599. }
  6600. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6601. const groups = this.groups;
  6602. for (let i = 0, l = groups.length; i < l; i++) {
  6603. const group = groups[i];
  6604. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6605. }
  6606. return geometry2;
  6607. }
  6608. toJSON() {
  6609. const data = {
  6610. metadata: {
  6611. version: 4.5,
  6612. type: 'BufferGeometry',
  6613. generator: 'BufferGeometry.toJSON'
  6614. }
  6615. }; // standard BufferGeometry serialization
  6616. data.uuid = this.uuid;
  6617. data.type = this.type;
  6618. if (this.name !== '') data.name = this.name;
  6619. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6620. if (this.parameters !== undefined) {
  6621. const parameters = this.parameters;
  6622. for (const key in parameters) {
  6623. if (parameters[key] !== undefined) data[key] = parameters[key];
  6624. }
  6625. return data;
  6626. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6627. data.data = {
  6628. attributes: {}
  6629. };
  6630. const index = this.index;
  6631. if (index !== null) {
  6632. data.data.index = {
  6633. type: index.array.constructor.name,
  6634. array: Array.prototype.slice.call(index.array)
  6635. };
  6636. }
  6637. const attributes = this.attributes;
  6638. for (const key in attributes) {
  6639. const attribute = attributes[key];
  6640. data.data.attributes[key] = attribute.toJSON(data.data);
  6641. }
  6642. const morphAttributes = {};
  6643. let hasMorphAttributes = false;
  6644. for (const key in this.morphAttributes) {
  6645. const attributeArray = this.morphAttributes[key];
  6646. const array = [];
  6647. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6648. const attribute = attributeArray[i];
  6649. array.push(attribute.toJSON(data.data));
  6650. }
  6651. if (array.length > 0) {
  6652. morphAttributes[key] = array;
  6653. hasMorphAttributes = true;
  6654. }
  6655. }
  6656. if (hasMorphAttributes) {
  6657. data.data.morphAttributes = morphAttributes;
  6658. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6659. }
  6660. const groups = this.groups;
  6661. if (groups.length > 0) {
  6662. data.data.groups = JSON.parse(JSON.stringify(groups));
  6663. }
  6664. const boundingSphere = this.boundingSphere;
  6665. if (boundingSphere !== null) {
  6666. data.data.boundingSphere = {
  6667. center: boundingSphere.center.toArray(),
  6668. radius: boundingSphere.radius
  6669. };
  6670. }
  6671. return data;
  6672. }
  6673. clone() {
  6674. return new this.constructor().copy(this);
  6675. }
  6676. copy(source) {
  6677. // reset
  6678. this.index = null;
  6679. this.attributes = {};
  6680. this.morphAttributes = {};
  6681. this.groups = [];
  6682. this.boundingBox = null;
  6683. this.boundingSphere = null; // used for storing cloned, shared data
  6684. const data = {}; // name
  6685. this.name = source.name; // index
  6686. const index = source.index;
  6687. if (index !== null) {
  6688. this.setIndex(index.clone(data));
  6689. } // attributes
  6690. const attributes = source.attributes;
  6691. for (const name in attributes) {
  6692. const attribute = attributes[name];
  6693. this.setAttribute(name, attribute.clone(data));
  6694. } // morph attributes
  6695. const morphAttributes = source.morphAttributes;
  6696. for (const name in morphAttributes) {
  6697. const array = [];
  6698. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6699. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6700. array.push(morphAttribute[i].clone(data));
  6701. }
  6702. this.morphAttributes[name] = array;
  6703. }
  6704. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6705. const groups = source.groups;
  6706. for (let i = 0, l = groups.length; i < l; i++) {
  6707. const group = groups[i];
  6708. this.addGroup(group.start, group.count, group.materialIndex);
  6709. } // bounding box
  6710. const boundingBox = source.boundingBox;
  6711. if (boundingBox !== null) {
  6712. this.boundingBox = boundingBox.clone();
  6713. } // bounding sphere
  6714. const boundingSphere = source.boundingSphere;
  6715. if (boundingSphere !== null) {
  6716. this.boundingSphere = boundingSphere.clone();
  6717. } // draw range
  6718. this.drawRange.start = source.drawRange.start;
  6719. this.drawRange.count = source.drawRange.count; // user data
  6720. this.userData = source.userData; // geometry generator parameters
  6721. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6722. return this;
  6723. }
  6724. dispose() {
  6725. this.dispatchEvent({
  6726. type: 'dispose'
  6727. });
  6728. }
  6729. }
  6730. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6731. const _ray$2 = /*@__PURE__*/new Ray();
  6732. const _sphere$3 = /*@__PURE__*/new Sphere();
  6733. const _vA$1 = /*@__PURE__*/new Vector3();
  6734. const _vB$1 = /*@__PURE__*/new Vector3();
  6735. const _vC$1 = /*@__PURE__*/new Vector3();
  6736. const _tempA = /*@__PURE__*/new Vector3();
  6737. const _tempB = /*@__PURE__*/new Vector3();
  6738. const _tempC = /*@__PURE__*/new Vector3();
  6739. const _morphA = /*@__PURE__*/new Vector3();
  6740. const _morphB = /*@__PURE__*/new Vector3();
  6741. const _morphC = /*@__PURE__*/new Vector3();
  6742. const _uvA$1 = /*@__PURE__*/new Vector2();
  6743. const _uvB$1 = /*@__PURE__*/new Vector2();
  6744. const _uvC$1 = /*@__PURE__*/new Vector2();
  6745. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6746. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6747. class Mesh extends Object3D {
  6748. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6749. super();
  6750. this.isMesh = true;
  6751. this.type = 'Mesh';
  6752. this.geometry = geometry;
  6753. this.material = material;
  6754. this.updateMorphTargets();
  6755. }
  6756. copy(source, recursive) {
  6757. super.copy(source, recursive);
  6758. if (source.morphTargetInfluences !== undefined) {
  6759. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6760. }
  6761. if (source.morphTargetDictionary !== undefined) {
  6762. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6763. }
  6764. this.material = source.material;
  6765. this.geometry = source.geometry;
  6766. return this;
  6767. }
  6768. updateMorphTargets() {
  6769. const geometry = this.geometry;
  6770. const morphAttributes = geometry.morphAttributes;
  6771. const keys = Object.keys(morphAttributes);
  6772. if (keys.length > 0) {
  6773. const morphAttribute = morphAttributes[keys[0]];
  6774. if (morphAttribute !== undefined) {
  6775. this.morphTargetInfluences = [];
  6776. this.morphTargetDictionary = {};
  6777. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6778. const name = morphAttribute[m].name || String(m);
  6779. this.morphTargetInfluences.push(0);
  6780. this.morphTargetDictionary[name] = m;
  6781. }
  6782. }
  6783. }
  6784. }
  6785. raycast(raycaster, intersects) {
  6786. const geometry = this.geometry;
  6787. const material = this.material;
  6788. const matrixWorld = this.matrixWorld;
  6789. if (material === undefined) return; // Checking boundingSphere distance to ray
  6790. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6791. _sphere$3.copy(geometry.boundingSphere);
  6792. _sphere$3.applyMatrix4(matrixWorld);
  6793. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6794. _inverseMatrix$2.copy(matrixWorld).invert();
  6795. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6796. if (geometry.boundingBox !== null) {
  6797. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6798. }
  6799. let intersection;
  6800. const index = geometry.index;
  6801. const position = geometry.attributes.position;
  6802. const morphPosition = geometry.morphAttributes.position;
  6803. const morphTargetsRelative = geometry.morphTargetsRelative;
  6804. const uv = geometry.attributes.uv;
  6805. const uv2 = geometry.attributes.uv2;
  6806. const groups = geometry.groups;
  6807. const drawRange = geometry.drawRange;
  6808. if (index !== null) {
  6809. // indexed buffer geometry
  6810. if (Array.isArray(material)) {
  6811. for (let i = 0, il = groups.length; i < il; i++) {
  6812. const group = groups[i];
  6813. const groupMaterial = material[group.materialIndex];
  6814. const start = Math.max(group.start, drawRange.start);
  6815. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6816. for (let j = start, jl = end; j < jl; j += 3) {
  6817. const a = index.getX(j);
  6818. const b = index.getX(j + 1);
  6819. const c = index.getX(j + 2);
  6820. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6821. if (intersection) {
  6822. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6823. intersection.face.materialIndex = group.materialIndex;
  6824. intersects.push(intersection);
  6825. }
  6826. }
  6827. }
  6828. } else {
  6829. const start = Math.max(0, drawRange.start);
  6830. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6831. for (let i = start, il = end; i < il; i += 3) {
  6832. const a = index.getX(i);
  6833. const b = index.getX(i + 1);
  6834. const c = index.getX(i + 2);
  6835. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6836. if (intersection) {
  6837. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6838. intersects.push(intersection);
  6839. }
  6840. }
  6841. }
  6842. } else if (position !== undefined) {
  6843. // non-indexed buffer geometry
  6844. if (Array.isArray(material)) {
  6845. for (let i = 0, il = groups.length; i < il; i++) {
  6846. const group = groups[i];
  6847. const groupMaterial = material[group.materialIndex];
  6848. const start = Math.max(group.start, drawRange.start);
  6849. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6850. for (let j = start, jl = end; j < jl; j += 3) {
  6851. const a = j;
  6852. const b = j + 1;
  6853. const c = j + 2;
  6854. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6855. if (intersection) {
  6856. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6857. intersection.face.materialIndex = group.materialIndex;
  6858. intersects.push(intersection);
  6859. }
  6860. }
  6861. }
  6862. } else {
  6863. const start = Math.max(0, drawRange.start);
  6864. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6865. for (let i = start, il = end; i < il; i += 3) {
  6866. const a = i;
  6867. const b = i + 1;
  6868. const c = i + 2;
  6869. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6870. if (intersection) {
  6871. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6872. intersects.push(intersection);
  6873. }
  6874. }
  6875. }
  6876. }
  6877. }
  6878. }
  6879. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6880. let intersect;
  6881. if (material.side === BackSide) {
  6882. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6883. } else {
  6884. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6885. }
  6886. if (intersect === null) return null;
  6887. _intersectionPointWorld.copy(point);
  6888. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6889. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6890. if (distance < raycaster.near || distance > raycaster.far) return null;
  6891. return {
  6892. distance: distance,
  6893. point: _intersectionPointWorld.clone(),
  6894. object: object
  6895. };
  6896. }
  6897. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6898. _vA$1.fromBufferAttribute(position, a);
  6899. _vB$1.fromBufferAttribute(position, b);
  6900. _vC$1.fromBufferAttribute(position, c);
  6901. const morphInfluences = object.morphTargetInfluences;
  6902. if (morphPosition && morphInfluences) {
  6903. _morphA.set(0, 0, 0);
  6904. _morphB.set(0, 0, 0);
  6905. _morphC.set(0, 0, 0);
  6906. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6907. const influence = morphInfluences[i];
  6908. const morphAttribute = morphPosition[i];
  6909. if (influence === 0) continue;
  6910. _tempA.fromBufferAttribute(morphAttribute, a);
  6911. _tempB.fromBufferAttribute(morphAttribute, b);
  6912. _tempC.fromBufferAttribute(morphAttribute, c);
  6913. if (morphTargetsRelative) {
  6914. _morphA.addScaledVector(_tempA, influence);
  6915. _morphB.addScaledVector(_tempB, influence);
  6916. _morphC.addScaledVector(_tempC, influence);
  6917. } else {
  6918. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6919. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6920. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6921. }
  6922. }
  6923. _vA$1.add(_morphA);
  6924. _vB$1.add(_morphB);
  6925. _vC$1.add(_morphC);
  6926. }
  6927. if (object.isSkinnedMesh) {
  6928. object.boneTransform(a, _vA$1);
  6929. object.boneTransform(b, _vB$1);
  6930. object.boneTransform(c, _vC$1);
  6931. }
  6932. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6933. if (intersection) {
  6934. if (uv) {
  6935. _uvA$1.fromBufferAttribute(uv, a);
  6936. _uvB$1.fromBufferAttribute(uv, b);
  6937. _uvC$1.fromBufferAttribute(uv, c);
  6938. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6939. }
  6940. if (uv2) {
  6941. _uvA$1.fromBufferAttribute(uv2, a);
  6942. _uvB$1.fromBufferAttribute(uv2, b);
  6943. _uvC$1.fromBufferAttribute(uv2, c);
  6944. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6945. }
  6946. const face = {
  6947. a: a,
  6948. b: b,
  6949. c: c,
  6950. normal: new Vector3(),
  6951. materialIndex: 0
  6952. };
  6953. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6954. intersection.face = face;
  6955. }
  6956. return intersection;
  6957. }
  6958. class BoxGeometry extends BufferGeometry {
  6959. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6960. super();
  6961. this.type = 'BoxGeometry';
  6962. this.parameters = {
  6963. width: width,
  6964. height: height,
  6965. depth: depth,
  6966. widthSegments: widthSegments,
  6967. heightSegments: heightSegments,
  6968. depthSegments: depthSegments
  6969. };
  6970. const scope = this; // segments
  6971. widthSegments = Math.floor(widthSegments);
  6972. heightSegments = Math.floor(heightSegments);
  6973. depthSegments = Math.floor(depthSegments); // buffers
  6974. const indices = [];
  6975. const vertices = [];
  6976. const normals = [];
  6977. const uvs = []; // helper variables
  6978. let numberOfVertices = 0;
  6979. let groupStart = 0; // build each side of the box geometry
  6980. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6981. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6982. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6983. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6984. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6985. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6986. // build geometry
  6987. this.setIndex(indices);
  6988. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6989. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6990. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6991. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6992. const segmentWidth = width / gridX;
  6993. const segmentHeight = height / gridY;
  6994. const widthHalf = width / 2;
  6995. const heightHalf = height / 2;
  6996. const depthHalf = depth / 2;
  6997. const gridX1 = gridX + 1;
  6998. const gridY1 = gridY + 1;
  6999. let vertexCounter = 0;
  7000. let groupCount = 0;
  7001. const vector = new Vector3(); // generate vertices, normals and uvs
  7002. for (let iy = 0; iy < gridY1; iy++) {
  7003. const y = iy * segmentHeight - heightHalf;
  7004. for (let ix = 0; ix < gridX1; ix++) {
  7005. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7006. vector[u] = x * udir;
  7007. vector[v] = y * vdir;
  7008. vector[w] = depthHalf; // now apply vector to vertex buffer
  7009. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7010. vector[u] = 0;
  7011. vector[v] = 0;
  7012. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7013. normals.push(vector.x, vector.y, vector.z); // uvs
  7014. uvs.push(ix / gridX);
  7015. uvs.push(1 - iy / gridY); // counters
  7016. vertexCounter += 1;
  7017. }
  7018. } // indices
  7019. // 1. you need three indices to draw a single face
  7020. // 2. a single segment consists of two faces
  7021. // 3. so we need to generate six (2*3) indices per segment
  7022. for (let iy = 0; iy < gridY; iy++) {
  7023. for (let ix = 0; ix < gridX; ix++) {
  7024. const a = numberOfVertices + ix + gridX1 * iy;
  7025. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7026. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7027. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7028. indices.push(a, b, d);
  7029. indices.push(b, c, d); // increase counter
  7030. groupCount += 6;
  7031. }
  7032. } // add a group to the geometry. this will ensure multi material support
  7033. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7034. groupStart += groupCount; // update total number of vertices
  7035. numberOfVertices += vertexCounter;
  7036. }
  7037. }
  7038. static fromJSON(data) {
  7039. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  7040. }
  7041. }
  7042. /**
  7043. * Uniform Utilities
  7044. */
  7045. function cloneUniforms(src) {
  7046. const dst = {};
  7047. for (const u in src) {
  7048. dst[u] = {};
  7049. for (const p in src[u]) {
  7050. const property = src[u][p];
  7051. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7052. dst[u][p] = property.clone();
  7053. } else if (Array.isArray(property)) {
  7054. dst[u][p] = property.slice();
  7055. } else {
  7056. dst[u][p] = property;
  7057. }
  7058. }
  7059. }
  7060. return dst;
  7061. }
  7062. function mergeUniforms(uniforms) {
  7063. const merged = {};
  7064. for (let u = 0; u < uniforms.length; u++) {
  7065. const tmp = cloneUniforms(uniforms[u]);
  7066. for (const p in tmp) {
  7067. merged[p] = tmp[p];
  7068. }
  7069. }
  7070. return merged;
  7071. }
  7072. function cloneUniformsGroups(src) {
  7073. const dst = [];
  7074. for (let u = 0; u < src.length; u++) {
  7075. dst.push(src[u].clone());
  7076. }
  7077. return dst;
  7078. } // Legacy
  7079. const UniformsUtils = {
  7080. clone: cloneUniforms,
  7081. merge: mergeUniforms
  7082. };
  7083. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7084. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7085. class ShaderMaterial extends Material {
  7086. constructor(parameters) {
  7087. super();
  7088. this.isShaderMaterial = true;
  7089. this.type = 'ShaderMaterial';
  7090. this.defines = {};
  7091. this.uniforms = {};
  7092. this.uniformsGroups = [];
  7093. this.vertexShader = default_vertex;
  7094. this.fragmentShader = default_fragment;
  7095. this.linewidth = 1;
  7096. this.wireframe = false;
  7097. this.wireframeLinewidth = 1;
  7098. this.fog = false; // set to use scene fog
  7099. this.lights = false; // set to use scene lights
  7100. this.clipping = false; // set to use user-defined clipping planes
  7101. this.extensions = {
  7102. derivatives: false,
  7103. // set to use derivatives
  7104. fragDepth: false,
  7105. // set to use fragment depth values
  7106. drawBuffers: false,
  7107. // set to use draw buffers
  7108. shaderTextureLOD: false // set to use shader texture LOD
  7109. }; // When rendered geometry doesn't include these attributes but the material does,
  7110. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7111. this.defaultAttributeValues = {
  7112. 'color': [1, 1, 1],
  7113. 'uv': [0, 0],
  7114. 'uv2': [0, 0]
  7115. };
  7116. this.index0AttributeName = undefined;
  7117. this.uniformsNeedUpdate = false;
  7118. this.glslVersion = null;
  7119. if (parameters !== undefined) {
  7120. this.setValues(parameters);
  7121. }
  7122. }
  7123. copy(source) {
  7124. super.copy(source);
  7125. this.fragmentShader = source.fragmentShader;
  7126. this.vertexShader = source.vertexShader;
  7127. this.uniforms = cloneUniforms(source.uniforms);
  7128. this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups);
  7129. this.defines = Object.assign({}, source.defines);
  7130. this.wireframe = source.wireframe;
  7131. this.wireframeLinewidth = source.wireframeLinewidth;
  7132. this.fog = source.fog;
  7133. this.lights = source.lights;
  7134. this.clipping = source.clipping;
  7135. this.extensions = Object.assign({}, source.extensions);
  7136. this.glslVersion = source.glslVersion;
  7137. return this;
  7138. }
  7139. toJSON(meta) {
  7140. const data = super.toJSON(meta);
  7141. data.glslVersion = this.glslVersion;
  7142. data.uniforms = {};
  7143. for (const name in this.uniforms) {
  7144. const uniform = this.uniforms[name];
  7145. const value = uniform.value;
  7146. if (value && value.isTexture) {
  7147. data.uniforms[name] = {
  7148. type: 't',
  7149. value: value.toJSON(meta).uuid
  7150. };
  7151. } else if (value && value.isColor) {
  7152. data.uniforms[name] = {
  7153. type: 'c',
  7154. value: value.getHex()
  7155. };
  7156. } else if (value && value.isVector2) {
  7157. data.uniforms[name] = {
  7158. type: 'v2',
  7159. value: value.toArray()
  7160. };
  7161. } else if (value && value.isVector3) {
  7162. data.uniforms[name] = {
  7163. type: 'v3',
  7164. value: value.toArray()
  7165. };
  7166. } else if (value && value.isVector4) {
  7167. data.uniforms[name] = {
  7168. type: 'v4',
  7169. value: value.toArray()
  7170. };
  7171. } else if (value && value.isMatrix3) {
  7172. data.uniforms[name] = {
  7173. type: 'm3',
  7174. value: value.toArray()
  7175. };
  7176. } else if (value && value.isMatrix4) {
  7177. data.uniforms[name] = {
  7178. type: 'm4',
  7179. value: value.toArray()
  7180. };
  7181. } else {
  7182. data.uniforms[name] = {
  7183. value: value
  7184. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7185. }
  7186. }
  7187. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7188. data.vertexShader = this.vertexShader;
  7189. data.fragmentShader = this.fragmentShader;
  7190. const extensions = {};
  7191. for (const key in this.extensions) {
  7192. if (this.extensions[key] === true) extensions[key] = true;
  7193. }
  7194. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7195. return data;
  7196. }
  7197. }
  7198. class Camera extends Object3D {
  7199. constructor() {
  7200. super();
  7201. this.isCamera = true;
  7202. this.type = 'Camera';
  7203. this.matrixWorldInverse = new Matrix4();
  7204. this.projectionMatrix = new Matrix4();
  7205. this.projectionMatrixInverse = new Matrix4();
  7206. }
  7207. copy(source, recursive) {
  7208. super.copy(source, recursive);
  7209. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7210. this.projectionMatrix.copy(source.projectionMatrix);
  7211. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7212. return this;
  7213. }
  7214. getWorldDirection(target) {
  7215. this.updateWorldMatrix(true, false);
  7216. const e = this.matrixWorld.elements;
  7217. return target.set(-e[8], -e[9], -e[10]).normalize();
  7218. }
  7219. updateMatrixWorld(force) {
  7220. super.updateMatrixWorld(force);
  7221. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7222. }
  7223. updateWorldMatrix(updateParents, updateChildren) {
  7224. super.updateWorldMatrix(updateParents, updateChildren);
  7225. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7226. }
  7227. clone() {
  7228. return new this.constructor().copy(this);
  7229. }
  7230. }
  7231. class PerspectiveCamera extends Camera {
  7232. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7233. super();
  7234. this.isPerspectiveCamera = true;
  7235. this.type = 'PerspectiveCamera';
  7236. this.fov = fov;
  7237. this.zoom = 1;
  7238. this.near = near;
  7239. this.far = far;
  7240. this.focus = 10;
  7241. this.aspect = aspect;
  7242. this.view = null;
  7243. this.filmGauge = 35; // width of the film (default in millimeters)
  7244. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7245. this.updateProjectionMatrix();
  7246. }
  7247. copy(source, recursive) {
  7248. super.copy(source, recursive);
  7249. this.fov = source.fov;
  7250. this.zoom = source.zoom;
  7251. this.near = source.near;
  7252. this.far = source.far;
  7253. this.focus = source.focus;
  7254. this.aspect = source.aspect;
  7255. this.view = source.view === null ? null : Object.assign({}, source.view);
  7256. this.filmGauge = source.filmGauge;
  7257. this.filmOffset = source.filmOffset;
  7258. return this;
  7259. }
  7260. /**
  7261. * Sets the FOV by focal length in respect to the current .filmGauge.
  7262. *
  7263. * The default film gauge is 35, so that the focal length can be specified for
  7264. * a 35mm (full frame) camera.
  7265. *
  7266. * Values for focal length and film gauge must have the same unit.
  7267. */
  7268. setFocalLength(focalLength) {
  7269. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7270. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7271. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7272. this.updateProjectionMatrix();
  7273. }
  7274. /**
  7275. * Calculates the focal length from the current .fov and .filmGauge.
  7276. */
  7277. getFocalLength() {
  7278. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7279. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7280. }
  7281. getEffectiveFOV() {
  7282. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7283. }
  7284. getFilmWidth() {
  7285. // film not completely covered in portrait format (aspect < 1)
  7286. return this.filmGauge * Math.min(this.aspect, 1);
  7287. }
  7288. getFilmHeight() {
  7289. // film not completely covered in landscape format (aspect > 1)
  7290. return this.filmGauge / Math.max(this.aspect, 1);
  7291. }
  7292. /**
  7293. * Sets an offset in a larger frustum. This is useful for multi-window or
  7294. * multi-monitor/multi-machine setups.
  7295. *
  7296. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7297. * the monitors are in grid like this
  7298. *
  7299. * +---+---+---+
  7300. * | A | B | C |
  7301. * +---+---+---+
  7302. * | D | E | F |
  7303. * +---+---+---+
  7304. *
  7305. * then for each monitor you would call it like this
  7306. *
  7307. * const w = 1920;
  7308. * const h = 1080;
  7309. * const fullWidth = w * 3;
  7310. * const fullHeight = h * 2;
  7311. *
  7312. * --A--
  7313. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7314. * --B--
  7315. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7316. * --C--
  7317. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7318. * --D--
  7319. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7320. * --E--
  7321. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7322. * --F--
  7323. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7324. *
  7325. * Note there is no reason monitors have to be the same size or in a grid.
  7326. */
  7327. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7328. this.aspect = fullWidth / fullHeight;
  7329. if (this.view === null) {
  7330. this.view = {
  7331. enabled: true,
  7332. fullWidth: 1,
  7333. fullHeight: 1,
  7334. offsetX: 0,
  7335. offsetY: 0,
  7336. width: 1,
  7337. height: 1
  7338. };
  7339. }
  7340. this.view.enabled = true;
  7341. this.view.fullWidth = fullWidth;
  7342. this.view.fullHeight = fullHeight;
  7343. this.view.offsetX = x;
  7344. this.view.offsetY = y;
  7345. this.view.width = width;
  7346. this.view.height = height;
  7347. this.updateProjectionMatrix();
  7348. }
  7349. clearViewOffset() {
  7350. if (this.view !== null) {
  7351. this.view.enabled = false;
  7352. }
  7353. this.updateProjectionMatrix();
  7354. }
  7355. updateProjectionMatrix() {
  7356. const near = this.near;
  7357. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7358. let height = 2 * top;
  7359. let width = this.aspect * height;
  7360. let left = -0.5 * width;
  7361. const view = this.view;
  7362. if (this.view !== null && this.view.enabled) {
  7363. const fullWidth = view.fullWidth,
  7364. fullHeight = view.fullHeight;
  7365. left += view.offsetX * width / fullWidth;
  7366. top -= view.offsetY * height / fullHeight;
  7367. width *= view.width / fullWidth;
  7368. height *= view.height / fullHeight;
  7369. }
  7370. const skew = this.filmOffset;
  7371. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7372. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7373. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7374. }
  7375. toJSON(meta) {
  7376. const data = super.toJSON(meta);
  7377. data.object.fov = this.fov;
  7378. data.object.zoom = this.zoom;
  7379. data.object.near = this.near;
  7380. data.object.far = this.far;
  7381. data.object.focus = this.focus;
  7382. data.object.aspect = this.aspect;
  7383. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7384. data.object.filmGauge = this.filmGauge;
  7385. data.object.filmOffset = this.filmOffset;
  7386. return data;
  7387. }
  7388. }
  7389. const fov = 90,
  7390. aspect = 1;
  7391. class CubeCamera extends Object3D {
  7392. constructor(near, far, renderTarget) {
  7393. super();
  7394. this.type = 'CubeCamera';
  7395. this.renderTarget = renderTarget;
  7396. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7397. cameraPX.layers = this.layers;
  7398. cameraPX.up.set(0, -1, 0);
  7399. cameraPX.lookAt(new Vector3(1, 0, 0));
  7400. this.add(cameraPX);
  7401. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7402. cameraNX.layers = this.layers;
  7403. cameraNX.up.set(0, -1, 0);
  7404. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7405. this.add(cameraNX);
  7406. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7407. cameraPY.layers = this.layers;
  7408. cameraPY.up.set(0, 0, 1);
  7409. cameraPY.lookAt(new Vector3(0, 1, 0));
  7410. this.add(cameraPY);
  7411. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7412. cameraNY.layers = this.layers;
  7413. cameraNY.up.set(0, 0, -1);
  7414. cameraNY.lookAt(new Vector3(0, -1, 0));
  7415. this.add(cameraNY);
  7416. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7417. cameraPZ.layers = this.layers;
  7418. cameraPZ.up.set(0, -1, 0);
  7419. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7420. this.add(cameraPZ);
  7421. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7422. cameraNZ.layers = this.layers;
  7423. cameraNZ.up.set(0, -1, 0);
  7424. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7425. this.add(cameraNZ);
  7426. }
  7427. update(renderer, scene) {
  7428. if (this.parent === null) this.updateMatrixWorld();
  7429. const renderTarget = this.renderTarget;
  7430. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7431. const currentRenderTarget = renderer.getRenderTarget();
  7432. const currentToneMapping = renderer.toneMapping;
  7433. const currentXrEnabled = renderer.xr.enabled;
  7434. renderer.toneMapping = NoToneMapping;
  7435. renderer.xr.enabled = false;
  7436. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7437. renderTarget.texture.generateMipmaps = false;
  7438. renderer.setRenderTarget(renderTarget, 0);
  7439. renderer.render(scene, cameraPX);
  7440. renderer.setRenderTarget(renderTarget, 1);
  7441. renderer.render(scene, cameraNX);
  7442. renderer.setRenderTarget(renderTarget, 2);
  7443. renderer.render(scene, cameraPY);
  7444. renderer.setRenderTarget(renderTarget, 3);
  7445. renderer.render(scene, cameraNY);
  7446. renderer.setRenderTarget(renderTarget, 4);
  7447. renderer.render(scene, cameraPZ);
  7448. renderTarget.texture.generateMipmaps = generateMipmaps;
  7449. renderer.setRenderTarget(renderTarget, 5);
  7450. renderer.render(scene, cameraNZ);
  7451. renderer.setRenderTarget(currentRenderTarget);
  7452. renderer.toneMapping = currentToneMapping;
  7453. renderer.xr.enabled = currentXrEnabled;
  7454. renderTarget.texture.needsPMREMUpdate = true;
  7455. }
  7456. }
  7457. class CubeTexture extends Texture {
  7458. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7459. images = images !== undefined ? images : [];
  7460. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7461. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7462. this.isCubeTexture = true;
  7463. this.flipY = false;
  7464. }
  7465. get images() {
  7466. return this.image;
  7467. }
  7468. set images(value) {
  7469. this.image = value;
  7470. }
  7471. }
  7472. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7473. constructor(size, options = {}) {
  7474. super(size, size, options);
  7475. this.isWebGLCubeRenderTarget = true;
  7476. const image = {
  7477. width: size,
  7478. height: size,
  7479. depth: 1
  7480. };
  7481. const images = [image, image, image, image, image, image];
  7482. this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding); // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7483. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7484. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7485. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7486. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7487. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7488. this.texture.isRenderTargetTexture = true;
  7489. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7490. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7491. }
  7492. fromEquirectangularTexture(renderer, texture) {
  7493. this.texture.type = texture.type;
  7494. this.texture.encoding = texture.encoding;
  7495. this.texture.generateMipmaps = texture.generateMipmaps;
  7496. this.texture.minFilter = texture.minFilter;
  7497. this.texture.magFilter = texture.magFilter;
  7498. const shader = {
  7499. uniforms: {
  7500. tEquirect: {
  7501. value: null
  7502. }
  7503. },
  7504. vertexShader:
  7505. /* glsl */
  7506. `
  7507. varying vec3 vWorldDirection;
  7508. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7509. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7510. }
  7511. void main() {
  7512. vWorldDirection = transformDirection( position, modelMatrix );
  7513. #include <begin_vertex>
  7514. #include <project_vertex>
  7515. }
  7516. `,
  7517. fragmentShader:
  7518. /* glsl */
  7519. `
  7520. uniform sampler2D tEquirect;
  7521. varying vec3 vWorldDirection;
  7522. #include <common>
  7523. void main() {
  7524. vec3 direction = normalize( vWorldDirection );
  7525. vec2 sampleUV = equirectUv( direction );
  7526. gl_FragColor = texture2D( tEquirect, sampleUV );
  7527. }
  7528. `
  7529. };
  7530. const geometry = new BoxGeometry(5, 5, 5);
  7531. const material = new ShaderMaterial({
  7532. name: 'CubemapFromEquirect',
  7533. uniforms: cloneUniforms(shader.uniforms),
  7534. vertexShader: shader.vertexShader,
  7535. fragmentShader: shader.fragmentShader,
  7536. side: BackSide,
  7537. blending: NoBlending
  7538. });
  7539. material.uniforms.tEquirect.value = texture;
  7540. const mesh = new Mesh(geometry, material);
  7541. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7542. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7543. const camera = new CubeCamera(1, 10, this);
  7544. camera.update(renderer, mesh);
  7545. texture.minFilter = currentMinFilter;
  7546. mesh.geometry.dispose();
  7547. mesh.material.dispose();
  7548. return this;
  7549. }
  7550. clear(renderer, color, depth, stencil) {
  7551. const currentRenderTarget = renderer.getRenderTarget();
  7552. for (let i = 0; i < 6; i++) {
  7553. renderer.setRenderTarget(this, i);
  7554. renderer.clear(color, depth, stencil);
  7555. }
  7556. renderer.setRenderTarget(currentRenderTarget);
  7557. }
  7558. }
  7559. const _vector1 = /*@__PURE__*/new Vector3();
  7560. const _vector2 = /*@__PURE__*/new Vector3();
  7561. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7562. class Plane {
  7563. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7564. this.isPlane = true; // normal is assumed to be normalized
  7565. this.normal = normal;
  7566. this.constant = constant;
  7567. }
  7568. set(normal, constant) {
  7569. this.normal.copy(normal);
  7570. this.constant = constant;
  7571. return this;
  7572. }
  7573. setComponents(x, y, z, w) {
  7574. this.normal.set(x, y, z);
  7575. this.constant = w;
  7576. return this;
  7577. }
  7578. setFromNormalAndCoplanarPoint(normal, point) {
  7579. this.normal.copy(normal);
  7580. this.constant = -point.dot(this.normal);
  7581. return this;
  7582. }
  7583. setFromCoplanarPoints(a, b, c) {
  7584. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7585. this.setFromNormalAndCoplanarPoint(normal, a);
  7586. return this;
  7587. }
  7588. copy(plane) {
  7589. this.normal.copy(plane.normal);
  7590. this.constant = plane.constant;
  7591. return this;
  7592. }
  7593. normalize() {
  7594. // Note: will lead to a divide by zero if the plane is invalid.
  7595. const inverseNormalLength = 1.0 / this.normal.length();
  7596. this.normal.multiplyScalar(inverseNormalLength);
  7597. this.constant *= inverseNormalLength;
  7598. return this;
  7599. }
  7600. negate() {
  7601. this.constant *= -1;
  7602. this.normal.negate();
  7603. return this;
  7604. }
  7605. distanceToPoint(point) {
  7606. return this.normal.dot(point) + this.constant;
  7607. }
  7608. distanceToSphere(sphere) {
  7609. return this.distanceToPoint(sphere.center) - sphere.radius;
  7610. }
  7611. projectPoint(point, target) {
  7612. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7613. }
  7614. intersectLine(line, target) {
  7615. const direction = line.delta(_vector1);
  7616. const denominator = this.normal.dot(direction);
  7617. if (denominator === 0) {
  7618. // line is coplanar, return origin
  7619. if (this.distanceToPoint(line.start) === 0) {
  7620. return target.copy(line.start);
  7621. } // Unsure if this is the correct method to handle this case.
  7622. return null;
  7623. }
  7624. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7625. if (t < 0 || t > 1) {
  7626. return null;
  7627. }
  7628. return target.copy(direction).multiplyScalar(t).add(line.start);
  7629. }
  7630. intersectsLine(line) {
  7631. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7632. const startSign = this.distanceToPoint(line.start);
  7633. const endSign = this.distanceToPoint(line.end);
  7634. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7635. }
  7636. intersectsBox(box) {
  7637. return box.intersectsPlane(this);
  7638. }
  7639. intersectsSphere(sphere) {
  7640. return sphere.intersectsPlane(this);
  7641. }
  7642. coplanarPoint(target) {
  7643. return target.copy(this.normal).multiplyScalar(-this.constant);
  7644. }
  7645. applyMatrix4(matrix, optionalNormalMatrix) {
  7646. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7647. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7648. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7649. this.constant = -referencePoint.dot(normal);
  7650. return this;
  7651. }
  7652. translate(offset) {
  7653. this.constant -= offset.dot(this.normal);
  7654. return this;
  7655. }
  7656. equals(plane) {
  7657. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7658. }
  7659. clone() {
  7660. return new this.constructor().copy(this);
  7661. }
  7662. }
  7663. const _sphere$2 = /*@__PURE__*/new Sphere();
  7664. const _vector$7 = /*@__PURE__*/new Vector3();
  7665. class Frustum {
  7666. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7667. this.planes = [p0, p1, p2, p3, p4, p5];
  7668. }
  7669. set(p0, p1, p2, p3, p4, p5) {
  7670. const planes = this.planes;
  7671. planes[0].copy(p0);
  7672. planes[1].copy(p1);
  7673. planes[2].copy(p2);
  7674. planes[3].copy(p3);
  7675. planes[4].copy(p4);
  7676. planes[5].copy(p5);
  7677. return this;
  7678. }
  7679. copy(frustum) {
  7680. const planes = this.planes;
  7681. for (let i = 0; i < 6; i++) {
  7682. planes[i].copy(frustum.planes[i]);
  7683. }
  7684. return this;
  7685. }
  7686. setFromProjectionMatrix(m) {
  7687. const planes = this.planes;
  7688. const me = m.elements;
  7689. const me0 = me[0],
  7690. me1 = me[1],
  7691. me2 = me[2],
  7692. me3 = me[3];
  7693. const me4 = me[4],
  7694. me5 = me[5],
  7695. me6 = me[6],
  7696. me7 = me[7];
  7697. const me8 = me[8],
  7698. me9 = me[9],
  7699. me10 = me[10],
  7700. me11 = me[11];
  7701. const me12 = me[12],
  7702. me13 = me[13],
  7703. me14 = me[14],
  7704. me15 = me[15];
  7705. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7706. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7707. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7708. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7709. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7710. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7711. return this;
  7712. }
  7713. intersectsObject(object) {
  7714. const geometry = object.geometry;
  7715. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7716. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7717. return this.intersectsSphere(_sphere$2);
  7718. }
  7719. intersectsSprite(sprite) {
  7720. _sphere$2.center.set(0, 0, 0);
  7721. _sphere$2.radius = 0.7071067811865476;
  7722. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7723. return this.intersectsSphere(_sphere$2);
  7724. }
  7725. intersectsSphere(sphere) {
  7726. const planes = this.planes;
  7727. const center = sphere.center;
  7728. const negRadius = -sphere.radius;
  7729. for (let i = 0; i < 6; i++) {
  7730. const distance = planes[i].distanceToPoint(center);
  7731. if (distance < negRadius) {
  7732. return false;
  7733. }
  7734. }
  7735. return true;
  7736. }
  7737. intersectsBox(box) {
  7738. const planes = this.planes;
  7739. for (let i = 0; i < 6; i++) {
  7740. const plane = planes[i]; // corner at max distance
  7741. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7742. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7743. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7744. if (plane.distanceToPoint(_vector$7) < 0) {
  7745. return false;
  7746. }
  7747. }
  7748. return true;
  7749. }
  7750. containsPoint(point) {
  7751. const planes = this.planes;
  7752. for (let i = 0; i < 6; i++) {
  7753. if (planes[i].distanceToPoint(point) < 0) {
  7754. return false;
  7755. }
  7756. }
  7757. return true;
  7758. }
  7759. clone() {
  7760. return new this.constructor().copy(this);
  7761. }
  7762. }
  7763. function WebGLAnimation() {
  7764. let context = null;
  7765. let isAnimating = false;
  7766. let animationLoop = null;
  7767. let requestId = null;
  7768. function onAnimationFrame(time, frame) {
  7769. animationLoop(time, frame);
  7770. requestId = context.requestAnimationFrame(onAnimationFrame);
  7771. }
  7772. return {
  7773. start: function () {
  7774. if (isAnimating === true) return;
  7775. if (animationLoop === null) return;
  7776. requestId = context.requestAnimationFrame(onAnimationFrame);
  7777. isAnimating = true;
  7778. },
  7779. stop: function () {
  7780. context.cancelAnimationFrame(requestId);
  7781. isAnimating = false;
  7782. },
  7783. setAnimationLoop: function (callback) {
  7784. animationLoop = callback;
  7785. },
  7786. setContext: function (value) {
  7787. context = value;
  7788. }
  7789. };
  7790. }
  7791. function WebGLAttributes(gl, capabilities) {
  7792. const isWebGL2 = capabilities.isWebGL2;
  7793. const buffers = new WeakMap();
  7794. function createBuffer(attribute, bufferType) {
  7795. const array = attribute.array;
  7796. const usage = attribute.usage;
  7797. const buffer = gl.createBuffer();
  7798. gl.bindBuffer(bufferType, buffer);
  7799. gl.bufferData(bufferType, array, usage);
  7800. attribute.onUploadCallback();
  7801. let type;
  7802. if (array instanceof Float32Array) {
  7803. type = gl.FLOAT;
  7804. } else if (array instanceof Uint16Array) {
  7805. if (attribute.isFloat16BufferAttribute) {
  7806. if (isWebGL2) {
  7807. type = gl.HALF_FLOAT;
  7808. } else {
  7809. throw new Error('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7810. }
  7811. } else {
  7812. type = gl.UNSIGNED_SHORT;
  7813. }
  7814. } else if (array instanceof Int16Array) {
  7815. type = gl.SHORT;
  7816. } else if (array instanceof Uint32Array) {
  7817. type = gl.UNSIGNED_INT;
  7818. } else if (array instanceof Int32Array) {
  7819. type = gl.INT;
  7820. } else if (array instanceof Int8Array) {
  7821. type = gl.BYTE;
  7822. } else if (array instanceof Uint8Array) {
  7823. type = gl.UNSIGNED_BYTE;
  7824. } else if (array instanceof Uint8ClampedArray) {
  7825. type = gl.UNSIGNED_BYTE;
  7826. } else {
  7827. throw new Error('THREE.WebGLAttributes: Unsupported buffer data format: ' + array);
  7828. }
  7829. return {
  7830. buffer: buffer,
  7831. type: type,
  7832. bytesPerElement: array.BYTES_PER_ELEMENT,
  7833. version: attribute.version
  7834. };
  7835. }
  7836. function updateBuffer(buffer, attribute, bufferType) {
  7837. const array = attribute.array;
  7838. const updateRange = attribute.updateRange;
  7839. gl.bindBuffer(bufferType, buffer);
  7840. if (updateRange.count === -1) {
  7841. // Not using update ranges
  7842. gl.bufferSubData(bufferType, 0, array);
  7843. } else {
  7844. if (isWebGL2) {
  7845. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7846. } else {
  7847. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7848. }
  7849. updateRange.count = -1; // reset range
  7850. }
  7851. } //
  7852. function get(attribute) {
  7853. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7854. return buffers.get(attribute);
  7855. }
  7856. function remove(attribute) {
  7857. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7858. const data = buffers.get(attribute);
  7859. if (data) {
  7860. gl.deleteBuffer(data.buffer);
  7861. buffers.delete(attribute);
  7862. }
  7863. }
  7864. function update(attribute, bufferType) {
  7865. if (attribute.isGLBufferAttribute) {
  7866. const cached = buffers.get(attribute);
  7867. if (!cached || cached.version < attribute.version) {
  7868. buffers.set(attribute, {
  7869. buffer: attribute.buffer,
  7870. type: attribute.type,
  7871. bytesPerElement: attribute.elementSize,
  7872. version: attribute.version
  7873. });
  7874. }
  7875. return;
  7876. }
  7877. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7878. const data = buffers.get(attribute);
  7879. if (data === undefined) {
  7880. buffers.set(attribute, createBuffer(attribute, bufferType));
  7881. } else if (data.version < attribute.version) {
  7882. updateBuffer(data.buffer, attribute, bufferType);
  7883. data.version = attribute.version;
  7884. }
  7885. }
  7886. return {
  7887. get: get,
  7888. remove: remove,
  7889. update: update
  7890. };
  7891. }
  7892. class PlaneGeometry extends BufferGeometry {
  7893. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7894. super();
  7895. this.type = 'PlaneGeometry';
  7896. this.parameters = {
  7897. width: width,
  7898. height: height,
  7899. widthSegments: widthSegments,
  7900. heightSegments: heightSegments
  7901. };
  7902. const width_half = width / 2;
  7903. const height_half = height / 2;
  7904. const gridX = Math.floor(widthSegments);
  7905. const gridY = Math.floor(heightSegments);
  7906. const gridX1 = gridX + 1;
  7907. const gridY1 = gridY + 1;
  7908. const segment_width = width / gridX;
  7909. const segment_height = height / gridY; //
  7910. const indices = [];
  7911. const vertices = [];
  7912. const normals = [];
  7913. const uvs = [];
  7914. for (let iy = 0; iy < gridY1; iy++) {
  7915. const y = iy * segment_height - height_half;
  7916. for (let ix = 0; ix < gridX1; ix++) {
  7917. const x = ix * segment_width - width_half;
  7918. vertices.push(x, -y, 0);
  7919. normals.push(0, 0, 1);
  7920. uvs.push(ix / gridX);
  7921. uvs.push(1 - iy / gridY);
  7922. }
  7923. }
  7924. for (let iy = 0; iy < gridY; iy++) {
  7925. for (let ix = 0; ix < gridX; ix++) {
  7926. const a = ix + gridX1 * iy;
  7927. const b = ix + gridX1 * (iy + 1);
  7928. const c = ix + 1 + gridX1 * (iy + 1);
  7929. const d = ix + 1 + gridX1 * iy;
  7930. indices.push(a, b, d);
  7931. indices.push(b, c, d);
  7932. }
  7933. }
  7934. this.setIndex(indices);
  7935. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7936. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7937. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7938. }
  7939. static fromJSON(data) {
  7940. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7941. }
  7942. }
  7943. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7944. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7945. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7946. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7947. 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";
  7948. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7949. var begin_vertex = "vec3 transformed = vec3( position );";
  7950. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7951. 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";
  7952. 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";
  7953. 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";
  7954. 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";
  7955. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7956. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7957. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7958. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7959. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7960. 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";
  7961. 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";
  7962. 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}";
  7963. 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";
  7964. 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";
  7965. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7966. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7967. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7968. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7969. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7970. 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}";
  7971. 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#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\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";
  7972. 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";
  7973. 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";
  7974. 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";
  7975. 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";
  7976. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7977. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7978. 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";
  7979. 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";
  7980. 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}";
  7981. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7982. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7983. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7984. 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\n#define Material_LightProbeLOD( material )\t(0)";
  7985. 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";
  7986. 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";
  7987. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7988. 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\n#define Material_LightProbeLOD( material )\t(0)";
  7989. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7990. 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\n#define Material_LightProbeLOD( material )\t(0)";
  7991. 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";
  7992. 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}";
  7993. 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\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 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, vSpotShadowCoord[ 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";
  7994. 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";
  7995. 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";
  7996. 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";
  7997. 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";
  7998. 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";
  7999. 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";
  8000. 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";
  8001. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8002. 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";
  8003. 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";
  8004. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8005. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8006. 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";
  8007. 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";
  8008. 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";
  8009. 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";
  8010. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\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;";
  8011. 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";
  8012. 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";
  8013. 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";
  8014. 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";
  8015. 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";
  8016. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8017. 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";
  8018. 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";
  8019. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8020. 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 );";
  8021. 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}\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}";
  8022. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8023. 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;";
  8024. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8025. 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";
  8026. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8027. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8028. var shadowmap_pars_fragment = "#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\tvarying vec4 vSpotShadowCoord[ 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";
  8029. var shadowmap_pars_vertex = "#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\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ 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 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";
  8030. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 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_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ 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";
  8031. 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, vSpotShadowCoord[ 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}";
  8032. 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";
  8033. 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";
  8034. 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";
  8035. 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";
  8036. 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";
  8037. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8038. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8039. 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; }";
  8040. 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";
  8041. 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 ( attenuationDistance == 0.0 ) {\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";
  8042. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8043. 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";
  8044. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8045. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8046. 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";
  8047. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8048. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\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";
  8049. const vertex$g = "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}";
  8050. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tgl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n\t#endif\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8051. 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}";
  8052. const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8053. 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}";
  8054. 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}";
  8055. 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}";
  8056. 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}";
  8057. 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}";
  8058. 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}";
  8059. 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}";
  8060. 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}";
  8061. 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}";
  8062. 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}";
  8063. 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}";
  8064. 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}";
  8065. 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}";
  8066. 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}";
  8067. 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}";
  8068. 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}";
  8069. 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}";
  8070. 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}";
  8071. 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}";
  8072. 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}";
  8073. 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}";
  8074. 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}";
  8075. 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}";
  8076. 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}";
  8077. 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}";
  8078. 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}";
  8079. 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}";
  8080. 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}";
  8081. const ShaderChunk = {
  8082. alphamap_fragment: alphamap_fragment,
  8083. alphamap_pars_fragment: alphamap_pars_fragment,
  8084. alphatest_fragment: alphatest_fragment,
  8085. alphatest_pars_fragment: alphatest_pars_fragment,
  8086. aomap_fragment: aomap_fragment,
  8087. aomap_pars_fragment: aomap_pars_fragment,
  8088. begin_vertex: begin_vertex,
  8089. beginnormal_vertex: beginnormal_vertex,
  8090. bsdfs: bsdfs,
  8091. iridescence_fragment: iridescence_fragment,
  8092. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8093. clipping_planes_fragment: clipping_planes_fragment,
  8094. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8095. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8096. clipping_planes_vertex: clipping_planes_vertex,
  8097. color_fragment: color_fragment,
  8098. color_pars_fragment: color_pars_fragment,
  8099. color_pars_vertex: color_pars_vertex,
  8100. color_vertex: color_vertex,
  8101. common: common,
  8102. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8103. defaultnormal_vertex: defaultnormal_vertex,
  8104. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8105. displacementmap_vertex: displacementmap_vertex,
  8106. emissivemap_fragment: emissivemap_fragment,
  8107. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8108. encodings_fragment: encodings_fragment,
  8109. encodings_pars_fragment: encodings_pars_fragment,
  8110. envmap_fragment: envmap_fragment,
  8111. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8112. envmap_pars_fragment: envmap_pars_fragment,
  8113. envmap_pars_vertex: envmap_pars_vertex,
  8114. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8115. envmap_vertex: envmap_vertex,
  8116. fog_vertex: fog_vertex,
  8117. fog_pars_vertex: fog_pars_vertex,
  8118. fog_fragment: fog_fragment,
  8119. fog_pars_fragment: fog_pars_fragment,
  8120. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8121. lightmap_fragment: lightmap_fragment,
  8122. lightmap_pars_fragment: lightmap_pars_fragment,
  8123. lights_lambert_fragment: lights_lambert_fragment,
  8124. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8125. lights_pars_begin: lights_pars_begin,
  8126. lights_toon_fragment: lights_toon_fragment,
  8127. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8128. lights_phong_fragment: lights_phong_fragment,
  8129. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8130. lights_physical_fragment: lights_physical_fragment,
  8131. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8132. lights_fragment_begin: lights_fragment_begin,
  8133. lights_fragment_maps: lights_fragment_maps,
  8134. lights_fragment_end: lights_fragment_end,
  8135. logdepthbuf_fragment: logdepthbuf_fragment,
  8136. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8137. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8138. logdepthbuf_vertex: logdepthbuf_vertex,
  8139. map_fragment: map_fragment,
  8140. map_pars_fragment: map_pars_fragment,
  8141. map_particle_fragment: map_particle_fragment,
  8142. map_particle_pars_fragment: map_particle_pars_fragment,
  8143. metalnessmap_fragment: metalnessmap_fragment,
  8144. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8145. morphcolor_vertex: morphcolor_vertex,
  8146. morphnormal_vertex: morphnormal_vertex,
  8147. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8148. morphtarget_vertex: morphtarget_vertex,
  8149. normal_fragment_begin: normal_fragment_begin,
  8150. normal_fragment_maps: normal_fragment_maps,
  8151. normal_pars_fragment: normal_pars_fragment,
  8152. normal_pars_vertex: normal_pars_vertex,
  8153. normal_vertex: normal_vertex,
  8154. normalmap_pars_fragment: normalmap_pars_fragment,
  8155. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8156. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8157. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8158. iridescence_pars_fragment: iridescence_pars_fragment,
  8159. output_fragment: output_fragment,
  8160. packing: packing,
  8161. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8162. project_vertex: project_vertex,
  8163. dithering_fragment: dithering_fragment,
  8164. dithering_pars_fragment: dithering_pars_fragment,
  8165. roughnessmap_fragment: roughnessmap_fragment,
  8166. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8167. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8168. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8169. shadowmap_vertex: shadowmap_vertex,
  8170. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8171. skinbase_vertex: skinbase_vertex,
  8172. skinning_pars_vertex: skinning_pars_vertex,
  8173. skinning_vertex: skinning_vertex,
  8174. skinnormal_vertex: skinnormal_vertex,
  8175. specularmap_fragment: specularmap_fragment,
  8176. specularmap_pars_fragment: specularmap_pars_fragment,
  8177. tonemapping_fragment: tonemapping_fragment,
  8178. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8179. transmission_fragment: transmission_fragment,
  8180. transmission_pars_fragment: transmission_pars_fragment,
  8181. uv_pars_fragment: uv_pars_fragment,
  8182. uv_pars_vertex: uv_pars_vertex,
  8183. uv_vertex: uv_vertex,
  8184. uv2_pars_fragment: uv2_pars_fragment,
  8185. uv2_pars_vertex: uv2_pars_vertex,
  8186. uv2_vertex: uv2_vertex,
  8187. worldpos_vertex: worldpos_vertex,
  8188. background_vert: vertex$g,
  8189. background_frag: fragment$g,
  8190. cube_vert: vertex$f,
  8191. cube_frag: fragment$f,
  8192. depth_vert: vertex$e,
  8193. depth_frag: fragment$e,
  8194. distanceRGBA_vert: vertex$d,
  8195. distanceRGBA_frag: fragment$d,
  8196. equirect_vert: vertex$c,
  8197. equirect_frag: fragment$c,
  8198. linedashed_vert: vertex$b,
  8199. linedashed_frag: fragment$b,
  8200. meshbasic_vert: vertex$a,
  8201. meshbasic_frag: fragment$a,
  8202. meshlambert_vert: vertex$9,
  8203. meshlambert_frag: fragment$9,
  8204. meshmatcap_vert: vertex$8,
  8205. meshmatcap_frag: fragment$8,
  8206. meshnormal_vert: vertex$7,
  8207. meshnormal_frag: fragment$7,
  8208. meshphong_vert: vertex$6,
  8209. meshphong_frag: fragment$6,
  8210. meshphysical_vert: vertex$5,
  8211. meshphysical_frag: fragment$5,
  8212. meshtoon_vert: vertex$4,
  8213. meshtoon_frag: fragment$4,
  8214. points_vert: vertex$3,
  8215. points_frag: fragment$3,
  8216. shadow_vert: vertex$2,
  8217. shadow_frag: fragment$2,
  8218. sprite_vert: vertex$1,
  8219. sprite_frag: fragment$1
  8220. };
  8221. /**
  8222. * Uniforms library for shared webgl shaders
  8223. */
  8224. const UniformsLib = {
  8225. common: {
  8226. diffuse: {
  8227. value: /*@__PURE__*/new Color(0xffffff)
  8228. },
  8229. opacity: {
  8230. value: 1.0
  8231. },
  8232. map: {
  8233. value: null
  8234. },
  8235. uvTransform: {
  8236. value: /*@__PURE__*/new Matrix3()
  8237. },
  8238. uv2Transform: {
  8239. value: /*@__PURE__*/new Matrix3()
  8240. },
  8241. alphaMap: {
  8242. value: null
  8243. },
  8244. alphaTest: {
  8245. value: 0
  8246. }
  8247. },
  8248. specularmap: {
  8249. specularMap: {
  8250. value: null
  8251. }
  8252. },
  8253. envmap: {
  8254. envMap: {
  8255. value: null
  8256. },
  8257. flipEnvMap: {
  8258. value: -1
  8259. },
  8260. reflectivity: {
  8261. value: 1.0
  8262. },
  8263. // basic, lambert, phong
  8264. ior: {
  8265. value: 1.5
  8266. },
  8267. // physical
  8268. refractionRatio: {
  8269. value: 0.98
  8270. } // basic, lambert, phong
  8271. },
  8272. aomap: {
  8273. aoMap: {
  8274. value: null
  8275. },
  8276. aoMapIntensity: {
  8277. value: 1
  8278. }
  8279. },
  8280. lightmap: {
  8281. lightMap: {
  8282. value: null
  8283. },
  8284. lightMapIntensity: {
  8285. value: 1
  8286. }
  8287. },
  8288. emissivemap: {
  8289. emissiveMap: {
  8290. value: null
  8291. }
  8292. },
  8293. bumpmap: {
  8294. bumpMap: {
  8295. value: null
  8296. },
  8297. bumpScale: {
  8298. value: 1
  8299. }
  8300. },
  8301. normalmap: {
  8302. normalMap: {
  8303. value: null
  8304. },
  8305. normalScale: {
  8306. value: /*@__PURE__*/new Vector2(1, 1)
  8307. }
  8308. },
  8309. displacementmap: {
  8310. displacementMap: {
  8311. value: null
  8312. },
  8313. displacementScale: {
  8314. value: 1
  8315. },
  8316. displacementBias: {
  8317. value: 0
  8318. }
  8319. },
  8320. roughnessmap: {
  8321. roughnessMap: {
  8322. value: null
  8323. }
  8324. },
  8325. metalnessmap: {
  8326. metalnessMap: {
  8327. value: null
  8328. }
  8329. },
  8330. gradientmap: {
  8331. gradientMap: {
  8332. value: null
  8333. }
  8334. },
  8335. fog: {
  8336. fogDensity: {
  8337. value: 0.00025
  8338. },
  8339. fogNear: {
  8340. value: 1
  8341. },
  8342. fogFar: {
  8343. value: 2000
  8344. },
  8345. fogColor: {
  8346. value: /*@__PURE__*/new Color(0xffffff)
  8347. }
  8348. },
  8349. lights: {
  8350. ambientLightColor: {
  8351. value: []
  8352. },
  8353. lightProbe: {
  8354. value: []
  8355. },
  8356. directionalLights: {
  8357. value: [],
  8358. properties: {
  8359. direction: {},
  8360. color: {}
  8361. }
  8362. },
  8363. directionalLightShadows: {
  8364. value: [],
  8365. properties: {
  8366. shadowBias: {},
  8367. shadowNormalBias: {},
  8368. shadowRadius: {},
  8369. shadowMapSize: {}
  8370. }
  8371. },
  8372. directionalShadowMap: {
  8373. value: []
  8374. },
  8375. directionalShadowMatrix: {
  8376. value: []
  8377. },
  8378. spotLights: {
  8379. value: [],
  8380. properties: {
  8381. color: {},
  8382. position: {},
  8383. direction: {},
  8384. distance: {},
  8385. coneCos: {},
  8386. penumbraCos: {},
  8387. decay: {}
  8388. }
  8389. },
  8390. spotLightShadows: {
  8391. value: [],
  8392. properties: {
  8393. shadowBias: {},
  8394. shadowNormalBias: {},
  8395. shadowRadius: {},
  8396. shadowMapSize: {}
  8397. }
  8398. },
  8399. spotShadowMap: {
  8400. value: []
  8401. },
  8402. spotShadowMatrix: {
  8403. value: []
  8404. },
  8405. pointLights: {
  8406. value: [],
  8407. properties: {
  8408. color: {},
  8409. position: {},
  8410. decay: {},
  8411. distance: {}
  8412. }
  8413. },
  8414. pointLightShadows: {
  8415. value: [],
  8416. properties: {
  8417. shadowBias: {},
  8418. shadowNormalBias: {},
  8419. shadowRadius: {},
  8420. shadowMapSize: {},
  8421. shadowCameraNear: {},
  8422. shadowCameraFar: {}
  8423. }
  8424. },
  8425. pointShadowMap: {
  8426. value: []
  8427. },
  8428. pointShadowMatrix: {
  8429. value: []
  8430. },
  8431. hemisphereLights: {
  8432. value: [],
  8433. properties: {
  8434. direction: {},
  8435. skyColor: {},
  8436. groundColor: {}
  8437. }
  8438. },
  8439. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8440. rectAreaLights: {
  8441. value: [],
  8442. properties: {
  8443. color: {},
  8444. position: {},
  8445. width: {},
  8446. height: {}
  8447. }
  8448. },
  8449. ltc_1: {
  8450. value: null
  8451. },
  8452. ltc_2: {
  8453. value: null
  8454. }
  8455. },
  8456. points: {
  8457. diffuse: {
  8458. value: /*@__PURE__*/new Color(0xffffff)
  8459. },
  8460. opacity: {
  8461. value: 1.0
  8462. },
  8463. size: {
  8464. value: 1.0
  8465. },
  8466. scale: {
  8467. value: 1.0
  8468. },
  8469. map: {
  8470. value: null
  8471. },
  8472. alphaMap: {
  8473. value: null
  8474. },
  8475. alphaTest: {
  8476. value: 0
  8477. },
  8478. uvTransform: {
  8479. value: /*@__PURE__*/new Matrix3()
  8480. }
  8481. },
  8482. sprite: {
  8483. diffuse: {
  8484. value: /*@__PURE__*/new Color(0xffffff)
  8485. },
  8486. opacity: {
  8487. value: 1.0
  8488. },
  8489. center: {
  8490. value: /*@__PURE__*/new Vector2(0.5, 0.5)
  8491. },
  8492. rotation: {
  8493. value: 0.0
  8494. },
  8495. map: {
  8496. value: null
  8497. },
  8498. alphaMap: {
  8499. value: null
  8500. },
  8501. alphaTest: {
  8502. value: 0
  8503. },
  8504. uvTransform: {
  8505. value: /*@__PURE__*/new Matrix3()
  8506. }
  8507. }
  8508. };
  8509. const ShaderLib = {
  8510. basic: {
  8511. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8512. vertexShader: ShaderChunk.meshbasic_vert,
  8513. fragmentShader: ShaderChunk.meshbasic_frag
  8514. },
  8515. lambert: {
  8516. 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, {
  8517. emissive: {
  8518. value: /*@__PURE__*/new Color(0x000000)
  8519. }
  8520. }]),
  8521. vertexShader: ShaderChunk.meshlambert_vert,
  8522. fragmentShader: ShaderChunk.meshlambert_frag
  8523. },
  8524. phong: {
  8525. 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, {
  8526. emissive: {
  8527. value: /*@__PURE__*/new Color(0x000000)
  8528. },
  8529. specular: {
  8530. value: /*@__PURE__*/new Color(0x111111)
  8531. },
  8532. shininess: {
  8533. value: 30
  8534. }
  8535. }]),
  8536. vertexShader: ShaderChunk.meshphong_vert,
  8537. fragmentShader: ShaderChunk.meshphong_frag
  8538. },
  8539. standard: {
  8540. 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, {
  8541. emissive: {
  8542. value: /*@__PURE__*/new Color(0x000000)
  8543. },
  8544. roughness: {
  8545. value: 1.0
  8546. },
  8547. metalness: {
  8548. value: 0.0
  8549. },
  8550. envMapIntensity: {
  8551. value: 1
  8552. } // temporary
  8553. }]),
  8554. vertexShader: ShaderChunk.meshphysical_vert,
  8555. fragmentShader: ShaderChunk.meshphysical_frag
  8556. },
  8557. toon: {
  8558. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8559. emissive: {
  8560. value: /*@__PURE__*/new Color(0x000000)
  8561. }
  8562. }]),
  8563. vertexShader: ShaderChunk.meshtoon_vert,
  8564. fragmentShader: ShaderChunk.meshtoon_frag
  8565. },
  8566. matcap: {
  8567. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8568. matcap: {
  8569. value: null
  8570. }
  8571. }]),
  8572. vertexShader: ShaderChunk.meshmatcap_vert,
  8573. fragmentShader: ShaderChunk.meshmatcap_frag
  8574. },
  8575. points: {
  8576. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8577. vertexShader: ShaderChunk.points_vert,
  8578. fragmentShader: ShaderChunk.points_frag
  8579. },
  8580. dashed: {
  8581. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8582. scale: {
  8583. value: 1
  8584. },
  8585. dashSize: {
  8586. value: 1
  8587. },
  8588. totalSize: {
  8589. value: 2
  8590. }
  8591. }]),
  8592. vertexShader: ShaderChunk.linedashed_vert,
  8593. fragmentShader: ShaderChunk.linedashed_frag
  8594. },
  8595. depth: {
  8596. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8597. vertexShader: ShaderChunk.depth_vert,
  8598. fragmentShader: ShaderChunk.depth_frag
  8599. },
  8600. normal: {
  8601. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8602. opacity: {
  8603. value: 1.0
  8604. }
  8605. }]),
  8606. vertexShader: ShaderChunk.meshnormal_vert,
  8607. fragmentShader: ShaderChunk.meshnormal_frag
  8608. },
  8609. sprite: {
  8610. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8611. vertexShader: ShaderChunk.sprite_vert,
  8612. fragmentShader: ShaderChunk.sprite_frag
  8613. },
  8614. background: {
  8615. uniforms: {
  8616. uvTransform: {
  8617. value: /*@__PURE__*/new Matrix3()
  8618. },
  8619. t2D: {
  8620. value: null
  8621. }
  8622. },
  8623. vertexShader: ShaderChunk.background_vert,
  8624. fragmentShader: ShaderChunk.background_frag
  8625. },
  8626. cube: {
  8627. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.envmap, {
  8628. opacity: {
  8629. value: 1.0
  8630. }
  8631. }]),
  8632. vertexShader: ShaderChunk.cube_vert,
  8633. fragmentShader: ShaderChunk.cube_frag
  8634. },
  8635. equirect: {
  8636. uniforms: {
  8637. tEquirect: {
  8638. value: null
  8639. }
  8640. },
  8641. vertexShader: ShaderChunk.equirect_vert,
  8642. fragmentShader: ShaderChunk.equirect_frag
  8643. },
  8644. distanceRGBA: {
  8645. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8646. referencePosition: {
  8647. value: /*@__PURE__*/new Vector3()
  8648. },
  8649. nearDistance: {
  8650. value: 1
  8651. },
  8652. farDistance: {
  8653. value: 1000
  8654. }
  8655. }]),
  8656. vertexShader: ShaderChunk.distanceRGBA_vert,
  8657. fragmentShader: ShaderChunk.distanceRGBA_frag
  8658. },
  8659. shadow: {
  8660. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8661. color: {
  8662. value: /*@__PURE__*/new Color(0x00000)
  8663. },
  8664. opacity: {
  8665. value: 1.0
  8666. }
  8667. }]),
  8668. vertexShader: ShaderChunk.shadow_vert,
  8669. fragmentShader: ShaderChunk.shadow_frag
  8670. }
  8671. };
  8672. ShaderLib.physical = {
  8673. uniforms: /*@__PURE__*/mergeUniforms([ShaderLib.standard.uniforms, {
  8674. clearcoat: {
  8675. value: 0
  8676. },
  8677. clearcoatMap: {
  8678. value: null
  8679. },
  8680. clearcoatRoughness: {
  8681. value: 0
  8682. },
  8683. clearcoatRoughnessMap: {
  8684. value: null
  8685. },
  8686. clearcoatNormalScale: {
  8687. value: /*@__PURE__*/new Vector2(1, 1)
  8688. },
  8689. clearcoatNormalMap: {
  8690. value: null
  8691. },
  8692. iridescence: {
  8693. value: 0
  8694. },
  8695. iridescenceMap: {
  8696. value: null
  8697. },
  8698. iridescenceIOR: {
  8699. value: 1.3
  8700. },
  8701. iridescenceThicknessMinimum: {
  8702. value: 100
  8703. },
  8704. iridescenceThicknessMaximum: {
  8705. value: 400
  8706. },
  8707. iridescenceThicknessMap: {
  8708. value: null
  8709. },
  8710. sheen: {
  8711. value: 0
  8712. },
  8713. sheenColor: {
  8714. value: /*@__PURE__*/new Color(0x000000)
  8715. },
  8716. sheenColorMap: {
  8717. value: null
  8718. },
  8719. sheenRoughness: {
  8720. value: 1
  8721. },
  8722. sheenRoughnessMap: {
  8723. value: null
  8724. },
  8725. transmission: {
  8726. value: 0
  8727. },
  8728. transmissionMap: {
  8729. value: null
  8730. },
  8731. transmissionSamplerSize: {
  8732. value: /*@__PURE__*/new Vector2()
  8733. },
  8734. transmissionSamplerMap: {
  8735. value: null
  8736. },
  8737. thickness: {
  8738. value: 0
  8739. },
  8740. thicknessMap: {
  8741. value: null
  8742. },
  8743. attenuationDistance: {
  8744. value: 0
  8745. },
  8746. attenuationColor: {
  8747. value: /*@__PURE__*/new Color(0x000000)
  8748. },
  8749. specularIntensity: {
  8750. value: 1
  8751. },
  8752. specularIntensityMap: {
  8753. value: null
  8754. },
  8755. specularColor: {
  8756. value: /*@__PURE__*/new Color(1, 1, 1)
  8757. },
  8758. specularColorMap: {
  8759. value: null
  8760. }
  8761. }]),
  8762. vertexShader: ShaderChunk.meshphysical_vert,
  8763. fragmentShader: ShaderChunk.meshphysical_frag
  8764. };
  8765. function WebGLBackground(renderer, cubemaps, state, objects, alpha, premultipliedAlpha) {
  8766. const clearColor = new Color(0x000000);
  8767. let clearAlpha = alpha === true ? 0 : 1;
  8768. let planeMesh;
  8769. let boxMesh;
  8770. let currentBackground = null;
  8771. let currentBackgroundVersion = 0;
  8772. let currentTonemapping = null;
  8773. function render(renderList, scene) {
  8774. let forceClear = false;
  8775. let background = scene.isScene === true ? scene.background : null;
  8776. if (background && background.isTexture) {
  8777. background = cubemaps.get(background);
  8778. } // Ignore background in AR
  8779. // TODO: Reconsider this.
  8780. const xr = renderer.xr;
  8781. const session = xr.getSession && xr.getSession();
  8782. if (session && session.environmentBlendMode === 'additive') {
  8783. background = null;
  8784. }
  8785. if (background === null) {
  8786. setClear(clearColor, clearAlpha);
  8787. } else if (background && background.isColor) {
  8788. setClear(background, 1);
  8789. forceClear = true;
  8790. }
  8791. if (renderer.autoClear || forceClear) {
  8792. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8793. }
  8794. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8795. if (boxMesh === undefined) {
  8796. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8797. name: 'BackgroundCubeMaterial',
  8798. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8799. vertexShader: ShaderLib.cube.vertexShader,
  8800. fragmentShader: ShaderLib.cube.fragmentShader,
  8801. side: BackSide,
  8802. depthTest: false,
  8803. depthWrite: false,
  8804. fog: false
  8805. }));
  8806. boxMesh.geometry.deleteAttribute('normal');
  8807. boxMesh.geometry.deleteAttribute('uv');
  8808. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8809. this.matrixWorld.copyPosition(camera.matrixWorld);
  8810. }; // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8811. Object.defineProperty(boxMesh.material, 'envMap', {
  8812. get: function () {
  8813. return this.uniforms.envMap.value;
  8814. }
  8815. });
  8816. objects.update(boxMesh);
  8817. }
  8818. boxMesh.material.uniforms.envMap.value = background;
  8819. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8820. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8821. boxMesh.material.needsUpdate = true;
  8822. currentBackground = background;
  8823. currentBackgroundVersion = background.version;
  8824. currentTonemapping = renderer.toneMapping;
  8825. }
  8826. boxMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8827. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8828. } else if (background && background.isTexture) {
  8829. if (planeMesh === undefined) {
  8830. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8831. name: 'BackgroundMaterial',
  8832. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8833. vertexShader: ShaderLib.background.vertexShader,
  8834. fragmentShader: ShaderLib.background.fragmentShader,
  8835. side: FrontSide,
  8836. depthTest: false,
  8837. depthWrite: false,
  8838. fog: false
  8839. }));
  8840. planeMesh.geometry.deleteAttribute('normal'); // add "map" material property so the renderer can evaluate it like for built-in materials
  8841. Object.defineProperty(planeMesh.material, 'map', {
  8842. get: function () {
  8843. return this.uniforms.t2D.value;
  8844. }
  8845. });
  8846. objects.update(planeMesh);
  8847. }
  8848. planeMesh.material.uniforms.t2D.value = background;
  8849. if (background.matrixAutoUpdate === true) {
  8850. background.updateMatrix();
  8851. }
  8852. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8853. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8854. planeMesh.material.needsUpdate = true;
  8855. currentBackground = background;
  8856. currentBackgroundVersion = background.version;
  8857. currentTonemapping = renderer.toneMapping;
  8858. }
  8859. planeMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8860. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8861. }
  8862. }
  8863. function setClear(color, alpha) {
  8864. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8865. }
  8866. return {
  8867. getClearColor: function () {
  8868. return clearColor;
  8869. },
  8870. setClearColor: function (color, alpha = 1) {
  8871. clearColor.set(color);
  8872. clearAlpha = alpha;
  8873. setClear(clearColor, clearAlpha);
  8874. },
  8875. getClearAlpha: function () {
  8876. return clearAlpha;
  8877. },
  8878. setClearAlpha: function (alpha) {
  8879. clearAlpha = alpha;
  8880. setClear(clearColor, clearAlpha);
  8881. },
  8882. render: render
  8883. };
  8884. }
  8885. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8886. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8887. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8888. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8889. const bindingStates = {};
  8890. const defaultState = createBindingState(null);
  8891. let currentState = defaultState;
  8892. let forceUpdate = false;
  8893. function setup(object, material, program, geometry, index) {
  8894. let updateBuffers = false;
  8895. if (vaoAvailable) {
  8896. const state = getBindingState(geometry, program, material);
  8897. if (currentState !== state) {
  8898. currentState = state;
  8899. bindVertexArrayObject(currentState.object);
  8900. }
  8901. updateBuffers = needsUpdate(object, geometry, program, index);
  8902. if (updateBuffers) saveCache(object, geometry, program, index);
  8903. } else {
  8904. const wireframe = material.wireframe === true;
  8905. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8906. currentState.geometry = geometry.id;
  8907. currentState.program = program.id;
  8908. currentState.wireframe = wireframe;
  8909. updateBuffers = true;
  8910. }
  8911. }
  8912. if (index !== null) {
  8913. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8914. }
  8915. if (updateBuffers || forceUpdate) {
  8916. forceUpdate = false;
  8917. setupVertexAttributes(object, material, program, geometry);
  8918. if (index !== null) {
  8919. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8920. }
  8921. }
  8922. }
  8923. function createVertexArrayObject() {
  8924. if (capabilities.isWebGL2) return gl.createVertexArray();
  8925. return extension.createVertexArrayOES();
  8926. }
  8927. function bindVertexArrayObject(vao) {
  8928. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8929. return extension.bindVertexArrayOES(vao);
  8930. }
  8931. function deleteVertexArrayObject(vao) {
  8932. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8933. return extension.deleteVertexArrayOES(vao);
  8934. }
  8935. function getBindingState(geometry, program, material) {
  8936. const wireframe = material.wireframe === true;
  8937. let programMap = bindingStates[geometry.id];
  8938. if (programMap === undefined) {
  8939. programMap = {};
  8940. bindingStates[geometry.id] = programMap;
  8941. }
  8942. let stateMap = programMap[program.id];
  8943. if (stateMap === undefined) {
  8944. stateMap = {};
  8945. programMap[program.id] = stateMap;
  8946. }
  8947. let state = stateMap[wireframe];
  8948. if (state === undefined) {
  8949. state = createBindingState(createVertexArrayObject());
  8950. stateMap[wireframe] = state;
  8951. }
  8952. return state;
  8953. }
  8954. function createBindingState(vao) {
  8955. const newAttributes = [];
  8956. const enabledAttributes = [];
  8957. const attributeDivisors = [];
  8958. for (let i = 0; i < maxVertexAttributes; i++) {
  8959. newAttributes[i] = 0;
  8960. enabledAttributes[i] = 0;
  8961. attributeDivisors[i] = 0;
  8962. }
  8963. return {
  8964. // for backward compatibility on non-VAO support browser
  8965. geometry: null,
  8966. program: null,
  8967. wireframe: false,
  8968. newAttributes: newAttributes,
  8969. enabledAttributes: enabledAttributes,
  8970. attributeDivisors: attributeDivisors,
  8971. object: vao,
  8972. attributes: {},
  8973. index: null
  8974. };
  8975. }
  8976. function needsUpdate(object, geometry, program, index) {
  8977. const cachedAttributes = currentState.attributes;
  8978. const geometryAttributes = geometry.attributes;
  8979. let attributesNum = 0;
  8980. const programAttributes = program.getAttributes();
  8981. for (const name in programAttributes) {
  8982. const programAttribute = programAttributes[name];
  8983. if (programAttribute.location >= 0) {
  8984. const cachedAttribute = cachedAttributes[name];
  8985. let geometryAttribute = geometryAttributes[name];
  8986. if (geometryAttribute === undefined) {
  8987. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8988. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8989. }
  8990. if (cachedAttribute === undefined) return true;
  8991. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8992. if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true;
  8993. attributesNum++;
  8994. }
  8995. }
  8996. if (currentState.attributesNum !== attributesNum) return true;
  8997. if (currentState.index !== index) return true;
  8998. return false;
  8999. }
  9000. function saveCache(object, geometry, program, index) {
  9001. const cache = {};
  9002. const attributes = geometry.attributes;
  9003. let attributesNum = 0;
  9004. const programAttributes = program.getAttributes();
  9005. for (const name in programAttributes) {
  9006. const programAttribute = programAttributes[name];
  9007. if (programAttribute.location >= 0) {
  9008. let attribute = attributes[name];
  9009. if (attribute === undefined) {
  9010. if (name === 'instanceMatrix' && object.instanceMatrix) attribute = object.instanceMatrix;
  9011. if (name === 'instanceColor' && object.instanceColor) attribute = object.instanceColor;
  9012. }
  9013. const data = {};
  9014. data.attribute = attribute;
  9015. if (attribute && attribute.data) {
  9016. data.data = attribute.data;
  9017. }
  9018. cache[name] = data;
  9019. attributesNum++;
  9020. }
  9021. }
  9022. currentState.attributes = cache;
  9023. currentState.attributesNum = attributesNum;
  9024. currentState.index = index;
  9025. }
  9026. function initAttributes() {
  9027. const newAttributes = currentState.newAttributes;
  9028. for (let i = 0, il = newAttributes.length; i < il; i++) {
  9029. newAttributes[i] = 0;
  9030. }
  9031. }
  9032. function enableAttribute(attribute) {
  9033. enableAttributeAndDivisor(attribute, 0);
  9034. }
  9035. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  9036. const newAttributes = currentState.newAttributes;
  9037. const enabledAttributes = currentState.enabledAttributes;
  9038. const attributeDivisors = currentState.attributeDivisors;
  9039. newAttributes[attribute] = 1;
  9040. if (enabledAttributes[attribute] === 0) {
  9041. gl.enableVertexAttribArray(attribute);
  9042. enabledAttributes[attribute] = 1;
  9043. }
  9044. if (attributeDivisors[attribute] !== meshPerAttribute) {
  9045. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  9046. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  9047. attributeDivisors[attribute] = meshPerAttribute;
  9048. }
  9049. }
  9050. function disableUnusedAttributes() {
  9051. const newAttributes = currentState.newAttributes;
  9052. const enabledAttributes = currentState.enabledAttributes;
  9053. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  9054. if (enabledAttributes[i] !== newAttributes[i]) {
  9055. gl.disableVertexAttribArray(i);
  9056. enabledAttributes[i] = 0;
  9057. }
  9058. }
  9059. }
  9060. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9061. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  9062. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9063. } else {
  9064. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9065. }
  9066. }
  9067. function setupVertexAttributes(object, material, program, geometry) {
  9068. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9069. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9070. }
  9071. initAttributes();
  9072. const geometryAttributes = geometry.attributes;
  9073. const programAttributes = program.getAttributes();
  9074. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9075. for (const name in programAttributes) {
  9076. const programAttribute = programAttributes[name];
  9077. if (programAttribute.location >= 0) {
  9078. let geometryAttribute = geometryAttributes[name];
  9079. if (geometryAttribute === undefined) {
  9080. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9081. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9082. }
  9083. if (geometryAttribute !== undefined) {
  9084. const normalized = geometryAttribute.normalized;
  9085. const size = geometryAttribute.itemSize;
  9086. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  9087. if (attribute === undefined) continue;
  9088. const buffer = attribute.buffer;
  9089. const type = attribute.type;
  9090. const bytesPerElement = attribute.bytesPerElement;
  9091. if (geometryAttribute.isInterleavedBufferAttribute) {
  9092. const data = geometryAttribute.data;
  9093. const stride = data.stride;
  9094. const offset = geometryAttribute.offset;
  9095. if (data.isInstancedInterleavedBuffer) {
  9096. for (let i = 0; i < programAttribute.locationSize; i++) {
  9097. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  9098. }
  9099. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9100. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9101. }
  9102. } else {
  9103. for (let i = 0; i < programAttribute.locationSize; i++) {
  9104. enableAttribute(programAttribute.location + i);
  9105. }
  9106. }
  9107. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9108. for (let i = 0; i < programAttribute.locationSize; i++) {
  9109. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  9110. }
  9111. } else {
  9112. if (geometryAttribute.isInstancedBufferAttribute) {
  9113. for (let i = 0; i < programAttribute.locationSize; i++) {
  9114. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  9115. }
  9116. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9117. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9118. }
  9119. } else {
  9120. for (let i = 0; i < programAttribute.locationSize; i++) {
  9121. enableAttribute(programAttribute.location + i);
  9122. }
  9123. }
  9124. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9125. for (let i = 0; i < programAttribute.locationSize; i++) {
  9126. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  9127. }
  9128. }
  9129. } else if (materialDefaultAttributeValues !== undefined) {
  9130. const value = materialDefaultAttributeValues[name];
  9131. if (value !== undefined) {
  9132. switch (value.length) {
  9133. case 2:
  9134. gl.vertexAttrib2fv(programAttribute.location, value);
  9135. break;
  9136. case 3:
  9137. gl.vertexAttrib3fv(programAttribute.location, value);
  9138. break;
  9139. case 4:
  9140. gl.vertexAttrib4fv(programAttribute.location, value);
  9141. break;
  9142. default:
  9143. gl.vertexAttrib1fv(programAttribute.location, value);
  9144. }
  9145. }
  9146. }
  9147. }
  9148. }
  9149. disableUnusedAttributes();
  9150. }
  9151. function dispose() {
  9152. reset();
  9153. for (const geometryId in bindingStates) {
  9154. const programMap = bindingStates[geometryId];
  9155. for (const programId in programMap) {
  9156. const stateMap = programMap[programId];
  9157. for (const wireframe in stateMap) {
  9158. deleteVertexArrayObject(stateMap[wireframe].object);
  9159. delete stateMap[wireframe];
  9160. }
  9161. delete programMap[programId];
  9162. }
  9163. delete bindingStates[geometryId];
  9164. }
  9165. }
  9166. function releaseStatesOfGeometry(geometry) {
  9167. if (bindingStates[geometry.id] === undefined) return;
  9168. const programMap = bindingStates[geometry.id];
  9169. for (const programId in programMap) {
  9170. const stateMap = programMap[programId];
  9171. for (const wireframe in stateMap) {
  9172. deleteVertexArrayObject(stateMap[wireframe].object);
  9173. delete stateMap[wireframe];
  9174. }
  9175. delete programMap[programId];
  9176. }
  9177. delete bindingStates[geometry.id];
  9178. }
  9179. function releaseStatesOfProgram(program) {
  9180. for (const geometryId in bindingStates) {
  9181. const programMap = bindingStates[geometryId];
  9182. if (programMap[program.id] === undefined) continue;
  9183. const stateMap = programMap[program.id];
  9184. for (const wireframe in stateMap) {
  9185. deleteVertexArrayObject(stateMap[wireframe].object);
  9186. delete stateMap[wireframe];
  9187. }
  9188. delete programMap[program.id];
  9189. }
  9190. }
  9191. function reset() {
  9192. resetDefaultState();
  9193. forceUpdate = true;
  9194. if (currentState === defaultState) return;
  9195. currentState = defaultState;
  9196. bindVertexArrayObject(currentState.object);
  9197. } // for backward-compatibility
  9198. function resetDefaultState() {
  9199. defaultState.geometry = null;
  9200. defaultState.program = null;
  9201. defaultState.wireframe = false;
  9202. }
  9203. return {
  9204. setup: setup,
  9205. reset: reset,
  9206. resetDefaultState: resetDefaultState,
  9207. dispose: dispose,
  9208. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9209. releaseStatesOfProgram: releaseStatesOfProgram,
  9210. initAttributes: initAttributes,
  9211. enableAttribute: enableAttribute,
  9212. disableUnusedAttributes: disableUnusedAttributes
  9213. };
  9214. }
  9215. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9216. const isWebGL2 = capabilities.isWebGL2;
  9217. let mode;
  9218. function setMode(value) {
  9219. mode = value;
  9220. }
  9221. function render(start, count) {
  9222. gl.drawArrays(mode, start, count);
  9223. info.update(count, mode, 1);
  9224. }
  9225. function renderInstances(start, count, primcount) {
  9226. if (primcount === 0) return;
  9227. let extension, methodName;
  9228. if (isWebGL2) {
  9229. extension = gl;
  9230. methodName = 'drawArraysInstanced';
  9231. } else {
  9232. extension = extensions.get('ANGLE_instanced_arrays');
  9233. methodName = 'drawArraysInstancedANGLE';
  9234. if (extension === null) {
  9235. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9236. return;
  9237. }
  9238. }
  9239. extension[methodName](mode, start, count, primcount);
  9240. info.update(count, mode, primcount);
  9241. } //
  9242. this.setMode = setMode;
  9243. this.render = render;
  9244. this.renderInstances = renderInstances;
  9245. }
  9246. function WebGLCapabilities(gl, extensions, parameters) {
  9247. let maxAnisotropy;
  9248. function getMaxAnisotropy() {
  9249. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9250. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9251. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9252. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9253. } else {
  9254. maxAnisotropy = 0;
  9255. }
  9256. return maxAnisotropy;
  9257. }
  9258. function getMaxPrecision(precision) {
  9259. if (precision === 'highp') {
  9260. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9261. return 'highp';
  9262. }
  9263. precision = 'mediump';
  9264. }
  9265. if (precision === 'mediump') {
  9266. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9267. return 'mediump';
  9268. }
  9269. }
  9270. return 'lowp';
  9271. }
  9272. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9273. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9274. const maxPrecision = getMaxPrecision(precision);
  9275. if (maxPrecision !== precision) {
  9276. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9277. precision = maxPrecision;
  9278. }
  9279. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9280. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9281. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9282. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9283. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9284. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9285. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9286. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9287. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9288. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9289. const vertexTextures = maxVertexTextures > 0;
  9290. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9291. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9292. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9293. return {
  9294. isWebGL2: isWebGL2,
  9295. drawBuffers: drawBuffers,
  9296. getMaxAnisotropy: getMaxAnisotropy,
  9297. getMaxPrecision: getMaxPrecision,
  9298. precision: precision,
  9299. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9300. maxTextures: maxTextures,
  9301. maxVertexTextures: maxVertexTextures,
  9302. maxTextureSize: maxTextureSize,
  9303. maxCubemapSize: maxCubemapSize,
  9304. maxAttributes: maxAttributes,
  9305. maxVertexUniforms: maxVertexUniforms,
  9306. maxVaryings: maxVaryings,
  9307. maxFragmentUniforms: maxFragmentUniforms,
  9308. vertexTextures: vertexTextures,
  9309. floatFragmentTextures: floatFragmentTextures,
  9310. floatVertexTextures: floatVertexTextures,
  9311. maxSamples: maxSamples
  9312. };
  9313. }
  9314. function WebGLClipping(properties) {
  9315. const scope = this;
  9316. let globalState = null,
  9317. numGlobalPlanes = 0,
  9318. localClippingEnabled = false,
  9319. renderingShadows = false;
  9320. const plane = new Plane(),
  9321. viewNormalMatrix = new Matrix3(),
  9322. uniform = {
  9323. value: null,
  9324. needsUpdate: false
  9325. };
  9326. this.uniform = uniform;
  9327. this.numPlanes = 0;
  9328. this.numIntersection = 0;
  9329. this.init = function (planes, enableLocalClipping, camera) {
  9330. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9331. // run another frame in order to reset the state:
  9332. numGlobalPlanes !== 0 || localClippingEnabled;
  9333. localClippingEnabled = enableLocalClipping;
  9334. globalState = projectPlanes(planes, camera, 0);
  9335. numGlobalPlanes = planes.length;
  9336. return enabled;
  9337. };
  9338. this.beginShadows = function () {
  9339. renderingShadows = true;
  9340. projectPlanes(null);
  9341. };
  9342. this.endShadows = function () {
  9343. renderingShadows = false;
  9344. resetGlobalState();
  9345. };
  9346. this.setState = function (material, camera, useCache) {
  9347. const planes = material.clippingPlanes,
  9348. clipIntersection = material.clipIntersection,
  9349. clipShadows = material.clipShadows;
  9350. const materialProperties = properties.get(material);
  9351. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9352. // there's no local clipping
  9353. if (renderingShadows) {
  9354. // there's no global clipping
  9355. projectPlanes(null);
  9356. } else {
  9357. resetGlobalState();
  9358. }
  9359. } else {
  9360. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9361. lGlobal = nGlobal * 4;
  9362. let dstArray = materialProperties.clippingState || null;
  9363. uniform.value = dstArray; // ensure unique state
  9364. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9365. for (let i = 0; i !== lGlobal; ++i) {
  9366. dstArray[i] = globalState[i];
  9367. }
  9368. materialProperties.clippingState = dstArray;
  9369. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9370. this.numPlanes += nGlobal;
  9371. }
  9372. };
  9373. function resetGlobalState() {
  9374. if (uniform.value !== globalState) {
  9375. uniform.value = globalState;
  9376. uniform.needsUpdate = numGlobalPlanes > 0;
  9377. }
  9378. scope.numPlanes = numGlobalPlanes;
  9379. scope.numIntersection = 0;
  9380. }
  9381. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9382. const nPlanes = planes !== null ? planes.length : 0;
  9383. let dstArray = null;
  9384. if (nPlanes !== 0) {
  9385. dstArray = uniform.value;
  9386. if (skipTransform !== true || dstArray === null) {
  9387. const flatSize = dstOffset + nPlanes * 4,
  9388. viewMatrix = camera.matrixWorldInverse;
  9389. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9390. if (dstArray === null || dstArray.length < flatSize) {
  9391. dstArray = new Float32Array(flatSize);
  9392. }
  9393. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9394. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9395. plane.normal.toArray(dstArray, i4);
  9396. dstArray[i4 + 3] = plane.constant;
  9397. }
  9398. }
  9399. uniform.value = dstArray;
  9400. uniform.needsUpdate = true;
  9401. }
  9402. scope.numPlanes = nPlanes;
  9403. scope.numIntersection = 0;
  9404. return dstArray;
  9405. }
  9406. }
  9407. function WebGLCubeMaps(renderer) {
  9408. let cubemaps = new WeakMap();
  9409. function mapTextureMapping(texture, mapping) {
  9410. if (mapping === EquirectangularReflectionMapping) {
  9411. texture.mapping = CubeReflectionMapping;
  9412. } else if (mapping === EquirectangularRefractionMapping) {
  9413. texture.mapping = CubeRefractionMapping;
  9414. }
  9415. return texture;
  9416. }
  9417. function get(texture) {
  9418. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9419. const mapping = texture.mapping;
  9420. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9421. if (cubemaps.has(texture)) {
  9422. const cubemap = cubemaps.get(texture).texture;
  9423. return mapTextureMapping(cubemap, texture.mapping);
  9424. } else {
  9425. const image = texture.image;
  9426. if (image && image.height > 0) {
  9427. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9428. renderTarget.fromEquirectangularTexture(renderer, texture);
  9429. cubemaps.set(texture, renderTarget);
  9430. texture.addEventListener('dispose', onTextureDispose);
  9431. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9432. } else {
  9433. // image not yet ready. try the conversion next frame
  9434. return null;
  9435. }
  9436. }
  9437. }
  9438. }
  9439. return texture;
  9440. }
  9441. function onTextureDispose(event) {
  9442. const texture = event.target;
  9443. texture.removeEventListener('dispose', onTextureDispose);
  9444. const cubemap = cubemaps.get(texture);
  9445. if (cubemap !== undefined) {
  9446. cubemaps.delete(texture);
  9447. cubemap.dispose();
  9448. }
  9449. }
  9450. function dispose() {
  9451. cubemaps = new WeakMap();
  9452. }
  9453. return {
  9454. get: get,
  9455. dispose: dispose
  9456. };
  9457. }
  9458. class OrthographicCamera extends Camera {
  9459. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9460. super();
  9461. this.isOrthographicCamera = true;
  9462. this.type = 'OrthographicCamera';
  9463. this.zoom = 1;
  9464. this.view = null;
  9465. this.left = left;
  9466. this.right = right;
  9467. this.top = top;
  9468. this.bottom = bottom;
  9469. this.near = near;
  9470. this.far = far;
  9471. this.updateProjectionMatrix();
  9472. }
  9473. copy(source, recursive) {
  9474. super.copy(source, recursive);
  9475. this.left = source.left;
  9476. this.right = source.right;
  9477. this.top = source.top;
  9478. this.bottom = source.bottom;
  9479. this.near = source.near;
  9480. this.far = source.far;
  9481. this.zoom = source.zoom;
  9482. this.view = source.view === null ? null : Object.assign({}, source.view);
  9483. return this;
  9484. }
  9485. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9486. if (this.view === null) {
  9487. this.view = {
  9488. enabled: true,
  9489. fullWidth: 1,
  9490. fullHeight: 1,
  9491. offsetX: 0,
  9492. offsetY: 0,
  9493. width: 1,
  9494. height: 1
  9495. };
  9496. }
  9497. this.view.enabled = true;
  9498. this.view.fullWidth = fullWidth;
  9499. this.view.fullHeight = fullHeight;
  9500. this.view.offsetX = x;
  9501. this.view.offsetY = y;
  9502. this.view.width = width;
  9503. this.view.height = height;
  9504. this.updateProjectionMatrix();
  9505. }
  9506. clearViewOffset() {
  9507. if (this.view !== null) {
  9508. this.view.enabled = false;
  9509. }
  9510. this.updateProjectionMatrix();
  9511. }
  9512. updateProjectionMatrix() {
  9513. const dx = (this.right - this.left) / (2 * this.zoom);
  9514. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9515. const cx = (this.right + this.left) / 2;
  9516. const cy = (this.top + this.bottom) / 2;
  9517. let left = cx - dx;
  9518. let right = cx + dx;
  9519. let top = cy + dy;
  9520. let bottom = cy - dy;
  9521. if (this.view !== null && this.view.enabled) {
  9522. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9523. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9524. left += scaleW * this.view.offsetX;
  9525. right = left + scaleW * this.view.width;
  9526. top -= scaleH * this.view.offsetY;
  9527. bottom = top - scaleH * this.view.height;
  9528. }
  9529. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9530. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9531. }
  9532. toJSON(meta) {
  9533. const data = super.toJSON(meta);
  9534. data.object.zoom = this.zoom;
  9535. data.object.left = this.left;
  9536. data.object.right = this.right;
  9537. data.object.top = this.top;
  9538. data.object.bottom = this.bottom;
  9539. data.object.near = this.near;
  9540. data.object.far = this.far;
  9541. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9542. return data;
  9543. }
  9544. }
  9545. const LOD_MIN = 4; // The standard deviations (radians) associated with the extra mips. These are
  9546. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9547. // geometric shadowing function. These sigma values squared must match the
  9548. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9549. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9550. // samples and exit early, but not recompile the shader.
  9551. const MAX_SAMPLES = 20;
  9552. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9553. const _clearColor = /*@__PURE__*/new Color();
  9554. let _oldTarget = null; // Golden Ratio
  9555. const PHI = (1 + Math.sqrt(5)) / 2;
  9556. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9557. // same axis), used as axis directions evenly spread on a sphere.
  9558. 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)];
  9559. /**
  9560. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9561. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9562. * blur to be quickly accessed based on material roughness. It is packed into a
  9563. * special CubeUV format that allows us to perform custom interpolation so that
  9564. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9565. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9566. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9567. * higher roughness levels. In this way we maintain resolution to smoothly
  9568. * interpolate diffuse lighting while limiting sampling computation.
  9569. *
  9570. * Paper: Fast, Accurate Image-Based Lighting
  9571. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9572. */
  9573. class PMREMGenerator {
  9574. constructor(renderer) {
  9575. this._renderer = renderer;
  9576. this._pingPongRenderTarget = null;
  9577. this._lodMax = 0;
  9578. this._cubeSize = 0;
  9579. this._lodPlanes = [];
  9580. this._sizeLods = [];
  9581. this._sigmas = [];
  9582. this._blurMaterial = null;
  9583. this._cubemapMaterial = null;
  9584. this._equirectMaterial = null;
  9585. this._compileMaterial(this._blurMaterial);
  9586. }
  9587. /**
  9588. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9589. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9590. * in radians to be applied to the scene before PMREM generation. Optional near
  9591. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9592. * is placed at the origin).
  9593. */
  9594. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9595. _oldTarget = this._renderer.getRenderTarget();
  9596. this._setSize(256);
  9597. const cubeUVRenderTarget = this._allocateTargets();
  9598. cubeUVRenderTarget.depthBuffer = true;
  9599. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9600. if (sigma > 0) {
  9601. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9602. }
  9603. this._applyPMREM(cubeUVRenderTarget);
  9604. this._cleanup(cubeUVRenderTarget);
  9605. return cubeUVRenderTarget;
  9606. }
  9607. /**
  9608. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9609. * or HDR. The ideal input image size is 1k (1024 x 512),
  9610. * as this matches best with the 256 x 256 cubemap output.
  9611. */
  9612. fromEquirectangular(equirectangular, renderTarget = null) {
  9613. return this._fromTexture(equirectangular, renderTarget);
  9614. }
  9615. /**
  9616. * Generates a PMREM from an cubemap texture, which can be either LDR
  9617. * or HDR. The ideal input cube size is 256 x 256,
  9618. * as this matches best with the 256 x 256 cubemap output.
  9619. */
  9620. fromCubemap(cubemap, renderTarget = null) {
  9621. return this._fromTexture(cubemap, renderTarget);
  9622. }
  9623. /**
  9624. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9625. * your texture's network fetch for increased concurrency.
  9626. */
  9627. compileCubemapShader() {
  9628. if (this._cubemapMaterial === null) {
  9629. this._cubemapMaterial = _getCubemapMaterial();
  9630. this._compileMaterial(this._cubemapMaterial);
  9631. }
  9632. }
  9633. /**
  9634. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9635. * your texture's network fetch for increased concurrency.
  9636. */
  9637. compileEquirectangularShader() {
  9638. if (this._equirectMaterial === null) {
  9639. this._equirectMaterial = _getEquirectMaterial();
  9640. this._compileMaterial(this._equirectMaterial);
  9641. }
  9642. }
  9643. /**
  9644. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9645. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9646. * one of them will cause any others to also become unusable.
  9647. */
  9648. dispose() {
  9649. this._dispose();
  9650. if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose();
  9651. if (this._equirectMaterial !== null) this._equirectMaterial.dispose();
  9652. } // private interface
  9653. _setSize(cubeSize) {
  9654. this._lodMax = Math.floor(Math.log2(cubeSize));
  9655. this._cubeSize = Math.pow(2, this._lodMax);
  9656. }
  9657. _dispose() {
  9658. if (this._blurMaterial !== null) this._blurMaterial.dispose();
  9659. if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
  9660. for (let i = 0; i < this._lodPlanes.length; i++) {
  9661. this._lodPlanes[i].dispose();
  9662. }
  9663. }
  9664. _cleanup(outputTarget) {
  9665. this._renderer.setRenderTarget(_oldTarget);
  9666. outputTarget.scissorTest = false;
  9667. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9668. }
  9669. _fromTexture(texture, renderTarget) {
  9670. if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) {
  9671. this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width);
  9672. } else {
  9673. // Equirectangular
  9674. this._setSize(texture.image.width / 4);
  9675. }
  9676. _oldTarget = this._renderer.getRenderTarget();
  9677. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9678. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9679. this._applyPMREM(cubeUVRenderTarget);
  9680. this._cleanup(cubeUVRenderTarget);
  9681. return cubeUVRenderTarget;
  9682. }
  9683. _allocateTargets() {
  9684. const width = 3 * Math.max(this._cubeSize, 16 * 7);
  9685. const height = 4 * this._cubeSize;
  9686. const params = {
  9687. magFilter: LinearFilter,
  9688. minFilter: LinearFilter,
  9689. generateMipmaps: false,
  9690. type: HalfFloatType,
  9691. format: RGBAFormat,
  9692. encoding: LinearEncoding,
  9693. depthBuffer: false
  9694. };
  9695. const cubeUVRenderTarget = _createRenderTarget(width, height, params);
  9696. if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width) {
  9697. if (this._pingPongRenderTarget !== null) {
  9698. this._dispose();
  9699. }
  9700. this._pingPongRenderTarget = _createRenderTarget(width, height, params);
  9701. const {
  9702. _lodMax
  9703. } = this;
  9704. ({
  9705. sizeLods: this._sizeLods,
  9706. lodPlanes: this._lodPlanes,
  9707. sigmas: this._sigmas
  9708. } = _createPlanes(_lodMax));
  9709. this._blurMaterial = _getBlurShader(_lodMax, width, height);
  9710. }
  9711. return cubeUVRenderTarget;
  9712. }
  9713. _compileMaterial(material) {
  9714. const tmpMesh = new Mesh(this._lodPlanes[0], material);
  9715. this._renderer.compile(tmpMesh, _flatCamera);
  9716. }
  9717. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9718. const fov = 90;
  9719. const aspect = 1;
  9720. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9721. const upSign = [1, -1, 1, 1, 1, 1];
  9722. const forwardSign = [1, 1, 1, -1, -1, -1];
  9723. const renderer = this._renderer;
  9724. const originalAutoClear = renderer.autoClear;
  9725. const toneMapping = renderer.toneMapping;
  9726. renderer.getClearColor(_clearColor);
  9727. renderer.toneMapping = NoToneMapping;
  9728. renderer.autoClear = false;
  9729. const backgroundMaterial = new MeshBasicMaterial({
  9730. name: 'PMREM.Background',
  9731. side: BackSide,
  9732. depthWrite: false,
  9733. depthTest: false
  9734. });
  9735. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9736. let useSolidColor = false;
  9737. const background = scene.background;
  9738. if (background) {
  9739. if (background.isColor) {
  9740. backgroundMaterial.color.copy(background);
  9741. scene.background = null;
  9742. useSolidColor = true;
  9743. }
  9744. } else {
  9745. backgroundMaterial.color.copy(_clearColor);
  9746. useSolidColor = true;
  9747. }
  9748. for (let i = 0; i < 6; i++) {
  9749. const col = i % 3;
  9750. if (col === 0) {
  9751. cubeCamera.up.set(0, upSign[i], 0);
  9752. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9753. } else if (col === 1) {
  9754. cubeCamera.up.set(0, 0, upSign[i]);
  9755. cubeCamera.lookAt(0, forwardSign[i], 0);
  9756. } else {
  9757. cubeCamera.up.set(0, upSign[i], 0);
  9758. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9759. }
  9760. const size = this._cubeSize;
  9761. _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size);
  9762. renderer.setRenderTarget(cubeUVRenderTarget);
  9763. if (useSolidColor) {
  9764. renderer.render(backgroundBox, cubeCamera);
  9765. }
  9766. renderer.render(scene, cubeCamera);
  9767. }
  9768. backgroundBox.geometry.dispose();
  9769. backgroundBox.material.dispose();
  9770. renderer.toneMapping = toneMapping;
  9771. renderer.autoClear = originalAutoClear;
  9772. scene.background = background;
  9773. }
  9774. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9775. const renderer = this._renderer;
  9776. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9777. if (isCubeTexture) {
  9778. if (this._cubemapMaterial === null) {
  9779. this._cubemapMaterial = _getCubemapMaterial();
  9780. }
  9781. this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
  9782. } else {
  9783. if (this._equirectMaterial === null) {
  9784. this._equirectMaterial = _getEquirectMaterial();
  9785. }
  9786. }
  9787. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9788. const mesh = new Mesh(this._lodPlanes[0], material);
  9789. const uniforms = material.uniforms;
  9790. uniforms['envMap'].value = texture;
  9791. const size = this._cubeSize;
  9792. _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size);
  9793. renderer.setRenderTarget(cubeUVRenderTarget);
  9794. renderer.render(mesh, _flatCamera);
  9795. }
  9796. _applyPMREM(cubeUVRenderTarget) {
  9797. const renderer = this._renderer;
  9798. const autoClear = renderer.autoClear;
  9799. renderer.autoClear = false;
  9800. for (let i = 1; i < this._lodPlanes.length; i++) {
  9801. const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]);
  9802. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9803. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9804. }
  9805. renderer.autoClear = autoClear;
  9806. }
  9807. /**
  9808. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9809. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9810. * the blur latitudinally (around the poles), and then longitudinally (towards
  9811. * the poles) to approximate the orthogonally-separable blur. It is least
  9812. * accurate at the poles, but still does a decent job.
  9813. */
  9814. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9815. const pingPongRenderTarget = this._pingPongRenderTarget;
  9816. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9817. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9818. }
  9819. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9820. const renderer = this._renderer;
  9821. const blurMaterial = this._blurMaterial;
  9822. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9823. console.error('blur direction must be either latitudinal or longitudinal!');
  9824. } // Number of standard deviations at which to cut off the discrete approximation.
  9825. const STANDARD_DEVIATIONS = 3;
  9826. const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial);
  9827. const blurUniforms = blurMaterial.uniforms;
  9828. const pixels = this._sizeLods[lodIn] - 1;
  9829. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9830. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9831. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9832. if (samples > MAX_SAMPLES) {
  9833. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9834. }
  9835. const weights = [];
  9836. let sum = 0;
  9837. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9838. const x = i / sigmaPixels;
  9839. const weight = Math.exp(-x * x / 2);
  9840. weights.push(weight);
  9841. if (i === 0) {
  9842. sum += weight;
  9843. } else if (i < samples) {
  9844. sum += 2 * weight;
  9845. }
  9846. }
  9847. for (let i = 0; i < weights.length; i++) {
  9848. weights[i] = weights[i] / sum;
  9849. }
  9850. blurUniforms['envMap'].value = targetIn.texture;
  9851. blurUniforms['samples'].value = samples;
  9852. blurUniforms['weights'].value = weights;
  9853. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9854. if (poleAxis) {
  9855. blurUniforms['poleAxis'].value = poleAxis;
  9856. }
  9857. const {
  9858. _lodMax
  9859. } = this;
  9860. blurUniforms['dTheta'].value = radiansPerPixel;
  9861. blurUniforms['mipInt'].value = _lodMax - lodIn;
  9862. const outputSize = this._sizeLods[lodOut];
  9863. const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0);
  9864. const y = 4 * (this._cubeSize - outputSize);
  9865. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9866. renderer.setRenderTarget(targetOut);
  9867. renderer.render(blurMesh, _flatCamera);
  9868. }
  9869. }
  9870. function _createPlanes(lodMax) {
  9871. const lodPlanes = [];
  9872. const sizeLods = [];
  9873. const sigmas = [];
  9874. let lod = lodMax;
  9875. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9876. for (let i = 0; i < totalLods; i++) {
  9877. const sizeLod = Math.pow(2, lod);
  9878. sizeLods.push(sizeLod);
  9879. let sigma = 1.0 / sizeLod;
  9880. if (i > lodMax - LOD_MIN) {
  9881. sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1];
  9882. } else if (i === 0) {
  9883. sigma = 0;
  9884. }
  9885. sigmas.push(sigma);
  9886. const texelSize = 1.0 / (sizeLod - 2);
  9887. const min = -texelSize;
  9888. const max = 1 + texelSize;
  9889. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9890. const cubeFaces = 6;
  9891. const vertices = 6;
  9892. const positionSize = 3;
  9893. const uvSize = 2;
  9894. const faceIndexSize = 1;
  9895. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9896. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9897. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9898. for (let face = 0; face < cubeFaces; face++) {
  9899. const x = face % 3 * 2 / 3 - 1;
  9900. const y = face > 2 ? 0 : -1;
  9901. 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];
  9902. position.set(coordinates, positionSize * vertices * face);
  9903. uv.set(uv1, uvSize * vertices * face);
  9904. const fill = [face, face, face, face, face, face];
  9905. faceIndex.set(fill, faceIndexSize * vertices * face);
  9906. }
  9907. const planes = new BufferGeometry();
  9908. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9909. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9910. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9911. lodPlanes.push(planes);
  9912. if (lod > LOD_MIN) {
  9913. lod--;
  9914. }
  9915. }
  9916. return {
  9917. lodPlanes,
  9918. sizeLods,
  9919. sigmas
  9920. };
  9921. }
  9922. function _createRenderTarget(width, height, params) {
  9923. const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params);
  9924. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9925. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9926. cubeUVRenderTarget.scissorTest = true;
  9927. return cubeUVRenderTarget;
  9928. }
  9929. function _setViewport(target, x, y, width, height) {
  9930. target.viewport.set(x, y, width, height);
  9931. target.scissor.set(x, y, width, height);
  9932. }
  9933. function _getBlurShader(lodMax, width, height) {
  9934. const weights = new Float32Array(MAX_SAMPLES);
  9935. const poleAxis = new Vector3(0, 1, 0);
  9936. const shaderMaterial = new ShaderMaterial({
  9937. name: 'SphericalGaussianBlur',
  9938. defines: {
  9939. 'n': MAX_SAMPLES,
  9940. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9941. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9942. 'CUBEUV_MAX_MIP': `${lodMax}.0`
  9943. },
  9944. uniforms: {
  9945. 'envMap': {
  9946. value: null
  9947. },
  9948. 'samples': {
  9949. value: 1
  9950. },
  9951. 'weights': {
  9952. value: weights
  9953. },
  9954. 'latitudinal': {
  9955. value: false
  9956. },
  9957. 'dTheta': {
  9958. value: 0
  9959. },
  9960. 'mipInt': {
  9961. value: 0
  9962. },
  9963. 'poleAxis': {
  9964. value: poleAxis
  9965. }
  9966. },
  9967. vertexShader: _getCommonVertexShader(),
  9968. fragmentShader:
  9969. /* glsl */
  9970. `
  9971. precision mediump float;
  9972. precision mediump int;
  9973. varying vec3 vOutputDirection;
  9974. uniform sampler2D envMap;
  9975. uniform int samples;
  9976. uniform float weights[ n ];
  9977. uniform bool latitudinal;
  9978. uniform float dTheta;
  9979. uniform float mipInt;
  9980. uniform vec3 poleAxis;
  9981. #define ENVMAP_TYPE_CUBE_UV
  9982. #include <cube_uv_reflection_fragment>
  9983. vec3 getSample( float theta, vec3 axis ) {
  9984. float cosTheta = cos( theta );
  9985. // Rodrigues' axis-angle rotation
  9986. vec3 sampleDirection = vOutputDirection * cosTheta
  9987. + cross( axis, vOutputDirection ) * sin( theta )
  9988. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9989. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9990. }
  9991. void main() {
  9992. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9993. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9994. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9995. }
  9996. axis = normalize( axis );
  9997. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9998. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9999. for ( int i = 1; i < n; i++ ) {
  10000. if ( i >= samples ) {
  10001. break;
  10002. }
  10003. float theta = dTheta * float( i );
  10004. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10005. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10006. }
  10007. }
  10008. `,
  10009. blending: NoBlending,
  10010. depthTest: false,
  10011. depthWrite: false
  10012. });
  10013. return shaderMaterial;
  10014. }
  10015. function _getEquirectMaterial() {
  10016. return new ShaderMaterial({
  10017. name: 'EquirectangularToCubeUV',
  10018. uniforms: {
  10019. 'envMap': {
  10020. value: null
  10021. }
  10022. },
  10023. vertexShader: _getCommonVertexShader(),
  10024. fragmentShader:
  10025. /* glsl */
  10026. `
  10027. precision mediump float;
  10028. precision mediump int;
  10029. varying vec3 vOutputDirection;
  10030. uniform sampler2D envMap;
  10031. #include <common>
  10032. void main() {
  10033. vec3 outputDirection = normalize( vOutputDirection );
  10034. vec2 uv = equirectUv( outputDirection );
  10035. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10036. }
  10037. `,
  10038. blending: NoBlending,
  10039. depthTest: false,
  10040. depthWrite: false
  10041. });
  10042. }
  10043. function _getCubemapMaterial() {
  10044. return new ShaderMaterial({
  10045. name: 'CubemapToCubeUV',
  10046. uniforms: {
  10047. 'envMap': {
  10048. value: null
  10049. },
  10050. 'flipEnvMap': {
  10051. value: -1
  10052. }
  10053. },
  10054. vertexShader: _getCommonVertexShader(),
  10055. fragmentShader:
  10056. /* glsl */
  10057. `
  10058. precision mediump float;
  10059. precision mediump int;
  10060. uniform float flipEnvMap;
  10061. varying vec3 vOutputDirection;
  10062. uniform samplerCube envMap;
  10063. void main() {
  10064. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10065. }
  10066. `,
  10067. blending: NoBlending,
  10068. depthTest: false,
  10069. depthWrite: false
  10070. });
  10071. }
  10072. function _getCommonVertexShader() {
  10073. return (
  10074. /* glsl */
  10075. `
  10076. precision mediump float;
  10077. precision mediump int;
  10078. attribute float faceIndex;
  10079. varying vec3 vOutputDirection;
  10080. // RH coordinate system; PMREM face-indexing convention
  10081. vec3 getDirection( vec2 uv, float face ) {
  10082. uv = 2.0 * uv - 1.0;
  10083. vec3 direction = vec3( uv, 1.0 );
  10084. if ( face == 0.0 ) {
  10085. direction = direction.zyx; // ( 1, v, u ) pos x
  10086. } else if ( face == 1.0 ) {
  10087. direction = direction.xzy;
  10088. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10089. } else if ( face == 2.0 ) {
  10090. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10091. } else if ( face == 3.0 ) {
  10092. direction = direction.zyx;
  10093. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10094. } else if ( face == 4.0 ) {
  10095. direction = direction.xzy;
  10096. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10097. } else if ( face == 5.0 ) {
  10098. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10099. }
  10100. return direction;
  10101. }
  10102. void main() {
  10103. vOutputDirection = getDirection( uv, faceIndex );
  10104. gl_Position = vec4( position, 1.0 );
  10105. }
  10106. `
  10107. );
  10108. }
  10109. function WebGLCubeUVMaps(renderer) {
  10110. let cubeUVmaps = new WeakMap();
  10111. let pmremGenerator = null;
  10112. function get(texture) {
  10113. if (texture && texture.isTexture) {
  10114. const mapping = texture.mapping;
  10115. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10116. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; // equirect/cube map to cubeUV conversion
  10117. if (isEquirectMap || isCubeMap) {
  10118. if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
  10119. texture.needsPMREMUpdate = false;
  10120. let renderTarget = cubeUVmaps.get(texture);
  10121. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10122. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
  10123. cubeUVmaps.set(texture, renderTarget);
  10124. return renderTarget.texture;
  10125. } else {
  10126. if (cubeUVmaps.has(texture)) {
  10127. return cubeUVmaps.get(texture).texture;
  10128. } else {
  10129. const image = texture.image;
  10130. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10131. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10132. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10133. cubeUVmaps.set(texture, renderTarget);
  10134. texture.addEventListener('dispose', onTextureDispose);
  10135. return renderTarget.texture;
  10136. } else {
  10137. // image not yet ready. try the conversion next frame
  10138. return null;
  10139. }
  10140. }
  10141. }
  10142. }
  10143. }
  10144. return texture;
  10145. }
  10146. function isCubeTextureComplete(image) {
  10147. let count = 0;
  10148. const length = 6;
  10149. for (let i = 0; i < length; i++) {
  10150. if (image[i] !== undefined) count++;
  10151. }
  10152. return count === length;
  10153. }
  10154. function onTextureDispose(event) {
  10155. const texture = event.target;
  10156. texture.removeEventListener('dispose', onTextureDispose);
  10157. const cubemapUV = cubeUVmaps.get(texture);
  10158. if (cubemapUV !== undefined) {
  10159. cubeUVmaps.delete(texture);
  10160. cubemapUV.dispose();
  10161. }
  10162. }
  10163. function dispose() {
  10164. cubeUVmaps = new WeakMap();
  10165. if (pmremGenerator !== null) {
  10166. pmremGenerator.dispose();
  10167. pmremGenerator = null;
  10168. }
  10169. }
  10170. return {
  10171. get: get,
  10172. dispose: dispose
  10173. };
  10174. }
  10175. function WebGLExtensions(gl) {
  10176. const extensions = {};
  10177. function getExtension(name) {
  10178. if (extensions[name] !== undefined) {
  10179. return extensions[name];
  10180. }
  10181. let extension;
  10182. switch (name) {
  10183. case 'WEBGL_depth_texture':
  10184. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10185. break;
  10186. case 'EXT_texture_filter_anisotropic':
  10187. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10188. break;
  10189. case 'WEBGL_compressed_texture_s3tc':
  10190. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10191. break;
  10192. case 'WEBGL_compressed_texture_pvrtc':
  10193. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10194. break;
  10195. default:
  10196. extension = gl.getExtension(name);
  10197. }
  10198. extensions[name] = extension;
  10199. return extension;
  10200. }
  10201. return {
  10202. has: function (name) {
  10203. return getExtension(name) !== null;
  10204. },
  10205. init: function (capabilities) {
  10206. if (capabilities.isWebGL2) {
  10207. getExtension('EXT_color_buffer_float');
  10208. } else {
  10209. getExtension('WEBGL_depth_texture');
  10210. getExtension('OES_texture_float');
  10211. getExtension('OES_texture_half_float');
  10212. getExtension('OES_texture_half_float_linear');
  10213. getExtension('OES_standard_derivatives');
  10214. getExtension('OES_element_index_uint');
  10215. getExtension('OES_vertex_array_object');
  10216. getExtension('ANGLE_instanced_arrays');
  10217. }
  10218. getExtension('OES_texture_float_linear');
  10219. getExtension('EXT_color_buffer_half_float');
  10220. getExtension('WEBGL_multisampled_render_to_texture');
  10221. },
  10222. get: function (name) {
  10223. const extension = getExtension(name);
  10224. if (extension === null) {
  10225. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10226. }
  10227. return extension;
  10228. }
  10229. };
  10230. }
  10231. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10232. const geometries = {};
  10233. const wireframeAttributes = new WeakMap();
  10234. function onGeometryDispose(event) {
  10235. const geometry = event.target;
  10236. if (geometry.index !== null) {
  10237. attributes.remove(geometry.index);
  10238. }
  10239. for (const name in geometry.attributes) {
  10240. attributes.remove(geometry.attributes[name]);
  10241. }
  10242. geometry.removeEventListener('dispose', onGeometryDispose);
  10243. delete geometries[geometry.id];
  10244. const attribute = wireframeAttributes.get(geometry);
  10245. if (attribute) {
  10246. attributes.remove(attribute);
  10247. wireframeAttributes.delete(geometry);
  10248. }
  10249. bindingStates.releaseStatesOfGeometry(geometry);
  10250. if (geometry.isInstancedBufferGeometry === true) {
  10251. delete geometry._maxInstanceCount;
  10252. } //
  10253. info.memory.geometries--;
  10254. }
  10255. function get(object, geometry) {
  10256. if (geometries[geometry.id] === true) return geometry;
  10257. geometry.addEventListener('dispose', onGeometryDispose);
  10258. geometries[geometry.id] = true;
  10259. info.memory.geometries++;
  10260. return geometry;
  10261. }
  10262. function update(geometry) {
  10263. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10264. for (const name in geometryAttributes) {
  10265. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10266. } // morph targets
  10267. const morphAttributes = geometry.morphAttributes;
  10268. for (const name in morphAttributes) {
  10269. const array = morphAttributes[name];
  10270. for (let i = 0, l = array.length; i < l; i++) {
  10271. attributes.update(array[i], gl.ARRAY_BUFFER);
  10272. }
  10273. }
  10274. }
  10275. function updateWireframeAttribute(geometry) {
  10276. const indices = [];
  10277. const geometryIndex = geometry.index;
  10278. const geometryPosition = geometry.attributes.position;
  10279. let version = 0;
  10280. if (geometryIndex !== null) {
  10281. const array = geometryIndex.array;
  10282. version = geometryIndex.version;
  10283. for (let i = 0, l = array.length; i < l; i += 3) {
  10284. const a = array[i + 0];
  10285. const b = array[i + 1];
  10286. const c = array[i + 2];
  10287. indices.push(a, b, b, c, c, a);
  10288. }
  10289. } else {
  10290. const array = geometryPosition.array;
  10291. version = geometryPosition.version;
  10292. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10293. const a = i + 0;
  10294. const b = i + 1;
  10295. const c = i + 2;
  10296. indices.push(a, b, b, c, c, a);
  10297. }
  10298. }
  10299. const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10300. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10301. //
  10302. const previousAttribute = wireframeAttributes.get(geometry);
  10303. if (previousAttribute) attributes.remove(previousAttribute); //
  10304. wireframeAttributes.set(geometry, attribute);
  10305. }
  10306. function getWireframeAttribute(geometry) {
  10307. const currentAttribute = wireframeAttributes.get(geometry);
  10308. if (currentAttribute) {
  10309. const geometryIndex = geometry.index;
  10310. if (geometryIndex !== null) {
  10311. // if the attribute is obsolete, create a new one
  10312. if (currentAttribute.version < geometryIndex.version) {
  10313. updateWireframeAttribute(geometry);
  10314. }
  10315. }
  10316. } else {
  10317. updateWireframeAttribute(geometry);
  10318. }
  10319. return wireframeAttributes.get(geometry);
  10320. }
  10321. return {
  10322. get: get,
  10323. update: update,
  10324. getWireframeAttribute: getWireframeAttribute
  10325. };
  10326. }
  10327. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10328. const isWebGL2 = capabilities.isWebGL2;
  10329. let mode;
  10330. function setMode(value) {
  10331. mode = value;
  10332. }
  10333. let type, bytesPerElement;
  10334. function setIndex(value) {
  10335. type = value.type;
  10336. bytesPerElement = value.bytesPerElement;
  10337. }
  10338. function render(start, count) {
  10339. gl.drawElements(mode, count, type, start * bytesPerElement);
  10340. info.update(count, mode, 1);
  10341. }
  10342. function renderInstances(start, count, primcount) {
  10343. if (primcount === 0) return;
  10344. let extension, methodName;
  10345. if (isWebGL2) {
  10346. extension = gl;
  10347. methodName = 'drawElementsInstanced';
  10348. } else {
  10349. extension = extensions.get('ANGLE_instanced_arrays');
  10350. methodName = 'drawElementsInstancedANGLE';
  10351. if (extension === null) {
  10352. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10353. return;
  10354. }
  10355. }
  10356. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10357. info.update(count, mode, primcount);
  10358. } //
  10359. this.setMode = setMode;
  10360. this.setIndex = setIndex;
  10361. this.render = render;
  10362. this.renderInstances = renderInstances;
  10363. }
  10364. function WebGLInfo(gl) {
  10365. const memory = {
  10366. geometries: 0,
  10367. textures: 0
  10368. };
  10369. const render = {
  10370. frame: 0,
  10371. calls: 0,
  10372. triangles: 0,
  10373. points: 0,
  10374. lines: 0
  10375. };
  10376. function update(count, mode, instanceCount) {
  10377. render.calls++;
  10378. switch (mode) {
  10379. case gl.TRIANGLES:
  10380. render.triangles += instanceCount * (count / 3);
  10381. break;
  10382. case gl.LINES:
  10383. render.lines += instanceCount * (count / 2);
  10384. break;
  10385. case gl.LINE_STRIP:
  10386. render.lines += instanceCount * (count - 1);
  10387. break;
  10388. case gl.LINE_LOOP:
  10389. render.lines += instanceCount * count;
  10390. break;
  10391. case gl.POINTS:
  10392. render.points += instanceCount * count;
  10393. break;
  10394. default:
  10395. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10396. break;
  10397. }
  10398. }
  10399. function reset() {
  10400. render.frame++;
  10401. render.calls = 0;
  10402. render.triangles = 0;
  10403. render.points = 0;
  10404. render.lines = 0;
  10405. }
  10406. return {
  10407. memory: memory,
  10408. render: render,
  10409. programs: null,
  10410. autoReset: true,
  10411. reset: reset,
  10412. update: update
  10413. };
  10414. }
  10415. function numericalSort(a, b) {
  10416. return a[0] - b[0];
  10417. }
  10418. function absNumericalSort(a, b) {
  10419. return Math.abs(b[1]) - Math.abs(a[1]);
  10420. }
  10421. function WebGLMorphtargets(gl, capabilities, textures) {
  10422. const influencesList = {};
  10423. const morphInfluences = new Float32Array(8);
  10424. const morphTextures = new WeakMap();
  10425. const morph = new Vector4();
  10426. const workInfluences = [];
  10427. for (let i = 0; i < 8; i++) {
  10428. workInfluences[i] = [i, 0];
  10429. }
  10430. function update(object, geometry, material, program) {
  10431. const objectInfluences = object.morphTargetInfluences;
  10432. if (capabilities.isWebGL2 === true) {
  10433. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10434. // into an array of data textures. Each layer represents a single morph target.
  10435. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10436. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  10437. let entry = morphTextures.get(geometry);
  10438. if (entry === undefined || entry.count !== morphTargetsCount) {
  10439. if (entry !== undefined) entry.texture.dispose();
  10440. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10441. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10442. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10443. const morphTargets = geometry.morphAttributes.position || [];
  10444. const morphNormals = geometry.morphAttributes.normal || [];
  10445. const morphColors = geometry.morphAttributes.color || [];
  10446. let vertexDataCount = 0;
  10447. if (hasMorphPosition === true) vertexDataCount = 1;
  10448. if (hasMorphNormals === true) vertexDataCount = 2;
  10449. if (hasMorphColors === true) vertexDataCount = 3;
  10450. let width = geometry.attributes.position.count * vertexDataCount;
  10451. let height = 1;
  10452. if (width > capabilities.maxTextureSize) {
  10453. height = Math.ceil(width / capabilities.maxTextureSize);
  10454. width = capabilities.maxTextureSize;
  10455. }
  10456. const buffer = new Float32Array(width * height * 4 * morphTargetsCount);
  10457. const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount);
  10458. texture.type = FloatType;
  10459. texture.needsUpdate = true; // fill buffer
  10460. const vertexDataStride = vertexDataCount * 4;
  10461. for (let i = 0; i < morphTargetsCount; i++) {
  10462. const morphTarget = morphTargets[i];
  10463. const morphNormal = morphNormals[i];
  10464. const morphColor = morphColors[i];
  10465. const offset = width * height * 4 * i;
  10466. for (let j = 0; j < morphTarget.count; j++) {
  10467. const stride = j * vertexDataStride;
  10468. if (hasMorphPosition === true) {
  10469. morph.fromBufferAttribute(morphTarget, j);
  10470. buffer[offset + stride + 0] = morph.x;
  10471. buffer[offset + stride + 1] = morph.y;
  10472. buffer[offset + stride + 2] = morph.z;
  10473. buffer[offset + stride + 3] = 0;
  10474. }
  10475. if (hasMorphNormals === true) {
  10476. morph.fromBufferAttribute(morphNormal, j);
  10477. buffer[offset + stride + 4] = morph.x;
  10478. buffer[offset + stride + 5] = morph.y;
  10479. buffer[offset + stride + 6] = morph.z;
  10480. buffer[offset + stride + 7] = 0;
  10481. }
  10482. if (hasMorphColors === true) {
  10483. morph.fromBufferAttribute(morphColor, j);
  10484. buffer[offset + stride + 8] = morph.x;
  10485. buffer[offset + stride + 9] = morph.y;
  10486. buffer[offset + stride + 10] = morph.z;
  10487. buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1;
  10488. }
  10489. }
  10490. }
  10491. entry = {
  10492. count: morphTargetsCount,
  10493. texture: texture,
  10494. size: new Vector2(width, height)
  10495. };
  10496. morphTextures.set(geometry, entry);
  10497. function disposeTexture() {
  10498. texture.dispose();
  10499. morphTextures.delete(geometry);
  10500. geometry.removeEventListener('dispose', disposeTexture);
  10501. }
  10502. geometry.addEventListener('dispose', disposeTexture);
  10503. } //
  10504. let morphInfluencesSum = 0;
  10505. for (let i = 0; i < objectInfluences.length; i++) {
  10506. morphInfluencesSum += objectInfluences[i];
  10507. }
  10508. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10509. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10510. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10511. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10512. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10513. } else {
  10514. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10515. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10516. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10517. let influences = influencesList[geometry.id];
  10518. if (influences === undefined || influences.length !== length) {
  10519. // initialise list
  10520. influences = [];
  10521. for (let i = 0; i < length; i++) {
  10522. influences[i] = [i, 0];
  10523. }
  10524. influencesList[geometry.id] = influences;
  10525. } // Collect influences
  10526. for (let i = 0; i < length; i++) {
  10527. const influence = influences[i];
  10528. influence[0] = i;
  10529. influence[1] = objectInfluences[i];
  10530. }
  10531. influences.sort(absNumericalSort);
  10532. for (let i = 0; i < 8; i++) {
  10533. if (i < length && influences[i][1]) {
  10534. workInfluences[i][0] = influences[i][0];
  10535. workInfluences[i][1] = influences[i][1];
  10536. } else {
  10537. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10538. workInfluences[i][1] = 0;
  10539. }
  10540. }
  10541. workInfluences.sort(numericalSort);
  10542. const morphTargets = geometry.morphAttributes.position;
  10543. const morphNormals = geometry.morphAttributes.normal;
  10544. let morphInfluencesSum = 0;
  10545. for (let i = 0; i < 8; i++) {
  10546. const influence = workInfluences[i];
  10547. const index = influence[0];
  10548. const value = influence[1];
  10549. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10550. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10551. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10552. }
  10553. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10554. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10555. }
  10556. morphInfluences[i] = value;
  10557. morphInfluencesSum += value;
  10558. } else {
  10559. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10560. geometry.deleteAttribute('morphTarget' + i);
  10561. }
  10562. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10563. geometry.deleteAttribute('morphNormal' + i);
  10564. }
  10565. morphInfluences[i] = 0;
  10566. }
  10567. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10568. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10569. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10570. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10571. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10572. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10573. }
  10574. }
  10575. return {
  10576. update: update
  10577. };
  10578. }
  10579. function WebGLObjects(gl, geometries, attributes, info) {
  10580. let updateMap = new WeakMap();
  10581. function update(object) {
  10582. const frame = info.render.frame;
  10583. const geometry = object.geometry;
  10584. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10585. if (updateMap.get(buffergeometry) !== frame) {
  10586. geometries.update(buffergeometry);
  10587. updateMap.set(buffergeometry, frame);
  10588. }
  10589. if (object.isInstancedMesh) {
  10590. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10591. object.addEventListener('dispose', onInstancedMeshDispose);
  10592. }
  10593. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10594. if (object.instanceColor !== null) {
  10595. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10596. }
  10597. }
  10598. return buffergeometry;
  10599. }
  10600. function dispose() {
  10601. updateMap = new WeakMap();
  10602. }
  10603. function onInstancedMeshDispose(event) {
  10604. const instancedMesh = event.target;
  10605. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10606. attributes.remove(instancedMesh.instanceMatrix);
  10607. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10608. }
  10609. return {
  10610. update: update,
  10611. dispose: dispose
  10612. };
  10613. }
  10614. /**
  10615. * Uniforms of a program.
  10616. * Those form a tree structure with a special top-level container for the root,
  10617. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10618. *
  10619. *
  10620. * Properties of inner nodes including the top-level container:
  10621. *
  10622. * .seq - array of nested uniforms
  10623. * .map - nested uniforms by name
  10624. *
  10625. *
  10626. * Methods of all nodes except the top-level container:
  10627. *
  10628. * .setValue( gl, value, [textures] )
  10629. *
  10630. * uploads a uniform value(s)
  10631. * the 'textures' parameter is needed for sampler uniforms
  10632. *
  10633. *
  10634. * Static methods of the top-level container (textures factorizations):
  10635. *
  10636. * .upload( gl, seq, values, textures )
  10637. *
  10638. * sets uniforms in 'seq' to 'values[id].value'
  10639. *
  10640. * .seqWithValue( seq, values ) : filteredSeq
  10641. *
  10642. * filters 'seq' entries with corresponding entry in values
  10643. *
  10644. *
  10645. * Methods of the top-level container (textures factorizations):
  10646. *
  10647. * .setValue( gl, name, value, textures )
  10648. *
  10649. * sets uniform with name 'name' to 'value'
  10650. *
  10651. * .setOptional( gl, obj, prop )
  10652. *
  10653. * like .set for an optional property of the object
  10654. *
  10655. */
  10656. const emptyTexture = /*@__PURE__*/new Texture();
  10657. const emptyArrayTexture = /*@__PURE__*/new DataArrayTexture();
  10658. const empty3dTexture = /*@__PURE__*/new Data3DTexture();
  10659. const emptyCubeTexture = /*@__PURE__*/new CubeTexture(); // --- Utilities ---
  10660. // Array Caches (provide typed arrays for temporary by size)
  10661. const arrayCacheF32 = [];
  10662. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10663. const mat4array = new Float32Array(16);
  10664. const mat3array = new Float32Array(9);
  10665. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10666. function flatten(array, nBlocks, blockSize) {
  10667. const firstElem = array[0];
  10668. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10669. // see http://jacksondunstan.com/articles/983
  10670. const n = nBlocks * blockSize;
  10671. let r = arrayCacheF32[n];
  10672. if (r === undefined) {
  10673. r = new Float32Array(n);
  10674. arrayCacheF32[n] = r;
  10675. }
  10676. if (nBlocks !== 0) {
  10677. firstElem.toArray(r, 0);
  10678. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10679. offset += blockSize;
  10680. array[i].toArray(r, offset);
  10681. }
  10682. }
  10683. return r;
  10684. }
  10685. function arraysEqual(a, b) {
  10686. if (a.length !== b.length) return false;
  10687. for (let i = 0, l = a.length; i < l; i++) {
  10688. if (a[i] !== b[i]) return false;
  10689. }
  10690. return true;
  10691. }
  10692. function copyArray(a, b) {
  10693. for (let i = 0, l = b.length; i < l; i++) {
  10694. a[i] = b[i];
  10695. }
  10696. } // Texture unit allocation
  10697. function allocTexUnits(textures, n) {
  10698. let r = arrayCacheI32[n];
  10699. if (r === undefined) {
  10700. r = new Int32Array(n);
  10701. arrayCacheI32[n] = r;
  10702. }
  10703. for (let i = 0; i !== n; ++i) {
  10704. r[i] = textures.allocateTextureUnit();
  10705. }
  10706. return r;
  10707. } // --- Setters ---
  10708. // Note: Defining these methods externally, because they come in a bunch
  10709. // and this way their names minify.
  10710. // Single scalar
  10711. function setValueV1f(gl, v) {
  10712. const cache = this.cache;
  10713. if (cache[0] === v) return;
  10714. gl.uniform1f(this.addr, v);
  10715. cache[0] = v;
  10716. } // Single float vector (from flat array or THREE.VectorN)
  10717. function setValueV2f(gl, v) {
  10718. const cache = this.cache;
  10719. if (v.x !== undefined) {
  10720. if (cache[0] !== v.x || cache[1] !== v.y) {
  10721. gl.uniform2f(this.addr, v.x, v.y);
  10722. cache[0] = v.x;
  10723. cache[1] = v.y;
  10724. }
  10725. } else {
  10726. if (arraysEqual(cache, v)) return;
  10727. gl.uniform2fv(this.addr, v);
  10728. copyArray(cache, v);
  10729. }
  10730. }
  10731. function setValueV3f(gl, v) {
  10732. const cache = this.cache;
  10733. if (v.x !== undefined) {
  10734. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10735. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10736. cache[0] = v.x;
  10737. cache[1] = v.y;
  10738. cache[2] = v.z;
  10739. }
  10740. } else if (v.r !== undefined) {
  10741. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10742. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10743. cache[0] = v.r;
  10744. cache[1] = v.g;
  10745. cache[2] = v.b;
  10746. }
  10747. } else {
  10748. if (arraysEqual(cache, v)) return;
  10749. gl.uniform3fv(this.addr, v);
  10750. copyArray(cache, v);
  10751. }
  10752. }
  10753. function setValueV4f(gl, v) {
  10754. const cache = this.cache;
  10755. if (v.x !== undefined) {
  10756. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10757. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10758. cache[0] = v.x;
  10759. cache[1] = v.y;
  10760. cache[2] = v.z;
  10761. cache[3] = v.w;
  10762. }
  10763. } else {
  10764. if (arraysEqual(cache, v)) return;
  10765. gl.uniform4fv(this.addr, v);
  10766. copyArray(cache, v);
  10767. }
  10768. } // Single matrix (from flat array or THREE.MatrixN)
  10769. function setValueM2(gl, v) {
  10770. const cache = this.cache;
  10771. const elements = v.elements;
  10772. if (elements === undefined) {
  10773. if (arraysEqual(cache, v)) return;
  10774. gl.uniformMatrix2fv(this.addr, false, v);
  10775. copyArray(cache, v);
  10776. } else {
  10777. if (arraysEqual(cache, elements)) return;
  10778. mat2array.set(elements);
  10779. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10780. copyArray(cache, elements);
  10781. }
  10782. }
  10783. function setValueM3(gl, v) {
  10784. const cache = this.cache;
  10785. const elements = v.elements;
  10786. if (elements === undefined) {
  10787. if (arraysEqual(cache, v)) return;
  10788. gl.uniformMatrix3fv(this.addr, false, v);
  10789. copyArray(cache, v);
  10790. } else {
  10791. if (arraysEqual(cache, elements)) return;
  10792. mat3array.set(elements);
  10793. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10794. copyArray(cache, elements);
  10795. }
  10796. }
  10797. function setValueM4(gl, v) {
  10798. const cache = this.cache;
  10799. const elements = v.elements;
  10800. if (elements === undefined) {
  10801. if (arraysEqual(cache, v)) return;
  10802. gl.uniformMatrix4fv(this.addr, false, v);
  10803. copyArray(cache, v);
  10804. } else {
  10805. if (arraysEqual(cache, elements)) return;
  10806. mat4array.set(elements);
  10807. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10808. copyArray(cache, elements);
  10809. }
  10810. } // Single integer / boolean
  10811. function setValueV1i(gl, v) {
  10812. const cache = this.cache;
  10813. if (cache[0] === v) return;
  10814. gl.uniform1i(this.addr, v);
  10815. cache[0] = v;
  10816. } // Single integer / boolean vector (from flat array)
  10817. function setValueV2i(gl, v) {
  10818. const cache = this.cache;
  10819. if (arraysEqual(cache, v)) return;
  10820. gl.uniform2iv(this.addr, v);
  10821. copyArray(cache, v);
  10822. }
  10823. function setValueV3i(gl, v) {
  10824. const cache = this.cache;
  10825. if (arraysEqual(cache, v)) return;
  10826. gl.uniform3iv(this.addr, v);
  10827. copyArray(cache, v);
  10828. }
  10829. function setValueV4i(gl, v) {
  10830. const cache = this.cache;
  10831. if (arraysEqual(cache, v)) return;
  10832. gl.uniform4iv(this.addr, v);
  10833. copyArray(cache, v);
  10834. } // Single unsigned integer
  10835. function setValueV1ui(gl, v) {
  10836. const cache = this.cache;
  10837. if (cache[0] === v) return;
  10838. gl.uniform1ui(this.addr, v);
  10839. cache[0] = v;
  10840. } // Single unsigned integer vector (from flat array)
  10841. function setValueV2ui(gl, v) {
  10842. const cache = this.cache;
  10843. if (arraysEqual(cache, v)) return;
  10844. gl.uniform2uiv(this.addr, v);
  10845. copyArray(cache, v);
  10846. }
  10847. function setValueV3ui(gl, v) {
  10848. const cache = this.cache;
  10849. if (arraysEqual(cache, v)) return;
  10850. gl.uniform3uiv(this.addr, v);
  10851. copyArray(cache, v);
  10852. }
  10853. function setValueV4ui(gl, v) {
  10854. const cache = this.cache;
  10855. if (arraysEqual(cache, v)) return;
  10856. gl.uniform4uiv(this.addr, v);
  10857. copyArray(cache, v);
  10858. } // Single texture (2D / Cube)
  10859. function setValueT1(gl, v, textures) {
  10860. const cache = this.cache;
  10861. const unit = textures.allocateTextureUnit();
  10862. if (cache[0] !== unit) {
  10863. gl.uniform1i(this.addr, unit);
  10864. cache[0] = unit;
  10865. }
  10866. textures.setTexture2D(v || emptyTexture, unit);
  10867. }
  10868. function setValueT3D1(gl, v, textures) {
  10869. const cache = this.cache;
  10870. const unit = textures.allocateTextureUnit();
  10871. if (cache[0] !== unit) {
  10872. gl.uniform1i(this.addr, unit);
  10873. cache[0] = unit;
  10874. }
  10875. textures.setTexture3D(v || empty3dTexture, unit);
  10876. }
  10877. function setValueT6(gl, v, textures) {
  10878. const cache = this.cache;
  10879. const unit = textures.allocateTextureUnit();
  10880. if (cache[0] !== unit) {
  10881. gl.uniform1i(this.addr, unit);
  10882. cache[0] = unit;
  10883. }
  10884. textures.setTextureCube(v || emptyCubeTexture, unit);
  10885. }
  10886. function setValueT2DArray1(gl, v, textures) {
  10887. const cache = this.cache;
  10888. const unit = textures.allocateTextureUnit();
  10889. if (cache[0] !== unit) {
  10890. gl.uniform1i(this.addr, unit);
  10891. cache[0] = unit;
  10892. }
  10893. textures.setTexture2DArray(v || emptyArrayTexture, unit);
  10894. } // Helper to pick the right setter for the singular case
  10895. function getSingularSetter(type) {
  10896. switch (type) {
  10897. case 0x1406:
  10898. return setValueV1f;
  10899. // FLOAT
  10900. case 0x8b50:
  10901. return setValueV2f;
  10902. // _VEC2
  10903. case 0x8b51:
  10904. return setValueV3f;
  10905. // _VEC3
  10906. case 0x8b52:
  10907. return setValueV4f;
  10908. // _VEC4
  10909. case 0x8b5a:
  10910. return setValueM2;
  10911. // _MAT2
  10912. case 0x8b5b:
  10913. return setValueM3;
  10914. // _MAT3
  10915. case 0x8b5c:
  10916. return setValueM4;
  10917. // _MAT4
  10918. case 0x1404:
  10919. case 0x8b56:
  10920. return setValueV1i;
  10921. // INT, BOOL
  10922. case 0x8b53:
  10923. case 0x8b57:
  10924. return setValueV2i;
  10925. // _VEC2
  10926. case 0x8b54:
  10927. case 0x8b58:
  10928. return setValueV3i;
  10929. // _VEC3
  10930. case 0x8b55:
  10931. case 0x8b59:
  10932. return setValueV4i;
  10933. // _VEC4
  10934. case 0x1405:
  10935. return setValueV1ui;
  10936. // UINT
  10937. case 0x8dc6:
  10938. return setValueV2ui;
  10939. // _VEC2
  10940. case 0x8dc7:
  10941. return setValueV3ui;
  10942. // _VEC3
  10943. case 0x8dc8:
  10944. return setValueV4ui;
  10945. // _VEC4
  10946. case 0x8b5e: // SAMPLER_2D
  10947. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10948. case 0x8dca: // INT_SAMPLER_2D
  10949. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10950. case 0x8b62:
  10951. // SAMPLER_2D_SHADOW
  10952. return setValueT1;
  10953. case 0x8b5f: // SAMPLER_3D
  10954. case 0x8dcb: // INT_SAMPLER_3D
  10955. case 0x8dd3:
  10956. // UNSIGNED_INT_SAMPLER_3D
  10957. return setValueT3D1;
  10958. case 0x8b60: // SAMPLER_CUBE
  10959. case 0x8dcc: // INT_SAMPLER_CUBE
  10960. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10961. case 0x8dc5:
  10962. // SAMPLER_CUBE_SHADOW
  10963. return setValueT6;
  10964. case 0x8dc1: // SAMPLER_2D_ARRAY
  10965. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10966. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10967. case 0x8dc4:
  10968. // SAMPLER_2D_ARRAY_SHADOW
  10969. return setValueT2DArray1;
  10970. }
  10971. } // Array of scalars
  10972. function setValueV1fArray(gl, v) {
  10973. gl.uniform1fv(this.addr, v);
  10974. } // Array of vectors (from flat array or array of THREE.VectorN)
  10975. function setValueV2fArray(gl, v) {
  10976. const data = flatten(v, this.size, 2);
  10977. gl.uniform2fv(this.addr, data);
  10978. }
  10979. function setValueV3fArray(gl, v) {
  10980. const data = flatten(v, this.size, 3);
  10981. gl.uniform3fv(this.addr, data);
  10982. }
  10983. function setValueV4fArray(gl, v) {
  10984. const data = flatten(v, this.size, 4);
  10985. gl.uniform4fv(this.addr, data);
  10986. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10987. function setValueM2Array(gl, v) {
  10988. const data = flatten(v, this.size, 4);
  10989. gl.uniformMatrix2fv(this.addr, false, data);
  10990. }
  10991. function setValueM3Array(gl, v) {
  10992. const data = flatten(v, this.size, 9);
  10993. gl.uniformMatrix3fv(this.addr, false, data);
  10994. }
  10995. function setValueM4Array(gl, v) {
  10996. const data = flatten(v, this.size, 16);
  10997. gl.uniformMatrix4fv(this.addr, false, data);
  10998. } // Array of integer / boolean
  10999. function setValueV1iArray(gl, v) {
  11000. gl.uniform1iv(this.addr, v);
  11001. } // Array of integer / boolean vectors (from flat array)
  11002. function setValueV2iArray(gl, v) {
  11003. gl.uniform2iv(this.addr, v);
  11004. }
  11005. function setValueV3iArray(gl, v) {
  11006. gl.uniform3iv(this.addr, v);
  11007. }
  11008. function setValueV4iArray(gl, v) {
  11009. gl.uniform4iv(this.addr, v);
  11010. } // Array of unsigned integer
  11011. function setValueV1uiArray(gl, v) {
  11012. gl.uniform1uiv(this.addr, v);
  11013. } // Array of unsigned integer vectors (from flat array)
  11014. function setValueV2uiArray(gl, v) {
  11015. gl.uniform2uiv(this.addr, v);
  11016. }
  11017. function setValueV3uiArray(gl, v) {
  11018. gl.uniform3uiv(this.addr, v);
  11019. }
  11020. function setValueV4uiArray(gl, v) {
  11021. gl.uniform4uiv(this.addr, v);
  11022. } // Array of textures (2D / 3D / Cube / 2DArray)
  11023. function setValueT1Array(gl, v, textures) {
  11024. const n = v.length;
  11025. const units = allocTexUnits(textures, n);
  11026. gl.uniform1iv(this.addr, units);
  11027. for (let i = 0; i !== n; ++i) {
  11028. textures.setTexture2D(v[i] || emptyTexture, units[i]);
  11029. }
  11030. }
  11031. function setValueT3DArray(gl, v, textures) {
  11032. const n = v.length;
  11033. const units = allocTexUnits(textures, n);
  11034. gl.uniform1iv(this.addr, units);
  11035. for (let i = 0; i !== n; ++i) {
  11036. textures.setTexture3D(v[i] || empty3dTexture, units[i]);
  11037. }
  11038. }
  11039. function setValueT6Array(gl, v, textures) {
  11040. const n = v.length;
  11041. const units = allocTexUnits(textures, n);
  11042. gl.uniform1iv(this.addr, units);
  11043. for (let i = 0; i !== n; ++i) {
  11044. textures.setTextureCube(v[i] || emptyCubeTexture, units[i]);
  11045. }
  11046. }
  11047. function setValueT2DArrayArray(gl, v, textures) {
  11048. const n = v.length;
  11049. const units = allocTexUnits(textures, n);
  11050. gl.uniform1iv(this.addr, units);
  11051. for (let i = 0; i !== n; ++i) {
  11052. textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]);
  11053. }
  11054. } // Helper to pick the right setter for a pure (bottom-level) array
  11055. function getPureArraySetter(type) {
  11056. switch (type) {
  11057. case 0x1406:
  11058. return setValueV1fArray;
  11059. // FLOAT
  11060. case 0x8b50:
  11061. return setValueV2fArray;
  11062. // _VEC2
  11063. case 0x8b51:
  11064. return setValueV3fArray;
  11065. // _VEC3
  11066. case 0x8b52:
  11067. return setValueV4fArray;
  11068. // _VEC4
  11069. case 0x8b5a:
  11070. return setValueM2Array;
  11071. // _MAT2
  11072. case 0x8b5b:
  11073. return setValueM3Array;
  11074. // _MAT3
  11075. case 0x8b5c:
  11076. return setValueM4Array;
  11077. // _MAT4
  11078. case 0x1404:
  11079. case 0x8b56:
  11080. return setValueV1iArray;
  11081. // INT, BOOL
  11082. case 0x8b53:
  11083. case 0x8b57:
  11084. return setValueV2iArray;
  11085. // _VEC2
  11086. case 0x8b54:
  11087. case 0x8b58:
  11088. return setValueV3iArray;
  11089. // _VEC3
  11090. case 0x8b55:
  11091. case 0x8b59:
  11092. return setValueV4iArray;
  11093. // _VEC4
  11094. case 0x1405:
  11095. return setValueV1uiArray;
  11096. // UINT
  11097. case 0x8dc6:
  11098. return setValueV2uiArray;
  11099. // _VEC2
  11100. case 0x8dc7:
  11101. return setValueV3uiArray;
  11102. // _VEC3
  11103. case 0x8dc8:
  11104. return setValueV4uiArray;
  11105. // _VEC4
  11106. case 0x8b5e: // SAMPLER_2D
  11107. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11108. case 0x8dca: // INT_SAMPLER_2D
  11109. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11110. case 0x8b62:
  11111. // SAMPLER_2D_SHADOW
  11112. return setValueT1Array;
  11113. case 0x8b5f: // SAMPLER_3D
  11114. case 0x8dcb: // INT_SAMPLER_3D
  11115. case 0x8dd3:
  11116. // UNSIGNED_INT_SAMPLER_3D
  11117. return setValueT3DArray;
  11118. case 0x8b60: // SAMPLER_CUBE
  11119. case 0x8dcc: // INT_SAMPLER_CUBE
  11120. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11121. case 0x8dc5:
  11122. // SAMPLER_CUBE_SHADOW
  11123. return setValueT6Array;
  11124. case 0x8dc1: // SAMPLER_2D_ARRAY
  11125. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11126. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11127. case 0x8dc4:
  11128. // SAMPLER_2D_ARRAY_SHADOW
  11129. return setValueT2DArrayArray;
  11130. }
  11131. } // --- Uniform Classes ---
  11132. class SingleUniform {
  11133. constructor(id, activeInfo, addr) {
  11134. this.id = id;
  11135. this.addr = addr;
  11136. this.cache = [];
  11137. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11138. }
  11139. }
  11140. class PureArrayUniform {
  11141. constructor(id, activeInfo, addr) {
  11142. this.id = id;
  11143. this.addr = addr;
  11144. this.cache = [];
  11145. this.size = activeInfo.size;
  11146. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11147. }
  11148. }
  11149. class StructuredUniform {
  11150. constructor(id) {
  11151. this.id = id;
  11152. this.seq = [];
  11153. this.map = {};
  11154. }
  11155. setValue(gl, value, textures) {
  11156. const seq = this.seq;
  11157. for (let i = 0, n = seq.length; i !== n; ++i) {
  11158. const u = seq[i];
  11159. u.setValue(gl, value[u.id], textures);
  11160. }
  11161. }
  11162. } // --- Top-level ---
  11163. // Parser - builds up the property tree from the path strings
  11164. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  11165. // - the identifier (member name or array index)
  11166. // - followed by an optional right bracket (found when array index)
  11167. // - followed by an optional left bracket or dot (type of subscript)
  11168. //
  11169. // Note: These portions can be read in a non-overlapping fashion and
  11170. // allow straightforward parsing of the hierarchy that WebGL encodes
  11171. // in the uniform names.
  11172. function addUniform(container, uniformObject) {
  11173. container.seq.push(uniformObject);
  11174. container.map[uniformObject.id] = uniformObject;
  11175. }
  11176. function parseUniform(activeInfo, addr, container) {
  11177. const path = activeInfo.name,
  11178. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11179. RePathPart.lastIndex = 0;
  11180. while (true) {
  11181. const match = RePathPart.exec(path),
  11182. matchEnd = RePathPart.lastIndex;
  11183. let id = match[1];
  11184. const idIsIndex = match[2] === ']',
  11185. subscript = match[3];
  11186. if (idIsIndex) id = id | 0; // convert to integer
  11187. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11188. // bare name or "pure" bottom-level array "[0]" suffix
  11189. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11190. break;
  11191. } else {
  11192. // step into inner node / create it in case it doesn't exist
  11193. const map = container.map;
  11194. let next = map[id];
  11195. if (next === undefined) {
  11196. next = new StructuredUniform(id);
  11197. addUniform(container, next);
  11198. }
  11199. container = next;
  11200. }
  11201. }
  11202. } // Root Container
  11203. class WebGLUniforms {
  11204. constructor(gl, program) {
  11205. this.seq = [];
  11206. this.map = {};
  11207. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11208. for (let i = 0; i < n; ++i) {
  11209. const info = gl.getActiveUniform(program, i),
  11210. addr = gl.getUniformLocation(program, info.name);
  11211. parseUniform(info, addr, this);
  11212. }
  11213. }
  11214. setValue(gl, name, value, textures) {
  11215. const u = this.map[name];
  11216. if (u !== undefined) u.setValue(gl, value, textures);
  11217. }
  11218. setOptional(gl, object, name) {
  11219. const v = object[name];
  11220. if (v !== undefined) this.setValue(gl, name, v);
  11221. }
  11222. static upload(gl, seq, values, textures) {
  11223. for (let i = 0, n = seq.length; i !== n; ++i) {
  11224. const u = seq[i],
  11225. v = values[u.id];
  11226. if (v.needsUpdate !== false) {
  11227. // note: always updating when .needsUpdate is undefined
  11228. u.setValue(gl, v.value, textures);
  11229. }
  11230. }
  11231. }
  11232. static seqWithValue(seq, values) {
  11233. const r = [];
  11234. for (let i = 0, n = seq.length; i !== n; ++i) {
  11235. const u = seq[i];
  11236. if (u.id in values) r.push(u);
  11237. }
  11238. return r;
  11239. }
  11240. }
  11241. function WebGLShader(gl, type, string) {
  11242. const shader = gl.createShader(type);
  11243. gl.shaderSource(shader, string);
  11244. gl.compileShader(shader);
  11245. return shader;
  11246. }
  11247. let programIdCount = 0;
  11248. function handleSource(string, errorLine) {
  11249. const lines = string.split('\n');
  11250. const lines2 = [];
  11251. const from = Math.max(errorLine - 6, 0);
  11252. const to = Math.min(errorLine + 6, lines.length);
  11253. for (let i = from; i < to; i++) {
  11254. const line = i + 1;
  11255. lines2.push(`${line === errorLine ? '>' : ' '} ${line}: ${lines[i]}`);
  11256. }
  11257. return lines2.join('\n');
  11258. }
  11259. function getEncodingComponents(encoding) {
  11260. switch (encoding) {
  11261. case LinearEncoding:
  11262. return ['Linear', '( value )'];
  11263. case sRGBEncoding:
  11264. return ['sRGB', '( value )'];
  11265. default:
  11266. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11267. return ['Linear', '( value )'];
  11268. }
  11269. }
  11270. function getShaderErrors(gl, shader, type) {
  11271. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11272. const errors = gl.getShaderInfoLog(shader).trim();
  11273. if (status && errors === '') return '';
  11274. const errorMatches = /ERROR: 0:(\d+)/.exec(errors);
  11275. if (errorMatches) {
  11276. // --enable-privileged-webgl-extension
  11277. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11278. const errorLine = parseInt(errorMatches[1]);
  11279. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource(gl.getShaderSource(shader), errorLine);
  11280. } else {
  11281. return errors;
  11282. }
  11283. }
  11284. function getTexelEncodingFunction(functionName, encoding) {
  11285. const components = getEncodingComponents(encoding);
  11286. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11287. }
  11288. function getToneMappingFunction(functionName, toneMapping) {
  11289. let toneMappingName;
  11290. switch (toneMapping) {
  11291. case LinearToneMapping:
  11292. toneMappingName = 'Linear';
  11293. break;
  11294. case ReinhardToneMapping:
  11295. toneMappingName = 'Reinhard';
  11296. break;
  11297. case CineonToneMapping:
  11298. toneMappingName = 'OptimizedCineon';
  11299. break;
  11300. case ACESFilmicToneMapping:
  11301. toneMappingName = 'ACESFilmic';
  11302. break;
  11303. case CustomToneMapping:
  11304. toneMappingName = 'Custom';
  11305. break;
  11306. default:
  11307. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11308. toneMappingName = 'Linear';
  11309. }
  11310. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11311. }
  11312. function generateExtensions(parameters) {
  11313. 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' : ''];
  11314. return chunks.filter(filterEmptyLine).join('\n');
  11315. }
  11316. function generateDefines(defines) {
  11317. const chunks = [];
  11318. for (const name in defines) {
  11319. const value = defines[name];
  11320. if (value === false) continue;
  11321. chunks.push('#define ' + name + ' ' + value);
  11322. }
  11323. return chunks.join('\n');
  11324. }
  11325. function fetchAttributeLocations(gl, program) {
  11326. const attributes = {};
  11327. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11328. for (let i = 0; i < n; i++) {
  11329. const info = gl.getActiveAttrib(program, i);
  11330. const name = info.name;
  11331. let locationSize = 1;
  11332. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11333. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11334. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11335. attributes[name] = {
  11336. type: info.type,
  11337. location: gl.getAttribLocation(program, name),
  11338. locationSize: locationSize
  11339. };
  11340. }
  11341. return attributes;
  11342. }
  11343. function filterEmptyLine(string) {
  11344. return string !== '';
  11345. }
  11346. function replaceLightNums(string, parameters) {
  11347. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).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/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  11348. }
  11349. function replaceClippingPlaneNums(string, parameters) {
  11350. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11351. } // Resolve Includes
  11352. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11353. function resolveIncludes(string) {
  11354. return string.replace(includePattern, includeReplacer);
  11355. }
  11356. function includeReplacer(match, include) {
  11357. const string = ShaderChunk[include];
  11358. if (string === undefined) {
  11359. throw new Error('Can not resolve #include <' + include + '>');
  11360. }
  11361. return resolveIncludes(string);
  11362. } // Unroll Loops
  11363. 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;
  11364. function unrollLoops(string) {
  11365. return string.replace(unrollLoopPattern, loopReplacer);
  11366. }
  11367. function loopReplacer(match, start, end, snippet) {
  11368. let string = '';
  11369. for (let i = parseInt(start); i < parseInt(end); i++) {
  11370. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11371. }
  11372. return string;
  11373. } //
  11374. function generatePrecision(parameters) {
  11375. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11376. if (parameters.precision === 'highp') {
  11377. precisionstring += '\n#define HIGH_PRECISION';
  11378. } else if (parameters.precision === 'mediump') {
  11379. precisionstring += '\n#define MEDIUM_PRECISION';
  11380. } else if (parameters.precision === 'lowp') {
  11381. precisionstring += '\n#define LOW_PRECISION';
  11382. }
  11383. return precisionstring;
  11384. }
  11385. function generateShadowMapTypeDefine(parameters) {
  11386. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11387. if (parameters.shadowMapType === PCFShadowMap) {
  11388. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11389. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11390. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11391. } else if (parameters.shadowMapType === VSMShadowMap) {
  11392. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11393. }
  11394. return shadowMapTypeDefine;
  11395. }
  11396. function generateEnvMapTypeDefine(parameters) {
  11397. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11398. if (parameters.envMap) {
  11399. switch (parameters.envMapMode) {
  11400. case CubeReflectionMapping:
  11401. case CubeRefractionMapping:
  11402. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11403. break;
  11404. case CubeUVReflectionMapping:
  11405. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11406. break;
  11407. }
  11408. }
  11409. return envMapTypeDefine;
  11410. }
  11411. function generateEnvMapModeDefine(parameters) {
  11412. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11413. if (parameters.envMap) {
  11414. switch (parameters.envMapMode) {
  11415. case CubeRefractionMapping:
  11416. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11417. break;
  11418. }
  11419. }
  11420. return envMapModeDefine;
  11421. }
  11422. function generateEnvMapBlendingDefine(parameters) {
  11423. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11424. if (parameters.envMap) {
  11425. switch (parameters.combine) {
  11426. case MultiplyOperation:
  11427. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11428. break;
  11429. case MixOperation:
  11430. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11431. break;
  11432. case AddOperation:
  11433. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11434. break;
  11435. }
  11436. }
  11437. return envMapBlendingDefine;
  11438. }
  11439. function generateCubeUVSize(parameters) {
  11440. const imageHeight = parameters.envMapCubeUVHeight;
  11441. if (imageHeight === null) return null;
  11442. const maxMip = Math.log2(imageHeight) - 2;
  11443. const texelHeight = 1.0 / imageHeight;
  11444. const texelWidth = 1.0 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16));
  11445. return {
  11446. texelWidth,
  11447. texelHeight,
  11448. maxMip
  11449. };
  11450. }
  11451. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11452. // TODO Send this event to Three.js DevTools
  11453. // console.log( 'WebGLProgram', cacheKey );
  11454. const gl = renderer.getContext();
  11455. const defines = parameters.defines;
  11456. let vertexShader = parameters.vertexShader;
  11457. let fragmentShader = parameters.fragmentShader;
  11458. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11459. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11460. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11461. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11462. const envMapCubeUVSize = generateCubeUVSize(parameters);
  11463. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11464. const customDefines = generateDefines(defines);
  11465. const program = gl.createProgram();
  11466. let prefixVertex, prefixFragment;
  11467. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11468. if (parameters.isRawShaderMaterial) {
  11469. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11470. if (prefixVertex.length > 0) {
  11471. prefixVertex += '\n';
  11472. }
  11473. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11474. if (prefixFragment.length > 0) {
  11475. prefixFragment += '\n';
  11476. }
  11477. } else {
  11478. 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');
  11479. 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'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11480. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.opaque ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11481. getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11482. }
  11483. vertexShader = resolveIncludes(vertexShader);
  11484. vertexShader = replaceLightNums(vertexShader, parameters);
  11485. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11486. fragmentShader = resolveIncludes(fragmentShader);
  11487. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11488. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11489. vertexShader = unrollLoops(vertexShader);
  11490. fragmentShader = unrollLoops(fragmentShader);
  11491. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11492. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11493. versionString = '#version 300 es\n';
  11494. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11495. 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;
  11496. }
  11497. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11498. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11499. // console.log( '*FRAGMENT*', fragmentGlsl );
  11500. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11501. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11502. gl.attachShader(program, glVertexShader);
  11503. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11504. if (parameters.index0AttributeName !== undefined) {
  11505. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11506. } else if (parameters.morphTargets === true) {
  11507. // programs with morphTargets displace position out of attribute 0
  11508. gl.bindAttribLocation(program, 0, 'position');
  11509. }
  11510. gl.linkProgram(program); // check for link errors
  11511. if (renderer.debug.checkShaderErrors) {
  11512. const programLog = gl.getProgramInfoLog(program).trim();
  11513. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11514. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11515. let runnable = true;
  11516. let haveDiagnostics = true;
  11517. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11518. runnable = false;
  11519. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11520. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11521. 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);
  11522. } else if (programLog !== '') {
  11523. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11524. } else if (vertexLog === '' || fragmentLog === '') {
  11525. haveDiagnostics = false;
  11526. }
  11527. if (haveDiagnostics) {
  11528. this.diagnostics = {
  11529. runnable: runnable,
  11530. programLog: programLog,
  11531. vertexShader: {
  11532. log: vertexLog,
  11533. prefix: prefixVertex
  11534. },
  11535. fragmentShader: {
  11536. log: fragmentLog,
  11537. prefix: prefixFragment
  11538. }
  11539. };
  11540. }
  11541. } // Clean up
  11542. // Crashes in iOS9 and iOS10. #18402
  11543. // gl.detachShader( program, glVertexShader );
  11544. // gl.detachShader( program, glFragmentShader );
  11545. gl.deleteShader(glVertexShader);
  11546. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11547. let cachedUniforms;
  11548. this.getUniforms = function () {
  11549. if (cachedUniforms === undefined) {
  11550. cachedUniforms = new WebGLUniforms(gl, program);
  11551. }
  11552. return cachedUniforms;
  11553. }; // set up caching for attribute locations
  11554. let cachedAttributes;
  11555. this.getAttributes = function () {
  11556. if (cachedAttributes === undefined) {
  11557. cachedAttributes = fetchAttributeLocations(gl, program);
  11558. }
  11559. return cachedAttributes;
  11560. }; // free resource
  11561. this.destroy = function () {
  11562. bindingStates.releaseStatesOfProgram(this);
  11563. gl.deleteProgram(program);
  11564. this.program = undefined;
  11565. }; //
  11566. this.name = parameters.shaderName;
  11567. this.id = programIdCount++;
  11568. this.cacheKey = cacheKey;
  11569. this.usedTimes = 1;
  11570. this.program = program;
  11571. this.vertexShader = glVertexShader;
  11572. this.fragmentShader = glFragmentShader;
  11573. return this;
  11574. }
  11575. let _id = 0;
  11576. class WebGLShaderCache {
  11577. constructor() {
  11578. this.shaderCache = new Map();
  11579. this.materialCache = new Map();
  11580. }
  11581. update(material) {
  11582. const vertexShader = material.vertexShader;
  11583. const fragmentShader = material.fragmentShader;
  11584. const vertexShaderStage = this._getShaderStage(vertexShader);
  11585. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11586. const materialShaders = this._getShaderCacheForMaterial(material);
  11587. if (materialShaders.has(vertexShaderStage) === false) {
  11588. materialShaders.add(vertexShaderStage);
  11589. vertexShaderStage.usedTimes++;
  11590. }
  11591. if (materialShaders.has(fragmentShaderStage) === false) {
  11592. materialShaders.add(fragmentShaderStage);
  11593. fragmentShaderStage.usedTimes++;
  11594. }
  11595. return this;
  11596. }
  11597. remove(material) {
  11598. const materialShaders = this.materialCache.get(material);
  11599. for (const shaderStage of materialShaders) {
  11600. shaderStage.usedTimes--;
  11601. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code);
  11602. }
  11603. this.materialCache.delete(material);
  11604. return this;
  11605. }
  11606. getVertexShaderID(material) {
  11607. return this._getShaderStage(material.vertexShader).id;
  11608. }
  11609. getFragmentShaderID(material) {
  11610. return this._getShaderStage(material.fragmentShader).id;
  11611. }
  11612. dispose() {
  11613. this.shaderCache.clear();
  11614. this.materialCache.clear();
  11615. }
  11616. _getShaderCacheForMaterial(material) {
  11617. const cache = this.materialCache;
  11618. let set = cache.get(material);
  11619. if (set === undefined) {
  11620. set = new Set();
  11621. cache.set(material, set);
  11622. }
  11623. return set;
  11624. }
  11625. _getShaderStage(code) {
  11626. const cache = this.shaderCache;
  11627. let stage = cache.get(code);
  11628. if (stage === undefined) {
  11629. stage = new WebGLShaderStage(code);
  11630. cache.set(code, stage);
  11631. }
  11632. return stage;
  11633. }
  11634. }
  11635. class WebGLShaderStage {
  11636. constructor(code) {
  11637. this.id = _id++;
  11638. this.code = code;
  11639. this.usedTimes = 0;
  11640. }
  11641. }
  11642. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11643. const _programLayers = new Layers();
  11644. const _customShaders = new WebGLShaderCache();
  11645. const programs = [];
  11646. const isWebGL2 = capabilities.isWebGL2;
  11647. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11648. const vertexTextures = capabilities.vertexTextures;
  11649. let precision = capabilities.precision;
  11650. const shaderIDs = {
  11651. MeshDepthMaterial: 'depth',
  11652. MeshDistanceMaterial: 'distanceRGBA',
  11653. MeshNormalMaterial: 'normal',
  11654. MeshBasicMaterial: 'basic',
  11655. MeshLambertMaterial: 'lambert',
  11656. MeshPhongMaterial: 'phong',
  11657. MeshToonMaterial: 'toon',
  11658. MeshStandardMaterial: 'physical',
  11659. MeshPhysicalMaterial: 'physical',
  11660. MeshMatcapMaterial: 'matcap',
  11661. LineBasicMaterial: 'basic',
  11662. LineDashedMaterial: 'dashed',
  11663. PointsMaterial: 'points',
  11664. ShadowMaterial: 'shadow',
  11665. SpriteMaterial: 'sprite'
  11666. };
  11667. function getParameters(material, lights, shadows, scene, object) {
  11668. const fog = scene.fog;
  11669. const geometry = object.geometry;
  11670. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11671. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11672. const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null;
  11673. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11674. // (not to blow over maxLights budget)
  11675. if (material.precision !== null) {
  11676. precision = capabilities.getMaxPrecision(material.precision);
  11677. if (precision !== material.precision) {
  11678. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11679. }
  11680. } //
  11681. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11682. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  11683. let morphTextureStride = 0;
  11684. if (geometry.morphAttributes.position !== undefined) morphTextureStride = 1;
  11685. if (geometry.morphAttributes.normal !== undefined) morphTextureStride = 2;
  11686. if (geometry.morphAttributes.color !== undefined) morphTextureStride = 3; //
  11687. let vertexShader, fragmentShader;
  11688. let customVertexShaderID, customFragmentShaderID;
  11689. if (shaderID) {
  11690. const shader = ShaderLib[shaderID];
  11691. vertexShader = shader.vertexShader;
  11692. fragmentShader = shader.fragmentShader;
  11693. } else {
  11694. vertexShader = material.vertexShader;
  11695. fragmentShader = material.fragmentShader;
  11696. _customShaders.update(material);
  11697. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11698. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11699. }
  11700. const currentRenderTarget = renderer.getRenderTarget();
  11701. const useAlphaTest = material.alphaTest > 0;
  11702. const useClearcoat = material.clearcoat > 0;
  11703. const useIridescence = material.iridescence > 0;
  11704. const parameters = {
  11705. isWebGL2: isWebGL2,
  11706. shaderID: shaderID,
  11707. shaderName: material.type,
  11708. vertexShader: vertexShader,
  11709. fragmentShader: fragmentShader,
  11710. defines: material.defines,
  11711. customVertexShaderID: customVertexShaderID,
  11712. customFragmentShaderID: customFragmentShaderID,
  11713. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11714. glslVersion: material.glslVersion,
  11715. precision: precision,
  11716. instancing: object.isInstancedMesh === true,
  11717. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11718. supportsVertexTextures: vertexTextures,
  11719. outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding,
  11720. map: !!material.map,
  11721. matcap: !!material.matcap,
  11722. envMap: !!envMap,
  11723. envMapMode: envMap && envMap.mapping,
  11724. envMapCubeUVHeight: envMapCubeUVHeight,
  11725. lightMap: !!material.lightMap,
  11726. aoMap: !!material.aoMap,
  11727. emissiveMap: !!material.emissiveMap,
  11728. bumpMap: !!material.bumpMap,
  11729. normalMap: !!material.normalMap,
  11730. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11731. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11732. decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding,
  11733. clearcoat: useClearcoat,
  11734. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11735. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11736. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11737. iridescence: useIridescence,
  11738. iridescenceMap: useIridescence && !!material.iridescenceMap,
  11739. iridescenceThicknessMap: useIridescence && !!material.iridescenceThicknessMap,
  11740. displacementMap: !!material.displacementMap,
  11741. roughnessMap: !!material.roughnessMap,
  11742. metalnessMap: !!material.metalnessMap,
  11743. specularMap: !!material.specularMap,
  11744. specularIntensityMap: !!material.specularIntensityMap,
  11745. specularColorMap: !!material.specularColorMap,
  11746. opaque: material.transparent === false && material.blending === NormalBlending,
  11747. alphaMap: !!material.alphaMap,
  11748. alphaTest: useAlphaTest,
  11749. gradientMap: !!material.gradientMap,
  11750. sheen: material.sheen > 0,
  11751. sheenColorMap: !!material.sheenColorMap,
  11752. sheenRoughnessMap: !!material.sheenRoughnessMap,
  11753. transmission: material.transmission > 0,
  11754. transmissionMap: !!material.transmissionMap,
  11755. thicknessMap: !!material.thicknessMap,
  11756. combine: material.combine,
  11757. vertexTangents: !!material.normalMap && !!geometry.attributes.tangent,
  11758. vertexColors: material.vertexColors,
  11759. vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11760. 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,
  11761. 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,
  11762. fog: !!fog,
  11763. useFog: material.fog === true,
  11764. fogExp2: fog && fog.isFogExp2,
  11765. flatShading: !!material.flatShading,
  11766. sizeAttenuation: material.sizeAttenuation,
  11767. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11768. skinning: object.isSkinnedMesh === true,
  11769. morphTargets: geometry.morphAttributes.position !== undefined,
  11770. morphNormals: geometry.morphAttributes.normal !== undefined,
  11771. morphColors: geometry.morphAttributes.color !== undefined,
  11772. morphTargetsCount: morphTargetsCount,
  11773. morphTextureStride: morphTextureStride,
  11774. numDirLights: lights.directional.length,
  11775. numPointLights: lights.point.length,
  11776. numSpotLights: lights.spot.length,
  11777. numRectAreaLights: lights.rectArea.length,
  11778. numHemiLights: lights.hemi.length,
  11779. numDirLightShadows: lights.directionalShadowMap.length,
  11780. numPointLightShadows: lights.pointShadowMap.length,
  11781. numSpotLightShadows: lights.spotShadowMap.length,
  11782. numClippingPlanes: clipping.numPlanes,
  11783. numClipIntersection: clipping.numIntersection,
  11784. dithering: material.dithering,
  11785. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11786. shadowMapType: renderer.shadowMap.type,
  11787. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11788. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11789. premultipliedAlpha: material.premultipliedAlpha,
  11790. doubleSided: material.side === DoubleSide,
  11791. flipSided: material.side === BackSide,
  11792. useDepthPacking: !!material.depthPacking,
  11793. depthPacking: material.depthPacking || 0,
  11794. index0AttributeName: material.index0AttributeName,
  11795. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11796. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11797. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11798. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11799. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11800. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11801. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11802. customProgramCacheKey: material.customProgramCacheKey()
  11803. };
  11804. return parameters;
  11805. }
  11806. function getProgramCacheKey(parameters) {
  11807. const array = [];
  11808. if (parameters.shaderID) {
  11809. array.push(parameters.shaderID);
  11810. } else {
  11811. array.push(parameters.customVertexShaderID);
  11812. array.push(parameters.customFragmentShaderID);
  11813. }
  11814. if (parameters.defines !== undefined) {
  11815. for (const name in parameters.defines) {
  11816. array.push(name);
  11817. array.push(parameters.defines[name]);
  11818. }
  11819. }
  11820. if (parameters.isRawShaderMaterial === false) {
  11821. getProgramCacheKeyParameters(array, parameters);
  11822. getProgramCacheKeyBooleans(array, parameters);
  11823. array.push(renderer.outputEncoding);
  11824. }
  11825. array.push(parameters.customProgramCacheKey);
  11826. return array.join();
  11827. }
  11828. function getProgramCacheKeyParameters(array, parameters) {
  11829. array.push(parameters.precision);
  11830. array.push(parameters.outputEncoding);
  11831. array.push(parameters.envMapMode);
  11832. array.push(parameters.envMapCubeUVHeight);
  11833. array.push(parameters.combine);
  11834. array.push(parameters.vertexUvs);
  11835. array.push(parameters.fogExp2);
  11836. array.push(parameters.sizeAttenuation);
  11837. array.push(parameters.morphTargetsCount);
  11838. array.push(parameters.morphAttributeCount);
  11839. array.push(parameters.numDirLights);
  11840. array.push(parameters.numPointLights);
  11841. array.push(parameters.numSpotLights);
  11842. array.push(parameters.numHemiLights);
  11843. array.push(parameters.numRectAreaLights);
  11844. array.push(parameters.numDirLightShadows);
  11845. array.push(parameters.numPointLightShadows);
  11846. array.push(parameters.numSpotLightShadows);
  11847. array.push(parameters.shadowMapType);
  11848. array.push(parameters.toneMapping);
  11849. array.push(parameters.numClippingPlanes);
  11850. array.push(parameters.numClipIntersection);
  11851. array.push(parameters.depthPacking);
  11852. }
  11853. function getProgramCacheKeyBooleans(array, parameters) {
  11854. _programLayers.disableAll();
  11855. if (parameters.isWebGL2) _programLayers.enable(0);
  11856. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  11857. if (parameters.instancing) _programLayers.enable(2);
  11858. if (parameters.instancingColor) _programLayers.enable(3);
  11859. if (parameters.map) _programLayers.enable(4);
  11860. if (parameters.matcap) _programLayers.enable(5);
  11861. if (parameters.envMap) _programLayers.enable(6);
  11862. if (parameters.lightMap) _programLayers.enable(7);
  11863. if (parameters.aoMap) _programLayers.enable(8);
  11864. if (parameters.emissiveMap) _programLayers.enable(9);
  11865. if (parameters.bumpMap) _programLayers.enable(10);
  11866. if (parameters.normalMap) _programLayers.enable(11);
  11867. if (parameters.objectSpaceNormalMap) _programLayers.enable(12);
  11868. if (parameters.tangentSpaceNormalMap) _programLayers.enable(13);
  11869. if (parameters.clearcoat) _programLayers.enable(14);
  11870. if (parameters.clearcoatMap) _programLayers.enable(15);
  11871. if (parameters.clearcoatRoughnessMap) _programLayers.enable(16);
  11872. if (parameters.clearcoatNormalMap) _programLayers.enable(17);
  11873. if (parameters.iridescence) _programLayers.enable(18);
  11874. if (parameters.iridescenceMap) _programLayers.enable(19);
  11875. if (parameters.iridescenceThicknessMap) _programLayers.enable(20);
  11876. if (parameters.displacementMap) _programLayers.enable(21);
  11877. if (parameters.specularMap) _programLayers.enable(22);
  11878. if (parameters.roughnessMap) _programLayers.enable(23);
  11879. if (parameters.metalnessMap) _programLayers.enable(24);
  11880. if (parameters.gradientMap) _programLayers.enable(25);
  11881. if (parameters.alphaMap) _programLayers.enable(26);
  11882. if (parameters.alphaTest) _programLayers.enable(27);
  11883. if (parameters.vertexColors) _programLayers.enable(28);
  11884. if (parameters.vertexAlphas) _programLayers.enable(29);
  11885. if (parameters.vertexUvs) _programLayers.enable(30);
  11886. if (parameters.vertexTangents) _programLayers.enable(31);
  11887. if (parameters.uvsVertexOnly) _programLayers.enable(32);
  11888. array.push(_programLayers.mask);
  11889. _programLayers.disableAll();
  11890. if (parameters.fog) _programLayers.enable(0);
  11891. if (parameters.useFog) _programLayers.enable(1);
  11892. if (parameters.flatShading) _programLayers.enable(2);
  11893. if (parameters.logarithmicDepthBuffer) _programLayers.enable(3);
  11894. if (parameters.skinning) _programLayers.enable(4);
  11895. if (parameters.morphTargets) _programLayers.enable(5);
  11896. if (parameters.morphNormals) _programLayers.enable(6);
  11897. if (parameters.morphColors) _programLayers.enable(7);
  11898. if (parameters.premultipliedAlpha) _programLayers.enable(8);
  11899. if (parameters.shadowMapEnabled) _programLayers.enable(9);
  11900. if (parameters.physicallyCorrectLights) _programLayers.enable(10);
  11901. if (parameters.doubleSided) _programLayers.enable(11);
  11902. if (parameters.flipSided) _programLayers.enable(12);
  11903. if (parameters.useDepthPacking) _programLayers.enable(13);
  11904. if (parameters.dithering) _programLayers.enable(14);
  11905. if (parameters.specularIntensityMap) _programLayers.enable(15);
  11906. if (parameters.specularColorMap) _programLayers.enable(16);
  11907. if (parameters.transmission) _programLayers.enable(17);
  11908. if (parameters.transmissionMap) _programLayers.enable(18);
  11909. if (parameters.thicknessMap) _programLayers.enable(19);
  11910. if (parameters.sheen) _programLayers.enable(20);
  11911. if (parameters.sheenColorMap) _programLayers.enable(21);
  11912. if (parameters.sheenRoughnessMap) _programLayers.enable(22);
  11913. if (parameters.decodeVideoTexture) _programLayers.enable(23);
  11914. if (parameters.opaque) _programLayers.enable(24);
  11915. array.push(_programLayers.mask);
  11916. }
  11917. function getUniforms(material) {
  11918. const shaderID = shaderIDs[material.type];
  11919. let uniforms;
  11920. if (shaderID) {
  11921. const shader = ShaderLib[shaderID];
  11922. uniforms = UniformsUtils.clone(shader.uniforms);
  11923. } else {
  11924. uniforms = material.uniforms;
  11925. }
  11926. return uniforms;
  11927. }
  11928. function acquireProgram(parameters, cacheKey) {
  11929. let program; // Check if code has been already compiled
  11930. for (let p = 0, pl = programs.length; p < pl; p++) {
  11931. const preexistingProgram = programs[p];
  11932. if (preexistingProgram.cacheKey === cacheKey) {
  11933. program = preexistingProgram;
  11934. ++program.usedTimes;
  11935. break;
  11936. }
  11937. }
  11938. if (program === undefined) {
  11939. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11940. programs.push(program);
  11941. }
  11942. return program;
  11943. }
  11944. function releaseProgram(program) {
  11945. if (--program.usedTimes === 0) {
  11946. // Remove from unordered set
  11947. const i = programs.indexOf(program);
  11948. programs[i] = programs[programs.length - 1];
  11949. programs.pop(); // Free WebGL resources
  11950. program.destroy();
  11951. }
  11952. }
  11953. function releaseShaderCache(material) {
  11954. _customShaders.remove(material);
  11955. }
  11956. function dispose() {
  11957. _customShaders.dispose();
  11958. }
  11959. return {
  11960. getParameters: getParameters,
  11961. getProgramCacheKey: getProgramCacheKey,
  11962. getUniforms: getUniforms,
  11963. acquireProgram: acquireProgram,
  11964. releaseProgram: releaseProgram,
  11965. releaseShaderCache: releaseShaderCache,
  11966. // Exposed for resource monitoring & error feedback via renderer.info:
  11967. programs: programs,
  11968. dispose: dispose
  11969. };
  11970. }
  11971. function WebGLProperties() {
  11972. let properties = new WeakMap();
  11973. function get(object) {
  11974. let map = properties.get(object);
  11975. if (map === undefined) {
  11976. map = {};
  11977. properties.set(object, map);
  11978. }
  11979. return map;
  11980. }
  11981. function remove(object) {
  11982. properties.delete(object);
  11983. }
  11984. function update(object, key, value) {
  11985. properties.get(object)[key] = value;
  11986. }
  11987. function dispose() {
  11988. properties = new WeakMap();
  11989. }
  11990. return {
  11991. get: get,
  11992. remove: remove,
  11993. update: update,
  11994. dispose: dispose
  11995. };
  11996. }
  11997. function painterSortStable(a, b) {
  11998. if (a.groupOrder !== b.groupOrder) {
  11999. return a.groupOrder - b.groupOrder;
  12000. } else if (a.renderOrder !== b.renderOrder) {
  12001. return a.renderOrder - b.renderOrder;
  12002. } else if (a.material.id !== b.material.id) {
  12003. return a.material.id - b.material.id;
  12004. } else if (a.z !== b.z) {
  12005. return a.z - b.z;
  12006. } else {
  12007. return a.id - b.id;
  12008. }
  12009. }
  12010. function reversePainterSortStable(a, b) {
  12011. if (a.groupOrder !== b.groupOrder) {
  12012. return a.groupOrder - b.groupOrder;
  12013. } else if (a.renderOrder !== b.renderOrder) {
  12014. return a.renderOrder - b.renderOrder;
  12015. } else if (a.z !== b.z) {
  12016. return b.z - a.z;
  12017. } else {
  12018. return a.id - b.id;
  12019. }
  12020. }
  12021. function WebGLRenderList() {
  12022. const renderItems = [];
  12023. let renderItemsIndex = 0;
  12024. const opaque = [];
  12025. const transmissive = [];
  12026. const transparent = [];
  12027. function init() {
  12028. renderItemsIndex = 0;
  12029. opaque.length = 0;
  12030. transmissive.length = 0;
  12031. transparent.length = 0;
  12032. }
  12033. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12034. let renderItem = renderItems[renderItemsIndex];
  12035. if (renderItem === undefined) {
  12036. renderItem = {
  12037. id: object.id,
  12038. object: object,
  12039. geometry: geometry,
  12040. material: material,
  12041. groupOrder: groupOrder,
  12042. renderOrder: object.renderOrder,
  12043. z: z,
  12044. group: group
  12045. };
  12046. renderItems[renderItemsIndex] = renderItem;
  12047. } else {
  12048. renderItem.id = object.id;
  12049. renderItem.object = object;
  12050. renderItem.geometry = geometry;
  12051. renderItem.material = material;
  12052. renderItem.groupOrder = groupOrder;
  12053. renderItem.renderOrder = object.renderOrder;
  12054. renderItem.z = z;
  12055. renderItem.group = group;
  12056. }
  12057. renderItemsIndex++;
  12058. return renderItem;
  12059. }
  12060. function push(object, geometry, material, groupOrder, z, group) {
  12061. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12062. if (material.transmission > 0.0) {
  12063. transmissive.push(renderItem);
  12064. } else if (material.transparent === true) {
  12065. transparent.push(renderItem);
  12066. } else {
  12067. opaque.push(renderItem);
  12068. }
  12069. }
  12070. function unshift(object, geometry, material, groupOrder, z, group) {
  12071. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12072. if (material.transmission > 0.0) {
  12073. transmissive.unshift(renderItem);
  12074. } else if (material.transparent === true) {
  12075. transparent.unshift(renderItem);
  12076. } else {
  12077. opaque.unshift(renderItem);
  12078. }
  12079. }
  12080. function sort(customOpaqueSort, customTransparentSort) {
  12081. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12082. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  12083. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12084. }
  12085. function finish() {
  12086. // Clear references from inactive renderItems in the list
  12087. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12088. const renderItem = renderItems[i];
  12089. if (renderItem.id === null) break;
  12090. renderItem.id = null;
  12091. renderItem.object = null;
  12092. renderItem.geometry = null;
  12093. renderItem.material = null;
  12094. renderItem.group = null;
  12095. }
  12096. }
  12097. return {
  12098. opaque: opaque,
  12099. transmissive: transmissive,
  12100. transparent: transparent,
  12101. init: init,
  12102. push: push,
  12103. unshift: unshift,
  12104. finish: finish,
  12105. sort: sort
  12106. };
  12107. }
  12108. function WebGLRenderLists() {
  12109. let lists = new WeakMap();
  12110. function get(scene, renderCallDepth) {
  12111. let list;
  12112. if (lists.has(scene) === false) {
  12113. list = new WebGLRenderList();
  12114. lists.set(scene, [list]);
  12115. } else {
  12116. if (renderCallDepth >= lists.get(scene).length) {
  12117. list = new WebGLRenderList();
  12118. lists.get(scene).push(list);
  12119. } else {
  12120. list = lists.get(scene)[renderCallDepth];
  12121. }
  12122. }
  12123. return list;
  12124. }
  12125. function dispose() {
  12126. lists = new WeakMap();
  12127. }
  12128. return {
  12129. get: get,
  12130. dispose: dispose
  12131. };
  12132. }
  12133. function UniformsCache() {
  12134. const lights = {};
  12135. return {
  12136. get: function (light) {
  12137. if (lights[light.id] !== undefined) {
  12138. return lights[light.id];
  12139. }
  12140. let uniforms;
  12141. switch (light.type) {
  12142. case 'DirectionalLight':
  12143. uniforms = {
  12144. direction: new Vector3(),
  12145. color: new Color()
  12146. };
  12147. break;
  12148. case 'SpotLight':
  12149. uniforms = {
  12150. position: new Vector3(),
  12151. direction: new Vector3(),
  12152. color: new Color(),
  12153. distance: 0,
  12154. coneCos: 0,
  12155. penumbraCos: 0,
  12156. decay: 0
  12157. };
  12158. break;
  12159. case 'PointLight':
  12160. uniforms = {
  12161. position: new Vector3(),
  12162. color: new Color(),
  12163. distance: 0,
  12164. decay: 0
  12165. };
  12166. break;
  12167. case 'HemisphereLight':
  12168. uniforms = {
  12169. direction: new Vector3(),
  12170. skyColor: new Color(),
  12171. groundColor: new Color()
  12172. };
  12173. break;
  12174. case 'RectAreaLight':
  12175. uniforms = {
  12176. color: new Color(),
  12177. position: new Vector3(),
  12178. halfWidth: new Vector3(),
  12179. halfHeight: new Vector3()
  12180. };
  12181. break;
  12182. }
  12183. lights[light.id] = uniforms;
  12184. return uniforms;
  12185. }
  12186. };
  12187. }
  12188. function ShadowUniformsCache() {
  12189. const lights = {};
  12190. return {
  12191. get: function (light) {
  12192. if (lights[light.id] !== undefined) {
  12193. return lights[light.id];
  12194. }
  12195. let uniforms;
  12196. switch (light.type) {
  12197. case 'DirectionalLight':
  12198. uniforms = {
  12199. shadowBias: 0,
  12200. shadowNormalBias: 0,
  12201. shadowRadius: 1,
  12202. shadowMapSize: new Vector2()
  12203. };
  12204. break;
  12205. case 'SpotLight':
  12206. uniforms = {
  12207. shadowBias: 0,
  12208. shadowNormalBias: 0,
  12209. shadowRadius: 1,
  12210. shadowMapSize: new Vector2()
  12211. };
  12212. break;
  12213. case 'PointLight':
  12214. uniforms = {
  12215. shadowBias: 0,
  12216. shadowNormalBias: 0,
  12217. shadowRadius: 1,
  12218. shadowMapSize: new Vector2(),
  12219. shadowCameraNear: 1,
  12220. shadowCameraFar: 1000
  12221. };
  12222. break;
  12223. // TODO (abelnation): set RectAreaLight shadow uniforms
  12224. }
  12225. lights[light.id] = uniforms;
  12226. return uniforms;
  12227. }
  12228. };
  12229. }
  12230. let nextVersion = 0;
  12231. function shadowCastingLightsFirst(lightA, lightB) {
  12232. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12233. }
  12234. function WebGLLights(extensions, capabilities) {
  12235. const cache = new UniformsCache();
  12236. const shadowCache = ShadowUniformsCache();
  12237. const state = {
  12238. version: 0,
  12239. hash: {
  12240. directionalLength: -1,
  12241. pointLength: -1,
  12242. spotLength: -1,
  12243. rectAreaLength: -1,
  12244. hemiLength: -1,
  12245. numDirectionalShadows: -1,
  12246. numPointShadows: -1,
  12247. numSpotShadows: -1
  12248. },
  12249. ambient: [0, 0, 0],
  12250. probe: [],
  12251. directional: [],
  12252. directionalShadow: [],
  12253. directionalShadowMap: [],
  12254. directionalShadowMatrix: [],
  12255. spot: [],
  12256. spotShadow: [],
  12257. spotShadowMap: [],
  12258. spotShadowMatrix: [],
  12259. rectArea: [],
  12260. rectAreaLTC1: null,
  12261. rectAreaLTC2: null,
  12262. point: [],
  12263. pointShadow: [],
  12264. pointShadowMap: [],
  12265. pointShadowMatrix: [],
  12266. hemi: []
  12267. };
  12268. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12269. const vector3 = new Vector3();
  12270. const matrix4 = new Matrix4();
  12271. const matrix42 = new Matrix4();
  12272. function setup(lights, physicallyCorrectLights) {
  12273. let r = 0,
  12274. g = 0,
  12275. b = 0;
  12276. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12277. let directionalLength = 0;
  12278. let pointLength = 0;
  12279. let spotLength = 0;
  12280. let rectAreaLength = 0;
  12281. let hemiLength = 0;
  12282. let numDirectionalShadows = 0;
  12283. let numPointShadows = 0;
  12284. let numSpotShadows = 0;
  12285. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  12286. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12287. for (let i = 0, l = lights.length; i < l; i++) {
  12288. const light = lights[i];
  12289. const color = light.color;
  12290. const intensity = light.intensity;
  12291. const distance = light.distance;
  12292. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12293. if (light.isAmbientLight) {
  12294. r += color.r * intensity * scaleFactor;
  12295. g += color.g * intensity * scaleFactor;
  12296. b += color.b * intensity * scaleFactor;
  12297. } else if (light.isLightProbe) {
  12298. for (let j = 0; j < 9; j++) {
  12299. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12300. }
  12301. } else if (light.isDirectionalLight) {
  12302. const uniforms = cache.get(light);
  12303. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12304. if (light.castShadow) {
  12305. const shadow = light.shadow;
  12306. const shadowUniforms = shadowCache.get(light);
  12307. shadowUniforms.shadowBias = shadow.bias;
  12308. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12309. shadowUniforms.shadowRadius = shadow.radius;
  12310. shadowUniforms.shadowMapSize = shadow.mapSize;
  12311. state.directionalShadow[directionalLength] = shadowUniforms;
  12312. state.directionalShadowMap[directionalLength] = shadowMap;
  12313. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12314. numDirectionalShadows++;
  12315. }
  12316. state.directional[directionalLength] = uniforms;
  12317. directionalLength++;
  12318. } else if (light.isSpotLight) {
  12319. const uniforms = cache.get(light);
  12320. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12321. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12322. uniforms.distance = distance;
  12323. uniforms.coneCos = Math.cos(light.angle);
  12324. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12325. uniforms.decay = light.decay;
  12326. if (light.castShadow) {
  12327. const shadow = light.shadow;
  12328. const shadowUniforms = shadowCache.get(light);
  12329. shadowUniforms.shadowBias = shadow.bias;
  12330. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12331. shadowUniforms.shadowRadius = shadow.radius;
  12332. shadowUniforms.shadowMapSize = shadow.mapSize;
  12333. state.spotShadow[spotLength] = shadowUniforms;
  12334. state.spotShadowMap[spotLength] = shadowMap;
  12335. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12336. numSpotShadows++;
  12337. }
  12338. state.spot[spotLength] = uniforms;
  12339. spotLength++;
  12340. } else if (light.isRectAreaLight) {
  12341. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12342. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12343. // (b) intensity is the brightness of the light
  12344. uniforms.color.copy(color).multiplyScalar(intensity);
  12345. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12346. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12347. state.rectArea[rectAreaLength] = uniforms;
  12348. rectAreaLength++;
  12349. } else if (light.isPointLight) {
  12350. const uniforms = cache.get(light);
  12351. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12352. uniforms.distance = light.distance;
  12353. uniforms.decay = light.decay;
  12354. if (light.castShadow) {
  12355. const shadow = light.shadow;
  12356. const shadowUniforms = shadowCache.get(light);
  12357. shadowUniforms.shadowBias = shadow.bias;
  12358. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12359. shadowUniforms.shadowRadius = shadow.radius;
  12360. shadowUniforms.shadowMapSize = shadow.mapSize;
  12361. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12362. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12363. state.pointShadow[pointLength] = shadowUniforms;
  12364. state.pointShadowMap[pointLength] = shadowMap;
  12365. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12366. numPointShadows++;
  12367. }
  12368. state.point[pointLength] = uniforms;
  12369. pointLength++;
  12370. } else if (light.isHemisphereLight) {
  12371. const uniforms = cache.get(light);
  12372. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12373. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12374. state.hemi[hemiLength] = uniforms;
  12375. hemiLength++;
  12376. }
  12377. }
  12378. if (rectAreaLength > 0) {
  12379. if (capabilities.isWebGL2) {
  12380. // WebGL 2
  12381. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12382. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12383. } else {
  12384. // WebGL 1
  12385. if (extensions.has('OES_texture_float_linear') === true) {
  12386. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12387. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12388. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12389. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12390. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12391. } else {
  12392. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12393. }
  12394. }
  12395. }
  12396. state.ambient[0] = r;
  12397. state.ambient[1] = g;
  12398. state.ambient[2] = b;
  12399. const hash = state.hash;
  12400. 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) {
  12401. state.directional.length = directionalLength;
  12402. state.spot.length = spotLength;
  12403. state.rectArea.length = rectAreaLength;
  12404. state.point.length = pointLength;
  12405. state.hemi.length = hemiLength;
  12406. state.directionalShadow.length = numDirectionalShadows;
  12407. state.directionalShadowMap.length = numDirectionalShadows;
  12408. state.pointShadow.length = numPointShadows;
  12409. state.pointShadowMap.length = numPointShadows;
  12410. state.spotShadow.length = numSpotShadows;
  12411. state.spotShadowMap.length = numSpotShadows;
  12412. state.directionalShadowMatrix.length = numDirectionalShadows;
  12413. state.pointShadowMatrix.length = numPointShadows;
  12414. state.spotShadowMatrix.length = numSpotShadows;
  12415. hash.directionalLength = directionalLength;
  12416. hash.pointLength = pointLength;
  12417. hash.spotLength = spotLength;
  12418. hash.rectAreaLength = rectAreaLength;
  12419. hash.hemiLength = hemiLength;
  12420. hash.numDirectionalShadows = numDirectionalShadows;
  12421. hash.numPointShadows = numPointShadows;
  12422. hash.numSpotShadows = numSpotShadows;
  12423. state.version = nextVersion++;
  12424. }
  12425. }
  12426. function setupView(lights, camera) {
  12427. let directionalLength = 0;
  12428. let pointLength = 0;
  12429. let spotLength = 0;
  12430. let rectAreaLength = 0;
  12431. let hemiLength = 0;
  12432. const viewMatrix = camera.matrixWorldInverse;
  12433. for (let i = 0, l = lights.length; i < l; i++) {
  12434. const light = lights[i];
  12435. if (light.isDirectionalLight) {
  12436. const uniforms = state.directional[directionalLength];
  12437. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12438. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12439. uniforms.direction.sub(vector3);
  12440. uniforms.direction.transformDirection(viewMatrix);
  12441. directionalLength++;
  12442. } else if (light.isSpotLight) {
  12443. const uniforms = state.spot[spotLength];
  12444. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12445. uniforms.position.applyMatrix4(viewMatrix);
  12446. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12447. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12448. uniforms.direction.sub(vector3);
  12449. uniforms.direction.transformDirection(viewMatrix);
  12450. spotLength++;
  12451. } else if (light.isRectAreaLight) {
  12452. const uniforms = state.rectArea[rectAreaLength];
  12453. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12454. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12455. matrix42.identity();
  12456. matrix4.copy(light.matrixWorld);
  12457. matrix4.premultiply(viewMatrix);
  12458. matrix42.extractRotation(matrix4);
  12459. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12460. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12461. uniforms.halfWidth.applyMatrix4(matrix42);
  12462. uniforms.halfHeight.applyMatrix4(matrix42);
  12463. rectAreaLength++;
  12464. } else if (light.isPointLight) {
  12465. const uniforms = state.point[pointLength];
  12466. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12467. uniforms.position.applyMatrix4(viewMatrix);
  12468. pointLength++;
  12469. } else if (light.isHemisphereLight) {
  12470. const uniforms = state.hemi[hemiLength];
  12471. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12472. uniforms.direction.transformDirection(viewMatrix);
  12473. hemiLength++;
  12474. }
  12475. }
  12476. }
  12477. return {
  12478. setup: setup,
  12479. setupView: setupView,
  12480. state: state
  12481. };
  12482. }
  12483. function WebGLRenderState(extensions, capabilities) {
  12484. const lights = new WebGLLights(extensions, capabilities);
  12485. const lightsArray = [];
  12486. const shadowsArray = [];
  12487. function init() {
  12488. lightsArray.length = 0;
  12489. shadowsArray.length = 0;
  12490. }
  12491. function pushLight(light) {
  12492. lightsArray.push(light);
  12493. }
  12494. function pushShadow(shadowLight) {
  12495. shadowsArray.push(shadowLight);
  12496. }
  12497. function setupLights(physicallyCorrectLights) {
  12498. lights.setup(lightsArray, physicallyCorrectLights);
  12499. }
  12500. function setupLightsView(camera) {
  12501. lights.setupView(lightsArray, camera);
  12502. }
  12503. const state = {
  12504. lightsArray: lightsArray,
  12505. shadowsArray: shadowsArray,
  12506. lights: lights
  12507. };
  12508. return {
  12509. init: init,
  12510. state: state,
  12511. setupLights: setupLights,
  12512. setupLightsView: setupLightsView,
  12513. pushLight: pushLight,
  12514. pushShadow: pushShadow
  12515. };
  12516. }
  12517. function WebGLRenderStates(extensions, capabilities) {
  12518. let renderStates = new WeakMap();
  12519. function get(scene, renderCallDepth = 0) {
  12520. let renderState;
  12521. if (renderStates.has(scene) === false) {
  12522. renderState = new WebGLRenderState(extensions, capabilities);
  12523. renderStates.set(scene, [renderState]);
  12524. } else {
  12525. if (renderCallDepth >= renderStates.get(scene).length) {
  12526. renderState = new WebGLRenderState(extensions, capabilities);
  12527. renderStates.get(scene).push(renderState);
  12528. } else {
  12529. renderState = renderStates.get(scene)[renderCallDepth];
  12530. }
  12531. }
  12532. return renderState;
  12533. }
  12534. function dispose() {
  12535. renderStates = new WeakMap();
  12536. }
  12537. return {
  12538. get: get,
  12539. dispose: dispose
  12540. };
  12541. }
  12542. class MeshDepthMaterial extends Material {
  12543. constructor(parameters) {
  12544. super();
  12545. this.isMeshDepthMaterial = true;
  12546. this.type = 'MeshDepthMaterial';
  12547. this.depthPacking = BasicDepthPacking;
  12548. this.map = null;
  12549. this.alphaMap = null;
  12550. this.displacementMap = null;
  12551. this.displacementScale = 1;
  12552. this.displacementBias = 0;
  12553. this.wireframe = false;
  12554. this.wireframeLinewidth = 1;
  12555. this.setValues(parameters);
  12556. }
  12557. copy(source) {
  12558. super.copy(source);
  12559. this.depthPacking = source.depthPacking;
  12560. this.map = source.map;
  12561. this.alphaMap = source.alphaMap;
  12562. this.displacementMap = source.displacementMap;
  12563. this.displacementScale = source.displacementScale;
  12564. this.displacementBias = source.displacementBias;
  12565. this.wireframe = source.wireframe;
  12566. this.wireframeLinewidth = source.wireframeLinewidth;
  12567. return this;
  12568. }
  12569. }
  12570. class MeshDistanceMaterial extends Material {
  12571. constructor(parameters) {
  12572. super();
  12573. this.isMeshDistanceMaterial = true;
  12574. this.type = 'MeshDistanceMaterial';
  12575. this.referencePosition = new Vector3();
  12576. this.nearDistance = 1;
  12577. this.farDistance = 1000;
  12578. this.map = null;
  12579. this.alphaMap = null;
  12580. this.displacementMap = null;
  12581. this.displacementScale = 1;
  12582. this.displacementBias = 0;
  12583. this.setValues(parameters);
  12584. }
  12585. copy(source) {
  12586. super.copy(source);
  12587. this.referencePosition.copy(source.referencePosition);
  12588. this.nearDistance = source.nearDistance;
  12589. this.farDistance = source.farDistance;
  12590. this.map = source.map;
  12591. this.alphaMap = source.alphaMap;
  12592. this.displacementMap = source.displacementMap;
  12593. this.displacementScale = source.displacementScale;
  12594. this.displacementBias = source.displacementBias;
  12595. return this;
  12596. }
  12597. }
  12598. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12599. 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}";
  12600. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12601. let _frustum = new Frustum();
  12602. const _shadowMapSize = new Vector2(),
  12603. _viewportSize = new Vector2(),
  12604. _viewport = new Vector4(),
  12605. _depthMaterial = new MeshDepthMaterial({
  12606. depthPacking: RGBADepthPacking
  12607. }),
  12608. _distanceMaterial = new MeshDistanceMaterial(),
  12609. _materialCache = {},
  12610. _maxTextureSize = _capabilities.maxTextureSize;
  12611. const shadowSide = {
  12612. 0: BackSide,
  12613. 1: FrontSide,
  12614. 2: DoubleSide
  12615. };
  12616. const shadowMaterialVertical = new ShaderMaterial({
  12617. defines: {
  12618. VSM_SAMPLES: 8
  12619. },
  12620. uniforms: {
  12621. shadow_pass: {
  12622. value: null
  12623. },
  12624. resolution: {
  12625. value: new Vector2()
  12626. },
  12627. radius: {
  12628. value: 4.0
  12629. }
  12630. },
  12631. vertexShader: vertex,
  12632. fragmentShader: fragment
  12633. });
  12634. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12635. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12636. const fullScreenTri = new BufferGeometry();
  12637. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12638. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12639. const scope = this;
  12640. this.enabled = false;
  12641. this.autoUpdate = true;
  12642. this.needsUpdate = false;
  12643. this.type = PCFShadowMap;
  12644. this.render = function (lights, scene, camera) {
  12645. if (scope.enabled === false) return;
  12646. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12647. if (lights.length === 0) return;
  12648. const currentRenderTarget = _renderer.getRenderTarget();
  12649. const activeCubeFace = _renderer.getActiveCubeFace();
  12650. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12651. const _state = _renderer.state; // Set GL state for depth map.
  12652. _state.setBlending(NoBlending);
  12653. _state.buffers.color.setClear(1, 1, 1, 1);
  12654. _state.buffers.depth.setTest(true);
  12655. _state.setScissorTest(false); // render depth map
  12656. for (let i = 0, il = lights.length; i < il; i++) {
  12657. const light = lights[i];
  12658. const shadow = light.shadow;
  12659. if (shadow === undefined) {
  12660. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12661. continue;
  12662. }
  12663. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12664. _shadowMapSize.copy(shadow.mapSize);
  12665. const shadowFrameExtents = shadow.getFrameExtents();
  12666. _shadowMapSize.multiply(shadowFrameExtents);
  12667. _viewportSize.copy(shadow.mapSize);
  12668. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12669. if (_shadowMapSize.x > _maxTextureSize) {
  12670. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12671. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12672. shadow.mapSize.x = _viewportSize.x;
  12673. }
  12674. if (_shadowMapSize.y > _maxTextureSize) {
  12675. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12676. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12677. shadow.mapSize.y = _viewportSize.y;
  12678. }
  12679. }
  12680. if (shadow.map === null) {
  12681. const pars = this.type !== VSMShadowMap ? {
  12682. minFilter: NearestFilter,
  12683. magFilter: NearestFilter
  12684. } : {};
  12685. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12686. shadow.map.texture.name = light.name + '.shadowMap';
  12687. shadow.camera.updateProjectionMatrix();
  12688. }
  12689. _renderer.setRenderTarget(shadow.map);
  12690. _renderer.clear();
  12691. const viewportCount = shadow.getViewportCount();
  12692. for (let vp = 0; vp < viewportCount; vp++) {
  12693. const viewport = shadow.getViewport(vp);
  12694. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12695. _state.viewport(_viewport);
  12696. shadow.updateMatrices(light, vp);
  12697. _frustum = shadow.getFrustum();
  12698. renderObject(scene, camera, shadow.camera, light, this.type);
  12699. } // do blur pass for VSM
  12700. if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) {
  12701. VSMPass(shadow, camera);
  12702. }
  12703. shadow.needsUpdate = false;
  12704. }
  12705. scope.needsUpdate = false;
  12706. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12707. };
  12708. function VSMPass(shadow, camera) {
  12709. const geometry = _objects.update(fullScreenMesh);
  12710. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  12711. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12712. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12713. shadowMaterialVertical.needsUpdate = true;
  12714. shadowMaterialHorizontal.needsUpdate = true;
  12715. }
  12716. if (shadow.mapPass === null) {
  12717. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y);
  12718. } // vertical pass
  12719. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12720. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12721. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12722. _renderer.setRenderTarget(shadow.mapPass);
  12723. _renderer.clear();
  12724. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12725. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12726. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12727. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12728. _renderer.setRenderTarget(shadow.map);
  12729. _renderer.clear();
  12730. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12731. }
  12732. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12733. let result = null;
  12734. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12735. if (customMaterial !== undefined) {
  12736. result = customMaterial;
  12737. } else {
  12738. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12739. }
  12740. if (_renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12741. // in this case we need a unique material instance reflecting the
  12742. // appropriate state
  12743. const keyA = result.uuid,
  12744. keyB = material.uuid;
  12745. let materialsForVariant = _materialCache[keyA];
  12746. if (materialsForVariant === undefined) {
  12747. materialsForVariant = {};
  12748. _materialCache[keyA] = materialsForVariant;
  12749. }
  12750. let cachedMaterial = materialsForVariant[keyB];
  12751. if (cachedMaterial === undefined) {
  12752. cachedMaterial = result.clone();
  12753. materialsForVariant[keyB] = cachedMaterial;
  12754. }
  12755. result = cachedMaterial;
  12756. }
  12757. result.visible = material.visible;
  12758. result.wireframe = material.wireframe;
  12759. if (type === VSMShadowMap) {
  12760. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12761. } else {
  12762. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12763. }
  12764. result.alphaMap = material.alphaMap;
  12765. result.alphaTest = material.alphaTest;
  12766. result.clipShadows = material.clipShadows;
  12767. result.clippingPlanes = material.clippingPlanes;
  12768. result.clipIntersection = material.clipIntersection;
  12769. result.displacementMap = material.displacementMap;
  12770. result.displacementScale = material.displacementScale;
  12771. result.displacementBias = material.displacementBias;
  12772. result.wireframeLinewidth = material.wireframeLinewidth;
  12773. result.linewidth = material.linewidth;
  12774. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12775. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12776. result.nearDistance = shadowCameraNear;
  12777. result.farDistance = shadowCameraFar;
  12778. }
  12779. return result;
  12780. }
  12781. function renderObject(object, camera, shadowCamera, light, type) {
  12782. if (object.visible === false) return;
  12783. const visible = object.layers.test(camera.layers);
  12784. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12785. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12786. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12787. const geometry = _objects.update(object);
  12788. const material = object.material;
  12789. if (Array.isArray(material)) {
  12790. const groups = geometry.groups;
  12791. for (let k = 0, kl = groups.length; k < kl; k++) {
  12792. const group = groups[k];
  12793. const groupMaterial = material[group.materialIndex];
  12794. if (groupMaterial && groupMaterial.visible) {
  12795. const depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12796. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12797. }
  12798. }
  12799. } else if (material.visible) {
  12800. const depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12801. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12802. }
  12803. }
  12804. }
  12805. const children = object.children;
  12806. for (let i = 0, l = children.length; i < l; i++) {
  12807. renderObject(children[i], camera, shadowCamera, light, type);
  12808. }
  12809. }
  12810. }
  12811. function WebGLState(gl, extensions, capabilities) {
  12812. const isWebGL2 = capabilities.isWebGL2;
  12813. function ColorBuffer() {
  12814. let locked = false;
  12815. const color = new Vector4();
  12816. let currentColorMask = null;
  12817. const currentColorClear = new Vector4(0, 0, 0, 0);
  12818. return {
  12819. setMask: function (colorMask) {
  12820. if (currentColorMask !== colorMask && !locked) {
  12821. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12822. currentColorMask = colorMask;
  12823. }
  12824. },
  12825. setLocked: function (lock) {
  12826. locked = lock;
  12827. },
  12828. setClear: function (r, g, b, a, premultipliedAlpha) {
  12829. if (premultipliedAlpha === true) {
  12830. r *= a;
  12831. g *= a;
  12832. b *= a;
  12833. }
  12834. color.set(r, g, b, a);
  12835. if (currentColorClear.equals(color) === false) {
  12836. gl.clearColor(r, g, b, a);
  12837. currentColorClear.copy(color);
  12838. }
  12839. },
  12840. reset: function () {
  12841. locked = false;
  12842. currentColorMask = null;
  12843. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12844. }
  12845. };
  12846. }
  12847. function DepthBuffer() {
  12848. let locked = false;
  12849. let currentDepthMask = null;
  12850. let currentDepthFunc = null;
  12851. let currentDepthClear = null;
  12852. return {
  12853. setTest: function (depthTest) {
  12854. if (depthTest) {
  12855. enable(gl.DEPTH_TEST);
  12856. } else {
  12857. disable(gl.DEPTH_TEST);
  12858. }
  12859. },
  12860. setMask: function (depthMask) {
  12861. if (currentDepthMask !== depthMask && !locked) {
  12862. gl.depthMask(depthMask);
  12863. currentDepthMask = depthMask;
  12864. }
  12865. },
  12866. setFunc: function (depthFunc) {
  12867. if (currentDepthFunc !== depthFunc) {
  12868. if (depthFunc) {
  12869. switch (depthFunc) {
  12870. case NeverDepth:
  12871. gl.depthFunc(gl.NEVER);
  12872. break;
  12873. case AlwaysDepth:
  12874. gl.depthFunc(gl.ALWAYS);
  12875. break;
  12876. case LessDepth:
  12877. gl.depthFunc(gl.LESS);
  12878. break;
  12879. case LessEqualDepth:
  12880. gl.depthFunc(gl.LEQUAL);
  12881. break;
  12882. case EqualDepth:
  12883. gl.depthFunc(gl.EQUAL);
  12884. break;
  12885. case GreaterEqualDepth:
  12886. gl.depthFunc(gl.GEQUAL);
  12887. break;
  12888. case GreaterDepth:
  12889. gl.depthFunc(gl.GREATER);
  12890. break;
  12891. case NotEqualDepth:
  12892. gl.depthFunc(gl.NOTEQUAL);
  12893. break;
  12894. default:
  12895. gl.depthFunc(gl.LEQUAL);
  12896. }
  12897. } else {
  12898. gl.depthFunc(gl.LEQUAL);
  12899. }
  12900. currentDepthFunc = depthFunc;
  12901. }
  12902. },
  12903. setLocked: function (lock) {
  12904. locked = lock;
  12905. },
  12906. setClear: function (depth) {
  12907. if (currentDepthClear !== depth) {
  12908. gl.clearDepth(depth);
  12909. currentDepthClear = depth;
  12910. }
  12911. },
  12912. reset: function () {
  12913. locked = false;
  12914. currentDepthMask = null;
  12915. currentDepthFunc = null;
  12916. currentDepthClear = null;
  12917. }
  12918. };
  12919. }
  12920. function StencilBuffer() {
  12921. let locked = false;
  12922. let currentStencilMask = null;
  12923. let currentStencilFunc = null;
  12924. let currentStencilRef = null;
  12925. let currentStencilFuncMask = null;
  12926. let currentStencilFail = null;
  12927. let currentStencilZFail = null;
  12928. let currentStencilZPass = null;
  12929. let currentStencilClear = null;
  12930. return {
  12931. setTest: function (stencilTest) {
  12932. if (!locked) {
  12933. if (stencilTest) {
  12934. enable(gl.STENCIL_TEST);
  12935. } else {
  12936. disable(gl.STENCIL_TEST);
  12937. }
  12938. }
  12939. },
  12940. setMask: function (stencilMask) {
  12941. if (currentStencilMask !== stencilMask && !locked) {
  12942. gl.stencilMask(stencilMask);
  12943. currentStencilMask = stencilMask;
  12944. }
  12945. },
  12946. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12947. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12948. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12949. currentStencilFunc = stencilFunc;
  12950. currentStencilRef = stencilRef;
  12951. currentStencilFuncMask = stencilMask;
  12952. }
  12953. },
  12954. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12955. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12956. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12957. currentStencilFail = stencilFail;
  12958. currentStencilZFail = stencilZFail;
  12959. currentStencilZPass = stencilZPass;
  12960. }
  12961. },
  12962. setLocked: function (lock) {
  12963. locked = lock;
  12964. },
  12965. setClear: function (stencil) {
  12966. if (currentStencilClear !== stencil) {
  12967. gl.clearStencil(stencil);
  12968. currentStencilClear = stencil;
  12969. }
  12970. },
  12971. reset: function () {
  12972. locked = false;
  12973. currentStencilMask = null;
  12974. currentStencilFunc = null;
  12975. currentStencilRef = null;
  12976. currentStencilFuncMask = null;
  12977. currentStencilFail = null;
  12978. currentStencilZFail = null;
  12979. currentStencilZPass = null;
  12980. currentStencilClear = null;
  12981. }
  12982. };
  12983. } //
  12984. const colorBuffer = new ColorBuffer();
  12985. const depthBuffer = new DepthBuffer();
  12986. const stencilBuffer = new StencilBuffer();
  12987. const uboBindings = new WeakMap();
  12988. const uboProgamMap = new WeakMap();
  12989. let enabledCapabilities = {};
  12990. let currentBoundFramebuffers = {};
  12991. let currentDrawbuffers = new WeakMap();
  12992. let defaultDrawbuffers = [];
  12993. let currentProgram = null;
  12994. let currentBlendingEnabled = false;
  12995. let currentBlending = null;
  12996. let currentBlendEquation = null;
  12997. let currentBlendSrc = null;
  12998. let currentBlendDst = null;
  12999. let currentBlendEquationAlpha = null;
  13000. let currentBlendSrcAlpha = null;
  13001. let currentBlendDstAlpha = null;
  13002. let currentPremultipledAlpha = false;
  13003. let currentFlipSided = null;
  13004. let currentCullFace = null;
  13005. let currentLineWidth = null;
  13006. let currentPolygonOffsetFactor = null;
  13007. let currentPolygonOffsetUnits = null;
  13008. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  13009. let lineWidthAvailable = false;
  13010. let version = 0;
  13011. const glVersion = gl.getParameter(gl.VERSION);
  13012. if (glVersion.indexOf('WebGL') !== -1) {
  13013. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  13014. lineWidthAvailable = version >= 1.0;
  13015. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13016. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  13017. lineWidthAvailable = version >= 2.0;
  13018. }
  13019. let currentTextureSlot = null;
  13020. let currentBoundTextures = {};
  13021. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  13022. const viewportParam = gl.getParameter(gl.VIEWPORT);
  13023. const currentScissor = new Vector4().fromArray(scissorParam);
  13024. const currentViewport = new Vector4().fromArray(viewportParam);
  13025. function createTexture(type, target, count) {
  13026. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13027. const texture = gl.createTexture();
  13028. gl.bindTexture(type, texture);
  13029. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13030. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13031. for (let i = 0; i < count; i++) {
  13032. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  13033. }
  13034. return texture;
  13035. }
  13036. const emptyTextures = {};
  13037. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  13038. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  13039. colorBuffer.setClear(0, 0, 0, 1);
  13040. depthBuffer.setClear(1);
  13041. stencilBuffer.setClear(0);
  13042. enable(gl.DEPTH_TEST);
  13043. depthBuffer.setFunc(LessEqualDepth);
  13044. setFlipSided(false);
  13045. setCullFace(CullFaceBack);
  13046. enable(gl.CULL_FACE);
  13047. setBlending(NoBlending); //
  13048. function enable(id) {
  13049. if (enabledCapabilities[id] !== true) {
  13050. gl.enable(id);
  13051. enabledCapabilities[id] = true;
  13052. }
  13053. }
  13054. function disable(id) {
  13055. if (enabledCapabilities[id] !== false) {
  13056. gl.disable(id);
  13057. enabledCapabilities[id] = false;
  13058. }
  13059. }
  13060. function bindFramebuffer(target, framebuffer) {
  13061. if (currentBoundFramebuffers[target] !== framebuffer) {
  13062. gl.bindFramebuffer(target, framebuffer);
  13063. currentBoundFramebuffers[target] = framebuffer;
  13064. if (isWebGL2) {
  13065. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13066. if (target === gl.DRAW_FRAMEBUFFER) {
  13067. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13068. }
  13069. if (target === gl.FRAMEBUFFER) {
  13070. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13071. }
  13072. }
  13073. return true;
  13074. }
  13075. return false;
  13076. }
  13077. function drawBuffers(renderTarget, framebuffer) {
  13078. let drawBuffers = defaultDrawbuffers;
  13079. let needsUpdate = false;
  13080. if (renderTarget) {
  13081. drawBuffers = currentDrawbuffers.get(framebuffer);
  13082. if (drawBuffers === undefined) {
  13083. drawBuffers = [];
  13084. currentDrawbuffers.set(framebuffer, drawBuffers);
  13085. }
  13086. if (renderTarget.isWebGLMultipleRenderTargets) {
  13087. const textures = renderTarget.texture;
  13088. if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13089. for (let i = 0, il = textures.length; i < il; i++) {
  13090. drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i;
  13091. }
  13092. drawBuffers.length = textures.length;
  13093. needsUpdate = true;
  13094. }
  13095. } else {
  13096. if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13097. drawBuffers[0] = gl.COLOR_ATTACHMENT0;
  13098. needsUpdate = true;
  13099. }
  13100. }
  13101. } else {
  13102. if (drawBuffers[0] !== gl.BACK) {
  13103. drawBuffers[0] = gl.BACK;
  13104. needsUpdate = true;
  13105. }
  13106. }
  13107. if (needsUpdate) {
  13108. if (capabilities.isWebGL2) {
  13109. gl.drawBuffers(drawBuffers);
  13110. } else {
  13111. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers);
  13112. }
  13113. }
  13114. }
  13115. function useProgram(program) {
  13116. if (currentProgram !== program) {
  13117. gl.useProgram(program);
  13118. currentProgram = program;
  13119. return true;
  13120. }
  13121. return false;
  13122. }
  13123. const equationToGL = {
  13124. [AddEquation]: gl.FUNC_ADD,
  13125. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13126. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13127. };
  13128. if (isWebGL2) {
  13129. equationToGL[MinEquation] = gl.MIN;
  13130. equationToGL[MaxEquation] = gl.MAX;
  13131. } else {
  13132. const extension = extensions.get('EXT_blend_minmax');
  13133. if (extension !== null) {
  13134. equationToGL[MinEquation] = extension.MIN_EXT;
  13135. equationToGL[MaxEquation] = extension.MAX_EXT;
  13136. }
  13137. }
  13138. const factorToGL = {
  13139. [ZeroFactor]: gl.ZERO,
  13140. [OneFactor]: gl.ONE,
  13141. [SrcColorFactor]: gl.SRC_COLOR,
  13142. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13143. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13144. [DstColorFactor]: gl.DST_COLOR,
  13145. [DstAlphaFactor]: gl.DST_ALPHA,
  13146. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13147. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13148. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13149. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13150. };
  13151. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13152. if (blending === NoBlending) {
  13153. if (currentBlendingEnabled === true) {
  13154. disable(gl.BLEND);
  13155. currentBlendingEnabled = false;
  13156. }
  13157. return;
  13158. }
  13159. if (currentBlendingEnabled === false) {
  13160. enable(gl.BLEND);
  13161. currentBlendingEnabled = true;
  13162. }
  13163. if (blending !== CustomBlending) {
  13164. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13165. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13166. gl.blendEquation(gl.FUNC_ADD);
  13167. currentBlendEquation = AddEquation;
  13168. currentBlendEquationAlpha = AddEquation;
  13169. }
  13170. if (premultipliedAlpha) {
  13171. switch (blending) {
  13172. case NormalBlending:
  13173. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13174. break;
  13175. case AdditiveBlending:
  13176. gl.blendFunc(gl.ONE, gl.ONE);
  13177. break;
  13178. case SubtractiveBlending:
  13179. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13180. break;
  13181. case MultiplyBlending:
  13182. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13183. break;
  13184. default:
  13185. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13186. break;
  13187. }
  13188. } else {
  13189. switch (blending) {
  13190. case NormalBlending:
  13191. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13192. break;
  13193. case AdditiveBlending:
  13194. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13195. break;
  13196. case SubtractiveBlending:
  13197. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13198. break;
  13199. case MultiplyBlending:
  13200. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13201. break;
  13202. default:
  13203. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13204. break;
  13205. }
  13206. }
  13207. currentBlendSrc = null;
  13208. currentBlendDst = null;
  13209. currentBlendSrcAlpha = null;
  13210. currentBlendDstAlpha = null;
  13211. currentBlending = blending;
  13212. currentPremultipledAlpha = premultipliedAlpha;
  13213. }
  13214. return;
  13215. } // custom blending
  13216. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13217. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13218. blendDstAlpha = blendDstAlpha || blendDst;
  13219. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13220. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13221. currentBlendEquation = blendEquation;
  13222. currentBlendEquationAlpha = blendEquationAlpha;
  13223. }
  13224. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13225. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13226. currentBlendSrc = blendSrc;
  13227. currentBlendDst = blendDst;
  13228. currentBlendSrcAlpha = blendSrcAlpha;
  13229. currentBlendDstAlpha = blendDstAlpha;
  13230. }
  13231. currentBlending = blending;
  13232. currentPremultipledAlpha = null;
  13233. }
  13234. function setMaterial(material, frontFaceCW) {
  13235. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13236. let flipSided = material.side === BackSide;
  13237. if (frontFaceCW) flipSided = !flipSided;
  13238. setFlipSided(flipSided);
  13239. 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);
  13240. depthBuffer.setFunc(material.depthFunc);
  13241. depthBuffer.setTest(material.depthTest);
  13242. depthBuffer.setMask(material.depthWrite);
  13243. colorBuffer.setMask(material.colorWrite);
  13244. const stencilWrite = material.stencilWrite;
  13245. stencilBuffer.setTest(stencilWrite);
  13246. if (stencilWrite) {
  13247. stencilBuffer.setMask(material.stencilWriteMask);
  13248. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13249. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13250. }
  13251. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13252. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13253. } //
  13254. function setFlipSided(flipSided) {
  13255. if (currentFlipSided !== flipSided) {
  13256. if (flipSided) {
  13257. gl.frontFace(gl.CW);
  13258. } else {
  13259. gl.frontFace(gl.CCW);
  13260. }
  13261. currentFlipSided = flipSided;
  13262. }
  13263. }
  13264. function setCullFace(cullFace) {
  13265. if (cullFace !== CullFaceNone) {
  13266. enable(gl.CULL_FACE);
  13267. if (cullFace !== currentCullFace) {
  13268. if (cullFace === CullFaceBack) {
  13269. gl.cullFace(gl.BACK);
  13270. } else if (cullFace === CullFaceFront) {
  13271. gl.cullFace(gl.FRONT);
  13272. } else {
  13273. gl.cullFace(gl.FRONT_AND_BACK);
  13274. }
  13275. }
  13276. } else {
  13277. disable(gl.CULL_FACE);
  13278. }
  13279. currentCullFace = cullFace;
  13280. }
  13281. function setLineWidth(width) {
  13282. if (width !== currentLineWidth) {
  13283. if (lineWidthAvailable) gl.lineWidth(width);
  13284. currentLineWidth = width;
  13285. }
  13286. }
  13287. function setPolygonOffset(polygonOffset, factor, units) {
  13288. if (polygonOffset) {
  13289. enable(gl.POLYGON_OFFSET_FILL);
  13290. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13291. gl.polygonOffset(factor, units);
  13292. currentPolygonOffsetFactor = factor;
  13293. currentPolygonOffsetUnits = units;
  13294. }
  13295. } else {
  13296. disable(gl.POLYGON_OFFSET_FILL);
  13297. }
  13298. }
  13299. function setScissorTest(scissorTest) {
  13300. if (scissorTest) {
  13301. enable(gl.SCISSOR_TEST);
  13302. } else {
  13303. disable(gl.SCISSOR_TEST);
  13304. }
  13305. } // texture
  13306. function activeTexture(webglSlot) {
  13307. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13308. if (currentTextureSlot !== webglSlot) {
  13309. gl.activeTexture(webglSlot);
  13310. currentTextureSlot = webglSlot;
  13311. }
  13312. }
  13313. function bindTexture(webglType, webglTexture) {
  13314. if (currentTextureSlot === null) {
  13315. activeTexture();
  13316. }
  13317. let boundTexture = currentBoundTextures[currentTextureSlot];
  13318. if (boundTexture === undefined) {
  13319. boundTexture = {
  13320. type: undefined,
  13321. texture: undefined
  13322. };
  13323. currentBoundTextures[currentTextureSlot] = boundTexture;
  13324. }
  13325. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13326. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13327. boundTexture.type = webglType;
  13328. boundTexture.texture = webglTexture;
  13329. }
  13330. }
  13331. function unbindTexture() {
  13332. const boundTexture = currentBoundTextures[currentTextureSlot];
  13333. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13334. gl.bindTexture(boundTexture.type, null);
  13335. boundTexture.type = undefined;
  13336. boundTexture.texture = undefined;
  13337. }
  13338. }
  13339. function compressedTexImage2D() {
  13340. try {
  13341. gl.compressedTexImage2D.apply(gl, arguments);
  13342. } catch (error) {
  13343. console.error('THREE.WebGLState:', error);
  13344. }
  13345. }
  13346. function texSubImage2D() {
  13347. try {
  13348. gl.texSubImage2D.apply(gl, arguments);
  13349. } catch (error) {
  13350. console.error('THREE.WebGLState:', error);
  13351. }
  13352. }
  13353. function texSubImage3D() {
  13354. try {
  13355. gl.texSubImage3D.apply(gl, arguments);
  13356. } catch (error) {
  13357. console.error('THREE.WebGLState:', error);
  13358. }
  13359. }
  13360. function compressedTexSubImage2D() {
  13361. try {
  13362. gl.compressedTexSubImage2D.apply(gl, arguments);
  13363. } catch (error) {
  13364. console.error('THREE.WebGLState:', error);
  13365. }
  13366. }
  13367. function texStorage2D() {
  13368. try {
  13369. gl.texStorage2D.apply(gl, arguments);
  13370. } catch (error) {
  13371. console.error('THREE.WebGLState:', error);
  13372. }
  13373. }
  13374. function texStorage3D() {
  13375. try {
  13376. gl.texStorage3D.apply(gl, arguments);
  13377. } catch (error) {
  13378. console.error('THREE.WebGLState:', error);
  13379. }
  13380. }
  13381. function texImage2D() {
  13382. try {
  13383. gl.texImage2D.apply(gl, arguments);
  13384. } catch (error) {
  13385. console.error('THREE.WebGLState:', error);
  13386. }
  13387. }
  13388. function texImage3D() {
  13389. try {
  13390. gl.texImage3D.apply(gl, arguments);
  13391. } catch (error) {
  13392. console.error('THREE.WebGLState:', error);
  13393. }
  13394. } //
  13395. function scissor(scissor) {
  13396. if (currentScissor.equals(scissor) === false) {
  13397. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13398. currentScissor.copy(scissor);
  13399. }
  13400. }
  13401. function viewport(viewport) {
  13402. if (currentViewport.equals(viewport) === false) {
  13403. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13404. currentViewport.copy(viewport);
  13405. }
  13406. }
  13407. function updateUBOMapping(uniformsGroup, program) {
  13408. let mapping = uboProgamMap.get(program);
  13409. if (mapping === undefined) {
  13410. mapping = new WeakMap();
  13411. uboProgamMap.set(program, mapping);
  13412. }
  13413. let blockIndex = mapping.get(uniformsGroup);
  13414. if (blockIndex === undefined) {
  13415. blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name);
  13416. mapping.set(uniformsGroup, blockIndex);
  13417. }
  13418. }
  13419. function uniformBlockBinding(uniformsGroup, program) {
  13420. const mapping = uboProgamMap.get(program);
  13421. const blockIndex = mapping.get(uniformsGroup);
  13422. if (uboBindings.get(uniformsGroup) !== blockIndex) {
  13423. // bind shader specific block index to global block point
  13424. gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex);
  13425. uboBindings.set(uniformsGroup, blockIndex);
  13426. }
  13427. } //
  13428. function reset() {
  13429. // reset state
  13430. gl.disable(gl.BLEND);
  13431. gl.disable(gl.CULL_FACE);
  13432. gl.disable(gl.DEPTH_TEST);
  13433. gl.disable(gl.POLYGON_OFFSET_FILL);
  13434. gl.disable(gl.SCISSOR_TEST);
  13435. gl.disable(gl.STENCIL_TEST);
  13436. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13437. gl.blendEquation(gl.FUNC_ADD);
  13438. gl.blendFunc(gl.ONE, gl.ZERO);
  13439. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13440. gl.colorMask(true, true, true, true);
  13441. gl.clearColor(0, 0, 0, 0);
  13442. gl.depthMask(true);
  13443. gl.depthFunc(gl.LESS);
  13444. gl.clearDepth(1);
  13445. gl.stencilMask(0xffffffff);
  13446. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13447. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13448. gl.clearStencil(0);
  13449. gl.cullFace(gl.BACK);
  13450. gl.frontFace(gl.CCW);
  13451. gl.polygonOffset(0, 0);
  13452. gl.activeTexture(gl.TEXTURE0);
  13453. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13454. if (isWebGL2 === true) {
  13455. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13456. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13457. }
  13458. gl.useProgram(null);
  13459. gl.lineWidth(1);
  13460. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13461. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13462. enabledCapabilities = {};
  13463. currentTextureSlot = null;
  13464. currentBoundTextures = {};
  13465. currentBoundFramebuffers = {};
  13466. currentDrawbuffers = new WeakMap();
  13467. defaultDrawbuffers = [];
  13468. currentProgram = null;
  13469. currentBlendingEnabled = false;
  13470. currentBlending = null;
  13471. currentBlendEquation = null;
  13472. currentBlendSrc = null;
  13473. currentBlendDst = null;
  13474. currentBlendEquationAlpha = null;
  13475. currentBlendSrcAlpha = null;
  13476. currentBlendDstAlpha = null;
  13477. currentPremultipledAlpha = false;
  13478. currentFlipSided = null;
  13479. currentCullFace = null;
  13480. currentLineWidth = null;
  13481. currentPolygonOffsetFactor = null;
  13482. currentPolygonOffsetUnits = null;
  13483. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13484. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13485. colorBuffer.reset();
  13486. depthBuffer.reset();
  13487. stencilBuffer.reset();
  13488. }
  13489. return {
  13490. buffers: {
  13491. color: colorBuffer,
  13492. depth: depthBuffer,
  13493. stencil: stencilBuffer
  13494. },
  13495. enable: enable,
  13496. disable: disable,
  13497. bindFramebuffer: bindFramebuffer,
  13498. drawBuffers: drawBuffers,
  13499. useProgram: useProgram,
  13500. setBlending: setBlending,
  13501. setMaterial: setMaterial,
  13502. setFlipSided: setFlipSided,
  13503. setCullFace: setCullFace,
  13504. setLineWidth: setLineWidth,
  13505. setPolygonOffset: setPolygonOffset,
  13506. setScissorTest: setScissorTest,
  13507. activeTexture: activeTexture,
  13508. bindTexture: bindTexture,
  13509. unbindTexture: unbindTexture,
  13510. compressedTexImage2D: compressedTexImage2D,
  13511. texImage2D: texImage2D,
  13512. texImage3D: texImage3D,
  13513. updateUBOMapping: updateUBOMapping,
  13514. uniformBlockBinding: uniformBlockBinding,
  13515. texStorage2D: texStorage2D,
  13516. texStorage3D: texStorage3D,
  13517. texSubImage2D: texSubImage2D,
  13518. texSubImage3D: texSubImage3D,
  13519. compressedTexSubImage2D: compressedTexSubImage2D,
  13520. scissor: scissor,
  13521. viewport: viewport,
  13522. reset: reset
  13523. };
  13524. }
  13525. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13526. const isWebGL2 = capabilities.isWebGL2;
  13527. const maxTextures = capabilities.maxTextures;
  13528. const maxCubemapSize = capabilities.maxCubemapSize;
  13529. const maxTextureSize = capabilities.maxTextureSize;
  13530. const maxSamples = capabilities.maxSamples;
  13531. const multisampledRTTExt = extensions.has('WEBGL_multisampled_render_to_texture') ? extensions.get('WEBGL_multisampled_render_to_texture') : null;
  13532. const supportsInvalidateFramebuffer = /OculusBrowser/g.test(navigator.userAgent);
  13533. const _videoTextures = new WeakMap();
  13534. let _canvas;
  13535. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13536. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13537. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13538. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13539. let useOffscreenCanvas = false;
  13540. try {
  13541. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' // eslint-disable-next-line compat/compat
  13542. && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13543. } catch (err) {// Ignore any errors
  13544. }
  13545. function createCanvas(width, height) {
  13546. // Use OffscreenCanvas when available. Specially needed in web workers
  13547. return useOffscreenCanvas ? // eslint-disable-next-line compat/compat
  13548. new OffscreenCanvas(width, height) : createElementNS('canvas');
  13549. }
  13550. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13551. let scale = 1; // handle case if texture exceeds max size
  13552. if (image.width > maxSize || image.height > maxSize) {
  13553. scale = maxSize / Math.max(image.width, image.height);
  13554. } // only perform resize if necessary
  13555. if (scale < 1 || needsPowerOfTwo === true) {
  13556. // only perform resize for certain image types
  13557. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13558. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13559. const width = floor(scale * image.width);
  13560. const height = floor(scale * image.height);
  13561. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13562. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13563. canvas.width = width;
  13564. canvas.height = height;
  13565. const context = canvas.getContext('2d');
  13566. context.drawImage(image, 0, 0, width, height);
  13567. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13568. return canvas;
  13569. } else {
  13570. if ('data' in image) {
  13571. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13572. }
  13573. return image;
  13574. }
  13575. }
  13576. return image;
  13577. }
  13578. function isPowerOfTwo$1(image) {
  13579. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13580. }
  13581. function textureNeedsPowerOfTwo(texture) {
  13582. if (isWebGL2) return false;
  13583. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13584. }
  13585. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13586. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13587. }
  13588. function generateMipmap(target) {
  13589. _gl.generateMipmap(target);
  13590. }
  13591. function getInternalFormat(internalFormatName, glFormat, glType, encoding, isVideoTexture = false) {
  13592. if (isWebGL2 === false) return glFormat;
  13593. if (internalFormatName !== null) {
  13594. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13595. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13596. }
  13597. let internalFormat = glFormat;
  13598. if (glFormat === _gl.RED) {
  13599. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13600. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13601. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13602. }
  13603. if (glFormat === _gl.RG) {
  13604. if (glType === _gl.FLOAT) internalFormat = _gl.RG32F;
  13605. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F;
  13606. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8;
  13607. }
  13608. if (glFormat === _gl.RGBA) {
  13609. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13610. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13611. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && isVideoTexture === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13612. if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4;
  13613. if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1;
  13614. }
  13615. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13616. extensions.get('EXT_color_buffer_float');
  13617. }
  13618. return internalFormat;
  13619. }
  13620. function getMipLevels(texture, image, supportsMips) {
  13621. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13622. return Math.log2(Math.max(image.width, image.height)) + 1;
  13623. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13624. // user-defined mipmaps
  13625. return texture.mipmaps.length;
  13626. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13627. return image.mipmaps.length;
  13628. } else {
  13629. // texture without mipmaps (only base level)
  13630. return 1;
  13631. }
  13632. } // Fallback filters for non-power-of-2 textures
  13633. function filterFallback(f) {
  13634. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13635. return _gl.NEAREST;
  13636. }
  13637. return _gl.LINEAR;
  13638. } //
  13639. function onTextureDispose(event) {
  13640. const texture = event.target;
  13641. texture.removeEventListener('dispose', onTextureDispose);
  13642. deallocateTexture(texture);
  13643. if (texture.isVideoTexture) {
  13644. _videoTextures.delete(texture);
  13645. }
  13646. }
  13647. function onRenderTargetDispose(event) {
  13648. const renderTarget = event.target;
  13649. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13650. deallocateRenderTarget(renderTarget);
  13651. } //
  13652. function deallocateTexture(texture) {
  13653. const textureProperties = properties.get(texture);
  13654. if (textureProperties.__webglInit === undefined) return; // check if it's necessary to remove the WebGLTexture object
  13655. const source = texture.source;
  13656. const webglTextures = _sources.get(source);
  13657. if (webglTextures) {
  13658. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13659. webglTexture.usedTimes--; // the WebGLTexture object is not used anymore, remove it
  13660. if (webglTexture.usedTimes === 0) {
  13661. deleteTexture(texture);
  13662. } // remove the weak map entry if no WebGLTexture uses the source anymore
  13663. if (Object.keys(webglTextures).length === 0) {
  13664. _sources.delete(source);
  13665. }
  13666. }
  13667. properties.remove(texture);
  13668. }
  13669. function deleteTexture(texture) {
  13670. const textureProperties = properties.get(texture);
  13671. _gl.deleteTexture(textureProperties.__webglTexture);
  13672. const source = texture.source;
  13673. const webglTextures = _sources.get(source);
  13674. delete webglTextures[textureProperties.__cacheKey];
  13675. info.memory.textures--;
  13676. }
  13677. function deallocateRenderTarget(renderTarget) {
  13678. const texture = renderTarget.texture;
  13679. const renderTargetProperties = properties.get(renderTarget);
  13680. const textureProperties = properties.get(texture);
  13681. if (textureProperties.__webglTexture !== undefined) {
  13682. _gl.deleteTexture(textureProperties.__webglTexture);
  13683. info.memory.textures--;
  13684. }
  13685. if (renderTarget.depthTexture) {
  13686. renderTarget.depthTexture.dispose();
  13687. }
  13688. if (renderTarget.isWebGLCubeRenderTarget) {
  13689. for (let i = 0; i < 6; i++) {
  13690. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13691. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13692. }
  13693. } else {
  13694. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13695. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13696. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13697. if (renderTargetProperties.__webglColorRenderbuffer) {
  13698. for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) {
  13699. if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]);
  13700. }
  13701. }
  13702. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13703. }
  13704. if (renderTarget.isWebGLMultipleRenderTargets) {
  13705. for (let i = 0, il = texture.length; i < il; i++) {
  13706. const attachmentProperties = properties.get(texture[i]);
  13707. if (attachmentProperties.__webglTexture) {
  13708. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13709. info.memory.textures--;
  13710. }
  13711. properties.remove(texture[i]);
  13712. }
  13713. }
  13714. properties.remove(texture);
  13715. properties.remove(renderTarget);
  13716. } //
  13717. let textureUnits = 0;
  13718. function resetTextureUnits() {
  13719. textureUnits = 0;
  13720. }
  13721. function allocateTextureUnit() {
  13722. const textureUnit = textureUnits;
  13723. if (textureUnit >= maxTextures) {
  13724. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13725. }
  13726. textureUnits += 1;
  13727. return textureUnit;
  13728. }
  13729. function getTextureCacheKey(texture) {
  13730. const array = [];
  13731. array.push(texture.wrapS);
  13732. array.push(texture.wrapT);
  13733. array.push(texture.magFilter);
  13734. array.push(texture.minFilter);
  13735. array.push(texture.anisotropy);
  13736. array.push(texture.internalFormat);
  13737. array.push(texture.format);
  13738. array.push(texture.type);
  13739. array.push(texture.generateMipmaps);
  13740. array.push(texture.premultiplyAlpha);
  13741. array.push(texture.flipY);
  13742. array.push(texture.unpackAlignment);
  13743. array.push(texture.encoding);
  13744. return array.join();
  13745. } //
  13746. function setTexture2D(texture, slot) {
  13747. const textureProperties = properties.get(texture);
  13748. if (texture.isVideoTexture) updateVideoTexture(texture);
  13749. if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) {
  13750. const image = texture.image;
  13751. if (image === null) {
  13752. console.warn('THREE.WebGLRenderer: Texture marked for update but no image data found.');
  13753. } else if (image.complete === false) {
  13754. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13755. } else {
  13756. uploadTexture(textureProperties, texture, slot);
  13757. return;
  13758. }
  13759. }
  13760. state.activeTexture(_gl.TEXTURE0 + slot);
  13761. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13762. }
  13763. function setTexture2DArray(texture, slot) {
  13764. const textureProperties = properties.get(texture);
  13765. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13766. uploadTexture(textureProperties, texture, slot);
  13767. return;
  13768. }
  13769. state.activeTexture(_gl.TEXTURE0 + slot);
  13770. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13771. }
  13772. function setTexture3D(texture, slot) {
  13773. const textureProperties = properties.get(texture);
  13774. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13775. uploadTexture(textureProperties, texture, slot);
  13776. return;
  13777. }
  13778. state.activeTexture(_gl.TEXTURE0 + slot);
  13779. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13780. }
  13781. function setTextureCube(texture, slot) {
  13782. const textureProperties = properties.get(texture);
  13783. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13784. uploadCubeTexture(textureProperties, texture, slot);
  13785. return;
  13786. }
  13787. state.activeTexture(_gl.TEXTURE0 + slot);
  13788. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13789. }
  13790. const wrappingToGL = {
  13791. [RepeatWrapping]: _gl.REPEAT,
  13792. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13793. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13794. };
  13795. const filterToGL = {
  13796. [NearestFilter]: _gl.NEAREST,
  13797. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13798. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13799. [LinearFilter]: _gl.LINEAR,
  13800. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13801. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13802. };
  13803. function setTextureParameters(textureType, texture, supportsMips) {
  13804. if (supportsMips) {
  13805. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13806. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13807. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13808. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13809. }
  13810. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13811. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13812. } else {
  13813. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13814. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13815. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13816. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13817. }
  13818. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13819. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13820. }
  13821. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13822. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13823. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13824. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13825. }
  13826. }
  13827. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13828. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13829. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13830. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13831. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13832. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13833. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13834. }
  13835. }
  13836. }
  13837. function initTexture(textureProperties, texture) {
  13838. let forceUpload = false;
  13839. if (textureProperties.__webglInit === undefined) {
  13840. textureProperties.__webglInit = true;
  13841. texture.addEventListener('dispose', onTextureDispose);
  13842. } // create Source <-> WebGLTextures mapping if necessary
  13843. const source = texture.source;
  13844. let webglTextures = _sources.get(source);
  13845. if (webglTextures === undefined) {
  13846. webglTextures = {};
  13847. _sources.set(source, webglTextures);
  13848. } // check if there is already a WebGLTexture object for the given texture parameters
  13849. const textureCacheKey = getTextureCacheKey(texture);
  13850. if (textureCacheKey !== textureProperties.__cacheKey) {
  13851. // if not, create a new instance of WebGLTexture
  13852. if (webglTextures[textureCacheKey] === undefined) {
  13853. // create new entry
  13854. webglTextures[textureCacheKey] = {
  13855. texture: _gl.createTexture(),
  13856. usedTimes: 0
  13857. };
  13858. info.memory.textures++; // when a new instance of WebGLTexture was created, a texture upload is required
  13859. // even if the image contents are identical
  13860. forceUpload = true;
  13861. }
  13862. webglTextures[textureCacheKey].usedTimes++; // every time the texture cache key changes, it's necessary to check if an instance of
  13863. // WebGLTexture can be deleted in order to avoid a memory leak.
  13864. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13865. if (webglTexture !== undefined) {
  13866. webglTextures[textureProperties.__cacheKey].usedTimes--;
  13867. if (webglTexture.usedTimes === 0) {
  13868. deleteTexture(texture);
  13869. }
  13870. } // store references to cache key and WebGLTexture object
  13871. textureProperties.__cacheKey = textureCacheKey;
  13872. textureProperties.__webglTexture = webglTextures[textureCacheKey].texture;
  13873. }
  13874. return forceUpload;
  13875. }
  13876. function uploadTexture(textureProperties, texture, slot) {
  13877. let textureType = _gl.TEXTURE_2D;
  13878. if (texture.isDataArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY;
  13879. if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D;
  13880. const forceUpload = initTexture(textureProperties, texture);
  13881. const source = texture.source;
  13882. state.activeTexture(_gl.TEXTURE0 + slot);
  13883. state.bindTexture(textureType, textureProperties.__webglTexture);
  13884. if (source.version !== source.__currentVersion || forceUpload === true) {
  13885. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13886. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13887. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13888. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13889. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13890. let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13891. image = verifyColorSpace(texture, image);
  13892. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13893. glFormat = utils.convert(texture.format, texture.encoding);
  13894. let glType = utils.convert(texture.type),
  13895. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture);
  13896. setTextureParameters(textureType, texture, supportsMips);
  13897. let mipmap;
  13898. const mipmaps = texture.mipmaps;
  13899. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13900. const allocateMemory = source.__currentVersion === undefined || forceUpload === true;
  13901. const levels = getMipLevels(texture, image, supportsMips);
  13902. if (texture.isDepthTexture) {
  13903. // populate depth texture with dummy data
  13904. glInternalFormat = _gl.DEPTH_COMPONENT;
  13905. if (isWebGL2) {
  13906. if (texture.type === FloatType) {
  13907. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13908. } else if (texture.type === UnsignedIntType) {
  13909. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13910. } else if (texture.type === UnsignedInt248Type) {
  13911. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13912. } else {
  13913. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13914. }
  13915. } else {
  13916. if (texture.type === FloatType) {
  13917. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13918. }
  13919. } // validation checks for WebGL 1
  13920. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13921. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13922. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13923. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13924. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13925. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13926. texture.type = UnsignedIntType;
  13927. glType = utils.convert(texture.type);
  13928. }
  13929. }
  13930. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13931. // Depth stencil textures need the DEPTH_STENCIL internal format
  13932. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13933. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13934. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13935. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13936. if (texture.type !== UnsignedInt248Type) {
  13937. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13938. texture.type = UnsignedInt248Type;
  13939. glType = utils.convert(texture.type);
  13940. }
  13941. } //
  13942. if (allocateMemory) {
  13943. if (useTexStorage) {
  13944. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  13945. } else {
  13946. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13947. }
  13948. }
  13949. } else if (texture.isDataTexture) {
  13950. // use manually created mipmaps if available
  13951. // if there are no manual mipmaps
  13952. // set 0 level mipmap and then use GL to generate other mipmap levels
  13953. if (mipmaps.length > 0 && supportsMips) {
  13954. if (useTexStorage && allocateMemory) {
  13955. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13956. }
  13957. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13958. mipmap = mipmaps[i];
  13959. if (useTexStorage) {
  13960. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13961. } else {
  13962. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13963. }
  13964. }
  13965. texture.generateMipmaps = false;
  13966. } else {
  13967. if (useTexStorage) {
  13968. if (allocateMemory) {
  13969. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13970. }
  13971. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  13972. } else {
  13973. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13974. }
  13975. }
  13976. } else if (texture.isCompressedTexture) {
  13977. if (useTexStorage && allocateMemory) {
  13978. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13979. }
  13980. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13981. mipmap = mipmaps[i];
  13982. if (texture.format !== RGBAFormat) {
  13983. if (glFormat !== null) {
  13984. if (useTexStorage) {
  13985. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  13986. } else {
  13987. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13988. }
  13989. } else {
  13990. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13991. }
  13992. } else {
  13993. if (useTexStorage) {
  13994. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13995. } else {
  13996. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13997. }
  13998. }
  13999. }
  14000. } else if (texture.isDataArrayTexture) {
  14001. if (useTexStorage) {
  14002. if (allocateMemory) {
  14003. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  14004. }
  14005. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14006. } else {
  14007. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14008. }
  14009. } else if (texture.isData3DTexture) {
  14010. if (useTexStorage) {
  14011. if (allocateMemory) {
  14012. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  14013. }
  14014. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14015. } else {
  14016. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14017. }
  14018. } else if (texture.isFramebufferTexture) {
  14019. if (allocateMemory) {
  14020. if (useTexStorage) {
  14021. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14022. } else {
  14023. let width = image.width,
  14024. height = image.height;
  14025. for (let i = 0; i < levels; i++) {
  14026. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null);
  14027. width >>= 1;
  14028. height >>= 1;
  14029. }
  14030. }
  14031. }
  14032. } else {
  14033. // regular Texture (image, video, canvas)
  14034. // use manually created mipmaps if available
  14035. // if there are no manual mipmaps
  14036. // set 0 level mipmap and then use GL to generate other mipmap levels
  14037. if (mipmaps.length > 0 && supportsMips) {
  14038. if (useTexStorage && allocateMemory) {
  14039. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14040. }
  14041. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14042. mipmap = mipmaps[i];
  14043. if (useTexStorage) {
  14044. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  14045. } else {
  14046. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  14047. }
  14048. }
  14049. texture.generateMipmaps = false;
  14050. } else {
  14051. if (useTexStorage) {
  14052. if (allocateMemory) {
  14053. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14054. }
  14055. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  14056. } else {
  14057. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  14058. }
  14059. }
  14060. }
  14061. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14062. generateMipmap(textureType);
  14063. }
  14064. source.__currentVersion = source.version;
  14065. if (texture.onUpdate) texture.onUpdate(texture);
  14066. }
  14067. textureProperties.__version = texture.version;
  14068. }
  14069. function uploadCubeTexture(textureProperties, texture, slot) {
  14070. if (texture.image.length !== 6) return;
  14071. const forceUpload = initTexture(textureProperties, texture);
  14072. const source = texture.source;
  14073. state.activeTexture(_gl.TEXTURE0 + slot);
  14074. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14075. if (source.version !== source.__currentVersion || forceUpload === true) {
  14076. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  14077. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  14078. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  14079. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  14080. const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture;
  14081. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14082. const cubeImage = [];
  14083. for (let i = 0; i < 6; i++) {
  14084. if (!isCompressed && !isDataTexture) {
  14085. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  14086. } else {
  14087. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14088. }
  14089. cubeImage[i] = verifyColorSpace(texture, cubeImage[i]);
  14090. }
  14091. const image = cubeImage[0],
  14092. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  14093. glFormat = utils.convert(texture.format, texture.encoding),
  14094. glType = utils.convert(texture.type),
  14095. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14096. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  14097. const allocateMemory = source.__currentVersion === undefined || forceUpload === true;
  14098. let levels = getMipLevels(texture, image, supportsMips);
  14099. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14100. let mipmaps;
  14101. if (isCompressed) {
  14102. if (useTexStorage && allocateMemory) {
  14103. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  14104. }
  14105. for (let i = 0; i < 6; i++) {
  14106. mipmaps = cubeImage[i].mipmaps;
  14107. for (let j = 0; j < mipmaps.length; j++) {
  14108. const mipmap = mipmaps[j];
  14109. if (texture.format !== RGBAFormat) {
  14110. if (glFormat !== null) {
  14111. if (useTexStorage) {
  14112. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14113. } else {
  14114. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14115. }
  14116. } else {
  14117. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14118. }
  14119. } else {
  14120. if (useTexStorage) {
  14121. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14122. } else {
  14123. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14124. }
  14125. }
  14126. }
  14127. }
  14128. } else {
  14129. mipmaps = texture.mipmaps;
  14130. if (useTexStorage && allocateMemory) {
  14131. // TODO: Uniformly handle mipmap definitions
  14132. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14133. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14134. if (mipmaps.length > 0) levels++;
  14135. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  14136. }
  14137. for (let i = 0; i < 6; i++) {
  14138. if (isDataTexture) {
  14139. if (useTexStorage) {
  14140. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  14141. } else {
  14142. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14143. }
  14144. for (let j = 0; j < mipmaps.length; j++) {
  14145. const mipmap = mipmaps[j];
  14146. const mipmapImage = mipmap.image[i].image;
  14147. if (useTexStorage) {
  14148. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  14149. } else {
  14150. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14151. }
  14152. }
  14153. } else {
  14154. if (useTexStorage) {
  14155. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  14156. } else {
  14157. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14158. }
  14159. for (let j = 0; j < mipmaps.length; j++) {
  14160. const mipmap = mipmaps[j];
  14161. if (useTexStorage) {
  14162. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  14163. } else {
  14164. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14165. }
  14166. }
  14167. }
  14168. }
  14169. }
  14170. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14171. // We assume images for cube map have the same size.
  14172. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14173. }
  14174. source.__currentVersion = source.version;
  14175. if (texture.onUpdate) texture.onUpdate(texture);
  14176. }
  14177. textureProperties.__version = texture.version;
  14178. } // Render targets
  14179. // Setup storage for target texture and bind it to correct framebuffer
  14180. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  14181. const glFormat = utils.convert(texture.format, texture.encoding);
  14182. const glType = utils.convert(texture.type);
  14183. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14184. const renderTargetProperties = properties.get(renderTarget);
  14185. if (!renderTargetProperties.__hasExternalTextures) {
  14186. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  14187. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  14188. } else {
  14189. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14190. }
  14191. }
  14192. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14193. if (useMultisampledRTT(renderTarget)) {
  14194. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  14195. } else {
  14196. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  14197. }
  14198. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14199. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14200. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14201. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  14202. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14203. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14204. if (isMultisample || useMultisampledRTT(renderTarget)) {
  14205. const depthTexture = renderTarget.depthTexture;
  14206. if (depthTexture && depthTexture.isDepthTexture) {
  14207. if (depthTexture.type === FloatType) {
  14208. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14209. } else if (depthTexture.type === UnsignedIntType) {
  14210. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14211. }
  14212. }
  14213. const samples = getRenderTargetSamples(renderTarget);
  14214. if (useMultisampledRTT(renderTarget)) {
  14215. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14216. } else {
  14217. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14218. }
  14219. } else {
  14220. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14221. }
  14222. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14223. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14224. const samples = getRenderTargetSamples(renderTarget);
  14225. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14226. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14227. } else if (useMultisampledRTT(renderTarget)) {
  14228. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14229. } else {
  14230. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14231. }
  14232. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14233. } else {
  14234. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14235. for (let i = 0; i < textures.length; i++) {
  14236. const texture = textures[i];
  14237. const glFormat = utils.convert(texture.format, texture.encoding);
  14238. const glType = utils.convert(texture.type);
  14239. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14240. const samples = getRenderTargetSamples(renderTarget);
  14241. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14242. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14243. } else if (useMultisampledRTT(renderTarget)) {
  14244. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14245. } else {
  14246. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14247. }
  14248. }
  14249. }
  14250. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14251. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14252. function setupDepthTexture(framebuffer, renderTarget) {
  14253. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14254. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14255. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14256. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14257. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14258. } // upload an empty depth texture with framebuffer size
  14259. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14260. renderTarget.depthTexture.image.width = renderTarget.width;
  14261. renderTarget.depthTexture.image.height = renderTarget.height;
  14262. renderTarget.depthTexture.needsUpdate = true;
  14263. }
  14264. setTexture2D(renderTarget.depthTexture, 0);
  14265. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14266. const samples = getRenderTargetSamples(renderTarget);
  14267. if (renderTarget.depthTexture.format === DepthFormat) {
  14268. if (useMultisampledRTT(renderTarget)) {
  14269. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14270. } else {
  14271. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14272. }
  14273. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14274. if (useMultisampledRTT(renderTarget)) {
  14275. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14276. } else {
  14277. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14278. }
  14279. } else {
  14280. throw new Error('Unknown depthTexture format');
  14281. }
  14282. } // Setup GL resources for a non-texture depth buffer
  14283. function setupDepthRenderbuffer(renderTarget) {
  14284. const renderTargetProperties = properties.get(renderTarget);
  14285. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14286. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14287. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14288. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14289. } else {
  14290. if (isCube) {
  14291. renderTargetProperties.__webglDepthbuffer = [];
  14292. for (let i = 0; i < 6; i++) {
  14293. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14294. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14295. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14296. }
  14297. } else {
  14298. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14299. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14300. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14301. }
  14302. }
  14303. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14304. } // rebind framebuffer with external textures
  14305. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14306. const renderTargetProperties = properties.get(renderTarget);
  14307. if (colorTexture !== undefined) {
  14308. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14309. }
  14310. if (depthTexture !== undefined) {
  14311. setupDepthRenderbuffer(renderTarget);
  14312. }
  14313. } // Set up GL resources for the render target
  14314. function setupRenderTarget(renderTarget) {
  14315. const texture = renderTarget.texture;
  14316. const renderTargetProperties = properties.get(renderTarget);
  14317. const textureProperties = properties.get(texture);
  14318. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14319. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14320. if (textureProperties.__webglTexture === undefined) {
  14321. textureProperties.__webglTexture = _gl.createTexture();
  14322. }
  14323. textureProperties.__version = texture.version;
  14324. info.memory.textures++;
  14325. }
  14326. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14327. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14328. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Setup framebuffer
  14329. if (isCube) {
  14330. renderTargetProperties.__webglFramebuffer = [];
  14331. for (let i = 0; i < 6; i++) {
  14332. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14333. }
  14334. } else {
  14335. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14336. if (isMultipleRenderTargets) {
  14337. if (capabilities.drawBuffers) {
  14338. const textures = renderTarget.texture;
  14339. for (let i = 0, il = textures.length; i < il; i++) {
  14340. const attachmentProperties = properties.get(textures[i]);
  14341. if (attachmentProperties.__webglTexture === undefined) {
  14342. attachmentProperties.__webglTexture = _gl.createTexture();
  14343. info.memory.textures++;
  14344. }
  14345. }
  14346. } else {
  14347. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14348. }
  14349. }
  14350. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14351. const textures = isMultipleRenderTargets ? texture : [texture];
  14352. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14353. renderTargetProperties.__webglColorRenderbuffer = [];
  14354. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14355. for (let i = 0; i < textures.length; i++) {
  14356. const texture = textures[i];
  14357. renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer();
  14358. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14359. const glFormat = utils.convert(texture.format, texture.encoding);
  14360. const glType = utils.convert(texture.type);
  14361. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14362. const samples = getRenderTargetSamples(renderTarget);
  14363. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14364. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14365. }
  14366. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14367. if (renderTarget.depthBuffer) {
  14368. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14369. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14370. }
  14371. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14372. }
  14373. } // Setup color buffer
  14374. if (isCube) {
  14375. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14376. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14377. for (let i = 0; i < 6; i++) {
  14378. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14379. }
  14380. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14381. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14382. }
  14383. state.unbindTexture();
  14384. } else if (isMultipleRenderTargets) {
  14385. const textures = renderTarget.texture;
  14386. for (let i = 0, il = textures.length; i < il; i++) {
  14387. const attachment = textures[i];
  14388. const attachmentProperties = properties.get(attachment);
  14389. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14390. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14391. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14392. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14393. generateMipmap(_gl.TEXTURE_2D);
  14394. }
  14395. }
  14396. state.unbindTexture();
  14397. } else {
  14398. let glTextureType = _gl.TEXTURE_2D;
  14399. if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) {
  14400. if (isWebGL2) {
  14401. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14402. } else {
  14403. console.error('THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.');
  14404. }
  14405. }
  14406. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14407. setTextureParameters(glTextureType, texture, supportsMips);
  14408. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14409. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14410. generateMipmap(glTextureType);
  14411. }
  14412. state.unbindTexture();
  14413. } // Setup depth and stencil buffers
  14414. if (renderTarget.depthBuffer) {
  14415. setupDepthRenderbuffer(renderTarget);
  14416. }
  14417. }
  14418. function updateRenderTargetMipmap(renderTarget) {
  14419. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14420. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14421. for (let i = 0, il = textures.length; i < il; i++) {
  14422. const texture = textures[i];
  14423. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14424. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14425. const webglTexture = properties.get(texture).__webglTexture;
  14426. state.bindTexture(target, webglTexture);
  14427. generateMipmap(target);
  14428. state.unbindTexture();
  14429. }
  14430. }
  14431. }
  14432. function updateMultisampleRenderTarget(renderTarget) {
  14433. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14434. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [renderTarget.texture];
  14435. const width = renderTarget.width;
  14436. const height = renderTarget.height;
  14437. let mask = _gl.COLOR_BUFFER_BIT;
  14438. const invalidationArray = [];
  14439. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14440. const renderTargetProperties = properties.get(renderTarget);
  14441. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; // If MRT we need to remove FBO attachments
  14442. if (isMultipleRenderTargets) {
  14443. for (let i = 0; i < textures.length; i++) {
  14444. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14445. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null);
  14446. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14447. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0);
  14448. }
  14449. }
  14450. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14451. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14452. for (let i = 0; i < textures.length; i++) {
  14453. invalidationArray.push(_gl.COLOR_ATTACHMENT0 + i);
  14454. if (renderTarget.depthBuffer) {
  14455. invalidationArray.push(depthStyle);
  14456. }
  14457. const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== undefined ? renderTargetProperties.__ignoreDepthValues : false;
  14458. if (ignoreDepthValues === false) {
  14459. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14460. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14461. }
  14462. if (isMultipleRenderTargets) {
  14463. _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14464. }
  14465. if (ignoreDepthValues === true) {
  14466. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14467. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14468. }
  14469. if (isMultipleRenderTargets) {
  14470. const webglTexture = properties.get(textures[i]).__webglTexture;
  14471. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0);
  14472. }
  14473. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14474. if (supportsInvalidateFramebuffer) {
  14475. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14476. }
  14477. }
  14478. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14479. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14480. if (isMultipleRenderTargets) {
  14481. for (let i = 0; i < textures.length; i++) {
  14482. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14483. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14484. const webglTexture = properties.get(textures[i]).__webglTexture;
  14485. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14486. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0);
  14487. }
  14488. }
  14489. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14490. }
  14491. }
  14492. function getRenderTargetSamples(renderTarget) {
  14493. return Math.min(maxSamples, renderTarget.samples);
  14494. }
  14495. function useMultisampledRTT(renderTarget) {
  14496. const renderTargetProperties = properties.get(renderTarget);
  14497. return isWebGL2 && renderTarget.samples > 0 && extensions.has('WEBGL_multisampled_render_to_texture') === true && renderTargetProperties.__useRenderToTexture !== false;
  14498. }
  14499. function updateVideoTexture(texture) {
  14500. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14501. if (_videoTextures.get(texture) !== frame) {
  14502. _videoTextures.set(texture, frame);
  14503. texture.update();
  14504. }
  14505. }
  14506. function verifyColorSpace(texture, image) {
  14507. const encoding = texture.encoding;
  14508. const format = texture.format;
  14509. const type = texture.type;
  14510. if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image;
  14511. if (encoding !== LinearEncoding) {
  14512. // sRGB
  14513. if (encoding === sRGBEncoding) {
  14514. if (isWebGL2 === false) {
  14515. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14516. if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) {
  14517. texture.format = _SRGBAFormat; // it's not possible to generate mips in WebGL 1 with this extension
  14518. texture.minFilter = LinearFilter;
  14519. texture.generateMipmaps = false;
  14520. } else {
  14521. // slow fallback (CPU decode)
  14522. image = ImageUtils.sRGBToLinear(image);
  14523. }
  14524. } else {
  14525. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14526. if (format !== RGBAFormat || type !== UnsignedByteType) {
  14527. console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.');
  14528. }
  14529. }
  14530. } else {
  14531. console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding);
  14532. }
  14533. }
  14534. return image;
  14535. } //
  14536. this.allocateTextureUnit = allocateTextureUnit;
  14537. this.resetTextureUnits = resetTextureUnits;
  14538. this.setTexture2D = setTexture2D;
  14539. this.setTexture2DArray = setTexture2DArray;
  14540. this.setTexture3D = setTexture3D;
  14541. this.setTextureCube = setTextureCube;
  14542. this.rebindTextures = rebindTextures;
  14543. this.setupRenderTarget = setupRenderTarget;
  14544. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14545. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14546. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14547. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14548. this.useMultisampledRTT = useMultisampledRTT;
  14549. }
  14550. function WebGLUtils(gl, extensions, capabilities) {
  14551. const isWebGL2 = capabilities.isWebGL2;
  14552. function convert(p, encoding = null) {
  14553. let extension;
  14554. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14555. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14556. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14557. if (p === ByteType) return gl.BYTE;
  14558. if (p === ShortType) return gl.SHORT;
  14559. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14560. if (p === IntType) return gl.INT;
  14561. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14562. if (p === FloatType) return gl.FLOAT;
  14563. if (p === HalfFloatType) {
  14564. if (isWebGL2) return gl.HALF_FLOAT;
  14565. extension = extensions.get('OES_texture_half_float');
  14566. if (extension !== null) {
  14567. return extension.HALF_FLOAT_OES;
  14568. } else {
  14569. return null;
  14570. }
  14571. }
  14572. if (p === AlphaFormat) return gl.ALPHA;
  14573. if (p === RGBAFormat) return gl.RGBA;
  14574. if (p === LuminanceFormat) return gl.LUMINANCE;
  14575. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14576. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14577. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14578. if (p === RedFormat) return gl.RED; // @deprecated since r137
  14579. if (p === RGBFormat) {
  14580. console.warn('THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228');
  14581. return gl.RGBA;
  14582. } // WebGL 1 sRGB fallback
  14583. if (p === _SRGBAFormat) {
  14584. extension = extensions.get('EXT_sRGB');
  14585. if (extension !== null) {
  14586. return extension.SRGB_ALPHA_EXT;
  14587. } else {
  14588. return null;
  14589. }
  14590. } // WebGL2 formats.
  14591. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14592. if (p === RGFormat) return gl.RG;
  14593. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14594. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER; // S3TC
  14595. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14596. if (encoding === sRGBEncoding) {
  14597. extension = extensions.get('WEBGL_compressed_texture_s3tc_srgb');
  14598. if (extension !== null) {
  14599. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14600. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14601. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14602. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14603. } else {
  14604. return null;
  14605. }
  14606. } else {
  14607. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14608. if (extension !== null) {
  14609. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14610. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14611. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14612. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14613. } else {
  14614. return null;
  14615. }
  14616. }
  14617. } // PVRTC
  14618. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14619. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14620. if (extension !== null) {
  14621. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14622. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14623. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14624. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14625. } else {
  14626. return null;
  14627. }
  14628. } // ETC1
  14629. if (p === RGB_ETC1_Format) {
  14630. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14631. if (extension !== null) {
  14632. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14633. } else {
  14634. return null;
  14635. }
  14636. } // ETC2
  14637. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14638. extension = extensions.get('WEBGL_compressed_texture_etc');
  14639. if (extension !== null) {
  14640. if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14641. if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14642. } else {
  14643. return null;
  14644. }
  14645. } // ASTC
  14646. 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) {
  14647. extension = extensions.get('WEBGL_compressed_texture_astc');
  14648. if (extension !== null) {
  14649. if (p === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14650. if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14651. if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14652. if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14653. if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14654. if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14655. if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14656. if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14657. if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14658. if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14659. if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14660. if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14661. if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14662. if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14663. } else {
  14664. return null;
  14665. }
  14666. } // BPTC
  14667. if (p === RGBA_BPTC_Format) {
  14668. extension = extensions.get('EXT_texture_compression_bptc');
  14669. if (extension !== null) {
  14670. if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14671. } else {
  14672. return null;
  14673. }
  14674. } //
  14675. if (p === UnsignedInt248Type) {
  14676. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  14677. extension = extensions.get('WEBGL_depth_texture');
  14678. if (extension !== null) {
  14679. return extension.UNSIGNED_INT_24_8_WEBGL;
  14680. } else {
  14681. return null;
  14682. }
  14683. } // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14684. return gl[p] !== undefined ? gl[p] : null;
  14685. }
  14686. return {
  14687. convert: convert
  14688. };
  14689. }
  14690. class ArrayCamera extends PerspectiveCamera {
  14691. constructor(array = []) {
  14692. super();
  14693. this.isArrayCamera = true;
  14694. this.cameras = array;
  14695. }
  14696. }
  14697. class Group extends Object3D {
  14698. constructor() {
  14699. super();
  14700. this.isGroup = true;
  14701. this.type = 'Group';
  14702. }
  14703. }
  14704. const _moveEvent = {
  14705. type: 'move'
  14706. };
  14707. class WebXRController {
  14708. constructor() {
  14709. this._targetRay = null;
  14710. this._grip = null;
  14711. this._hand = null;
  14712. }
  14713. getHandSpace() {
  14714. if (this._hand === null) {
  14715. this._hand = new Group();
  14716. this._hand.matrixAutoUpdate = false;
  14717. this._hand.visible = false;
  14718. this._hand.joints = {};
  14719. this._hand.inputState = {
  14720. pinching: false
  14721. };
  14722. }
  14723. return this._hand;
  14724. }
  14725. getTargetRaySpace() {
  14726. if (this._targetRay === null) {
  14727. this._targetRay = new Group();
  14728. this._targetRay.matrixAutoUpdate = false;
  14729. this._targetRay.visible = false;
  14730. this._targetRay.hasLinearVelocity = false;
  14731. this._targetRay.linearVelocity = new Vector3();
  14732. this._targetRay.hasAngularVelocity = false;
  14733. this._targetRay.angularVelocity = new Vector3();
  14734. }
  14735. return this._targetRay;
  14736. }
  14737. getGripSpace() {
  14738. if (this._grip === null) {
  14739. this._grip = new Group();
  14740. this._grip.matrixAutoUpdate = false;
  14741. this._grip.visible = false;
  14742. this._grip.hasLinearVelocity = false;
  14743. this._grip.linearVelocity = new Vector3();
  14744. this._grip.hasAngularVelocity = false;
  14745. this._grip.angularVelocity = new Vector3();
  14746. }
  14747. return this._grip;
  14748. }
  14749. dispatchEvent(event) {
  14750. if (this._targetRay !== null) {
  14751. this._targetRay.dispatchEvent(event);
  14752. }
  14753. if (this._grip !== null) {
  14754. this._grip.dispatchEvent(event);
  14755. }
  14756. if (this._hand !== null) {
  14757. this._hand.dispatchEvent(event);
  14758. }
  14759. return this;
  14760. }
  14761. disconnect(inputSource) {
  14762. this.dispatchEvent({
  14763. type: 'disconnected',
  14764. data: inputSource
  14765. });
  14766. if (this._targetRay !== null) {
  14767. this._targetRay.visible = false;
  14768. }
  14769. if (this._grip !== null) {
  14770. this._grip.visible = false;
  14771. }
  14772. if (this._hand !== null) {
  14773. this._hand.visible = false;
  14774. }
  14775. return this;
  14776. }
  14777. update(inputSource, frame, referenceSpace) {
  14778. let inputPose = null;
  14779. let gripPose = null;
  14780. let handPose = null;
  14781. const targetRay = this._targetRay;
  14782. const grip = this._grip;
  14783. const hand = this._hand;
  14784. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14785. if (hand && inputSource.hand) {
  14786. handPose = true;
  14787. for (const inputjoint of inputSource.hand.values()) {
  14788. // Update the joints groups with the XRJoint poses
  14789. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14790. if (hand.joints[inputjoint.jointName] === undefined) {
  14791. // The transform of this joint will be updated with the joint pose on each frame
  14792. const joint = new Group();
  14793. joint.matrixAutoUpdate = false;
  14794. joint.visible = false;
  14795. hand.joints[inputjoint.jointName] = joint; // ??
  14796. hand.add(joint);
  14797. }
  14798. const joint = hand.joints[inputjoint.jointName];
  14799. if (jointPose !== null) {
  14800. joint.matrix.fromArray(jointPose.transform.matrix);
  14801. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14802. joint.jointRadius = jointPose.radius;
  14803. }
  14804. joint.visible = jointPose !== null;
  14805. } // Custom events
  14806. // Check pinchz
  14807. const indexTip = hand.joints['index-finger-tip'];
  14808. const thumbTip = hand.joints['thumb-tip'];
  14809. const distance = indexTip.position.distanceTo(thumbTip.position);
  14810. const distanceToPinch = 0.02;
  14811. const threshold = 0.005;
  14812. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14813. hand.inputState.pinching = false;
  14814. this.dispatchEvent({
  14815. type: 'pinchend',
  14816. handedness: inputSource.handedness,
  14817. target: this
  14818. });
  14819. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14820. hand.inputState.pinching = true;
  14821. this.dispatchEvent({
  14822. type: 'pinchstart',
  14823. handedness: inputSource.handedness,
  14824. target: this
  14825. });
  14826. }
  14827. } else {
  14828. if (grip !== null && inputSource.gripSpace) {
  14829. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14830. if (gripPose !== null) {
  14831. grip.matrix.fromArray(gripPose.transform.matrix);
  14832. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14833. if (gripPose.linearVelocity) {
  14834. grip.hasLinearVelocity = true;
  14835. grip.linearVelocity.copy(gripPose.linearVelocity);
  14836. } else {
  14837. grip.hasLinearVelocity = false;
  14838. }
  14839. if (gripPose.angularVelocity) {
  14840. grip.hasAngularVelocity = true;
  14841. grip.angularVelocity.copy(gripPose.angularVelocity);
  14842. } else {
  14843. grip.hasAngularVelocity = false;
  14844. }
  14845. }
  14846. }
  14847. }
  14848. if (targetRay !== null) {
  14849. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  14850. if (inputPose === null && gripPose !== null) {
  14851. inputPose = gripPose;
  14852. }
  14853. if (inputPose !== null) {
  14854. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14855. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14856. if (inputPose.linearVelocity) {
  14857. targetRay.hasLinearVelocity = true;
  14858. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14859. } else {
  14860. targetRay.hasLinearVelocity = false;
  14861. }
  14862. if (inputPose.angularVelocity) {
  14863. targetRay.hasAngularVelocity = true;
  14864. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14865. } else {
  14866. targetRay.hasAngularVelocity = false;
  14867. }
  14868. this.dispatchEvent(_moveEvent);
  14869. }
  14870. }
  14871. }
  14872. if (targetRay !== null) {
  14873. targetRay.visible = inputPose !== null;
  14874. }
  14875. if (grip !== null) {
  14876. grip.visible = gripPose !== null;
  14877. }
  14878. if (hand !== null) {
  14879. hand.visible = handPose !== null;
  14880. }
  14881. return this;
  14882. }
  14883. }
  14884. class DepthTexture extends Texture {
  14885. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  14886. format = format !== undefined ? format : DepthFormat;
  14887. if (format !== DepthFormat && format !== DepthStencilFormat) {
  14888. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  14889. }
  14890. if (type === undefined && format === DepthFormat) type = UnsignedIntType;
  14891. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  14892. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  14893. this.isDepthTexture = true;
  14894. this.image = {
  14895. width: width,
  14896. height: height
  14897. };
  14898. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14899. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14900. this.flipY = false;
  14901. this.generateMipmaps = false;
  14902. }
  14903. }
  14904. class WebXRManager extends EventDispatcher {
  14905. constructor(renderer, gl) {
  14906. super();
  14907. const scope = this;
  14908. let session = null;
  14909. let framebufferScaleFactor = 1.0;
  14910. let referenceSpace = null;
  14911. let referenceSpaceType = 'local-floor';
  14912. let customReferenceSpace = null;
  14913. let pose = null;
  14914. let glBinding = null;
  14915. let glProjLayer = null;
  14916. let glBaseLayer = null;
  14917. let xrFrame = null;
  14918. const attributes = gl.getContextAttributes();
  14919. let initialRenderTarget = null;
  14920. let newRenderTarget = null;
  14921. const controllers = [];
  14922. const controllerInputSources = []; //
  14923. const cameraL = new PerspectiveCamera();
  14924. cameraL.layers.enable(1);
  14925. cameraL.viewport = new Vector4();
  14926. const cameraR = new PerspectiveCamera();
  14927. cameraR.layers.enable(2);
  14928. cameraR.viewport = new Vector4();
  14929. const cameras = [cameraL, cameraR];
  14930. const cameraVR = new ArrayCamera();
  14931. cameraVR.layers.enable(1);
  14932. cameraVR.layers.enable(2);
  14933. let _currentDepthNear = null;
  14934. let _currentDepthFar = null; //
  14935. this.cameraAutoUpdate = true;
  14936. this.enabled = false;
  14937. this.isPresenting = false;
  14938. this.getController = function (index) {
  14939. let controller = controllers[index];
  14940. if (controller === undefined) {
  14941. controller = new WebXRController();
  14942. controllers[index] = controller;
  14943. }
  14944. return controller.getTargetRaySpace();
  14945. };
  14946. this.getControllerGrip = function (index) {
  14947. let controller = controllers[index];
  14948. if (controller === undefined) {
  14949. controller = new WebXRController();
  14950. controllers[index] = controller;
  14951. }
  14952. return controller.getGripSpace();
  14953. };
  14954. this.getHand = function (index) {
  14955. let controller = controllers[index];
  14956. if (controller === undefined) {
  14957. controller = new WebXRController();
  14958. controllers[index] = controller;
  14959. }
  14960. return controller.getHandSpace();
  14961. }; //
  14962. function onSessionEvent(event) {
  14963. const controllerIndex = controllerInputSources.indexOf(event.inputSource);
  14964. if (controllerIndex === -1) {
  14965. return;
  14966. }
  14967. const controller = controllers[controllerIndex];
  14968. if (controller !== undefined) {
  14969. controller.dispatchEvent({
  14970. type: event.type,
  14971. data: event.inputSource
  14972. });
  14973. }
  14974. }
  14975. function onSessionEnd() {
  14976. session.removeEventListener('select', onSessionEvent);
  14977. session.removeEventListener('selectstart', onSessionEvent);
  14978. session.removeEventListener('selectend', onSessionEvent);
  14979. session.removeEventListener('squeeze', onSessionEvent);
  14980. session.removeEventListener('squeezestart', onSessionEvent);
  14981. session.removeEventListener('squeezeend', onSessionEvent);
  14982. session.removeEventListener('end', onSessionEnd);
  14983. session.removeEventListener('inputsourceschange', onInputSourcesChange);
  14984. for (let i = 0; i < controllers.length; i++) {
  14985. const inputSource = controllerInputSources[i];
  14986. if (inputSource === null) continue;
  14987. controllerInputSources[i] = null;
  14988. controllers[i].disconnect(inputSource);
  14989. }
  14990. _currentDepthNear = null;
  14991. _currentDepthFar = null; // restore framebuffer/rendering state
  14992. renderer.setRenderTarget(initialRenderTarget);
  14993. glBaseLayer = null;
  14994. glProjLayer = null;
  14995. glBinding = null;
  14996. session = null;
  14997. newRenderTarget = null; //
  14998. animation.stop();
  14999. scope.isPresenting = false;
  15000. scope.dispatchEvent({
  15001. type: 'sessionend'
  15002. });
  15003. }
  15004. this.setFramebufferScaleFactor = function (value) {
  15005. framebufferScaleFactor = value;
  15006. if (scope.isPresenting === true) {
  15007. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  15008. }
  15009. };
  15010. this.setReferenceSpaceType = function (value) {
  15011. referenceSpaceType = value;
  15012. if (scope.isPresenting === true) {
  15013. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  15014. }
  15015. };
  15016. this.getReferenceSpace = function () {
  15017. return customReferenceSpace || referenceSpace;
  15018. };
  15019. this.setReferenceSpace = function (space) {
  15020. customReferenceSpace = space;
  15021. };
  15022. this.getBaseLayer = function () {
  15023. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15024. };
  15025. this.getBinding = function () {
  15026. return glBinding;
  15027. };
  15028. this.getFrame = function () {
  15029. return xrFrame;
  15030. };
  15031. this.getSession = function () {
  15032. return session;
  15033. };
  15034. this.setSession = async function (value) {
  15035. session = value;
  15036. if (session !== null) {
  15037. initialRenderTarget = renderer.getRenderTarget();
  15038. session.addEventListener('select', onSessionEvent);
  15039. session.addEventListener('selectstart', onSessionEvent);
  15040. session.addEventListener('selectend', onSessionEvent);
  15041. session.addEventListener('squeeze', onSessionEvent);
  15042. session.addEventListener('squeezestart', onSessionEvent);
  15043. session.addEventListener('squeezeend', onSessionEvent);
  15044. session.addEventListener('end', onSessionEnd);
  15045. session.addEventListener('inputsourceschange', onInputSourcesChange);
  15046. if (attributes.xrCompatible !== true) {
  15047. await gl.makeXRCompatible();
  15048. }
  15049. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  15050. const layerInit = {
  15051. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  15052. alpha: attributes.alpha,
  15053. depth: attributes.depth,
  15054. stencil: attributes.stencil,
  15055. framebufferScaleFactor: framebufferScaleFactor
  15056. };
  15057. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  15058. session.updateRenderState({
  15059. baseLayer: glBaseLayer
  15060. });
  15061. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  15062. format: RGBAFormat,
  15063. type: UnsignedByteType,
  15064. encoding: renderer.outputEncoding,
  15065. stencilBuffer: attributes.stencil
  15066. });
  15067. } else {
  15068. let depthFormat = null;
  15069. let depthType = null;
  15070. let glDepthFormat = null;
  15071. if (attributes.depth) {
  15072. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15073. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15074. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15075. }
  15076. const projectionlayerInit = {
  15077. colorFormat: gl.RGBA8,
  15078. depthFormat: glDepthFormat,
  15079. scaleFactor: framebufferScaleFactor
  15080. };
  15081. glBinding = new XRWebGLBinding(session, gl);
  15082. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  15083. session.updateRenderState({
  15084. layers: [glProjLayer]
  15085. });
  15086. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  15087. format: RGBAFormat,
  15088. type: UnsignedByteType,
  15089. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  15090. stencilBuffer: attributes.stencil,
  15091. encoding: renderer.outputEncoding,
  15092. samples: attributes.antialias ? 4 : 0
  15093. });
  15094. const renderTargetProperties = renderer.properties.get(newRenderTarget);
  15095. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15096. }
  15097. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15098. // Set foveation to maximum.
  15099. this.setFoveation(1.0);
  15100. customReferenceSpace = null;
  15101. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  15102. animation.setContext(session);
  15103. animation.start();
  15104. scope.isPresenting = true;
  15105. scope.dispatchEvent({
  15106. type: 'sessionstart'
  15107. });
  15108. }
  15109. };
  15110. function onInputSourcesChange(event) {
  15111. // Notify disconnected
  15112. for (let i = 0; i < event.removed.length; i++) {
  15113. const inputSource = event.removed[i];
  15114. const index = controllerInputSources.indexOf(inputSource);
  15115. if (index >= 0) {
  15116. controllerInputSources[index] = null;
  15117. controllers[index].dispatchEvent({
  15118. type: 'disconnected',
  15119. data: inputSource
  15120. });
  15121. }
  15122. } // Notify connected
  15123. for (let i = 0; i < event.added.length; i++) {
  15124. const inputSource = event.added[i];
  15125. let controllerIndex = controllerInputSources.indexOf(inputSource);
  15126. if (controllerIndex === -1) {
  15127. // Assign input source a controller that currently has no input source
  15128. for (let i = 0; i < controllers.length; i++) {
  15129. if (i >= controllerInputSources.length) {
  15130. controllerInputSources.push(inputSource);
  15131. controllerIndex = i;
  15132. break;
  15133. } else if (controllerInputSources[i] === null) {
  15134. controllerInputSources[i] = inputSource;
  15135. controllerIndex = i;
  15136. break;
  15137. }
  15138. } // If all controllers do currently receive input we ignore new ones
  15139. if (controllerIndex === -1) break;
  15140. }
  15141. const controller = controllers[controllerIndex];
  15142. if (controller) {
  15143. controller.dispatchEvent({
  15144. type: 'connected',
  15145. data: inputSource
  15146. });
  15147. }
  15148. }
  15149. } //
  15150. const cameraLPos = new Vector3();
  15151. const cameraRPos = new Vector3();
  15152. /**
  15153. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15154. * the cameras' projection and world matrices have already been set.
  15155. * And that near and far planes are identical for both cameras.
  15156. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15157. */
  15158. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15159. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15160. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15161. const ipd = cameraLPos.distanceTo(cameraRPos);
  15162. const projL = cameraL.projectionMatrix.elements;
  15163. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15164. // most likely identical top and bottom frustum extents.
  15165. // Use the left camera for these values.
  15166. const near = projL[14] / (projL[10] - 1);
  15167. const far = projL[14] / (projL[10] + 1);
  15168. const topFov = (projL[9] + 1) / projL[5];
  15169. const bottomFov = (projL[9] - 1) / projL[5];
  15170. const leftFov = (projL[8] - 1) / projL[0];
  15171. const rightFov = (projR[8] + 1) / projR[0];
  15172. const left = near * leftFov;
  15173. const right = near * rightFov; // Calculate the new camera's position offset from the
  15174. // left camera. xOffset should be roughly half `ipd`.
  15175. const zOffset = ipd / (-leftFov + rightFov);
  15176. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15177. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15178. camera.translateX(xOffset);
  15179. camera.translateZ(zOffset);
  15180. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15181. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  15182. // the values so that the near plane's position does not change in world space,
  15183. // although must now be relative to the new union camera.
  15184. const near2 = near + zOffset;
  15185. const far2 = far + zOffset;
  15186. const left2 = left - xOffset;
  15187. const right2 = right + (ipd - xOffset);
  15188. const top2 = topFov * far / far2 * near2;
  15189. const bottom2 = bottomFov * far / far2 * near2;
  15190. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15191. }
  15192. function updateCamera(camera, parent) {
  15193. if (parent === null) {
  15194. camera.matrixWorld.copy(camera.matrix);
  15195. } else {
  15196. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15197. }
  15198. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  15199. }
  15200. this.updateCamera = function (camera) {
  15201. if (session === null) return;
  15202. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15203. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15204. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  15205. // Note that the new renderState won't apply until the next frame. See #18320
  15206. session.updateRenderState({
  15207. depthNear: cameraVR.near,
  15208. depthFar: cameraVR.far
  15209. });
  15210. _currentDepthNear = cameraVR.near;
  15211. _currentDepthFar = cameraVR.far;
  15212. }
  15213. const parent = camera.parent;
  15214. const cameras = cameraVR.cameras;
  15215. updateCamera(cameraVR, parent);
  15216. for (let i = 0; i < cameras.length; i++) {
  15217. updateCamera(cameras[i], parent);
  15218. }
  15219. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  15220. camera.matrix.copy(cameraVR.matrix);
  15221. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  15222. const children = camera.children;
  15223. for (let i = 0, l = children.length; i < l; i++) {
  15224. children[i].updateMatrixWorld(true);
  15225. } // update projection matrix for proper view frustum culling
  15226. if (cameras.length === 2) {
  15227. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15228. } else {
  15229. // assume single camera setup (AR)
  15230. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  15231. }
  15232. };
  15233. this.getCamera = function () {
  15234. return cameraVR;
  15235. };
  15236. this.getFoveation = function () {
  15237. if (glProjLayer !== null) {
  15238. return glProjLayer.fixedFoveation;
  15239. }
  15240. if (glBaseLayer !== null) {
  15241. return glBaseLayer.fixedFoveation;
  15242. }
  15243. return undefined;
  15244. };
  15245. this.setFoveation = function (foveation) {
  15246. // 0 = no foveation = full resolution
  15247. // 1 = maximum foveation = the edges render at lower resolution
  15248. if (glProjLayer !== null) {
  15249. glProjLayer.fixedFoveation = foveation;
  15250. }
  15251. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  15252. glBaseLayer.fixedFoveation = foveation;
  15253. }
  15254. }; // Animation Loop
  15255. let onAnimationFrameCallback = null;
  15256. function onAnimationFrame(time, frame) {
  15257. pose = frame.getViewerPose(customReferenceSpace || referenceSpace);
  15258. xrFrame = frame;
  15259. if (pose !== null) {
  15260. const views = pose.views;
  15261. if (glBaseLayer !== null) {
  15262. renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
  15263. renderer.setRenderTarget(newRenderTarget);
  15264. }
  15265. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  15266. if (views.length !== cameraVR.cameras.length) {
  15267. cameraVR.cameras.length = 0;
  15268. cameraVRNeedsUpdate = true;
  15269. }
  15270. for (let i = 0; i < views.length; i++) {
  15271. const view = views[i];
  15272. let viewport = null;
  15273. if (glBaseLayer !== null) {
  15274. viewport = glBaseLayer.getViewport(view);
  15275. } else {
  15276. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  15277. viewport = glSubImage.viewport; // For side-by-side projection, we only produce a single texture for both eyes.
  15278. if (i === 0) {
  15279. renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
  15280. renderer.setRenderTarget(newRenderTarget);
  15281. }
  15282. }
  15283. let camera = cameras[i];
  15284. if (camera === undefined) {
  15285. camera = new PerspectiveCamera();
  15286. camera.layers.enable(i);
  15287. camera.viewport = new Vector4();
  15288. cameras[i] = camera;
  15289. }
  15290. camera.matrix.fromArray(view.transform.matrix);
  15291. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15292. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15293. if (i === 0) {
  15294. cameraVR.matrix.copy(camera.matrix);
  15295. }
  15296. if (cameraVRNeedsUpdate === true) {
  15297. cameraVR.cameras.push(camera);
  15298. }
  15299. }
  15300. } //
  15301. for (let i = 0; i < controllers.length; i++) {
  15302. const inputSource = controllerInputSources[i];
  15303. const controller = controllers[i];
  15304. if (inputSource !== null && controller !== undefined) {
  15305. controller.update(inputSource, frame, customReferenceSpace || referenceSpace);
  15306. }
  15307. }
  15308. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  15309. xrFrame = null;
  15310. }
  15311. const animation = new WebGLAnimation();
  15312. animation.setAnimationLoop(onAnimationFrame);
  15313. this.setAnimationLoop = function (callback) {
  15314. onAnimationFrameCallback = callback;
  15315. };
  15316. this.dispose = function () {};
  15317. }
  15318. }
  15319. function WebGLMaterials(renderer, properties) {
  15320. function refreshFogUniforms(uniforms, fog) {
  15321. uniforms.fogColor.value.copy(fog.color);
  15322. if (fog.isFog) {
  15323. uniforms.fogNear.value = fog.near;
  15324. uniforms.fogFar.value = fog.far;
  15325. } else if (fog.isFogExp2) {
  15326. uniforms.fogDensity.value = fog.density;
  15327. }
  15328. }
  15329. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  15330. if (material.isMeshBasicMaterial) {
  15331. refreshUniformsCommon(uniforms, material);
  15332. } else if (material.isMeshLambertMaterial) {
  15333. refreshUniformsCommon(uniforms, material);
  15334. } else if (material.isMeshToonMaterial) {
  15335. refreshUniformsCommon(uniforms, material);
  15336. refreshUniformsToon(uniforms, material);
  15337. } else if (material.isMeshPhongMaterial) {
  15338. refreshUniformsCommon(uniforms, material);
  15339. refreshUniformsPhong(uniforms, material);
  15340. } else if (material.isMeshStandardMaterial) {
  15341. refreshUniformsCommon(uniforms, material);
  15342. refreshUniformsStandard(uniforms, material);
  15343. if (material.isMeshPhysicalMaterial) {
  15344. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  15345. }
  15346. } else if (material.isMeshMatcapMaterial) {
  15347. refreshUniformsCommon(uniforms, material);
  15348. refreshUniformsMatcap(uniforms, material);
  15349. } else if (material.isMeshDepthMaterial) {
  15350. refreshUniformsCommon(uniforms, material);
  15351. } else if (material.isMeshDistanceMaterial) {
  15352. refreshUniformsCommon(uniforms, material);
  15353. refreshUniformsDistance(uniforms, material);
  15354. } else if (material.isMeshNormalMaterial) {
  15355. refreshUniformsCommon(uniforms, material);
  15356. } else if (material.isLineBasicMaterial) {
  15357. refreshUniformsLine(uniforms, material);
  15358. if (material.isLineDashedMaterial) {
  15359. refreshUniformsDash(uniforms, material);
  15360. }
  15361. } else if (material.isPointsMaterial) {
  15362. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  15363. } else if (material.isSpriteMaterial) {
  15364. refreshUniformsSprites(uniforms, material);
  15365. } else if (material.isShadowMaterial) {
  15366. uniforms.color.value.copy(material.color);
  15367. uniforms.opacity.value = material.opacity;
  15368. } else if (material.isShaderMaterial) {
  15369. material.uniformsNeedUpdate = false; // #15581
  15370. }
  15371. }
  15372. function refreshUniformsCommon(uniforms, material) {
  15373. uniforms.opacity.value = material.opacity;
  15374. if (material.color) {
  15375. uniforms.diffuse.value.copy(material.color);
  15376. }
  15377. if (material.emissive) {
  15378. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15379. }
  15380. if (material.map) {
  15381. uniforms.map.value = material.map;
  15382. }
  15383. if (material.alphaMap) {
  15384. uniforms.alphaMap.value = material.alphaMap;
  15385. }
  15386. if (material.bumpMap) {
  15387. uniforms.bumpMap.value = material.bumpMap;
  15388. uniforms.bumpScale.value = material.bumpScale;
  15389. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15390. }
  15391. if (material.displacementMap) {
  15392. uniforms.displacementMap.value = material.displacementMap;
  15393. uniforms.displacementScale.value = material.displacementScale;
  15394. uniforms.displacementBias.value = material.displacementBias;
  15395. }
  15396. if (material.emissiveMap) {
  15397. uniforms.emissiveMap.value = material.emissiveMap;
  15398. }
  15399. if (material.normalMap) {
  15400. uniforms.normalMap.value = material.normalMap;
  15401. uniforms.normalScale.value.copy(material.normalScale);
  15402. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15403. }
  15404. if (material.specularMap) {
  15405. uniforms.specularMap.value = material.specularMap;
  15406. }
  15407. if (material.alphaTest > 0) {
  15408. uniforms.alphaTest.value = material.alphaTest;
  15409. }
  15410. const envMap = properties.get(material).envMap;
  15411. if (envMap) {
  15412. uniforms.envMap.value = envMap;
  15413. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  15414. uniforms.reflectivity.value = material.reflectivity;
  15415. uniforms.ior.value = material.ior;
  15416. uniforms.refractionRatio.value = material.refractionRatio;
  15417. }
  15418. if (material.lightMap) {
  15419. uniforms.lightMap.value = material.lightMap; // artist-friendly light intensity scaling factor
  15420. const scaleFactor = renderer.physicallyCorrectLights !== true ? Math.PI : 1;
  15421. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15422. }
  15423. if (material.aoMap) {
  15424. uniforms.aoMap.value = material.aoMap;
  15425. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15426. } // uv repeat and offset setting priorities
  15427. // 1. color map
  15428. // 2. specular map
  15429. // 3. displacementMap map
  15430. // 4. normal map
  15431. // 5. bump map
  15432. // 6. roughnessMap map
  15433. // 7. metalnessMap map
  15434. // 8. alphaMap map
  15435. // 9. emissiveMap map
  15436. // 10. clearcoat map
  15437. // 11. clearcoat normal map
  15438. // 12. clearcoat roughnessMap map
  15439. // 13. iridescence map
  15440. // 14. iridescence thickness map
  15441. // 15. specular intensity map
  15442. // 16. specular tint map
  15443. // 17. transmission map
  15444. // 18. thickness map
  15445. let uvScaleMap;
  15446. if (material.map) {
  15447. uvScaleMap = material.map;
  15448. } else if (material.specularMap) {
  15449. uvScaleMap = material.specularMap;
  15450. } else if (material.displacementMap) {
  15451. uvScaleMap = material.displacementMap;
  15452. } else if (material.normalMap) {
  15453. uvScaleMap = material.normalMap;
  15454. } else if (material.bumpMap) {
  15455. uvScaleMap = material.bumpMap;
  15456. } else if (material.roughnessMap) {
  15457. uvScaleMap = material.roughnessMap;
  15458. } else if (material.metalnessMap) {
  15459. uvScaleMap = material.metalnessMap;
  15460. } else if (material.alphaMap) {
  15461. uvScaleMap = material.alphaMap;
  15462. } else if (material.emissiveMap) {
  15463. uvScaleMap = material.emissiveMap;
  15464. } else if (material.clearcoatMap) {
  15465. uvScaleMap = material.clearcoatMap;
  15466. } else if (material.clearcoatNormalMap) {
  15467. uvScaleMap = material.clearcoatNormalMap;
  15468. } else if (material.clearcoatRoughnessMap) {
  15469. uvScaleMap = material.clearcoatRoughnessMap;
  15470. } else if (material.iridescenceMap) {
  15471. uvScaleMap = material.iridescenceMap;
  15472. } else if (material.iridescenceThicknessMap) {
  15473. uvScaleMap = material.iridescenceThicknessMap;
  15474. } else if (material.specularIntensityMap) {
  15475. uvScaleMap = material.specularIntensityMap;
  15476. } else if (material.specularColorMap) {
  15477. uvScaleMap = material.specularColorMap;
  15478. } else if (material.transmissionMap) {
  15479. uvScaleMap = material.transmissionMap;
  15480. } else if (material.thicknessMap) {
  15481. uvScaleMap = material.thicknessMap;
  15482. } else if (material.sheenColorMap) {
  15483. uvScaleMap = material.sheenColorMap;
  15484. } else if (material.sheenRoughnessMap) {
  15485. uvScaleMap = material.sheenRoughnessMap;
  15486. }
  15487. if (uvScaleMap !== undefined) {
  15488. // backwards compatibility
  15489. if (uvScaleMap.isWebGLRenderTarget) {
  15490. uvScaleMap = uvScaleMap.texture;
  15491. }
  15492. if (uvScaleMap.matrixAutoUpdate === true) {
  15493. uvScaleMap.updateMatrix();
  15494. }
  15495. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15496. } // uv repeat and offset setting priorities for uv2
  15497. // 1. ao map
  15498. // 2. light map
  15499. let uv2ScaleMap;
  15500. if (material.aoMap) {
  15501. uv2ScaleMap = material.aoMap;
  15502. } else if (material.lightMap) {
  15503. uv2ScaleMap = material.lightMap;
  15504. }
  15505. if (uv2ScaleMap !== undefined) {
  15506. // backwards compatibility
  15507. if (uv2ScaleMap.isWebGLRenderTarget) {
  15508. uv2ScaleMap = uv2ScaleMap.texture;
  15509. }
  15510. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15511. uv2ScaleMap.updateMatrix();
  15512. }
  15513. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15514. }
  15515. }
  15516. function refreshUniformsLine(uniforms, material) {
  15517. uniforms.diffuse.value.copy(material.color);
  15518. uniforms.opacity.value = material.opacity;
  15519. }
  15520. function refreshUniformsDash(uniforms, material) {
  15521. uniforms.dashSize.value = material.dashSize;
  15522. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15523. uniforms.scale.value = material.scale;
  15524. }
  15525. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  15526. uniforms.diffuse.value.copy(material.color);
  15527. uniforms.opacity.value = material.opacity;
  15528. uniforms.size.value = material.size * pixelRatio;
  15529. uniforms.scale.value = height * 0.5;
  15530. if (material.map) {
  15531. uniforms.map.value = material.map;
  15532. }
  15533. if (material.alphaMap) {
  15534. uniforms.alphaMap.value = material.alphaMap;
  15535. }
  15536. if (material.alphaTest > 0) {
  15537. uniforms.alphaTest.value = material.alphaTest;
  15538. } // uv repeat and offset setting priorities
  15539. // 1. color map
  15540. // 2. alpha map
  15541. let uvScaleMap;
  15542. if (material.map) {
  15543. uvScaleMap = material.map;
  15544. } else if (material.alphaMap) {
  15545. uvScaleMap = material.alphaMap;
  15546. }
  15547. if (uvScaleMap !== undefined) {
  15548. if (uvScaleMap.matrixAutoUpdate === true) {
  15549. uvScaleMap.updateMatrix();
  15550. }
  15551. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15552. }
  15553. }
  15554. function refreshUniformsSprites(uniforms, material) {
  15555. uniforms.diffuse.value.copy(material.color);
  15556. uniforms.opacity.value = material.opacity;
  15557. uniforms.rotation.value = material.rotation;
  15558. if (material.map) {
  15559. uniforms.map.value = material.map;
  15560. }
  15561. if (material.alphaMap) {
  15562. uniforms.alphaMap.value = material.alphaMap;
  15563. }
  15564. if (material.alphaTest > 0) {
  15565. uniforms.alphaTest.value = material.alphaTest;
  15566. } // uv repeat and offset setting priorities
  15567. // 1. color map
  15568. // 2. alpha map
  15569. let uvScaleMap;
  15570. if (material.map) {
  15571. uvScaleMap = material.map;
  15572. } else if (material.alphaMap) {
  15573. uvScaleMap = material.alphaMap;
  15574. }
  15575. if (uvScaleMap !== undefined) {
  15576. if (uvScaleMap.matrixAutoUpdate === true) {
  15577. uvScaleMap.updateMatrix();
  15578. }
  15579. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15580. }
  15581. }
  15582. function refreshUniformsPhong(uniforms, material) {
  15583. uniforms.specular.value.copy(material.specular);
  15584. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15585. }
  15586. function refreshUniformsToon(uniforms, material) {
  15587. if (material.gradientMap) {
  15588. uniforms.gradientMap.value = material.gradientMap;
  15589. }
  15590. }
  15591. function refreshUniformsStandard(uniforms, material) {
  15592. uniforms.roughness.value = material.roughness;
  15593. uniforms.metalness.value = material.metalness;
  15594. if (material.roughnessMap) {
  15595. uniforms.roughnessMap.value = material.roughnessMap;
  15596. }
  15597. if (material.metalnessMap) {
  15598. uniforms.metalnessMap.value = material.metalnessMap;
  15599. }
  15600. const envMap = properties.get(material).envMap;
  15601. if (envMap) {
  15602. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15603. uniforms.envMapIntensity.value = material.envMapIntensity;
  15604. }
  15605. }
  15606. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  15607. uniforms.ior.value = material.ior; // also part of uniforms common
  15608. if (material.sheen > 0) {
  15609. uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
  15610. uniforms.sheenRoughness.value = material.sheenRoughness;
  15611. if (material.sheenColorMap) {
  15612. uniforms.sheenColorMap.value = material.sheenColorMap;
  15613. }
  15614. if (material.sheenRoughnessMap) {
  15615. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15616. }
  15617. }
  15618. if (material.clearcoat > 0) {
  15619. uniforms.clearcoat.value = material.clearcoat;
  15620. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15621. if (material.clearcoatMap) {
  15622. uniforms.clearcoatMap.value = material.clearcoatMap;
  15623. }
  15624. if (material.clearcoatRoughnessMap) {
  15625. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15626. }
  15627. if (material.clearcoatNormalMap) {
  15628. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15629. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15630. if (material.side === BackSide) {
  15631. uniforms.clearcoatNormalScale.value.negate();
  15632. }
  15633. }
  15634. }
  15635. if (material.iridescence > 0) {
  15636. uniforms.iridescence.value = material.iridescence;
  15637. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15638. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0];
  15639. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1];
  15640. if (material.iridescenceMap) {
  15641. uniforms.iridescenceMap.value = material.iridescenceMap;
  15642. }
  15643. if (material.iridescenceThicknessMap) {
  15644. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15645. }
  15646. }
  15647. if (material.transmission > 0) {
  15648. uniforms.transmission.value = material.transmission;
  15649. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15650. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  15651. if (material.transmissionMap) {
  15652. uniforms.transmissionMap.value = material.transmissionMap;
  15653. }
  15654. uniforms.thickness.value = material.thickness;
  15655. if (material.thicknessMap) {
  15656. uniforms.thicknessMap.value = material.thicknessMap;
  15657. }
  15658. uniforms.attenuationDistance.value = material.attenuationDistance;
  15659. uniforms.attenuationColor.value.copy(material.attenuationColor);
  15660. }
  15661. uniforms.specularIntensity.value = material.specularIntensity;
  15662. uniforms.specularColor.value.copy(material.specularColor);
  15663. if (material.specularIntensityMap) {
  15664. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15665. }
  15666. if (material.specularColorMap) {
  15667. uniforms.specularColorMap.value = material.specularColorMap;
  15668. }
  15669. }
  15670. function refreshUniformsMatcap(uniforms, material) {
  15671. if (material.matcap) {
  15672. uniforms.matcap.value = material.matcap;
  15673. }
  15674. }
  15675. function refreshUniformsDistance(uniforms, material) {
  15676. uniforms.referencePosition.value.copy(material.referencePosition);
  15677. uniforms.nearDistance.value = material.nearDistance;
  15678. uniforms.farDistance.value = material.farDistance;
  15679. }
  15680. return {
  15681. refreshFogUniforms: refreshFogUniforms,
  15682. refreshMaterialUniforms: refreshMaterialUniforms
  15683. };
  15684. }
  15685. function WebGLUniformsGroups(gl, info, capabilities, state) {
  15686. let buffers = {};
  15687. let updateList = {};
  15688. let allocatedBindingPoints = [];
  15689. const maxBindingPoints = capabilities.isWebGL2 ? gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS) : 0; // binding points are global whereas block indices are per shader program
  15690. function bind(uniformsGroup, program) {
  15691. const webglProgram = program.program;
  15692. state.uniformBlockBinding(uniformsGroup, webglProgram);
  15693. }
  15694. function update(uniformsGroup, program) {
  15695. let buffer = buffers[uniformsGroup.id];
  15696. if (buffer === undefined) {
  15697. prepareUniformsGroup(uniformsGroup);
  15698. buffer = createBuffer(uniformsGroup);
  15699. buffers[uniformsGroup.id] = buffer;
  15700. uniformsGroup.addEventListener('dispose', onUniformsGroupsDispose);
  15701. } // ensure to update the binding points/block indices mapping for this program
  15702. const webglProgram = program.program;
  15703. state.updateUBOMapping(uniformsGroup, webglProgram); // update UBO once per frame
  15704. const frame = info.render.frame;
  15705. if (updateList[uniformsGroup.id] !== frame) {
  15706. updateBufferData(uniformsGroup);
  15707. updateList[uniformsGroup.id] = frame;
  15708. }
  15709. }
  15710. function createBuffer(uniformsGroup) {
  15711. // the setup of an UBO is independent of a particular shader program but global
  15712. const bindingPointIndex = allocateBindingPointIndex();
  15713. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15714. const buffer = gl.createBuffer();
  15715. const size = uniformsGroup.__size;
  15716. const usage = uniformsGroup.usage;
  15717. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  15718. gl.bufferData(gl.UNIFORM_BUFFER, size, usage);
  15719. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  15720. gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer);
  15721. return buffer;
  15722. }
  15723. function allocateBindingPointIndex() {
  15724. for (let i = 0; i < maxBindingPoints; i++) {
  15725. if (allocatedBindingPoints.indexOf(i) === -1) {
  15726. allocatedBindingPoints.push(i);
  15727. return i;
  15728. }
  15729. }
  15730. console.error('THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.');
  15731. return 0;
  15732. }
  15733. function updateBufferData(uniformsGroup) {
  15734. const buffer = buffers[uniformsGroup.id];
  15735. const uniforms = uniformsGroup.uniforms;
  15736. const cache = uniformsGroup.__cache;
  15737. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  15738. for (let i = 0, il = uniforms.length; i < il; i++) {
  15739. const uniform = uniforms[i]; // partly update the buffer if necessary
  15740. if (hasUniformChanged(uniform, i, cache) === true) {
  15741. const value = uniform.value;
  15742. const offset = uniform.__offset;
  15743. if (typeof value === 'number') {
  15744. uniform.__data[0] = value;
  15745. gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
  15746. } else {
  15747. if (uniform.value.isMatrix3) {
  15748. // manually converting 3x3 to 3x4
  15749. uniform.__data[0] = uniform.value.elements[0];
  15750. uniform.__data[1] = uniform.value.elements[1];
  15751. uniform.__data[2] = uniform.value.elements[2];
  15752. uniform.__data[3] = uniform.value.elements[0];
  15753. uniform.__data[4] = uniform.value.elements[3];
  15754. uniform.__data[5] = uniform.value.elements[4];
  15755. uniform.__data[6] = uniform.value.elements[5];
  15756. uniform.__data[7] = uniform.value.elements[0];
  15757. uniform.__data[8] = uniform.value.elements[6];
  15758. uniform.__data[9] = uniform.value.elements[7];
  15759. uniform.__data[10] = uniform.value.elements[8];
  15760. uniform.__data[11] = uniform.value.elements[0];
  15761. } else {
  15762. value.toArray(uniform.__data);
  15763. }
  15764. gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
  15765. }
  15766. }
  15767. }
  15768. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  15769. }
  15770. function hasUniformChanged(uniform, index, cache) {
  15771. const value = uniform.value;
  15772. if (cache[index] === undefined) {
  15773. // cache entry does not exist so far
  15774. if (typeof value === 'number') {
  15775. cache[index] = value;
  15776. } else {
  15777. cache[index] = value.clone();
  15778. }
  15779. return true;
  15780. } else {
  15781. // compare current value with cached entry
  15782. if (typeof value === 'number') {
  15783. if (cache[index] !== value) {
  15784. cache[index] = value;
  15785. return true;
  15786. }
  15787. } else {
  15788. const cachedObject = cache[index];
  15789. if (cachedObject.equals(value) === false) {
  15790. cachedObject.copy(value);
  15791. return true;
  15792. }
  15793. }
  15794. }
  15795. return false;
  15796. }
  15797. function prepareUniformsGroup(uniformsGroup) {
  15798. // determine total buffer size according to the STD140 layout
  15799. // Hint: STD140 is the only supported layout in WebGL 2
  15800. const uniforms = uniformsGroup.uniforms;
  15801. let offset = 0; // global buffer offset in bytes
  15802. const chunkSize = 16; // size of a chunk in bytes
  15803. let chunkOffset = 0; // offset within a single chunk in bytes
  15804. for (let i = 0, l = uniforms.length; i < l; i++) {
  15805. const uniform = uniforms[i];
  15806. const info = getUniformSize(uniform); // the following two properties will be used for partial buffer updates
  15807. uniform.__data = new Float32Array(info.storage / Float32Array.BYTES_PER_ELEMENT);
  15808. uniform.__offset = offset; //
  15809. if (i > 0) {
  15810. chunkOffset = offset % chunkSize;
  15811. const remainingSizeInChunk = chunkSize - chunkOffset; // check for chunk overflow
  15812. if (chunkOffset !== 0 && remainingSizeInChunk - info.boundary < 0) {
  15813. // add padding and adjust offset
  15814. offset += chunkSize - chunkOffset;
  15815. uniform.__offset = offset;
  15816. }
  15817. }
  15818. offset += info.storage;
  15819. } // ensure correct final padding
  15820. chunkOffset = offset % chunkSize;
  15821. if (chunkOffset > 0) offset += chunkSize - chunkOffset; //
  15822. uniformsGroup.__size = offset;
  15823. uniformsGroup.__cache = {};
  15824. return this;
  15825. }
  15826. function getUniformSize(uniform) {
  15827. const value = uniform.value;
  15828. const info = {
  15829. boundary: 0,
  15830. // bytes
  15831. storage: 0 // bytes
  15832. }; // determine sizes according to STD140
  15833. if (typeof value === 'number') {
  15834. // float/int
  15835. info.boundary = 4;
  15836. info.storage = 4;
  15837. } else if (value.isVector2) {
  15838. // vec2
  15839. info.boundary = 8;
  15840. info.storage = 8;
  15841. } else if (value.isVector3 || value.isColor) {
  15842. // vec3
  15843. info.boundary = 16;
  15844. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  15845. } else if (value.isVector4) {
  15846. // vec4
  15847. info.boundary = 16;
  15848. info.storage = 16;
  15849. } else if (value.isMatrix3) {
  15850. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  15851. info.boundary = 48;
  15852. info.storage = 48;
  15853. } else if (value.isMatrix4) {
  15854. // mat4
  15855. info.boundary = 64;
  15856. info.storage = 64;
  15857. } else if (value.isTexture) {
  15858. console.warn('THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.');
  15859. } else {
  15860. console.warn('THREE.WebGLRenderer: Unsupported uniform value type.', value);
  15861. }
  15862. return info;
  15863. }
  15864. function onUniformsGroupsDispose(event) {
  15865. const uniformsGroup = event.target;
  15866. uniformsGroup.removeEventListener('dispose', onUniformsGroupsDispose);
  15867. const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex);
  15868. allocatedBindingPoints.splice(index, 1);
  15869. gl.deleteBuffer(buffers[uniformsGroup.id]);
  15870. delete buffers[uniformsGroup.id];
  15871. delete updateList[uniformsGroup.id];
  15872. }
  15873. function dispose() {
  15874. for (const id in buffers) {
  15875. gl.deleteBuffer(buffers[id]);
  15876. }
  15877. allocatedBindingPoints = [];
  15878. buffers = {};
  15879. updateList = {};
  15880. }
  15881. return {
  15882. bind: bind,
  15883. update: update,
  15884. dispose: dispose
  15885. };
  15886. }
  15887. function createCanvasElement() {
  15888. const canvas = createElementNS('canvas');
  15889. canvas.style.display = 'block';
  15890. return canvas;
  15891. }
  15892. function WebGLRenderer(parameters = {}) {
  15893. this.isWebGLRenderer = true;
  15894. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15895. _context = parameters.context !== undefined ? parameters.context : null,
  15896. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15897. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15898. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15899. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15900. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15901. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15902. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15903. let _alpha;
  15904. if (_context !== null) {
  15905. _alpha = _context.getContextAttributes().alpha;
  15906. } else {
  15907. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  15908. }
  15909. let currentRenderList = null;
  15910. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15911. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15912. const renderListStack = [];
  15913. const renderStateStack = []; // public properties
  15914. this.domElement = _canvas; // Debug configuration container
  15915. this.debug = {
  15916. /**
  15917. * Enables error checking and reporting when shader programs are being compiled
  15918. * @type {boolean}
  15919. */
  15920. checkShaderErrors: true
  15921. }; // clearing
  15922. this.autoClear = true;
  15923. this.autoClearColor = true;
  15924. this.autoClearDepth = true;
  15925. this.autoClearStencil = true; // scene graph
  15926. this.sortObjects = true; // user-defined clipping
  15927. this.clippingPlanes = [];
  15928. this.localClippingEnabled = false; // physically based shading
  15929. this.outputEncoding = LinearEncoding; // physical lights
  15930. this.physicallyCorrectLights = false; // tone mapping
  15931. this.toneMapping = NoToneMapping;
  15932. this.toneMappingExposure = 1.0; //
  15933. Object.defineProperties(this, {
  15934. // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d
  15935. gammaFactor: {
  15936. get: function () {
  15937. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  15938. return 2;
  15939. },
  15940. set: function () {
  15941. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  15942. }
  15943. }
  15944. }); // internal properties
  15945. const _this = this;
  15946. let _isContextLost = false; // internal state cache
  15947. let _currentActiveCubeFace = 0;
  15948. let _currentActiveMipmapLevel = 0;
  15949. let _currentRenderTarget = null;
  15950. let _currentMaterialId = -1;
  15951. let _currentCamera = null;
  15952. const _currentViewport = new Vector4();
  15953. const _currentScissor = new Vector4();
  15954. let _currentScissorTest = null; //
  15955. let _width = _canvas.width;
  15956. let _height = _canvas.height;
  15957. let _pixelRatio = 1;
  15958. let _opaqueSort = null;
  15959. let _transparentSort = null;
  15960. const _viewport = new Vector4(0, 0, _width, _height);
  15961. const _scissor = new Vector4(0, 0, _width, _height);
  15962. let _scissorTest = false; // frustum
  15963. const _frustum = new Frustum(); // clipping
  15964. let _clippingEnabled = false;
  15965. let _localClippingEnabled = false; // transmission
  15966. let _transmissionRenderTarget = null; // camera matrices cache
  15967. const _projScreenMatrix = new Matrix4();
  15968. const _vector2 = new Vector2();
  15969. const _vector3 = new Vector3();
  15970. const _emptyScene = {
  15971. background: null,
  15972. fog: null,
  15973. environment: null,
  15974. overrideMaterial: null,
  15975. isScene: true
  15976. };
  15977. function getTargetPixelRatio() {
  15978. return _currentRenderTarget === null ? _pixelRatio : 1;
  15979. } // initialize
  15980. let _gl = _context;
  15981. function getContext(contextNames, contextAttributes) {
  15982. for (let i = 0; i < contextNames.length; i++) {
  15983. const contextName = contextNames[i];
  15984. const context = _canvas.getContext(contextName, contextAttributes);
  15985. if (context !== null) return context;
  15986. }
  15987. return null;
  15988. }
  15989. try {
  15990. const contextAttributes = {
  15991. alpha: true,
  15992. depth: _depth,
  15993. stencil: _stencil,
  15994. antialias: _antialias,
  15995. premultipliedAlpha: _premultipliedAlpha,
  15996. preserveDrawingBuffer: _preserveDrawingBuffer,
  15997. powerPreference: _powerPreference,
  15998. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15999. }; // OffscreenCanvas does not have setAttribute, see #22811
  16000. if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`); // event listeners must be registered before WebGL context is created, see #12753
  16001. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  16002. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  16003. _canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
  16004. if (_gl === null) {
  16005. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  16006. if (_this.isWebGL1Renderer === true) {
  16007. contextNames.shift();
  16008. }
  16009. _gl = getContext(contextNames, contextAttributes);
  16010. if (_gl === null) {
  16011. if (getContext(contextNames)) {
  16012. throw new Error('Error creating WebGL context with your selected attributes.');
  16013. } else {
  16014. throw new Error('Error creating WebGL context.');
  16015. }
  16016. }
  16017. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16018. if (_gl.getShaderPrecisionFormat === undefined) {
  16019. _gl.getShaderPrecisionFormat = function () {
  16020. return {
  16021. 'rangeMin': 1,
  16022. 'rangeMax': 1,
  16023. 'precision': 1
  16024. };
  16025. };
  16026. }
  16027. } catch (error) {
  16028. console.error('THREE.WebGLRenderer: ' + error.message);
  16029. throw error;
  16030. }
  16031. let extensions, capabilities, state, info;
  16032. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16033. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16034. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16035. let utils, bindingStates, uniformsGroups;
  16036. function initGLContext() {
  16037. extensions = new WebGLExtensions(_gl);
  16038. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  16039. extensions.init(capabilities);
  16040. utils = new WebGLUtils(_gl, extensions, capabilities);
  16041. state = new WebGLState(_gl, extensions, capabilities);
  16042. info = new WebGLInfo(_gl);
  16043. properties = new WebGLProperties();
  16044. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  16045. cubemaps = new WebGLCubeMaps(_this);
  16046. cubeuvmaps = new WebGLCubeUVMaps(_this);
  16047. attributes = new WebGLAttributes(_gl, capabilities);
  16048. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  16049. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  16050. objects = new WebGLObjects(_gl, geometries, attributes, info);
  16051. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  16052. clipping = new WebGLClipping(properties);
  16053. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  16054. materials = new WebGLMaterials(_this, properties);
  16055. renderLists = new WebGLRenderLists();
  16056. renderStates = new WebGLRenderStates(extensions, capabilities);
  16057. background = new WebGLBackground(_this, cubemaps, state, objects, _alpha, _premultipliedAlpha);
  16058. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  16059. uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state);
  16060. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  16061. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  16062. info.programs = programCache.programs;
  16063. _this.capabilities = capabilities;
  16064. _this.extensions = extensions;
  16065. _this.properties = properties;
  16066. _this.renderLists = renderLists;
  16067. _this.shadowMap = shadowMap;
  16068. _this.state = state;
  16069. _this.info = info;
  16070. }
  16071. initGLContext(); // xr
  16072. const xr = new WebXRManager(_this, _gl);
  16073. this.xr = xr; // API
  16074. this.getContext = function () {
  16075. return _gl;
  16076. };
  16077. this.getContextAttributes = function () {
  16078. return _gl.getContextAttributes();
  16079. };
  16080. this.forceContextLoss = function () {
  16081. const extension = extensions.get('WEBGL_lose_context');
  16082. if (extension) extension.loseContext();
  16083. };
  16084. this.forceContextRestore = function () {
  16085. const extension = extensions.get('WEBGL_lose_context');
  16086. if (extension) extension.restoreContext();
  16087. };
  16088. this.getPixelRatio = function () {
  16089. return _pixelRatio;
  16090. };
  16091. this.setPixelRatio = function (value) {
  16092. if (value === undefined) return;
  16093. _pixelRatio = value;
  16094. this.setSize(_width, _height, false);
  16095. };
  16096. this.getSize = function (target) {
  16097. return target.set(_width, _height);
  16098. };
  16099. this.setSize = function (width, height, updateStyle) {
  16100. if (xr.isPresenting) {
  16101. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  16102. return;
  16103. }
  16104. _width = width;
  16105. _height = height;
  16106. _canvas.width = Math.floor(width * _pixelRatio);
  16107. _canvas.height = Math.floor(height * _pixelRatio);
  16108. if (updateStyle !== false) {
  16109. _canvas.style.width = width + 'px';
  16110. _canvas.style.height = height + 'px';
  16111. }
  16112. this.setViewport(0, 0, width, height);
  16113. };
  16114. this.getDrawingBufferSize = function (target) {
  16115. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  16116. };
  16117. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  16118. _width = width;
  16119. _height = height;
  16120. _pixelRatio = pixelRatio;
  16121. _canvas.width = Math.floor(width * pixelRatio);
  16122. _canvas.height = Math.floor(height * pixelRatio);
  16123. this.setViewport(0, 0, width, height);
  16124. };
  16125. this.getCurrentViewport = function (target) {
  16126. return target.copy(_currentViewport);
  16127. };
  16128. this.getViewport = function (target) {
  16129. return target.copy(_viewport);
  16130. };
  16131. this.setViewport = function (x, y, width, height) {
  16132. if (x.isVector4) {
  16133. _viewport.set(x.x, x.y, x.z, x.w);
  16134. } else {
  16135. _viewport.set(x, y, width, height);
  16136. }
  16137. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  16138. };
  16139. this.getScissor = function (target) {
  16140. return target.copy(_scissor);
  16141. };
  16142. this.setScissor = function (x, y, width, height) {
  16143. if (x.isVector4) {
  16144. _scissor.set(x.x, x.y, x.z, x.w);
  16145. } else {
  16146. _scissor.set(x, y, width, height);
  16147. }
  16148. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  16149. };
  16150. this.getScissorTest = function () {
  16151. return _scissorTest;
  16152. };
  16153. this.setScissorTest = function (boolean) {
  16154. state.setScissorTest(_scissorTest = boolean);
  16155. };
  16156. this.setOpaqueSort = function (method) {
  16157. _opaqueSort = method;
  16158. };
  16159. this.setTransparentSort = function (method) {
  16160. _transparentSort = method;
  16161. }; // Clearing
  16162. this.getClearColor = function (target) {
  16163. return target.copy(background.getClearColor());
  16164. };
  16165. this.setClearColor = function () {
  16166. background.setClearColor.apply(background, arguments);
  16167. };
  16168. this.getClearAlpha = function () {
  16169. return background.getClearAlpha();
  16170. };
  16171. this.setClearAlpha = function () {
  16172. background.setClearAlpha.apply(background, arguments);
  16173. };
  16174. this.clear = function (color = true, depth = true, stencil = true) {
  16175. let bits = 0;
  16176. if (color) bits |= _gl.COLOR_BUFFER_BIT;
  16177. if (depth) bits |= _gl.DEPTH_BUFFER_BIT;
  16178. if (stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  16179. _gl.clear(bits);
  16180. };
  16181. this.clearColor = function () {
  16182. this.clear(true, false, false);
  16183. };
  16184. this.clearDepth = function () {
  16185. this.clear(false, true, false);
  16186. };
  16187. this.clearStencil = function () {
  16188. this.clear(false, false, true);
  16189. }; //
  16190. this.dispose = function () {
  16191. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  16192. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  16193. _canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
  16194. renderLists.dispose();
  16195. renderStates.dispose();
  16196. properties.dispose();
  16197. cubemaps.dispose();
  16198. cubeuvmaps.dispose();
  16199. objects.dispose();
  16200. bindingStates.dispose();
  16201. uniformsGroups.dispose();
  16202. programCache.dispose();
  16203. xr.dispose();
  16204. xr.removeEventListener('sessionstart', onXRSessionStart);
  16205. xr.removeEventListener('sessionend', onXRSessionEnd);
  16206. if (_transmissionRenderTarget) {
  16207. _transmissionRenderTarget.dispose();
  16208. _transmissionRenderTarget = null;
  16209. }
  16210. animation.stop();
  16211. }; // Events
  16212. function onContextLost(event) {
  16213. event.preventDefault();
  16214. console.log('THREE.WebGLRenderer: Context Lost.');
  16215. _isContextLost = true;
  16216. }
  16217. function
  16218. /* event */
  16219. onContextRestore() {
  16220. console.log('THREE.WebGLRenderer: Context Restored.');
  16221. _isContextLost = false;
  16222. const infoAutoReset = info.autoReset;
  16223. const shadowMapEnabled = shadowMap.enabled;
  16224. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16225. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16226. const shadowMapType = shadowMap.type;
  16227. initGLContext();
  16228. info.autoReset = infoAutoReset;
  16229. shadowMap.enabled = shadowMapEnabled;
  16230. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16231. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16232. shadowMap.type = shadowMapType;
  16233. }
  16234. function onContextCreationError(event) {
  16235. console.error('THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage);
  16236. }
  16237. function onMaterialDispose(event) {
  16238. const material = event.target;
  16239. material.removeEventListener('dispose', onMaterialDispose);
  16240. deallocateMaterial(material);
  16241. } // Buffer deallocation
  16242. function deallocateMaterial(material) {
  16243. releaseMaterialProgramReferences(material);
  16244. properties.remove(material);
  16245. }
  16246. function releaseMaterialProgramReferences(material) {
  16247. const programs = properties.get(material).programs;
  16248. if (programs !== undefined) {
  16249. programs.forEach(function (program) {
  16250. programCache.releaseProgram(program);
  16251. });
  16252. if (material.isShaderMaterial) {
  16253. programCache.releaseShaderCache(material);
  16254. }
  16255. }
  16256. } // Buffer rendering
  16257. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  16258. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16259. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  16260. const program = setProgram(camera, scene, geometry, material, object);
  16261. state.setMaterial(material, frontFaceCW); //
  16262. let index = geometry.index;
  16263. const position = geometry.attributes.position; //
  16264. if (index === null) {
  16265. if (position === undefined || position.count === 0) return;
  16266. } else if (index.count === 0) {
  16267. return;
  16268. } //
  16269. let rangeFactor = 1;
  16270. if (material.wireframe === true) {
  16271. index = geometries.getWireframeAttribute(geometry);
  16272. rangeFactor = 2;
  16273. }
  16274. bindingStates.setup(object, material, program, geometry, index);
  16275. let attribute;
  16276. let renderer = bufferRenderer;
  16277. if (index !== null) {
  16278. attribute = attributes.get(index);
  16279. renderer = indexedBufferRenderer;
  16280. renderer.setIndex(attribute);
  16281. } //
  16282. const dataCount = index !== null ? index.count : position.count;
  16283. const rangeStart = geometry.drawRange.start * rangeFactor;
  16284. const rangeCount = geometry.drawRange.count * rangeFactor;
  16285. const groupStart = group !== null ? group.start * rangeFactor : 0;
  16286. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16287. const drawStart = Math.max(rangeStart, groupStart);
  16288. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  16289. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  16290. if (drawCount === 0) return; //
  16291. if (object.isMesh) {
  16292. if (material.wireframe === true) {
  16293. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  16294. renderer.setMode(_gl.LINES);
  16295. } else {
  16296. renderer.setMode(_gl.TRIANGLES);
  16297. }
  16298. } else if (object.isLine) {
  16299. let lineWidth = material.linewidth;
  16300. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16301. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16302. if (object.isLineSegments) {
  16303. renderer.setMode(_gl.LINES);
  16304. } else if (object.isLineLoop) {
  16305. renderer.setMode(_gl.LINE_LOOP);
  16306. } else {
  16307. renderer.setMode(_gl.LINE_STRIP);
  16308. }
  16309. } else if (object.isPoints) {
  16310. renderer.setMode(_gl.POINTS);
  16311. } else if (object.isSprite) {
  16312. renderer.setMode(_gl.TRIANGLES);
  16313. }
  16314. if (object.isInstancedMesh) {
  16315. renderer.renderInstances(drawStart, drawCount, object.count);
  16316. } else if (geometry.isInstancedBufferGeometry) {
  16317. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  16318. renderer.renderInstances(drawStart, drawCount, instanceCount);
  16319. } else {
  16320. renderer.render(drawStart, drawCount);
  16321. }
  16322. }; // Compile
  16323. this.compile = function (scene, camera) {
  16324. currentRenderState = renderStates.get(scene);
  16325. currentRenderState.init();
  16326. renderStateStack.push(currentRenderState);
  16327. scene.traverseVisible(function (object) {
  16328. if (object.isLight && object.layers.test(camera.layers)) {
  16329. currentRenderState.pushLight(object);
  16330. if (object.castShadow) {
  16331. currentRenderState.pushShadow(object);
  16332. }
  16333. }
  16334. });
  16335. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16336. scene.traverse(function (object) {
  16337. const material = object.material;
  16338. if (material) {
  16339. if (Array.isArray(material)) {
  16340. for (let i = 0; i < material.length; i++) {
  16341. const material2 = material[i];
  16342. getProgram(material2, scene, object);
  16343. }
  16344. } else {
  16345. getProgram(material, scene, object);
  16346. }
  16347. }
  16348. });
  16349. renderStateStack.pop();
  16350. currentRenderState = null;
  16351. }; // Animation Loop
  16352. let onAnimationFrameCallback = null;
  16353. function onAnimationFrame(time) {
  16354. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16355. }
  16356. function onXRSessionStart() {
  16357. animation.stop();
  16358. }
  16359. function onXRSessionEnd() {
  16360. animation.start();
  16361. }
  16362. const animation = new WebGLAnimation();
  16363. animation.setAnimationLoop(onAnimationFrame);
  16364. if (typeof self !== 'undefined') animation.setContext(self);
  16365. this.setAnimationLoop = function (callback) {
  16366. onAnimationFrameCallback = callback;
  16367. xr.setAnimationLoop(callback);
  16368. callback === null ? animation.stop() : animation.start();
  16369. };
  16370. xr.addEventListener('sessionstart', onXRSessionStart);
  16371. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  16372. this.render = function (scene, camera) {
  16373. if (camera !== undefined && camera.isCamera !== true) {
  16374. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16375. return;
  16376. }
  16377. if (_isContextLost === true) return; // update scene graph
  16378. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16379. if (camera.parent === null) camera.updateMatrixWorld();
  16380. if (xr.enabled === true && xr.isPresenting === true) {
  16381. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  16382. camera = xr.getCamera(); // use XR camera for rendering
  16383. } //
  16384. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  16385. currentRenderState = renderStates.get(scene, renderStateStack.length);
  16386. currentRenderState.init();
  16387. renderStateStack.push(currentRenderState);
  16388. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16389. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  16390. _localClippingEnabled = this.localClippingEnabled;
  16391. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16392. currentRenderList = renderLists.get(scene, renderListStack.length);
  16393. currentRenderList.init();
  16394. renderListStack.push(currentRenderList);
  16395. projectObject(scene, camera, 0, _this.sortObjects);
  16396. currentRenderList.finish();
  16397. if (_this.sortObjects === true) {
  16398. currentRenderList.sort(_opaqueSort, _transparentSort);
  16399. } //
  16400. if (_clippingEnabled === true) clipping.beginShadows();
  16401. const shadowsArray = currentRenderState.state.shadowsArray;
  16402. shadowMap.render(shadowsArray, scene, camera);
  16403. if (_clippingEnabled === true) clipping.endShadows(); //
  16404. if (this.info.autoReset === true) this.info.reset(); //
  16405. background.render(currentRenderList, scene); // render scene
  16406. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16407. if (camera.isArrayCamera) {
  16408. const cameras = camera.cameras;
  16409. for (let i = 0, l = cameras.length; i < l; i++) {
  16410. const camera2 = cameras[i];
  16411. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  16412. }
  16413. } else {
  16414. renderScene(currentRenderList, scene, camera);
  16415. } //
  16416. if (_currentRenderTarget !== null) {
  16417. // resolve multisample renderbuffers to a single-sample texture if necessary
  16418. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  16419. textures.updateRenderTargetMipmap(_currentRenderTarget);
  16420. } //
  16421. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // _gl.finish();
  16422. bindingStates.resetDefaultState();
  16423. _currentMaterialId = -1;
  16424. _currentCamera = null;
  16425. renderStateStack.pop();
  16426. if (renderStateStack.length > 0) {
  16427. currentRenderState = renderStateStack[renderStateStack.length - 1];
  16428. } else {
  16429. currentRenderState = null;
  16430. }
  16431. renderListStack.pop();
  16432. if (renderListStack.length > 0) {
  16433. currentRenderList = renderListStack[renderListStack.length - 1];
  16434. } else {
  16435. currentRenderList = null;
  16436. }
  16437. };
  16438. function projectObject(object, camera, groupOrder, sortObjects) {
  16439. if (object.visible === false) return;
  16440. const visible = object.layers.test(camera.layers);
  16441. if (visible) {
  16442. if (object.isGroup) {
  16443. groupOrder = object.renderOrder;
  16444. } else if (object.isLOD) {
  16445. if (object.autoUpdate === true) object.update(camera);
  16446. } else if (object.isLight) {
  16447. currentRenderState.pushLight(object);
  16448. if (object.castShadow) {
  16449. currentRenderState.pushShadow(object);
  16450. }
  16451. } else if (object.isSprite) {
  16452. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16453. if (sortObjects) {
  16454. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16455. }
  16456. const geometry = objects.update(object);
  16457. const material = object.material;
  16458. if (material.visible) {
  16459. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16460. }
  16461. }
  16462. } else if (object.isMesh || object.isLine || object.isPoints) {
  16463. if (object.isSkinnedMesh) {
  16464. // update skeleton only once in a frame
  16465. if (object.skeleton.frame !== info.render.frame) {
  16466. object.skeleton.update();
  16467. object.skeleton.frame = info.render.frame;
  16468. }
  16469. }
  16470. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16471. if (sortObjects) {
  16472. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16473. }
  16474. const geometry = objects.update(object);
  16475. const material = object.material;
  16476. if (Array.isArray(material)) {
  16477. const groups = geometry.groups;
  16478. for (let i = 0, l = groups.length; i < l; i++) {
  16479. const group = groups[i];
  16480. const groupMaterial = material[group.materialIndex];
  16481. if (groupMaterial && groupMaterial.visible) {
  16482. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16483. }
  16484. }
  16485. } else if (material.visible) {
  16486. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16487. }
  16488. }
  16489. }
  16490. }
  16491. const children = object.children;
  16492. for (let i = 0, l = children.length; i < l; i++) {
  16493. projectObject(children[i], camera, groupOrder, sortObjects);
  16494. }
  16495. }
  16496. function renderScene(currentRenderList, scene, camera, viewport) {
  16497. const opaqueObjects = currentRenderList.opaque;
  16498. const transmissiveObjects = currentRenderList.transmissive;
  16499. const transparentObjects = currentRenderList.transparent;
  16500. currentRenderState.setupLightsView(camera);
  16501. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  16502. if (viewport) state.viewport(_currentViewport.copy(viewport));
  16503. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  16504. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  16505. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  16506. state.buffers.depth.setTest(true);
  16507. state.buffers.depth.setMask(true);
  16508. state.buffers.color.setMask(true);
  16509. state.setPolygonOffset(false);
  16510. }
  16511. function renderTransmissionPass(opaqueObjects, scene, camera) {
  16512. const isWebGL2 = capabilities.isWebGL2;
  16513. if (_transmissionRenderTarget === null) {
  16514. _transmissionRenderTarget = new WebGLRenderTarget(1, 1, {
  16515. generateMipmaps: true,
  16516. type: extensions.has('EXT_color_buffer_half_float') ? HalfFloatType : UnsignedByteType,
  16517. minFilter: LinearMipmapLinearFilter,
  16518. samples: isWebGL2 && _antialias === true ? 4 : 0
  16519. });
  16520. }
  16521. _this.getDrawingBufferSize(_vector2);
  16522. if (isWebGL2) {
  16523. _transmissionRenderTarget.setSize(_vector2.x, _vector2.y);
  16524. } else {
  16525. _transmissionRenderTarget.setSize(floorPowerOfTwo(_vector2.x), floorPowerOfTwo(_vector2.y));
  16526. } //
  16527. const currentRenderTarget = _this.getRenderTarget();
  16528. _this.setRenderTarget(_transmissionRenderTarget);
  16529. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  16530. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16531. const currentToneMapping = _this.toneMapping;
  16532. _this.toneMapping = NoToneMapping;
  16533. renderObjects(opaqueObjects, scene, camera);
  16534. _this.toneMapping = currentToneMapping;
  16535. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  16536. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  16537. _this.setRenderTarget(currentRenderTarget);
  16538. }
  16539. function renderObjects(renderList, scene, camera) {
  16540. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16541. for (let i = 0, l = renderList.length; i < l; i++) {
  16542. const renderItem = renderList[i];
  16543. const object = renderItem.object;
  16544. const geometry = renderItem.geometry;
  16545. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16546. const group = renderItem.group;
  16547. if (object.layers.test(camera.layers)) {
  16548. renderObject(object, scene, camera, geometry, material, group);
  16549. }
  16550. }
  16551. }
  16552. function renderObject(object, scene, camera, geometry, material, group) {
  16553. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16554. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16555. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16556. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  16557. if (material.transparent === true && material.side === DoubleSide) {
  16558. material.side = BackSide;
  16559. material.needsUpdate = true;
  16560. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16561. material.side = FrontSide;
  16562. material.needsUpdate = true;
  16563. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16564. material.side = DoubleSide;
  16565. } else {
  16566. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16567. }
  16568. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16569. }
  16570. function getProgram(material, scene, object) {
  16571. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16572. const materialProperties = properties.get(material);
  16573. const lights = currentRenderState.state.lights;
  16574. const shadowsArray = currentRenderState.state.shadowsArray;
  16575. const lightsStateVersion = lights.state.version;
  16576. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  16577. const programCacheKey = programCache.getProgramCacheKey(parameters);
  16578. let programs = materialProperties.programs; // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16579. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16580. materialProperties.fog = scene.fog;
  16581. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  16582. if (programs === undefined) {
  16583. // new material
  16584. material.addEventListener('dispose', onMaterialDispose);
  16585. programs = new Map();
  16586. materialProperties.programs = programs;
  16587. }
  16588. let program = programs.get(programCacheKey);
  16589. if (program !== undefined) {
  16590. // early out if program and light state is identical
  16591. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  16592. updateCommonMaterialProperties(material, parameters);
  16593. return program;
  16594. }
  16595. } else {
  16596. parameters.uniforms = programCache.getUniforms(material);
  16597. material.onBuild(object, parameters, _this);
  16598. material.onBeforeCompile(parameters, _this);
  16599. program = programCache.acquireProgram(parameters, programCacheKey);
  16600. programs.set(programCacheKey, program);
  16601. materialProperties.uniforms = parameters.uniforms;
  16602. }
  16603. const uniforms = materialProperties.uniforms;
  16604. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16605. uniforms.clippingPlanes = clipping.uniform;
  16606. }
  16607. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  16608. materialProperties.needsLights = materialNeedsLights(material);
  16609. materialProperties.lightsStateVersion = lightsStateVersion;
  16610. if (materialProperties.needsLights) {
  16611. // wire up the material to this renderer's lighting state
  16612. uniforms.ambientLightColor.value = lights.state.ambient;
  16613. uniforms.lightProbe.value = lights.state.probe;
  16614. uniforms.directionalLights.value = lights.state.directional;
  16615. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16616. uniforms.spotLights.value = lights.state.spot;
  16617. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16618. uniforms.rectAreaLights.value = lights.state.rectArea;
  16619. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16620. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16621. uniforms.pointLights.value = lights.state.point;
  16622. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16623. uniforms.hemisphereLights.value = lights.state.hemi;
  16624. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16625. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16626. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16627. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16628. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16629. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16630. }
  16631. const progUniforms = program.getUniforms();
  16632. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16633. materialProperties.currentProgram = program;
  16634. materialProperties.uniformsList = uniformsList;
  16635. return program;
  16636. }
  16637. function updateCommonMaterialProperties(material, parameters) {
  16638. const materialProperties = properties.get(material);
  16639. materialProperties.outputEncoding = parameters.outputEncoding;
  16640. materialProperties.instancing = parameters.instancing;
  16641. materialProperties.skinning = parameters.skinning;
  16642. materialProperties.morphTargets = parameters.morphTargets;
  16643. materialProperties.morphNormals = parameters.morphNormals;
  16644. materialProperties.morphColors = parameters.morphColors;
  16645. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16646. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16647. materialProperties.numIntersection = parameters.numClipIntersection;
  16648. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16649. materialProperties.vertexTangents = parameters.vertexTangents;
  16650. materialProperties.toneMapping = parameters.toneMapping;
  16651. }
  16652. function setProgram(camera, scene, geometry, material, object) {
  16653. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16654. textures.resetTextureUnits();
  16655. const fog = scene.fog;
  16656. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16657. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding;
  16658. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  16659. const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16660. const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
  16661. const morphTargets = !!geometry.morphAttributes.position;
  16662. const morphNormals = !!geometry.morphAttributes.normal;
  16663. const morphColors = !!geometry.morphAttributes.color;
  16664. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16665. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16666. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  16667. const materialProperties = properties.get(material);
  16668. const lights = currentRenderState.state.lights;
  16669. if (_clippingEnabled === true) {
  16670. if (_localClippingEnabled === true || camera !== _currentCamera) {
  16671. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16672. // object instead of the material, once it becomes feasible
  16673. // (#8465, #8379)
  16674. clipping.setState(material, camera, useCache);
  16675. }
  16676. } //
  16677. let needsProgramChange = false;
  16678. if (material.version === materialProperties.__version) {
  16679. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16680. needsProgramChange = true;
  16681. } else if (materialProperties.outputEncoding !== encoding) {
  16682. needsProgramChange = true;
  16683. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  16684. needsProgramChange = true;
  16685. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  16686. needsProgramChange = true;
  16687. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  16688. needsProgramChange = true;
  16689. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  16690. needsProgramChange = true;
  16691. } else if (materialProperties.envMap !== envMap) {
  16692. needsProgramChange = true;
  16693. } else if (material.fog === true && materialProperties.fog !== fog) {
  16694. needsProgramChange = true;
  16695. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  16696. needsProgramChange = true;
  16697. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  16698. needsProgramChange = true;
  16699. } else if (materialProperties.vertexTangents !== vertexTangents) {
  16700. needsProgramChange = true;
  16701. } else if (materialProperties.morphTargets !== morphTargets) {
  16702. needsProgramChange = true;
  16703. } else if (materialProperties.morphNormals !== morphNormals) {
  16704. needsProgramChange = true;
  16705. } else if (materialProperties.morphColors !== morphColors) {
  16706. needsProgramChange = true;
  16707. } else if (materialProperties.toneMapping !== toneMapping) {
  16708. needsProgramChange = true;
  16709. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  16710. needsProgramChange = true;
  16711. }
  16712. } else {
  16713. needsProgramChange = true;
  16714. materialProperties.__version = material.version;
  16715. } //
  16716. let program = materialProperties.currentProgram;
  16717. if (needsProgramChange === true) {
  16718. program = getProgram(material, scene, object);
  16719. }
  16720. let refreshProgram = false;
  16721. let refreshMaterial = false;
  16722. let refreshLights = false;
  16723. const p_uniforms = program.getUniforms(),
  16724. m_uniforms = materialProperties.uniforms;
  16725. if (state.useProgram(program.program)) {
  16726. refreshProgram = true;
  16727. refreshMaterial = true;
  16728. refreshLights = true;
  16729. }
  16730. if (material.id !== _currentMaterialId) {
  16731. _currentMaterialId = material.id;
  16732. refreshMaterial = true;
  16733. }
  16734. if (refreshProgram || _currentCamera !== camera) {
  16735. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16736. if (capabilities.logarithmicDepthBuffer) {
  16737. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16738. }
  16739. if (_currentCamera !== camera) {
  16740. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16741. // now, in case this material supports lights - or later, when
  16742. // the next material that does gets activated:
  16743. refreshMaterial = true; // set to true on material change
  16744. refreshLights = true; // remains set until update done
  16745. } // load material specific uniforms
  16746. // (shader material also gets them for the sake of genericity)
  16747. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  16748. const uCamPos = p_uniforms.map.cameraPosition;
  16749. if (uCamPos !== undefined) {
  16750. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16751. }
  16752. }
  16753. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  16754. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  16755. }
  16756. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  16757. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16758. }
  16759. } // skinning and morph target uniforms must be set even if material didn't change
  16760. // auto-setting of texture unit for bone and morph texture must go before other textures
  16761. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16762. if (object.isSkinnedMesh) {
  16763. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16764. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16765. const skeleton = object.skeleton;
  16766. if (skeleton) {
  16767. if (capabilities.floatVertexTextures) {
  16768. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  16769. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16770. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16771. } else {
  16772. console.warn('THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.');
  16773. }
  16774. }
  16775. }
  16776. const morphAttributes = geometry.morphAttributes;
  16777. if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined && capabilities.isWebGL2 === true) {
  16778. morphtargets.update(object, geometry, material, program);
  16779. }
  16780. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16781. materialProperties.receiveShadow = object.receiveShadow;
  16782. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16783. } // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  16784. if (material.isMeshGouraudMaterial && material.envMap !== null) {
  16785. m_uniforms.envMap.value = envMap;
  16786. m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  16787. }
  16788. if (refreshMaterial) {
  16789. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16790. if (materialProperties.needsLights) {
  16791. // the current material requires lighting info
  16792. // note: all lighting uniforms are always set correctly
  16793. // they simply reference the renderer's state for their
  16794. // values
  16795. //
  16796. // use the current material's .needsUpdate flags to set
  16797. // the GL state when required
  16798. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16799. } // refresh uniforms common to several materials
  16800. if (fog && material.fog === true) {
  16801. materials.refreshFogUniforms(m_uniforms, fog);
  16802. }
  16803. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  16804. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16805. }
  16806. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16807. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16808. material.uniformsNeedUpdate = false;
  16809. }
  16810. if (material.isSpriteMaterial) {
  16811. p_uniforms.setValue(_gl, 'center', object.center);
  16812. } // common matrices
  16813. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16814. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16815. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld); // UBOs
  16816. if (material.isShaderMaterial || material.isRawShaderMaterial) {
  16817. const groups = material.uniformsGroups;
  16818. for (let i = 0, l = groups.length; i < l; i++) {
  16819. if (capabilities.isWebGL2) {
  16820. const group = groups[i];
  16821. uniformsGroups.update(group, program);
  16822. uniformsGroups.bind(group, program);
  16823. } else {
  16824. console.warn('THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.');
  16825. }
  16826. }
  16827. }
  16828. return program;
  16829. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16830. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16831. uniforms.ambientLightColor.needsUpdate = value;
  16832. uniforms.lightProbe.needsUpdate = value;
  16833. uniforms.directionalLights.needsUpdate = value;
  16834. uniforms.directionalLightShadows.needsUpdate = value;
  16835. uniforms.pointLights.needsUpdate = value;
  16836. uniforms.pointLightShadows.needsUpdate = value;
  16837. uniforms.spotLights.needsUpdate = value;
  16838. uniforms.spotLightShadows.needsUpdate = value;
  16839. uniforms.rectAreaLights.needsUpdate = value;
  16840. uniforms.hemisphereLights.needsUpdate = value;
  16841. }
  16842. function materialNeedsLights(material) {
  16843. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16844. }
  16845. this.getActiveCubeFace = function () {
  16846. return _currentActiveCubeFace;
  16847. };
  16848. this.getActiveMipmapLevel = function () {
  16849. return _currentActiveMipmapLevel;
  16850. };
  16851. this.getRenderTarget = function () {
  16852. return _currentRenderTarget;
  16853. };
  16854. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  16855. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  16856. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  16857. const renderTargetProperties = properties.get(renderTarget);
  16858. renderTargetProperties.__hasExternalTextures = true;
  16859. if (renderTargetProperties.__hasExternalTextures) {
  16860. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16861. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  16862. // The multisample_render_to_texture extension doesn't work properly if there
  16863. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16864. if (extensions.has('WEBGL_multisampled_render_to_texture') === true) {
  16865. console.warn('THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided');
  16866. renderTargetProperties.__useRenderToTexture = false;
  16867. }
  16868. }
  16869. }
  16870. };
  16871. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  16872. const renderTargetProperties = properties.get(renderTarget);
  16873. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16874. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16875. };
  16876. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16877. _currentRenderTarget = renderTarget;
  16878. _currentActiveCubeFace = activeCubeFace;
  16879. _currentActiveMipmapLevel = activeMipmapLevel;
  16880. let useDefaultFramebuffer = true;
  16881. if (renderTarget) {
  16882. const renderTargetProperties = properties.get(renderTarget);
  16883. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  16884. // We need to make sure to rebind the framebuffer.
  16885. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  16886. useDefaultFramebuffer = false;
  16887. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  16888. textures.setupRenderTarget(renderTarget);
  16889. } else if (renderTargetProperties.__hasExternalTextures) {
  16890. // Color and depth texture must be rebound in order for the swapchain to update.
  16891. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  16892. }
  16893. }
  16894. let framebuffer = null;
  16895. let isCube = false;
  16896. let isRenderTarget3D = false;
  16897. if (renderTarget) {
  16898. const texture = renderTarget.texture;
  16899. if (texture.isData3DTexture || texture.isDataArrayTexture) {
  16900. isRenderTarget3D = true;
  16901. }
  16902. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16903. if (renderTarget.isWebGLCubeRenderTarget) {
  16904. framebuffer = __webglFramebuffer[activeCubeFace];
  16905. isCube = true;
  16906. } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) {
  16907. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16908. } else {
  16909. framebuffer = __webglFramebuffer;
  16910. }
  16911. _currentViewport.copy(renderTarget.viewport);
  16912. _currentScissor.copy(renderTarget.scissor);
  16913. _currentScissorTest = renderTarget.scissorTest;
  16914. } else {
  16915. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16916. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16917. _currentScissorTest = _scissorTest;
  16918. }
  16919. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16920. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  16921. state.drawBuffers(renderTarget, framebuffer);
  16922. }
  16923. state.viewport(_currentViewport);
  16924. state.scissor(_currentScissor);
  16925. state.setScissorTest(_currentScissorTest);
  16926. if (isCube) {
  16927. const textureProperties = properties.get(renderTarget.texture);
  16928. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16929. } else if (isRenderTarget3D) {
  16930. const textureProperties = properties.get(renderTarget.texture);
  16931. const layer = activeCubeFace || 0;
  16932. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16933. }
  16934. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16935. };
  16936. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16937. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16938. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16939. return;
  16940. }
  16941. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16942. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16943. framebuffer = framebuffer[activeCubeFaceIndex];
  16944. }
  16945. if (framebuffer) {
  16946. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16947. try {
  16948. const texture = renderTarget.texture;
  16949. const textureFormat = texture.format;
  16950. const textureType = texture.type;
  16951. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16952. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16953. return;
  16954. }
  16955. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16956. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16957. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16958. !halfFloatSupportedByExt) {
  16959. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16960. return;
  16961. } // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16962. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16963. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16964. }
  16965. } finally {
  16966. // restore framebuffer of current render target if necessary
  16967. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16968. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16969. }
  16970. }
  16971. };
  16972. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16973. const levelScale = Math.pow(2, -level);
  16974. const width = Math.floor(texture.image.width * levelScale);
  16975. const height = Math.floor(texture.image.height * levelScale);
  16976. textures.setTexture2D(texture, 0);
  16977. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  16978. state.unbindTexture();
  16979. };
  16980. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16981. const width = srcTexture.image.width;
  16982. const height = srcTexture.image.height;
  16983. const glFormat = utils.convert(dstTexture.format);
  16984. const glType = utils.convert(dstTexture.type);
  16985. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16986. // parameters, make sure they are correct for the dstTexture
  16987. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16988. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16989. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16990. if (srcTexture.isDataTexture) {
  16991. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16992. } else {
  16993. if (srcTexture.isCompressedTexture) {
  16994. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16995. } else {
  16996. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16997. }
  16998. } // Generate mipmaps only when copying level 0
  16999. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  17000. state.unbindTexture();
  17001. };
  17002. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  17003. if (_this.isWebGL1Renderer) {
  17004. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  17005. return;
  17006. }
  17007. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17008. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17009. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17010. const glFormat = utils.convert(dstTexture.format);
  17011. const glType = utils.convert(dstTexture.type);
  17012. let glTarget;
  17013. if (dstTexture.isData3DTexture) {
  17014. textures.setTexture3D(dstTexture, 0);
  17015. glTarget = _gl.TEXTURE_3D;
  17016. } else if (dstTexture.isDataArrayTexture) {
  17017. textures.setTexture2DArray(dstTexture, 0);
  17018. glTarget = _gl.TEXTURE_2D_ARRAY;
  17019. } else {
  17020. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  17021. return;
  17022. }
  17023. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  17024. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  17025. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  17026. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  17027. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  17028. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  17029. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  17030. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  17031. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  17032. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  17033. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  17034. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  17035. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  17036. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  17037. if (srcTexture.isDataTexture || srcTexture.isData3DTexture) {
  17038. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  17039. } else {
  17040. if (srcTexture.isCompressedTexture) {
  17041. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  17042. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  17043. } else {
  17044. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  17045. }
  17046. }
  17047. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  17048. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  17049. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  17050. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  17051. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  17052. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  17053. state.unbindTexture();
  17054. };
  17055. this.initTexture = function (texture) {
  17056. if (texture.isCubeTexture) {
  17057. textures.setTextureCube(texture, 0);
  17058. } else if (texture.isData3DTexture) {
  17059. textures.setTexture3D(texture, 0);
  17060. } else if (texture.isDataArrayTexture) {
  17061. textures.setTexture2DArray(texture, 0);
  17062. } else {
  17063. textures.setTexture2D(texture, 0);
  17064. }
  17065. state.unbindTexture();
  17066. };
  17067. this.resetState = function () {
  17068. _currentActiveCubeFace = 0;
  17069. _currentActiveMipmapLevel = 0;
  17070. _currentRenderTarget = null;
  17071. state.reset();
  17072. bindingStates.reset();
  17073. };
  17074. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17075. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17076. detail: this
  17077. }));
  17078. }
  17079. }
  17080. class WebGL1Renderer extends WebGLRenderer {}
  17081. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17082. class FogExp2 {
  17083. constructor(color, density = 0.00025) {
  17084. this.isFogExp2 = true;
  17085. this.name = '';
  17086. this.color = new Color(color);
  17087. this.density = density;
  17088. }
  17089. clone() {
  17090. return new FogExp2(this.color, this.density);
  17091. }
  17092. toJSON() {
  17093. return {
  17094. type: 'FogExp2',
  17095. color: this.color.getHex(),
  17096. density: this.density
  17097. };
  17098. }
  17099. }
  17100. class Fog {
  17101. constructor(color, near = 1, far = 1000) {
  17102. this.isFog = true;
  17103. this.name = '';
  17104. this.color = new Color(color);
  17105. this.near = near;
  17106. this.far = far;
  17107. }
  17108. clone() {
  17109. return new Fog(this.color, this.near, this.far);
  17110. }
  17111. toJSON() {
  17112. return {
  17113. type: 'Fog',
  17114. color: this.color.getHex(),
  17115. near: this.near,
  17116. far: this.far
  17117. };
  17118. }
  17119. }
  17120. class Scene extends Object3D {
  17121. constructor() {
  17122. super();
  17123. this.isScene = true;
  17124. this.type = 'Scene';
  17125. this.background = null;
  17126. this.environment = null;
  17127. this.fog = null;
  17128. this.overrideMaterial = null;
  17129. this.autoUpdate = true; // checked by the renderer
  17130. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17131. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17132. detail: this
  17133. }));
  17134. }
  17135. }
  17136. copy(source, recursive) {
  17137. super.copy(source, recursive);
  17138. if (source.background !== null) this.background = source.background.clone();
  17139. if (source.environment !== null) this.environment = source.environment.clone();
  17140. if (source.fog !== null) this.fog = source.fog.clone();
  17141. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  17142. this.autoUpdate = source.autoUpdate;
  17143. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17144. return this;
  17145. }
  17146. toJSON(meta) {
  17147. const data = super.toJSON(meta);
  17148. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  17149. return data;
  17150. }
  17151. }
  17152. class InterleavedBuffer {
  17153. constructor(array, stride) {
  17154. this.isInterleavedBuffer = true;
  17155. this.array = array;
  17156. this.stride = stride;
  17157. this.count = array !== undefined ? array.length / stride : 0;
  17158. this.usage = StaticDrawUsage;
  17159. this.updateRange = {
  17160. offset: 0,
  17161. count: -1
  17162. };
  17163. this.version = 0;
  17164. this.uuid = generateUUID();
  17165. }
  17166. onUploadCallback() {}
  17167. set needsUpdate(value) {
  17168. if (value === true) this.version++;
  17169. }
  17170. setUsage(value) {
  17171. this.usage = value;
  17172. return this;
  17173. }
  17174. copy(source) {
  17175. this.array = new source.array.constructor(source.array);
  17176. this.count = source.count;
  17177. this.stride = source.stride;
  17178. this.usage = source.usage;
  17179. return this;
  17180. }
  17181. copyAt(index1, attribute, index2) {
  17182. index1 *= this.stride;
  17183. index2 *= attribute.stride;
  17184. for (let i = 0, l = this.stride; i < l; i++) {
  17185. this.array[index1 + i] = attribute.array[index2 + i];
  17186. }
  17187. return this;
  17188. }
  17189. set(value, offset = 0) {
  17190. this.array.set(value, offset);
  17191. return this;
  17192. }
  17193. clone(data) {
  17194. if (data.arrayBuffers === undefined) {
  17195. data.arrayBuffers = {};
  17196. }
  17197. if (this.array.buffer._uuid === undefined) {
  17198. this.array.buffer._uuid = generateUUID();
  17199. }
  17200. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17201. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  17202. }
  17203. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  17204. const ib = new this.constructor(array, this.stride);
  17205. ib.setUsage(this.usage);
  17206. return ib;
  17207. }
  17208. onUpload(callback) {
  17209. this.onUploadCallback = callback;
  17210. return this;
  17211. }
  17212. toJSON(data) {
  17213. if (data.arrayBuffers === undefined) {
  17214. data.arrayBuffers = {};
  17215. } // generate UUID for array buffer if necessary
  17216. if (this.array.buffer._uuid === undefined) {
  17217. this.array.buffer._uuid = generateUUID();
  17218. }
  17219. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17220. data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer));
  17221. } //
  17222. return {
  17223. uuid: this.uuid,
  17224. buffer: this.array.buffer._uuid,
  17225. type: this.array.constructor.name,
  17226. stride: this.stride
  17227. };
  17228. }
  17229. }
  17230. const _vector$6 = /*@__PURE__*/new Vector3();
  17231. class InterleavedBufferAttribute {
  17232. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  17233. this.isInterleavedBufferAttribute = true;
  17234. this.name = '';
  17235. this.data = interleavedBuffer;
  17236. this.itemSize = itemSize;
  17237. this.offset = offset;
  17238. this.normalized = normalized === true;
  17239. }
  17240. get count() {
  17241. return this.data.count;
  17242. }
  17243. get array() {
  17244. return this.data.array;
  17245. }
  17246. set needsUpdate(value) {
  17247. this.data.needsUpdate = value;
  17248. }
  17249. applyMatrix4(m) {
  17250. for (let i = 0, l = this.data.count; i < l; i++) {
  17251. _vector$6.fromBufferAttribute(this, i);
  17252. _vector$6.applyMatrix4(m);
  17253. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17254. }
  17255. return this;
  17256. }
  17257. applyNormalMatrix(m) {
  17258. for (let i = 0, l = this.count; i < l; i++) {
  17259. _vector$6.fromBufferAttribute(this, i);
  17260. _vector$6.applyNormalMatrix(m);
  17261. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17262. }
  17263. return this;
  17264. }
  17265. transformDirection(m) {
  17266. for (let i = 0, l = this.count; i < l; i++) {
  17267. _vector$6.fromBufferAttribute(this, i);
  17268. _vector$6.transformDirection(m);
  17269. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17270. }
  17271. return this;
  17272. }
  17273. setX(index, x) {
  17274. if (this.normalized) x = normalize(x, this.array);
  17275. this.data.array[index * this.data.stride + this.offset] = x;
  17276. return this;
  17277. }
  17278. setY(index, y) {
  17279. if (this.normalized) y = normalize(y, this.array);
  17280. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17281. return this;
  17282. }
  17283. setZ(index, z) {
  17284. if (this.normalized) z = normalize(z, this.array);
  17285. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17286. return this;
  17287. }
  17288. setW(index, w) {
  17289. if (this.normalized) w = normalize(w, this.array);
  17290. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17291. return this;
  17292. }
  17293. getX(index) {
  17294. let x = this.data.array[index * this.data.stride + this.offset];
  17295. if (this.normalized) x = denormalize(x, this.array);
  17296. return x;
  17297. }
  17298. getY(index) {
  17299. let y = this.data.array[index * this.data.stride + this.offset + 1];
  17300. if (this.normalized) y = denormalize(y, this.array);
  17301. return y;
  17302. }
  17303. getZ(index) {
  17304. let z = this.data.array[index * this.data.stride + this.offset + 2];
  17305. if (this.normalized) z = denormalize(z, this.array);
  17306. return z;
  17307. }
  17308. getW(index) {
  17309. let w = this.data.array[index * this.data.stride + this.offset + 3];
  17310. if (this.normalized) w = denormalize(w, this.array);
  17311. return w;
  17312. }
  17313. setXY(index, x, y) {
  17314. index = index * this.data.stride + this.offset;
  17315. if (this.normalized) {
  17316. x = normalize(x, this.array);
  17317. y = normalize(y, this.array);
  17318. }
  17319. this.data.array[index + 0] = x;
  17320. this.data.array[index + 1] = y;
  17321. return this;
  17322. }
  17323. setXYZ(index, x, y, z) {
  17324. index = index * this.data.stride + this.offset;
  17325. if (this.normalized) {
  17326. x = normalize(x, this.array);
  17327. y = normalize(y, this.array);
  17328. z = normalize(z, this.array);
  17329. }
  17330. this.data.array[index + 0] = x;
  17331. this.data.array[index + 1] = y;
  17332. this.data.array[index + 2] = z;
  17333. return this;
  17334. }
  17335. setXYZW(index, x, y, z, w) {
  17336. index = index * this.data.stride + this.offset;
  17337. if (this.normalized) {
  17338. x = normalize(x, this.array);
  17339. y = normalize(y, this.array);
  17340. z = normalize(z, this.array);
  17341. w = normalize(w, this.array);
  17342. }
  17343. this.data.array[index + 0] = x;
  17344. this.data.array[index + 1] = y;
  17345. this.data.array[index + 2] = z;
  17346. this.data.array[index + 3] = w;
  17347. return this;
  17348. }
  17349. clone(data) {
  17350. if (data === undefined) {
  17351. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.');
  17352. const array = [];
  17353. for (let i = 0; i < this.count; i++) {
  17354. const index = i * this.data.stride + this.offset;
  17355. for (let j = 0; j < this.itemSize; j++) {
  17356. array.push(this.data.array[index + j]);
  17357. }
  17358. }
  17359. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  17360. } else {
  17361. if (data.interleavedBuffers === undefined) {
  17362. data.interleavedBuffers = {};
  17363. }
  17364. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17365. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  17366. }
  17367. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  17368. }
  17369. }
  17370. toJSON(data) {
  17371. if (data === undefined) {
  17372. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.');
  17373. const array = [];
  17374. for (let i = 0; i < this.count; i++) {
  17375. const index = i * this.data.stride + this.offset;
  17376. for (let j = 0; j < this.itemSize; j++) {
  17377. array.push(this.data.array[index + j]);
  17378. }
  17379. } // deinterleave data and save it as an ordinary buffer attribute for now
  17380. return {
  17381. itemSize: this.itemSize,
  17382. type: this.array.constructor.name,
  17383. array: array,
  17384. normalized: this.normalized
  17385. };
  17386. } else {
  17387. // save as true interleaved attribtue
  17388. if (data.interleavedBuffers === undefined) {
  17389. data.interleavedBuffers = {};
  17390. }
  17391. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17392. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  17393. }
  17394. return {
  17395. isInterleavedBufferAttribute: true,
  17396. itemSize: this.itemSize,
  17397. data: this.data.uuid,
  17398. offset: this.offset,
  17399. normalized: this.normalized
  17400. };
  17401. }
  17402. }
  17403. }
  17404. class SpriteMaterial extends Material {
  17405. constructor(parameters) {
  17406. super();
  17407. this.isSpriteMaterial = true;
  17408. this.type = 'SpriteMaterial';
  17409. this.color = new Color(0xffffff);
  17410. this.map = null;
  17411. this.alphaMap = null;
  17412. this.rotation = 0;
  17413. this.sizeAttenuation = true;
  17414. this.transparent = true;
  17415. this.fog = true;
  17416. this.setValues(parameters);
  17417. }
  17418. copy(source) {
  17419. super.copy(source);
  17420. this.color.copy(source.color);
  17421. this.map = source.map;
  17422. this.alphaMap = source.alphaMap;
  17423. this.rotation = source.rotation;
  17424. this.sizeAttenuation = source.sizeAttenuation;
  17425. this.fog = source.fog;
  17426. return this;
  17427. }
  17428. }
  17429. let _geometry;
  17430. const _intersectPoint = /*@__PURE__*/new Vector3();
  17431. const _worldScale = /*@__PURE__*/new Vector3();
  17432. const _mvPosition = /*@__PURE__*/new Vector3();
  17433. const _alignedPosition = /*@__PURE__*/new Vector2();
  17434. const _rotatedPosition = /*@__PURE__*/new Vector2();
  17435. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  17436. const _vA = /*@__PURE__*/new Vector3();
  17437. const _vB = /*@__PURE__*/new Vector3();
  17438. const _vC = /*@__PURE__*/new Vector3();
  17439. const _uvA = /*@__PURE__*/new Vector2();
  17440. const _uvB = /*@__PURE__*/new Vector2();
  17441. const _uvC = /*@__PURE__*/new Vector2();
  17442. class Sprite extends Object3D {
  17443. constructor(material) {
  17444. super();
  17445. this.isSprite = true;
  17446. this.type = 'Sprite';
  17447. if (_geometry === undefined) {
  17448. _geometry = new BufferGeometry();
  17449. 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]);
  17450. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17451. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17452. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17453. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17454. }
  17455. this.geometry = _geometry;
  17456. this.material = material !== undefined ? material : new SpriteMaterial();
  17457. this.center = new Vector2(0.5, 0.5);
  17458. }
  17459. raycast(raycaster, intersects) {
  17460. if (raycaster.camera === null) {
  17461. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17462. }
  17463. _worldScale.setFromMatrixScale(this.matrixWorld);
  17464. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17465. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17466. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17467. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17468. _worldScale.multiplyScalar(-_mvPosition.z);
  17469. }
  17470. const rotation = this.material.rotation;
  17471. let sin, cos;
  17472. if (rotation !== 0) {
  17473. cos = Math.cos(rotation);
  17474. sin = Math.sin(rotation);
  17475. }
  17476. const center = this.center;
  17477. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17478. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17479. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17480. _uvA.set(0, 0);
  17481. _uvB.set(1, 0);
  17482. _uvC.set(1, 1); // check first triangle
  17483. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  17484. if (intersect === null) {
  17485. // check second triangle
  17486. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17487. _uvB.set(0, 1);
  17488. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  17489. if (intersect === null) {
  17490. return;
  17491. }
  17492. }
  17493. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17494. if (distance < raycaster.near || distance > raycaster.far) return;
  17495. intersects.push({
  17496. distance: distance,
  17497. point: _intersectPoint.clone(),
  17498. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  17499. face: null,
  17500. object: this
  17501. });
  17502. }
  17503. copy(source, recursive) {
  17504. super.copy(source, recursive);
  17505. if (source.center !== undefined) this.center.copy(source.center);
  17506. this.material = source.material;
  17507. return this;
  17508. }
  17509. }
  17510. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17511. // compute position in camera space
  17512. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17513. if (sin !== undefined) {
  17514. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17515. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17516. } else {
  17517. _rotatedPosition.copy(_alignedPosition);
  17518. }
  17519. vertexPosition.copy(mvPosition);
  17520. vertexPosition.x += _rotatedPosition.x;
  17521. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17522. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17523. }
  17524. const _v1$2 = /*@__PURE__*/new Vector3();
  17525. const _v2$1 = /*@__PURE__*/new Vector3();
  17526. class LOD extends Object3D {
  17527. constructor() {
  17528. super();
  17529. this._currentLevel = 0;
  17530. this.type = 'LOD';
  17531. Object.defineProperties(this, {
  17532. levels: {
  17533. enumerable: true,
  17534. value: []
  17535. },
  17536. isLOD: {
  17537. value: true
  17538. }
  17539. });
  17540. this.autoUpdate = true;
  17541. }
  17542. copy(source) {
  17543. super.copy(source, false);
  17544. const levels = source.levels;
  17545. for (let i = 0, l = levels.length; i < l; i++) {
  17546. const level = levels[i];
  17547. this.addLevel(level.object.clone(), level.distance);
  17548. }
  17549. this.autoUpdate = source.autoUpdate;
  17550. return this;
  17551. }
  17552. addLevel(object, distance = 0) {
  17553. distance = Math.abs(distance);
  17554. const levels = this.levels;
  17555. let l;
  17556. for (l = 0; l < levels.length; l++) {
  17557. if (distance < levels[l].distance) {
  17558. break;
  17559. }
  17560. }
  17561. levels.splice(l, 0, {
  17562. distance: distance,
  17563. object: object
  17564. });
  17565. this.add(object);
  17566. return this;
  17567. }
  17568. getCurrentLevel() {
  17569. return this._currentLevel;
  17570. }
  17571. getObjectForDistance(distance) {
  17572. const levels = this.levels;
  17573. if (levels.length > 0) {
  17574. let i, l;
  17575. for (i = 1, l = levels.length; i < l; i++) {
  17576. if (distance < levels[i].distance) {
  17577. break;
  17578. }
  17579. }
  17580. return levels[i - 1].object;
  17581. }
  17582. return null;
  17583. }
  17584. raycast(raycaster, intersects) {
  17585. const levels = this.levels;
  17586. if (levels.length > 0) {
  17587. _v1$2.setFromMatrixPosition(this.matrixWorld);
  17588. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  17589. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17590. }
  17591. }
  17592. update(camera) {
  17593. const levels = this.levels;
  17594. if (levels.length > 1) {
  17595. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  17596. _v2$1.setFromMatrixPosition(this.matrixWorld);
  17597. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  17598. levels[0].object.visible = true;
  17599. let i, l;
  17600. for (i = 1, l = levels.length; i < l; i++) {
  17601. if (distance >= levels[i].distance) {
  17602. levels[i - 1].object.visible = false;
  17603. levels[i].object.visible = true;
  17604. } else {
  17605. break;
  17606. }
  17607. }
  17608. this._currentLevel = i - 1;
  17609. for (; i < l; i++) {
  17610. levels[i].object.visible = false;
  17611. }
  17612. }
  17613. }
  17614. toJSON(meta) {
  17615. const data = super.toJSON(meta);
  17616. if (this.autoUpdate === false) data.object.autoUpdate = false;
  17617. data.object.levels = [];
  17618. const levels = this.levels;
  17619. for (let i = 0, l = levels.length; i < l; i++) {
  17620. const level = levels[i];
  17621. data.object.levels.push({
  17622. object: level.object.uuid,
  17623. distance: level.distance
  17624. });
  17625. }
  17626. return data;
  17627. }
  17628. }
  17629. const _basePosition = /*@__PURE__*/new Vector3();
  17630. const _skinIndex = /*@__PURE__*/new Vector4();
  17631. const _skinWeight = /*@__PURE__*/new Vector4();
  17632. const _vector$5 = /*@__PURE__*/new Vector3();
  17633. const _matrix = /*@__PURE__*/new Matrix4();
  17634. class SkinnedMesh extends Mesh {
  17635. constructor(geometry, material) {
  17636. super(geometry, material);
  17637. this.isSkinnedMesh = true;
  17638. this.type = 'SkinnedMesh';
  17639. this.bindMode = 'attached';
  17640. this.bindMatrix = new Matrix4();
  17641. this.bindMatrixInverse = new Matrix4();
  17642. }
  17643. copy(source, recursive) {
  17644. super.copy(source, recursive);
  17645. this.bindMode = source.bindMode;
  17646. this.bindMatrix.copy(source.bindMatrix);
  17647. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  17648. this.skeleton = source.skeleton;
  17649. return this;
  17650. }
  17651. bind(skeleton, bindMatrix) {
  17652. this.skeleton = skeleton;
  17653. if (bindMatrix === undefined) {
  17654. this.updateMatrixWorld(true);
  17655. this.skeleton.calculateInverses();
  17656. bindMatrix = this.matrixWorld;
  17657. }
  17658. this.bindMatrix.copy(bindMatrix);
  17659. this.bindMatrixInverse.copy(bindMatrix).invert();
  17660. }
  17661. pose() {
  17662. this.skeleton.pose();
  17663. }
  17664. normalizeSkinWeights() {
  17665. const vector = new Vector4();
  17666. const skinWeight = this.geometry.attributes.skinWeight;
  17667. for (let i = 0, l = skinWeight.count; i < l; i++) {
  17668. vector.fromBufferAttribute(skinWeight, i);
  17669. const scale = 1.0 / vector.manhattanLength();
  17670. if (scale !== Infinity) {
  17671. vector.multiplyScalar(scale);
  17672. } else {
  17673. vector.set(1, 0, 0, 0); // do something reasonable
  17674. }
  17675. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17676. }
  17677. }
  17678. updateMatrixWorld(force) {
  17679. super.updateMatrixWorld(force);
  17680. if (this.bindMode === 'attached') {
  17681. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  17682. } else if (this.bindMode === 'detached') {
  17683. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  17684. } else {
  17685. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17686. }
  17687. }
  17688. boneTransform(index, target) {
  17689. const skeleton = this.skeleton;
  17690. const geometry = this.geometry;
  17691. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  17692. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  17693. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  17694. target.set(0, 0, 0);
  17695. for (let i = 0; i < 4; i++) {
  17696. const weight = _skinWeight.getComponent(i);
  17697. if (weight !== 0) {
  17698. const boneIndex = _skinIndex.getComponent(i);
  17699. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  17700. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  17701. }
  17702. }
  17703. return target.applyMatrix4(this.bindMatrixInverse);
  17704. }
  17705. }
  17706. class Bone extends Object3D {
  17707. constructor() {
  17708. super();
  17709. this.isBone = true;
  17710. this.type = 'Bone';
  17711. }
  17712. }
  17713. class DataTexture extends Texture {
  17714. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  17715. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17716. this.isDataTexture = true;
  17717. this.image = {
  17718. data: data,
  17719. width: width,
  17720. height: height
  17721. };
  17722. this.generateMipmaps = false;
  17723. this.flipY = false;
  17724. this.unpackAlignment = 1;
  17725. }
  17726. }
  17727. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  17728. const _identityMatrix = /*@__PURE__*/new Matrix4();
  17729. class Skeleton {
  17730. constructor(bones = [], boneInverses = []) {
  17731. this.uuid = generateUUID();
  17732. this.bones = bones.slice(0);
  17733. this.boneInverses = boneInverses;
  17734. this.boneMatrices = null;
  17735. this.boneTexture = null;
  17736. this.boneTextureSize = 0;
  17737. this.frame = -1;
  17738. this.init();
  17739. }
  17740. init() {
  17741. const bones = this.bones;
  17742. const boneInverses = this.boneInverses;
  17743. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  17744. if (boneInverses.length === 0) {
  17745. this.calculateInverses();
  17746. } else {
  17747. // handle special case
  17748. if (bones.length !== boneInverses.length) {
  17749. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  17750. this.boneInverses = [];
  17751. for (let i = 0, il = this.bones.length; i < il; i++) {
  17752. this.boneInverses.push(new Matrix4());
  17753. }
  17754. }
  17755. }
  17756. }
  17757. calculateInverses() {
  17758. this.boneInverses.length = 0;
  17759. for (let i = 0, il = this.bones.length; i < il; i++) {
  17760. const inverse = new Matrix4();
  17761. if (this.bones[i]) {
  17762. inverse.copy(this.bones[i].matrixWorld).invert();
  17763. }
  17764. this.boneInverses.push(inverse);
  17765. }
  17766. }
  17767. pose() {
  17768. // recover the bind-time world matrices
  17769. for (let i = 0, il = this.bones.length; i < il; i++) {
  17770. const bone = this.bones[i];
  17771. if (bone) {
  17772. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  17773. }
  17774. } // compute the local matrices, positions, rotations and scales
  17775. for (let i = 0, il = this.bones.length; i < il; i++) {
  17776. const bone = this.bones[i];
  17777. if (bone) {
  17778. if (bone.parent && bone.parent.isBone) {
  17779. bone.matrix.copy(bone.parent.matrixWorld).invert();
  17780. bone.matrix.multiply(bone.matrixWorld);
  17781. } else {
  17782. bone.matrix.copy(bone.matrixWorld);
  17783. }
  17784. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17785. }
  17786. }
  17787. }
  17788. update() {
  17789. const bones = this.bones;
  17790. const boneInverses = this.boneInverses;
  17791. const boneMatrices = this.boneMatrices;
  17792. const boneTexture = this.boneTexture; // flatten bone matrices to array
  17793. for (let i = 0, il = bones.length; i < il; i++) {
  17794. // compute the offset between the current and the original transform
  17795. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17796. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17797. _offsetMatrix.toArray(boneMatrices, i * 16);
  17798. }
  17799. if (boneTexture !== null) {
  17800. boneTexture.needsUpdate = true;
  17801. }
  17802. }
  17803. clone() {
  17804. return new Skeleton(this.bones, this.boneInverses);
  17805. }
  17806. computeBoneTexture() {
  17807. // layout (1 matrix = 4 pixels)
  17808. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17809. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17810. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17811. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17812. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17813. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  17814. size = ceilPowerOfTwo(size);
  17815. size = Math.max(size, 4);
  17816. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  17817. boneMatrices.set(this.boneMatrices); // copy current values
  17818. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  17819. boneTexture.needsUpdate = true;
  17820. this.boneMatrices = boneMatrices;
  17821. this.boneTexture = boneTexture;
  17822. this.boneTextureSize = size;
  17823. return this;
  17824. }
  17825. getBoneByName(name) {
  17826. for (let i = 0, il = this.bones.length; i < il; i++) {
  17827. const bone = this.bones[i];
  17828. if (bone.name === name) {
  17829. return bone;
  17830. }
  17831. }
  17832. return undefined;
  17833. }
  17834. dispose() {
  17835. if (this.boneTexture !== null) {
  17836. this.boneTexture.dispose();
  17837. this.boneTexture = null;
  17838. }
  17839. }
  17840. fromJSON(json, bones) {
  17841. this.uuid = json.uuid;
  17842. for (let i = 0, l = json.bones.length; i < l; i++) {
  17843. const uuid = json.bones[i];
  17844. let bone = bones[uuid];
  17845. if (bone === undefined) {
  17846. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  17847. bone = new Bone();
  17848. }
  17849. this.bones.push(bone);
  17850. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  17851. }
  17852. this.init();
  17853. return this;
  17854. }
  17855. toJSON() {
  17856. const data = {
  17857. metadata: {
  17858. version: 4.5,
  17859. type: 'Skeleton',
  17860. generator: 'Skeleton.toJSON'
  17861. },
  17862. bones: [],
  17863. boneInverses: []
  17864. };
  17865. data.uuid = this.uuid;
  17866. const bones = this.bones;
  17867. const boneInverses = this.boneInverses;
  17868. for (let i = 0, l = bones.length; i < l; i++) {
  17869. const bone = bones[i];
  17870. data.bones.push(bone.uuid);
  17871. const boneInverse = boneInverses[i];
  17872. data.boneInverses.push(boneInverse.toArray());
  17873. }
  17874. return data;
  17875. }
  17876. }
  17877. class InstancedBufferAttribute extends BufferAttribute {
  17878. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17879. super(array, itemSize, normalized);
  17880. this.isInstancedBufferAttribute = true;
  17881. this.meshPerAttribute = meshPerAttribute;
  17882. }
  17883. copy(source) {
  17884. super.copy(source);
  17885. this.meshPerAttribute = source.meshPerAttribute;
  17886. return this;
  17887. }
  17888. toJSON() {
  17889. const data = super.toJSON();
  17890. data.meshPerAttribute = this.meshPerAttribute;
  17891. data.isInstancedBufferAttribute = true;
  17892. return data;
  17893. }
  17894. }
  17895. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17896. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17897. const _instanceIntersects = [];
  17898. const _mesh = /*@__PURE__*/new Mesh();
  17899. class InstancedMesh extends Mesh {
  17900. constructor(geometry, material, count) {
  17901. super(geometry, material);
  17902. this.isInstancedMesh = true;
  17903. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17904. this.instanceColor = null;
  17905. this.count = count;
  17906. this.frustumCulled = false;
  17907. }
  17908. copy(source, recursive) {
  17909. super.copy(source, recursive);
  17910. this.instanceMatrix.copy(source.instanceMatrix);
  17911. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17912. this.count = source.count;
  17913. return this;
  17914. }
  17915. getColorAt(index, color) {
  17916. color.fromArray(this.instanceColor.array, index * 3);
  17917. }
  17918. getMatrixAt(index, matrix) {
  17919. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17920. }
  17921. raycast(raycaster, intersects) {
  17922. const matrixWorld = this.matrixWorld;
  17923. const raycastTimes = this.count;
  17924. _mesh.geometry = this.geometry;
  17925. _mesh.material = this.material;
  17926. if (_mesh.material === undefined) return;
  17927. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17928. // calculate the world matrix for each instance
  17929. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17930. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17931. _mesh.matrixWorld = _instanceWorldMatrix;
  17932. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17933. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17934. const intersect = _instanceIntersects[i];
  17935. intersect.instanceId = instanceId;
  17936. intersect.object = this;
  17937. intersects.push(intersect);
  17938. }
  17939. _instanceIntersects.length = 0;
  17940. }
  17941. }
  17942. setColorAt(index, color) {
  17943. if (this.instanceColor === null) {
  17944. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17945. }
  17946. color.toArray(this.instanceColor.array, index * 3);
  17947. }
  17948. setMatrixAt(index, matrix) {
  17949. matrix.toArray(this.instanceMatrix.array, index * 16);
  17950. }
  17951. updateMorphTargets() {}
  17952. dispose() {
  17953. this.dispatchEvent({
  17954. type: 'dispose'
  17955. });
  17956. }
  17957. }
  17958. class LineBasicMaterial extends Material {
  17959. constructor(parameters) {
  17960. super();
  17961. this.isLineBasicMaterial = true;
  17962. this.type = 'LineBasicMaterial';
  17963. this.color = new Color(0xffffff);
  17964. this.linewidth = 1;
  17965. this.linecap = 'round';
  17966. this.linejoin = 'round';
  17967. this.fog = true;
  17968. this.setValues(parameters);
  17969. }
  17970. copy(source) {
  17971. super.copy(source);
  17972. this.color.copy(source.color);
  17973. this.linewidth = source.linewidth;
  17974. this.linecap = source.linecap;
  17975. this.linejoin = source.linejoin;
  17976. this.fog = source.fog;
  17977. return this;
  17978. }
  17979. }
  17980. const _start$1 = /*@__PURE__*/new Vector3();
  17981. const _end$1 = /*@__PURE__*/new Vector3();
  17982. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17983. const _ray$1 = /*@__PURE__*/new Ray();
  17984. const _sphere$1 = /*@__PURE__*/new Sphere();
  17985. class Line extends Object3D {
  17986. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17987. super();
  17988. this.isLine = true;
  17989. this.type = 'Line';
  17990. this.geometry = geometry;
  17991. this.material = material;
  17992. this.updateMorphTargets();
  17993. }
  17994. copy(source, recursive) {
  17995. super.copy(source, recursive);
  17996. this.material = source.material;
  17997. this.geometry = source.geometry;
  17998. return this;
  17999. }
  18000. computeLineDistances() {
  18001. const geometry = this.geometry; // we assume non-indexed geometry
  18002. if (geometry.index === null) {
  18003. const positionAttribute = geometry.attributes.position;
  18004. const lineDistances = [0];
  18005. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  18006. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  18007. _end$1.fromBufferAttribute(positionAttribute, i);
  18008. lineDistances[i] = lineDistances[i - 1];
  18009. lineDistances[i] += _start$1.distanceTo(_end$1);
  18010. }
  18011. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18012. } else {
  18013. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18014. }
  18015. return this;
  18016. }
  18017. raycast(raycaster, intersects) {
  18018. const geometry = this.geometry;
  18019. const matrixWorld = this.matrixWorld;
  18020. const threshold = raycaster.params.Line.threshold;
  18021. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  18022. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18023. _sphere$1.copy(geometry.boundingSphere);
  18024. _sphere$1.applyMatrix4(matrixWorld);
  18025. _sphere$1.radius += threshold;
  18026. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  18027. _inverseMatrix$1.copy(matrixWorld).invert();
  18028. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  18029. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18030. const localThresholdSq = localThreshold * localThreshold;
  18031. const vStart = new Vector3();
  18032. const vEnd = new Vector3();
  18033. const interSegment = new Vector3();
  18034. const interRay = new Vector3();
  18035. const step = this.isLineSegments ? 2 : 1;
  18036. const index = geometry.index;
  18037. const attributes = geometry.attributes;
  18038. const positionAttribute = attributes.position;
  18039. if (index !== null) {
  18040. const start = Math.max(0, drawRange.start);
  18041. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18042. for (let i = start, l = end - 1; i < l; i += step) {
  18043. const a = index.getX(i);
  18044. const b = index.getX(i + 1);
  18045. vStart.fromBufferAttribute(positionAttribute, a);
  18046. vEnd.fromBufferAttribute(positionAttribute, b);
  18047. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18048. if (distSq > localThresholdSq) continue;
  18049. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18050. const distance = raycaster.ray.origin.distanceTo(interRay);
  18051. if (distance < raycaster.near || distance > raycaster.far) continue;
  18052. intersects.push({
  18053. distance: distance,
  18054. // What do we want? intersection point on the ray or on the segment??
  18055. // point: raycaster.ray.at( distance ),
  18056. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18057. index: i,
  18058. face: null,
  18059. faceIndex: null,
  18060. object: this
  18061. });
  18062. }
  18063. } else {
  18064. const start = Math.max(0, drawRange.start);
  18065. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18066. for (let i = start, l = end - 1; i < l; i += step) {
  18067. vStart.fromBufferAttribute(positionAttribute, i);
  18068. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  18069. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18070. if (distSq > localThresholdSq) continue;
  18071. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18072. const distance = raycaster.ray.origin.distanceTo(interRay);
  18073. if (distance < raycaster.near || distance > raycaster.far) continue;
  18074. intersects.push({
  18075. distance: distance,
  18076. // What do we want? intersection point on the ray or on the segment??
  18077. // point: raycaster.ray.at( distance ),
  18078. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18079. index: i,
  18080. face: null,
  18081. faceIndex: null,
  18082. object: this
  18083. });
  18084. }
  18085. }
  18086. }
  18087. updateMorphTargets() {
  18088. const geometry = this.geometry;
  18089. const morphAttributes = geometry.morphAttributes;
  18090. const keys = Object.keys(morphAttributes);
  18091. if (keys.length > 0) {
  18092. const morphAttribute = morphAttributes[keys[0]];
  18093. if (morphAttribute !== undefined) {
  18094. this.morphTargetInfluences = [];
  18095. this.morphTargetDictionary = {};
  18096. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18097. const name = morphAttribute[m].name || String(m);
  18098. this.morphTargetInfluences.push(0);
  18099. this.morphTargetDictionary[name] = m;
  18100. }
  18101. }
  18102. }
  18103. }
  18104. }
  18105. const _start = /*@__PURE__*/new Vector3();
  18106. const _end = /*@__PURE__*/new Vector3();
  18107. class LineSegments extends Line {
  18108. constructor(geometry, material) {
  18109. super(geometry, material);
  18110. this.isLineSegments = true;
  18111. this.type = 'LineSegments';
  18112. }
  18113. computeLineDistances() {
  18114. const geometry = this.geometry; // we assume non-indexed geometry
  18115. if (geometry.index === null) {
  18116. const positionAttribute = geometry.attributes.position;
  18117. const lineDistances = [];
  18118. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  18119. _start.fromBufferAttribute(positionAttribute, i);
  18120. _end.fromBufferAttribute(positionAttribute, i + 1);
  18121. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  18122. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  18123. }
  18124. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18125. } else {
  18126. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18127. }
  18128. return this;
  18129. }
  18130. }
  18131. class LineLoop extends Line {
  18132. constructor(geometry, material) {
  18133. super(geometry, material);
  18134. this.isLineLoop = true;
  18135. this.type = 'LineLoop';
  18136. }
  18137. }
  18138. class PointsMaterial extends Material {
  18139. constructor(parameters) {
  18140. super();
  18141. this.isPointsMaterial = true;
  18142. this.type = 'PointsMaterial';
  18143. this.color = new Color(0xffffff);
  18144. this.map = null;
  18145. this.alphaMap = null;
  18146. this.size = 1;
  18147. this.sizeAttenuation = true;
  18148. this.fog = true;
  18149. this.setValues(parameters);
  18150. }
  18151. copy(source) {
  18152. super.copy(source);
  18153. this.color.copy(source.color);
  18154. this.map = source.map;
  18155. this.alphaMap = source.alphaMap;
  18156. this.size = source.size;
  18157. this.sizeAttenuation = source.sizeAttenuation;
  18158. this.fog = source.fog;
  18159. return this;
  18160. }
  18161. }
  18162. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  18163. const _ray = /*@__PURE__*/new Ray();
  18164. const _sphere = /*@__PURE__*/new Sphere();
  18165. const _position$2 = /*@__PURE__*/new Vector3();
  18166. class Points extends Object3D {
  18167. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  18168. super();
  18169. this.isPoints = true;
  18170. this.type = 'Points';
  18171. this.geometry = geometry;
  18172. this.material = material;
  18173. this.updateMorphTargets();
  18174. }
  18175. copy(source, recursive) {
  18176. super.copy(source, recursive);
  18177. this.material = source.material;
  18178. this.geometry = source.geometry;
  18179. return this;
  18180. }
  18181. raycast(raycaster, intersects) {
  18182. const geometry = this.geometry;
  18183. const matrixWorld = this.matrixWorld;
  18184. const threshold = raycaster.params.Points.threshold;
  18185. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  18186. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18187. _sphere.copy(geometry.boundingSphere);
  18188. _sphere.applyMatrix4(matrixWorld);
  18189. _sphere.radius += threshold;
  18190. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  18191. _inverseMatrix.copy(matrixWorld).invert();
  18192. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  18193. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18194. const localThresholdSq = localThreshold * localThreshold;
  18195. const index = geometry.index;
  18196. const attributes = geometry.attributes;
  18197. const positionAttribute = attributes.position;
  18198. if (index !== null) {
  18199. const start = Math.max(0, drawRange.start);
  18200. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18201. for (let i = start, il = end; i < il; i++) {
  18202. const a = index.getX(i);
  18203. _position$2.fromBufferAttribute(positionAttribute, a);
  18204. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18205. }
  18206. } else {
  18207. const start = Math.max(0, drawRange.start);
  18208. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18209. for (let i = start, l = end; i < l; i++) {
  18210. _position$2.fromBufferAttribute(positionAttribute, i);
  18211. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18212. }
  18213. }
  18214. }
  18215. updateMorphTargets() {
  18216. const geometry = this.geometry;
  18217. const morphAttributes = geometry.morphAttributes;
  18218. const keys = Object.keys(morphAttributes);
  18219. if (keys.length > 0) {
  18220. const morphAttribute = morphAttributes[keys[0]];
  18221. if (morphAttribute !== undefined) {
  18222. this.morphTargetInfluences = [];
  18223. this.morphTargetDictionary = {};
  18224. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18225. const name = morphAttribute[m].name || String(m);
  18226. this.morphTargetInfluences.push(0);
  18227. this.morphTargetDictionary[name] = m;
  18228. }
  18229. }
  18230. }
  18231. }
  18232. }
  18233. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  18234. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  18235. if (rayPointDistanceSq < localThresholdSq) {
  18236. const intersectPoint = new Vector3();
  18237. _ray.closestPointToPoint(point, intersectPoint);
  18238. intersectPoint.applyMatrix4(matrixWorld);
  18239. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  18240. if (distance < raycaster.near || distance > raycaster.far) return;
  18241. intersects.push({
  18242. distance: distance,
  18243. distanceToRay: Math.sqrt(rayPointDistanceSq),
  18244. point: intersectPoint,
  18245. index: index,
  18246. face: null,
  18247. object: object
  18248. });
  18249. }
  18250. }
  18251. class VideoTexture extends Texture {
  18252. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18253. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18254. this.isVideoTexture = true;
  18255. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18256. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18257. this.generateMipmaps = false;
  18258. const scope = this;
  18259. function updateVideo() {
  18260. scope.needsUpdate = true;
  18261. video.requestVideoFrameCallback(updateVideo);
  18262. }
  18263. if ('requestVideoFrameCallback' in video) {
  18264. video.requestVideoFrameCallback(updateVideo);
  18265. }
  18266. }
  18267. clone() {
  18268. return new this.constructor(this.image).copy(this);
  18269. }
  18270. update() {
  18271. const video = this.image;
  18272. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  18273. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  18274. this.needsUpdate = true;
  18275. }
  18276. }
  18277. }
  18278. class FramebufferTexture extends Texture {
  18279. constructor(width, height, format) {
  18280. super({
  18281. width,
  18282. height
  18283. });
  18284. this.isFramebufferTexture = true;
  18285. this.format = format;
  18286. this.magFilter = NearestFilter;
  18287. this.minFilter = NearestFilter;
  18288. this.generateMipmaps = false;
  18289. this.needsUpdate = true;
  18290. }
  18291. }
  18292. class CompressedTexture extends Texture {
  18293. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  18294. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18295. this.isCompressedTexture = true;
  18296. this.image = {
  18297. width: width,
  18298. height: height
  18299. };
  18300. this.mipmaps = mipmaps; // no flipping for cube textures
  18301. // (also flipping doesn't work for compressed textures )
  18302. this.flipY = false; // can't generate mipmaps for compressed textures
  18303. // mips must be embedded in DDS files
  18304. this.generateMipmaps = false;
  18305. }
  18306. }
  18307. class CanvasTexture extends Texture {
  18308. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18309. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18310. this.isCanvasTexture = true;
  18311. this.needsUpdate = true;
  18312. }
  18313. }
  18314. /**
  18315. * Extensible curve object.
  18316. *
  18317. * Some common of curve methods:
  18318. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18319. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18320. * .getPoints(), .getSpacedPoints()
  18321. * .getLength()
  18322. * .updateArcLengths()
  18323. *
  18324. * This following curves inherit from THREE.Curve:
  18325. *
  18326. * -- 2D curves --
  18327. * THREE.ArcCurve
  18328. * THREE.CubicBezierCurve
  18329. * THREE.EllipseCurve
  18330. * THREE.LineCurve
  18331. * THREE.QuadraticBezierCurve
  18332. * THREE.SplineCurve
  18333. *
  18334. * -- 3D curves --
  18335. * THREE.CatmullRomCurve3
  18336. * THREE.CubicBezierCurve3
  18337. * THREE.LineCurve3
  18338. * THREE.QuadraticBezierCurve3
  18339. *
  18340. * A series of curves can be represented as a THREE.CurvePath.
  18341. *
  18342. **/
  18343. class Curve {
  18344. constructor() {
  18345. this.type = 'Curve';
  18346. this.arcLengthDivisions = 200;
  18347. } // Virtual base class method to overwrite and implement in subclasses
  18348. // - t [0 .. 1]
  18349. getPoint() {
  18350. console.warn('THREE.Curve: .getPoint() not implemented.');
  18351. return null;
  18352. } // Get point at relative position in curve according to arc length
  18353. // - u [0 .. 1]
  18354. getPointAt(u, optionalTarget) {
  18355. const t = this.getUtoTmapping(u);
  18356. return this.getPoint(t, optionalTarget);
  18357. } // Get sequence of points using getPoint( t )
  18358. getPoints(divisions = 5) {
  18359. const points = [];
  18360. for (let d = 0; d <= divisions; d++) {
  18361. points.push(this.getPoint(d / divisions));
  18362. }
  18363. return points;
  18364. } // Get sequence of points using getPointAt( u )
  18365. getSpacedPoints(divisions = 5) {
  18366. const points = [];
  18367. for (let d = 0; d <= divisions; d++) {
  18368. points.push(this.getPointAt(d / divisions));
  18369. }
  18370. return points;
  18371. } // Get total curve arc length
  18372. getLength() {
  18373. const lengths = this.getLengths();
  18374. return lengths[lengths.length - 1];
  18375. } // Get list of cumulative segment lengths
  18376. getLengths(divisions = this.arcLengthDivisions) {
  18377. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18378. return this.cacheArcLengths;
  18379. }
  18380. this.needsUpdate = false;
  18381. const cache = [];
  18382. let current,
  18383. last = this.getPoint(0);
  18384. let sum = 0;
  18385. cache.push(0);
  18386. for (let p = 1; p <= divisions; p++) {
  18387. current = this.getPoint(p / divisions);
  18388. sum += current.distanceTo(last);
  18389. cache.push(sum);
  18390. last = current;
  18391. }
  18392. this.cacheArcLengths = cache;
  18393. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18394. }
  18395. updateArcLengths() {
  18396. this.needsUpdate = true;
  18397. this.getLengths();
  18398. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18399. getUtoTmapping(u, distance) {
  18400. const arcLengths = this.getLengths();
  18401. let i = 0;
  18402. const il = arcLengths.length;
  18403. let targetArcLength; // The targeted u distance value to get
  18404. if (distance) {
  18405. targetArcLength = distance;
  18406. } else {
  18407. targetArcLength = u * arcLengths[il - 1];
  18408. } // binary search for the index with largest value smaller than target u distance
  18409. let low = 0,
  18410. high = il - 1,
  18411. comparison;
  18412. while (low <= high) {
  18413. 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
  18414. comparison = arcLengths[i] - targetArcLength;
  18415. if (comparison < 0) {
  18416. low = i + 1;
  18417. } else if (comparison > 0) {
  18418. high = i - 1;
  18419. } else {
  18420. high = i;
  18421. break; // DONE
  18422. }
  18423. }
  18424. i = high;
  18425. if (arcLengths[i] === targetArcLength) {
  18426. return i / (il - 1);
  18427. } // we could get finer grain at lengths, or use simple interpolation between two points
  18428. const lengthBefore = arcLengths[i];
  18429. const lengthAfter = arcLengths[i + 1];
  18430. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18431. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18432. const t = (i + segmentFraction) / (il - 1);
  18433. return t;
  18434. } // Returns a unit vector tangent at t
  18435. // In case any sub curve does not implement its tangent derivation,
  18436. // 2 points a small delta apart will be used to find its gradient
  18437. // which seems to give a reasonable approximation
  18438. getTangent(t, optionalTarget) {
  18439. const delta = 0.0001;
  18440. let t1 = t - delta;
  18441. let t2 = t + delta; // Capping in case of danger
  18442. if (t1 < 0) t1 = 0;
  18443. if (t2 > 1) t2 = 1;
  18444. const pt1 = this.getPoint(t1);
  18445. const pt2 = this.getPoint(t2);
  18446. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18447. tangent.copy(pt2).sub(pt1).normalize();
  18448. return tangent;
  18449. }
  18450. getTangentAt(u, optionalTarget) {
  18451. const t = this.getUtoTmapping(u);
  18452. return this.getTangent(t, optionalTarget);
  18453. }
  18454. computeFrenetFrames(segments, closed) {
  18455. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18456. const normal = new Vector3();
  18457. const tangents = [];
  18458. const normals = [];
  18459. const binormals = [];
  18460. const vec = new Vector3();
  18461. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18462. for (let i = 0; i <= segments; i++) {
  18463. const u = i / segments;
  18464. tangents[i] = this.getTangentAt(u, new Vector3());
  18465. } // select an initial normal vector perpendicular to the first tangent vector,
  18466. // and in the direction of the minimum tangent xyz component
  18467. normals[0] = new Vector3();
  18468. binormals[0] = new Vector3();
  18469. let min = Number.MAX_VALUE;
  18470. const tx = Math.abs(tangents[0].x);
  18471. const ty = Math.abs(tangents[0].y);
  18472. const tz = Math.abs(tangents[0].z);
  18473. if (tx <= min) {
  18474. min = tx;
  18475. normal.set(1, 0, 0);
  18476. }
  18477. if (ty <= min) {
  18478. min = ty;
  18479. normal.set(0, 1, 0);
  18480. }
  18481. if (tz <= min) {
  18482. normal.set(0, 0, 1);
  18483. }
  18484. vec.crossVectors(tangents[0], normal).normalize();
  18485. normals[0].crossVectors(tangents[0], vec);
  18486. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18487. for (let i = 1; i <= segments; i++) {
  18488. normals[i] = normals[i - 1].clone();
  18489. binormals[i] = binormals[i - 1].clone();
  18490. vec.crossVectors(tangents[i - 1], tangents[i]);
  18491. if (vec.length() > Number.EPSILON) {
  18492. vec.normalize();
  18493. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18494. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18495. }
  18496. binormals[i].crossVectors(tangents[i], normals[i]);
  18497. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18498. if (closed === true) {
  18499. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18500. theta /= segments;
  18501. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18502. theta = -theta;
  18503. }
  18504. for (let i = 1; i <= segments; i++) {
  18505. // twist a little...
  18506. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18507. binormals[i].crossVectors(tangents[i], normals[i]);
  18508. }
  18509. }
  18510. return {
  18511. tangents: tangents,
  18512. normals: normals,
  18513. binormals: binormals
  18514. };
  18515. }
  18516. clone() {
  18517. return new this.constructor().copy(this);
  18518. }
  18519. copy(source) {
  18520. this.arcLengthDivisions = source.arcLengthDivisions;
  18521. return this;
  18522. }
  18523. toJSON() {
  18524. const data = {
  18525. metadata: {
  18526. version: 4.5,
  18527. type: 'Curve',
  18528. generator: 'Curve.toJSON'
  18529. }
  18530. };
  18531. data.arcLengthDivisions = this.arcLengthDivisions;
  18532. data.type = this.type;
  18533. return data;
  18534. }
  18535. fromJSON(json) {
  18536. this.arcLengthDivisions = json.arcLengthDivisions;
  18537. return this;
  18538. }
  18539. }
  18540. class EllipseCurve extends Curve {
  18541. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18542. super();
  18543. this.isEllipseCurve = true;
  18544. this.type = 'EllipseCurve';
  18545. this.aX = aX;
  18546. this.aY = aY;
  18547. this.xRadius = xRadius;
  18548. this.yRadius = yRadius;
  18549. this.aStartAngle = aStartAngle;
  18550. this.aEndAngle = aEndAngle;
  18551. this.aClockwise = aClockwise;
  18552. this.aRotation = aRotation;
  18553. }
  18554. getPoint(t, optionalTarget) {
  18555. const point = optionalTarget || new Vector2();
  18556. const twoPi = Math.PI * 2;
  18557. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18558. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18559. while (deltaAngle < 0) deltaAngle += twoPi;
  18560. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18561. if (deltaAngle < Number.EPSILON) {
  18562. if (samePoints) {
  18563. deltaAngle = 0;
  18564. } else {
  18565. deltaAngle = twoPi;
  18566. }
  18567. }
  18568. if (this.aClockwise === true && !samePoints) {
  18569. if (deltaAngle === twoPi) {
  18570. deltaAngle = -twoPi;
  18571. } else {
  18572. deltaAngle = deltaAngle - twoPi;
  18573. }
  18574. }
  18575. const angle = this.aStartAngle + t * deltaAngle;
  18576. let x = this.aX + this.xRadius * Math.cos(angle);
  18577. let y = this.aY + this.yRadius * Math.sin(angle);
  18578. if (this.aRotation !== 0) {
  18579. const cos = Math.cos(this.aRotation);
  18580. const sin = Math.sin(this.aRotation);
  18581. const tx = x - this.aX;
  18582. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18583. x = tx * cos - ty * sin + this.aX;
  18584. y = tx * sin + ty * cos + this.aY;
  18585. }
  18586. return point.set(x, y);
  18587. }
  18588. copy(source) {
  18589. super.copy(source);
  18590. this.aX = source.aX;
  18591. this.aY = source.aY;
  18592. this.xRadius = source.xRadius;
  18593. this.yRadius = source.yRadius;
  18594. this.aStartAngle = source.aStartAngle;
  18595. this.aEndAngle = source.aEndAngle;
  18596. this.aClockwise = source.aClockwise;
  18597. this.aRotation = source.aRotation;
  18598. return this;
  18599. }
  18600. toJSON() {
  18601. const data = super.toJSON();
  18602. data.aX = this.aX;
  18603. data.aY = this.aY;
  18604. data.xRadius = this.xRadius;
  18605. data.yRadius = this.yRadius;
  18606. data.aStartAngle = this.aStartAngle;
  18607. data.aEndAngle = this.aEndAngle;
  18608. data.aClockwise = this.aClockwise;
  18609. data.aRotation = this.aRotation;
  18610. return data;
  18611. }
  18612. fromJSON(json) {
  18613. super.fromJSON(json);
  18614. this.aX = json.aX;
  18615. this.aY = json.aY;
  18616. this.xRadius = json.xRadius;
  18617. this.yRadius = json.yRadius;
  18618. this.aStartAngle = json.aStartAngle;
  18619. this.aEndAngle = json.aEndAngle;
  18620. this.aClockwise = json.aClockwise;
  18621. this.aRotation = json.aRotation;
  18622. return this;
  18623. }
  18624. }
  18625. class ArcCurve extends EllipseCurve {
  18626. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18627. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18628. this.isArcCurve = true;
  18629. this.type = 'ArcCurve';
  18630. }
  18631. }
  18632. /**
  18633. * Centripetal CatmullRom Curve - which is useful for avoiding
  18634. * cusps and self-intersections in non-uniform catmull rom curves.
  18635. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18636. *
  18637. * curve.type accepts centripetal(default), chordal and catmullrom
  18638. * curve.tension is used for catmullrom which defaults to 0.5
  18639. */
  18640. /*
  18641. Based on an optimized c++ solution in
  18642. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18643. - http://ideone.com/NoEbVM
  18644. This CubicPoly class could be used for reusing some variables and calculations,
  18645. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18646. which can be placed in CurveUtils.
  18647. */
  18648. function CubicPoly() {
  18649. let c0 = 0,
  18650. c1 = 0,
  18651. c2 = 0,
  18652. c3 = 0;
  18653. /*
  18654. * Compute coefficients for a cubic polynomial
  18655. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18656. * such that
  18657. * p(0) = x0, p(1) = x1
  18658. * and
  18659. * p'(0) = t0, p'(1) = t1.
  18660. */
  18661. function init(x0, x1, t0, t1) {
  18662. c0 = x0;
  18663. c1 = t0;
  18664. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18665. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18666. }
  18667. return {
  18668. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18669. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18670. },
  18671. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18672. // compute tangents when parameterized in [t1,t2]
  18673. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18674. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18675. t1 *= dt1;
  18676. t2 *= dt1;
  18677. init(x1, x2, t1, t2);
  18678. },
  18679. calc: function (t) {
  18680. const t2 = t * t;
  18681. const t3 = t2 * t;
  18682. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18683. }
  18684. };
  18685. } //
  18686. const tmp = /*@__PURE__*/new Vector3();
  18687. const px = /*@__PURE__*/new CubicPoly();
  18688. const py = /*@__PURE__*/new CubicPoly();
  18689. const pz = /*@__PURE__*/new CubicPoly();
  18690. class CatmullRomCurve3 extends Curve {
  18691. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18692. super();
  18693. this.isCatmullRomCurve3 = true;
  18694. this.type = 'CatmullRomCurve3';
  18695. this.points = points;
  18696. this.closed = closed;
  18697. this.curveType = curveType;
  18698. this.tension = tension;
  18699. }
  18700. getPoint(t, optionalTarget = new Vector3()) {
  18701. const point = optionalTarget;
  18702. const points = this.points;
  18703. const l = points.length;
  18704. const p = (l - (this.closed ? 0 : 1)) * t;
  18705. let intPoint = Math.floor(p);
  18706. let weight = p - intPoint;
  18707. if (this.closed) {
  18708. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18709. } else if (weight === 0 && intPoint === l - 1) {
  18710. intPoint = l - 2;
  18711. weight = 1;
  18712. }
  18713. let p0, p3; // 4 points (p1 & p2 defined below)
  18714. if (this.closed || intPoint > 0) {
  18715. p0 = points[(intPoint - 1) % l];
  18716. } else {
  18717. // extrapolate first point
  18718. tmp.subVectors(points[0], points[1]).add(points[0]);
  18719. p0 = tmp;
  18720. }
  18721. const p1 = points[intPoint % l];
  18722. const p2 = points[(intPoint + 1) % l];
  18723. if (this.closed || intPoint + 2 < l) {
  18724. p3 = points[(intPoint + 2) % l];
  18725. } else {
  18726. // extrapolate last point
  18727. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18728. p3 = tmp;
  18729. }
  18730. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18731. // init Centripetal / Chordal Catmull-Rom
  18732. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18733. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18734. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18735. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18736. if (dt1 < 1e-4) dt1 = 1.0;
  18737. if (dt0 < 1e-4) dt0 = dt1;
  18738. if (dt2 < 1e-4) dt2 = dt1;
  18739. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18740. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18741. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18742. } else if (this.curveType === 'catmullrom') {
  18743. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18744. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18745. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18746. }
  18747. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18748. return point;
  18749. }
  18750. copy(source) {
  18751. super.copy(source);
  18752. this.points = [];
  18753. for (let i = 0, l = source.points.length; i < l; i++) {
  18754. const point = source.points[i];
  18755. this.points.push(point.clone());
  18756. }
  18757. this.closed = source.closed;
  18758. this.curveType = source.curveType;
  18759. this.tension = source.tension;
  18760. return this;
  18761. }
  18762. toJSON() {
  18763. const data = super.toJSON();
  18764. data.points = [];
  18765. for (let i = 0, l = this.points.length; i < l; i++) {
  18766. const point = this.points[i];
  18767. data.points.push(point.toArray());
  18768. }
  18769. data.closed = this.closed;
  18770. data.curveType = this.curveType;
  18771. data.tension = this.tension;
  18772. return data;
  18773. }
  18774. fromJSON(json) {
  18775. super.fromJSON(json);
  18776. this.points = [];
  18777. for (let i = 0, l = json.points.length; i < l; i++) {
  18778. const point = json.points[i];
  18779. this.points.push(new Vector3().fromArray(point));
  18780. }
  18781. this.closed = json.closed;
  18782. this.curveType = json.curveType;
  18783. this.tension = json.tension;
  18784. return this;
  18785. }
  18786. }
  18787. /**
  18788. * Bezier Curves formulas obtained from
  18789. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18790. */
  18791. function CatmullRom(t, p0, p1, p2, p3) {
  18792. const v0 = (p2 - p0) * 0.5;
  18793. const v1 = (p3 - p1) * 0.5;
  18794. const t2 = t * t;
  18795. const t3 = t * t2;
  18796. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18797. } //
  18798. function QuadraticBezierP0(t, p) {
  18799. const k = 1 - t;
  18800. return k * k * p;
  18801. }
  18802. function QuadraticBezierP1(t, p) {
  18803. return 2 * (1 - t) * t * p;
  18804. }
  18805. function QuadraticBezierP2(t, p) {
  18806. return t * t * p;
  18807. }
  18808. function QuadraticBezier(t, p0, p1, p2) {
  18809. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18810. } //
  18811. function CubicBezierP0(t, p) {
  18812. const k = 1 - t;
  18813. return k * k * k * p;
  18814. }
  18815. function CubicBezierP1(t, p) {
  18816. const k = 1 - t;
  18817. return 3 * k * k * t * p;
  18818. }
  18819. function CubicBezierP2(t, p) {
  18820. return 3 * (1 - t) * t * t * p;
  18821. }
  18822. function CubicBezierP3(t, p) {
  18823. return t * t * t * p;
  18824. }
  18825. function CubicBezier(t, p0, p1, p2, p3) {
  18826. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18827. }
  18828. class CubicBezierCurve extends Curve {
  18829. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18830. super();
  18831. this.isCubicBezierCurve = true;
  18832. this.type = 'CubicBezierCurve';
  18833. this.v0 = v0;
  18834. this.v1 = v1;
  18835. this.v2 = v2;
  18836. this.v3 = v3;
  18837. }
  18838. getPoint(t, optionalTarget = new Vector2()) {
  18839. const point = optionalTarget;
  18840. const v0 = this.v0,
  18841. v1 = this.v1,
  18842. v2 = this.v2,
  18843. v3 = this.v3;
  18844. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18845. return point;
  18846. }
  18847. copy(source) {
  18848. super.copy(source);
  18849. this.v0.copy(source.v0);
  18850. this.v1.copy(source.v1);
  18851. this.v2.copy(source.v2);
  18852. this.v3.copy(source.v3);
  18853. return this;
  18854. }
  18855. toJSON() {
  18856. const data = super.toJSON();
  18857. data.v0 = this.v0.toArray();
  18858. data.v1 = this.v1.toArray();
  18859. data.v2 = this.v2.toArray();
  18860. data.v3 = this.v3.toArray();
  18861. return data;
  18862. }
  18863. fromJSON(json) {
  18864. super.fromJSON(json);
  18865. this.v0.fromArray(json.v0);
  18866. this.v1.fromArray(json.v1);
  18867. this.v2.fromArray(json.v2);
  18868. this.v3.fromArray(json.v3);
  18869. return this;
  18870. }
  18871. }
  18872. class CubicBezierCurve3 extends Curve {
  18873. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18874. super();
  18875. this.isCubicBezierCurve3 = true;
  18876. this.type = 'CubicBezierCurve3';
  18877. this.v0 = v0;
  18878. this.v1 = v1;
  18879. this.v2 = v2;
  18880. this.v3 = v3;
  18881. }
  18882. getPoint(t, optionalTarget = new Vector3()) {
  18883. const point = optionalTarget;
  18884. const v0 = this.v0,
  18885. v1 = this.v1,
  18886. v2 = this.v2,
  18887. v3 = this.v3;
  18888. 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));
  18889. return point;
  18890. }
  18891. copy(source) {
  18892. super.copy(source);
  18893. this.v0.copy(source.v0);
  18894. this.v1.copy(source.v1);
  18895. this.v2.copy(source.v2);
  18896. this.v3.copy(source.v3);
  18897. return this;
  18898. }
  18899. toJSON() {
  18900. const data = super.toJSON();
  18901. data.v0 = this.v0.toArray();
  18902. data.v1 = this.v1.toArray();
  18903. data.v2 = this.v2.toArray();
  18904. data.v3 = this.v3.toArray();
  18905. return data;
  18906. }
  18907. fromJSON(json) {
  18908. super.fromJSON(json);
  18909. this.v0.fromArray(json.v0);
  18910. this.v1.fromArray(json.v1);
  18911. this.v2.fromArray(json.v2);
  18912. this.v3.fromArray(json.v3);
  18913. return this;
  18914. }
  18915. }
  18916. class LineCurve extends Curve {
  18917. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18918. super();
  18919. this.isLineCurve = true;
  18920. this.type = 'LineCurve';
  18921. this.v1 = v1;
  18922. this.v2 = v2;
  18923. }
  18924. getPoint(t, optionalTarget = new Vector2()) {
  18925. const point = optionalTarget;
  18926. if (t === 1) {
  18927. point.copy(this.v2);
  18928. } else {
  18929. point.copy(this.v2).sub(this.v1);
  18930. point.multiplyScalar(t).add(this.v1);
  18931. }
  18932. return point;
  18933. } // Line curve is linear, so we can overwrite default getPointAt
  18934. getPointAt(u, optionalTarget) {
  18935. return this.getPoint(u, optionalTarget);
  18936. }
  18937. getTangent(t, optionalTarget) {
  18938. const tangent = optionalTarget || new Vector2();
  18939. tangent.copy(this.v2).sub(this.v1).normalize();
  18940. return tangent;
  18941. }
  18942. copy(source) {
  18943. super.copy(source);
  18944. this.v1.copy(source.v1);
  18945. this.v2.copy(source.v2);
  18946. return this;
  18947. }
  18948. toJSON() {
  18949. const data = super.toJSON();
  18950. data.v1 = this.v1.toArray();
  18951. data.v2 = this.v2.toArray();
  18952. return data;
  18953. }
  18954. fromJSON(json) {
  18955. super.fromJSON(json);
  18956. this.v1.fromArray(json.v1);
  18957. this.v2.fromArray(json.v2);
  18958. return this;
  18959. }
  18960. }
  18961. class LineCurve3 extends Curve {
  18962. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  18963. super();
  18964. this.isLineCurve3 = true;
  18965. this.type = 'LineCurve3';
  18966. this.v1 = v1;
  18967. this.v2 = v2;
  18968. }
  18969. getPoint(t, optionalTarget = new Vector3()) {
  18970. const point = optionalTarget;
  18971. if (t === 1) {
  18972. point.copy(this.v2);
  18973. } else {
  18974. point.copy(this.v2).sub(this.v1);
  18975. point.multiplyScalar(t).add(this.v1);
  18976. }
  18977. return point;
  18978. } // Line curve is linear, so we can overwrite default getPointAt
  18979. getPointAt(u, optionalTarget) {
  18980. return this.getPoint(u, optionalTarget);
  18981. }
  18982. copy(source) {
  18983. super.copy(source);
  18984. this.v1.copy(source.v1);
  18985. this.v2.copy(source.v2);
  18986. return this;
  18987. }
  18988. toJSON() {
  18989. const data = super.toJSON();
  18990. data.v1 = this.v1.toArray();
  18991. data.v2 = this.v2.toArray();
  18992. return data;
  18993. }
  18994. fromJSON(json) {
  18995. super.fromJSON(json);
  18996. this.v1.fromArray(json.v1);
  18997. this.v2.fromArray(json.v2);
  18998. return this;
  18999. }
  19000. }
  19001. class QuadraticBezierCurve extends Curve {
  19002. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  19003. super();
  19004. this.isQuadraticBezierCurve = true;
  19005. this.type = 'QuadraticBezierCurve';
  19006. this.v0 = v0;
  19007. this.v1 = v1;
  19008. this.v2 = v2;
  19009. }
  19010. getPoint(t, optionalTarget = new Vector2()) {
  19011. const point = optionalTarget;
  19012. const v0 = this.v0,
  19013. v1 = this.v1,
  19014. v2 = this.v2;
  19015. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  19016. return point;
  19017. }
  19018. copy(source) {
  19019. super.copy(source);
  19020. this.v0.copy(source.v0);
  19021. this.v1.copy(source.v1);
  19022. this.v2.copy(source.v2);
  19023. return this;
  19024. }
  19025. toJSON() {
  19026. const data = super.toJSON();
  19027. data.v0 = this.v0.toArray();
  19028. data.v1 = this.v1.toArray();
  19029. data.v2 = this.v2.toArray();
  19030. return data;
  19031. }
  19032. fromJSON(json) {
  19033. super.fromJSON(json);
  19034. this.v0.fromArray(json.v0);
  19035. this.v1.fromArray(json.v1);
  19036. this.v2.fromArray(json.v2);
  19037. return this;
  19038. }
  19039. }
  19040. class QuadraticBezierCurve3 extends Curve {
  19041. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  19042. super();
  19043. this.isQuadraticBezierCurve3 = true;
  19044. this.type = 'QuadraticBezierCurve3';
  19045. this.v0 = v0;
  19046. this.v1 = v1;
  19047. this.v2 = v2;
  19048. }
  19049. getPoint(t, optionalTarget = new Vector3()) {
  19050. const point = optionalTarget;
  19051. const v0 = this.v0,
  19052. v1 = this.v1,
  19053. v2 = this.v2;
  19054. 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));
  19055. return point;
  19056. }
  19057. copy(source) {
  19058. super.copy(source);
  19059. this.v0.copy(source.v0);
  19060. this.v1.copy(source.v1);
  19061. this.v2.copy(source.v2);
  19062. return this;
  19063. }
  19064. toJSON() {
  19065. const data = super.toJSON();
  19066. data.v0 = this.v0.toArray();
  19067. data.v1 = this.v1.toArray();
  19068. data.v2 = this.v2.toArray();
  19069. return data;
  19070. }
  19071. fromJSON(json) {
  19072. super.fromJSON(json);
  19073. this.v0.fromArray(json.v0);
  19074. this.v1.fromArray(json.v1);
  19075. this.v2.fromArray(json.v2);
  19076. return this;
  19077. }
  19078. }
  19079. class SplineCurve extends Curve {
  19080. constructor(points = []) {
  19081. super();
  19082. this.isSplineCurve = true;
  19083. this.type = 'SplineCurve';
  19084. this.points = points;
  19085. }
  19086. getPoint(t, optionalTarget = new Vector2()) {
  19087. const point = optionalTarget;
  19088. const points = this.points;
  19089. const p = (points.length - 1) * t;
  19090. const intPoint = Math.floor(p);
  19091. const weight = p - intPoint;
  19092. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  19093. const p1 = points[intPoint];
  19094. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  19095. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  19096. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  19097. return point;
  19098. }
  19099. copy(source) {
  19100. super.copy(source);
  19101. this.points = [];
  19102. for (let i = 0, l = source.points.length; i < l; i++) {
  19103. const point = source.points[i];
  19104. this.points.push(point.clone());
  19105. }
  19106. return this;
  19107. }
  19108. toJSON() {
  19109. const data = super.toJSON();
  19110. data.points = [];
  19111. for (let i = 0, l = this.points.length; i < l; i++) {
  19112. const point = this.points[i];
  19113. data.points.push(point.toArray());
  19114. }
  19115. return data;
  19116. }
  19117. fromJSON(json) {
  19118. super.fromJSON(json);
  19119. this.points = [];
  19120. for (let i = 0, l = json.points.length; i < l; i++) {
  19121. const point = json.points[i];
  19122. this.points.push(new Vector2().fromArray(point));
  19123. }
  19124. return this;
  19125. }
  19126. }
  19127. var Curves = /*#__PURE__*/Object.freeze({
  19128. __proto__: null,
  19129. ArcCurve: ArcCurve,
  19130. CatmullRomCurve3: CatmullRomCurve3,
  19131. CubicBezierCurve: CubicBezierCurve,
  19132. CubicBezierCurve3: CubicBezierCurve3,
  19133. EllipseCurve: EllipseCurve,
  19134. LineCurve: LineCurve,
  19135. LineCurve3: LineCurve3,
  19136. QuadraticBezierCurve: QuadraticBezierCurve,
  19137. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19138. SplineCurve: SplineCurve
  19139. });
  19140. /**************************************************************
  19141. * Curved Path - a curve path is simply a array of connected
  19142. * curves, but retains the api of a curve
  19143. **************************************************************/
  19144. class CurvePath extends Curve {
  19145. constructor() {
  19146. super();
  19147. this.type = 'CurvePath';
  19148. this.curves = [];
  19149. this.autoClose = false; // Automatically closes the path
  19150. }
  19151. add(curve) {
  19152. this.curves.push(curve);
  19153. }
  19154. closePath() {
  19155. // Add a line curve if start and end of lines are not connected
  19156. const startPoint = this.curves[0].getPoint(0);
  19157. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  19158. if (!startPoint.equals(endPoint)) {
  19159. this.curves.push(new LineCurve(endPoint, startPoint));
  19160. }
  19161. } // To get accurate point with reference to
  19162. // entire path distance at time t,
  19163. // following has to be done:
  19164. // 1. Length of each sub path have to be known
  19165. // 2. Locate and identify type of curve
  19166. // 3. Get t for the curve
  19167. // 4. Return curve.getPointAt(t')
  19168. getPoint(t, optionalTarget) {
  19169. const d = t * this.getLength();
  19170. const curveLengths = this.getCurveLengths();
  19171. let i = 0; // To think about boundaries points.
  19172. while (i < curveLengths.length) {
  19173. if (curveLengths[i] >= d) {
  19174. const diff = curveLengths[i] - d;
  19175. const curve = this.curves[i];
  19176. const segmentLength = curve.getLength();
  19177. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19178. return curve.getPointAt(u, optionalTarget);
  19179. }
  19180. i++;
  19181. }
  19182. return null; // loop where sum != 0, sum > d , sum+1 <d
  19183. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19184. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19185. // getPoint() depends on getLength
  19186. getLength() {
  19187. const lens = this.getCurveLengths();
  19188. return lens[lens.length - 1];
  19189. } // cacheLengths must be recalculated.
  19190. updateArcLengths() {
  19191. this.needsUpdate = true;
  19192. this.cacheLengths = null;
  19193. this.getCurveLengths();
  19194. } // Compute lengths and cache them
  19195. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19196. getCurveLengths() {
  19197. // We use cache values if curves and cache array are same length
  19198. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  19199. return this.cacheLengths;
  19200. } // Get length of sub-curve
  19201. // Push sums into cached array
  19202. const lengths = [];
  19203. let sums = 0;
  19204. for (let i = 0, l = this.curves.length; i < l; i++) {
  19205. sums += this.curves[i].getLength();
  19206. lengths.push(sums);
  19207. }
  19208. this.cacheLengths = lengths;
  19209. return lengths;
  19210. }
  19211. getSpacedPoints(divisions = 40) {
  19212. const points = [];
  19213. for (let i = 0; i <= divisions; i++) {
  19214. points.push(this.getPoint(i / divisions));
  19215. }
  19216. if (this.autoClose) {
  19217. points.push(points[0]);
  19218. }
  19219. return points;
  19220. }
  19221. getPoints(divisions = 12) {
  19222. const points = [];
  19223. let last;
  19224. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19225. const curve = curves[i];
  19226. const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19227. const pts = curve.getPoints(resolution);
  19228. for (let j = 0; j < pts.length; j++) {
  19229. const point = pts[j];
  19230. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19231. points.push(point);
  19232. last = point;
  19233. }
  19234. }
  19235. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19236. points.push(points[0]);
  19237. }
  19238. return points;
  19239. }
  19240. copy(source) {
  19241. super.copy(source);
  19242. this.curves = [];
  19243. for (let i = 0, l = source.curves.length; i < l; i++) {
  19244. const curve = source.curves[i];
  19245. this.curves.push(curve.clone());
  19246. }
  19247. this.autoClose = source.autoClose;
  19248. return this;
  19249. }
  19250. toJSON() {
  19251. const data = super.toJSON();
  19252. data.autoClose = this.autoClose;
  19253. data.curves = [];
  19254. for (let i = 0, l = this.curves.length; i < l; i++) {
  19255. const curve = this.curves[i];
  19256. data.curves.push(curve.toJSON());
  19257. }
  19258. return data;
  19259. }
  19260. fromJSON(json) {
  19261. super.fromJSON(json);
  19262. this.autoClose = json.autoClose;
  19263. this.curves = [];
  19264. for (let i = 0, l = json.curves.length; i < l; i++) {
  19265. const curve = json.curves[i];
  19266. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19267. }
  19268. return this;
  19269. }
  19270. }
  19271. class Path extends CurvePath {
  19272. constructor(points) {
  19273. super();
  19274. this.type = 'Path';
  19275. this.currentPoint = new Vector2();
  19276. if (points) {
  19277. this.setFromPoints(points);
  19278. }
  19279. }
  19280. setFromPoints(points) {
  19281. this.moveTo(points[0].x, points[0].y);
  19282. for (let i = 1, l = points.length; i < l; i++) {
  19283. this.lineTo(points[i].x, points[i].y);
  19284. }
  19285. return this;
  19286. }
  19287. moveTo(x, y) {
  19288. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19289. return this;
  19290. }
  19291. lineTo(x, y) {
  19292. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19293. this.curves.push(curve);
  19294. this.currentPoint.set(x, y);
  19295. return this;
  19296. }
  19297. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19298. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19299. this.curves.push(curve);
  19300. this.currentPoint.set(aX, aY);
  19301. return this;
  19302. }
  19303. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19304. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19305. this.curves.push(curve);
  19306. this.currentPoint.set(aX, aY);
  19307. return this;
  19308. }
  19309. splineThru(pts
  19310. /*Array of Vector*/
  19311. ) {
  19312. const npts = [this.currentPoint.clone()].concat(pts);
  19313. const curve = new SplineCurve(npts);
  19314. this.curves.push(curve);
  19315. this.currentPoint.copy(pts[pts.length - 1]);
  19316. return this;
  19317. }
  19318. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19319. const x0 = this.currentPoint.x;
  19320. const y0 = this.currentPoint.y;
  19321. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19322. return this;
  19323. }
  19324. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19325. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19326. return this;
  19327. }
  19328. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19329. const x0 = this.currentPoint.x;
  19330. const y0 = this.currentPoint.y;
  19331. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19332. return this;
  19333. }
  19334. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19335. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19336. if (this.curves.length > 0) {
  19337. // if a previous curve is present, attempt to join
  19338. const firstPoint = curve.getPoint(0);
  19339. if (!firstPoint.equals(this.currentPoint)) {
  19340. this.lineTo(firstPoint.x, firstPoint.y);
  19341. }
  19342. }
  19343. this.curves.push(curve);
  19344. const lastPoint = curve.getPoint(1);
  19345. this.currentPoint.copy(lastPoint);
  19346. return this;
  19347. }
  19348. copy(source) {
  19349. super.copy(source);
  19350. this.currentPoint.copy(source.currentPoint);
  19351. return this;
  19352. }
  19353. toJSON() {
  19354. const data = super.toJSON();
  19355. data.currentPoint = this.currentPoint.toArray();
  19356. return data;
  19357. }
  19358. fromJSON(json) {
  19359. super.fromJSON(json);
  19360. this.currentPoint.fromArray(json.currentPoint);
  19361. return this;
  19362. }
  19363. }
  19364. class LatheGeometry extends BufferGeometry {
  19365. 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) {
  19366. super();
  19367. this.type = 'LatheGeometry';
  19368. this.parameters = {
  19369. points: points,
  19370. segments: segments,
  19371. phiStart: phiStart,
  19372. phiLength: phiLength
  19373. };
  19374. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19375. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  19376. const indices = [];
  19377. const vertices = [];
  19378. const uvs = [];
  19379. const initNormals = [];
  19380. const normals = []; // helper variables
  19381. const inverseSegments = 1.0 / segments;
  19382. const vertex = new Vector3();
  19383. const uv = new Vector2();
  19384. const normal = new Vector3();
  19385. const curNormal = new Vector3();
  19386. const prevNormal = new Vector3();
  19387. let dx = 0;
  19388. let dy = 0; // pre-compute normals for initial "meridian"
  19389. for (let j = 0; j <= points.length - 1; j++) {
  19390. switch (j) {
  19391. case 0:
  19392. // special handling for 1st vertex on path
  19393. dx = points[j + 1].x - points[j].x;
  19394. dy = points[j + 1].y - points[j].y;
  19395. normal.x = dy * 1.0;
  19396. normal.y = -dx;
  19397. normal.z = dy * 0.0;
  19398. prevNormal.copy(normal);
  19399. normal.normalize();
  19400. initNormals.push(normal.x, normal.y, normal.z);
  19401. break;
  19402. case points.length - 1:
  19403. // special handling for last Vertex on path
  19404. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  19405. break;
  19406. default:
  19407. // default handling for all vertices in between
  19408. dx = points[j + 1].x - points[j].x;
  19409. dy = points[j + 1].y - points[j].y;
  19410. normal.x = dy * 1.0;
  19411. normal.y = -dx;
  19412. normal.z = dy * 0.0;
  19413. curNormal.copy(normal);
  19414. normal.x += prevNormal.x;
  19415. normal.y += prevNormal.y;
  19416. normal.z += prevNormal.z;
  19417. normal.normalize();
  19418. initNormals.push(normal.x, normal.y, normal.z);
  19419. prevNormal.copy(curNormal);
  19420. }
  19421. } // generate vertices, uvs and normals
  19422. for (let i = 0; i <= segments; i++) {
  19423. const phi = phiStart + i * inverseSegments * phiLength;
  19424. const sin = Math.sin(phi);
  19425. const cos = Math.cos(phi);
  19426. for (let j = 0; j <= points.length - 1; j++) {
  19427. // vertex
  19428. vertex.x = points[j].x * sin;
  19429. vertex.y = points[j].y;
  19430. vertex.z = points[j].x * cos;
  19431. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19432. uv.x = i / segments;
  19433. uv.y = j / (points.length - 1);
  19434. uvs.push(uv.x, uv.y); // normal
  19435. const x = initNormals[3 * j + 0] * sin;
  19436. const y = initNormals[3 * j + 1];
  19437. const z = initNormals[3 * j + 0] * cos;
  19438. normals.push(x, y, z);
  19439. }
  19440. } // indices
  19441. for (let i = 0; i < segments; i++) {
  19442. for (let j = 0; j < points.length - 1; j++) {
  19443. const base = j + i * points.length;
  19444. const a = base;
  19445. const b = base + points.length;
  19446. const c = base + points.length + 1;
  19447. const d = base + 1; // faces
  19448. indices.push(a, b, d);
  19449. indices.push(c, d, b);
  19450. }
  19451. } // build geometry
  19452. this.setIndex(indices);
  19453. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19454. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19455. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19456. }
  19457. static fromJSON(data) {
  19458. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  19459. }
  19460. }
  19461. class CapsuleGeometry extends LatheGeometry {
  19462. constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) {
  19463. const path = new Path();
  19464. path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0);
  19465. path.absarc(0, length / 2, radius, 0, Math.PI * 0.5);
  19466. super(path.getPoints(capSegments), radialSegments);
  19467. this.type = 'CapsuleGeometry';
  19468. this.parameters = {
  19469. radius: radius,
  19470. height: length,
  19471. capSegments: capSegments,
  19472. radialSegments: radialSegments
  19473. };
  19474. }
  19475. static fromJSON(data) {
  19476. return new CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments);
  19477. }
  19478. }
  19479. class CircleGeometry extends BufferGeometry {
  19480. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  19481. super();
  19482. this.type = 'CircleGeometry';
  19483. this.parameters = {
  19484. radius: radius,
  19485. segments: segments,
  19486. thetaStart: thetaStart,
  19487. thetaLength: thetaLength
  19488. };
  19489. segments = Math.max(3, segments); // buffers
  19490. const indices = [];
  19491. const vertices = [];
  19492. const normals = [];
  19493. const uvs = []; // helper variables
  19494. const vertex = new Vector3();
  19495. const uv = new Vector2(); // center point
  19496. vertices.push(0, 0, 0);
  19497. normals.push(0, 0, 1);
  19498. uvs.push(0.5, 0.5);
  19499. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  19500. const segment = thetaStart + s / segments * thetaLength; // vertex
  19501. vertex.x = radius * Math.cos(segment);
  19502. vertex.y = radius * Math.sin(segment);
  19503. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19504. normals.push(0, 0, 1); // uvs
  19505. uv.x = (vertices[i] / radius + 1) / 2;
  19506. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19507. uvs.push(uv.x, uv.y);
  19508. } // indices
  19509. for (let i = 1; i <= segments; i++) {
  19510. indices.push(i, i + 1, 0);
  19511. } // build geometry
  19512. this.setIndex(indices);
  19513. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19514. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19515. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19516. }
  19517. static fromJSON(data) {
  19518. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  19519. }
  19520. }
  19521. class CylinderGeometry extends BufferGeometry {
  19522. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19523. super();
  19524. this.type = 'CylinderGeometry';
  19525. this.parameters = {
  19526. radiusTop: radiusTop,
  19527. radiusBottom: radiusBottom,
  19528. height: height,
  19529. radialSegments: radialSegments,
  19530. heightSegments: heightSegments,
  19531. openEnded: openEnded,
  19532. thetaStart: thetaStart,
  19533. thetaLength: thetaLength
  19534. };
  19535. const scope = this;
  19536. radialSegments = Math.floor(radialSegments);
  19537. heightSegments = Math.floor(heightSegments); // buffers
  19538. const indices = [];
  19539. const vertices = [];
  19540. const normals = [];
  19541. const uvs = []; // helper variables
  19542. let index = 0;
  19543. const indexArray = [];
  19544. const halfHeight = height / 2;
  19545. let groupStart = 0; // generate geometry
  19546. generateTorso();
  19547. if (openEnded === false) {
  19548. if (radiusTop > 0) generateCap(true);
  19549. if (radiusBottom > 0) generateCap(false);
  19550. } // build geometry
  19551. this.setIndex(indices);
  19552. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19553. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19554. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19555. function generateTorso() {
  19556. const normal = new Vector3();
  19557. const vertex = new Vector3();
  19558. let groupCount = 0; // this will be used to calculate the normal
  19559. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19560. for (let y = 0; y <= heightSegments; y++) {
  19561. const indexRow = [];
  19562. const v = y / heightSegments; // calculate the radius of the current row
  19563. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  19564. for (let x = 0; x <= radialSegments; x++) {
  19565. const u = x / radialSegments;
  19566. const theta = u * thetaLength + thetaStart;
  19567. const sinTheta = Math.sin(theta);
  19568. const cosTheta = Math.cos(theta); // vertex
  19569. vertex.x = radius * sinTheta;
  19570. vertex.y = -v * height + halfHeight;
  19571. vertex.z = radius * cosTheta;
  19572. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19573. normal.set(sinTheta, slope, cosTheta).normalize();
  19574. normals.push(normal.x, normal.y, normal.z); // uv
  19575. uvs.push(u, 1 - v); // save index of vertex in respective row
  19576. indexRow.push(index++);
  19577. } // now save vertices of the row in our index array
  19578. indexArray.push(indexRow);
  19579. } // generate indices
  19580. for (let x = 0; x < radialSegments; x++) {
  19581. for (let y = 0; y < heightSegments; y++) {
  19582. // we use the index array to access the correct indices
  19583. const a = indexArray[y][x];
  19584. const b = indexArray[y + 1][x];
  19585. const c = indexArray[y + 1][x + 1];
  19586. const d = indexArray[y][x + 1]; // faces
  19587. indices.push(a, b, d);
  19588. indices.push(b, c, d); // update group counter
  19589. groupCount += 6;
  19590. }
  19591. } // add a group to the geometry. this will ensure multi material support
  19592. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19593. groupStart += groupCount;
  19594. }
  19595. function generateCap(top) {
  19596. // save the index of the first center vertex
  19597. const centerIndexStart = index;
  19598. const uv = new Vector2();
  19599. const vertex = new Vector3();
  19600. let groupCount = 0;
  19601. const radius = top === true ? radiusTop : radiusBottom;
  19602. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  19603. // because the geometry needs one set of uvs per face,
  19604. // we must generate a center vertex per face/segment
  19605. for (let x = 1; x <= radialSegments; x++) {
  19606. // vertex
  19607. vertices.push(0, halfHeight * sign, 0); // normal
  19608. normals.push(0, sign, 0); // uv
  19609. uvs.push(0.5, 0.5); // increase index
  19610. index++;
  19611. } // save the index of the last center vertex
  19612. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19613. for (let x = 0; x <= radialSegments; x++) {
  19614. const u = x / radialSegments;
  19615. const theta = u * thetaLength + thetaStart;
  19616. const cosTheta = Math.cos(theta);
  19617. const sinTheta = Math.sin(theta); // vertex
  19618. vertex.x = radius * sinTheta;
  19619. vertex.y = halfHeight * sign;
  19620. vertex.z = radius * cosTheta;
  19621. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19622. normals.push(0, sign, 0); // uv
  19623. uv.x = cosTheta * 0.5 + 0.5;
  19624. uv.y = sinTheta * 0.5 * sign + 0.5;
  19625. uvs.push(uv.x, uv.y); // increase index
  19626. index++;
  19627. } // generate indices
  19628. for (let x = 0; x < radialSegments; x++) {
  19629. const c = centerIndexStart + x;
  19630. const i = centerIndexEnd + x;
  19631. if (top === true) {
  19632. // face top
  19633. indices.push(i, i + 1, c);
  19634. } else {
  19635. // face bottom
  19636. indices.push(i + 1, i, c);
  19637. }
  19638. groupCount += 3;
  19639. } // add a group to the geometry. this will ensure multi material support
  19640. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19641. groupStart += groupCount;
  19642. }
  19643. }
  19644. static fromJSON(data) {
  19645. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19646. }
  19647. }
  19648. class ConeGeometry extends CylinderGeometry {
  19649. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19650. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19651. this.type = 'ConeGeometry';
  19652. this.parameters = {
  19653. radius: radius,
  19654. height: height,
  19655. radialSegments: radialSegments,
  19656. heightSegments: heightSegments,
  19657. openEnded: openEnded,
  19658. thetaStart: thetaStart,
  19659. thetaLength: thetaLength
  19660. };
  19661. }
  19662. static fromJSON(data) {
  19663. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19664. }
  19665. }
  19666. class PolyhedronGeometry extends BufferGeometry {
  19667. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  19668. super();
  19669. this.type = 'PolyhedronGeometry';
  19670. this.parameters = {
  19671. vertices: vertices,
  19672. indices: indices,
  19673. radius: radius,
  19674. detail: detail
  19675. }; // default buffer data
  19676. const vertexBuffer = [];
  19677. const uvBuffer = []; // the subdivision creates the vertex buffer data
  19678. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  19679. applyRadius(radius); // finally, create the uv data
  19680. generateUVs(); // build non-indexed geometry
  19681. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  19682. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  19683. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  19684. if (detail === 0) {
  19685. this.computeVertexNormals(); // flat normals
  19686. } else {
  19687. this.normalizeNormals(); // smooth normals
  19688. } // helper functions
  19689. function subdivide(detail) {
  19690. const a = new Vector3();
  19691. const b = new Vector3();
  19692. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  19693. for (let i = 0; i < indices.length; i += 3) {
  19694. // get the vertices of the face
  19695. getVertexByIndex(indices[i + 0], a);
  19696. getVertexByIndex(indices[i + 1], b);
  19697. getVertexByIndex(indices[i + 2], c); // perform subdivision
  19698. subdivideFace(a, b, c, detail);
  19699. }
  19700. }
  19701. function subdivideFace(a, b, c, detail) {
  19702. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  19703. const v = []; // construct all of the vertices for this subdivision
  19704. for (let i = 0; i <= cols; i++) {
  19705. v[i] = [];
  19706. const aj = a.clone().lerp(c, i / cols);
  19707. const bj = b.clone().lerp(c, i / cols);
  19708. const rows = cols - i;
  19709. for (let j = 0; j <= rows; j++) {
  19710. if (j === 0 && i === cols) {
  19711. v[i][j] = aj;
  19712. } else {
  19713. v[i][j] = aj.clone().lerp(bj, j / rows);
  19714. }
  19715. }
  19716. } // construct all of the faces
  19717. for (let i = 0; i < cols; i++) {
  19718. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  19719. const k = Math.floor(j / 2);
  19720. if (j % 2 === 0) {
  19721. pushVertex(v[i][k + 1]);
  19722. pushVertex(v[i + 1][k]);
  19723. pushVertex(v[i][k]);
  19724. } else {
  19725. pushVertex(v[i][k + 1]);
  19726. pushVertex(v[i + 1][k + 1]);
  19727. pushVertex(v[i + 1][k]);
  19728. }
  19729. }
  19730. }
  19731. }
  19732. function applyRadius(radius) {
  19733. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  19734. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19735. vertex.x = vertexBuffer[i + 0];
  19736. vertex.y = vertexBuffer[i + 1];
  19737. vertex.z = vertexBuffer[i + 2];
  19738. vertex.normalize().multiplyScalar(radius);
  19739. vertexBuffer[i + 0] = vertex.x;
  19740. vertexBuffer[i + 1] = vertex.y;
  19741. vertexBuffer[i + 2] = vertex.z;
  19742. }
  19743. }
  19744. function generateUVs() {
  19745. const vertex = new Vector3();
  19746. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19747. vertex.x = vertexBuffer[i + 0];
  19748. vertex.y = vertexBuffer[i + 1];
  19749. vertex.z = vertexBuffer[i + 2];
  19750. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  19751. const v = inclination(vertex) / Math.PI + 0.5;
  19752. uvBuffer.push(u, 1 - v);
  19753. }
  19754. correctUVs();
  19755. correctSeam();
  19756. }
  19757. function correctSeam() {
  19758. // handle case when face straddles the seam, see #3269
  19759. for (let i = 0; i < uvBuffer.length; i += 6) {
  19760. // uv data of a single face
  19761. const x0 = uvBuffer[i + 0];
  19762. const x1 = uvBuffer[i + 2];
  19763. const x2 = uvBuffer[i + 4];
  19764. const max = Math.max(x0, x1, x2);
  19765. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  19766. if (max > 0.9 && min < 0.1) {
  19767. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  19768. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  19769. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  19770. }
  19771. }
  19772. }
  19773. function pushVertex(vertex) {
  19774. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  19775. }
  19776. function getVertexByIndex(index, vertex) {
  19777. const stride = index * 3;
  19778. vertex.x = vertices[stride + 0];
  19779. vertex.y = vertices[stride + 1];
  19780. vertex.z = vertices[stride + 2];
  19781. }
  19782. function correctUVs() {
  19783. const a = new Vector3();
  19784. const b = new Vector3();
  19785. const c = new Vector3();
  19786. const centroid = new Vector3();
  19787. const uvA = new Vector2();
  19788. const uvB = new Vector2();
  19789. const uvC = new Vector2();
  19790. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  19791. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  19792. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  19793. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  19794. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  19795. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  19796. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  19797. centroid.copy(a).add(b).add(c).divideScalar(3);
  19798. const azi = azimuth(centroid);
  19799. correctUV(uvA, j + 0, a, azi);
  19800. correctUV(uvB, j + 2, b, azi);
  19801. correctUV(uvC, j + 4, c, azi);
  19802. }
  19803. }
  19804. function correctUV(uv, stride, vector, azimuth) {
  19805. if (azimuth < 0 && uv.x === 1) {
  19806. uvBuffer[stride] = uv.x - 1;
  19807. }
  19808. if (vector.x === 0 && vector.z === 0) {
  19809. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  19810. }
  19811. } // Angle around the Y axis, counter-clockwise when looking from above.
  19812. function azimuth(vector) {
  19813. return Math.atan2(vector.z, -vector.x);
  19814. } // Angle above the XZ plane.
  19815. function inclination(vector) {
  19816. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  19817. }
  19818. }
  19819. static fromJSON(data) {
  19820. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  19821. }
  19822. }
  19823. class DodecahedronGeometry extends PolyhedronGeometry {
  19824. constructor(radius = 1, detail = 0) {
  19825. const t = (1 + Math.sqrt(5)) / 2;
  19826. const r = 1 / t;
  19827. const vertices = [// (±1, ±1, ±1)
  19828. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
  19829. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  19830. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  19831. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  19832. 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];
  19833. super(vertices, indices, radius, detail);
  19834. this.type = 'DodecahedronGeometry';
  19835. this.parameters = {
  19836. radius: radius,
  19837. detail: detail
  19838. };
  19839. }
  19840. static fromJSON(data) {
  19841. return new DodecahedronGeometry(data.radius, data.detail);
  19842. }
  19843. }
  19844. const _v0 = /*@__PURE__*/new Vector3();
  19845. const _v1$1 = /*@__PURE__*/new Vector3();
  19846. const _normal = /*@__PURE__*/new Vector3();
  19847. const _triangle = /*@__PURE__*/new Triangle();
  19848. class EdgesGeometry extends BufferGeometry {
  19849. constructor(geometry = null, thresholdAngle = 1) {
  19850. super();
  19851. this.type = 'EdgesGeometry';
  19852. this.parameters = {
  19853. geometry: geometry,
  19854. thresholdAngle: thresholdAngle
  19855. };
  19856. if (geometry !== null) {
  19857. const precisionPoints = 4;
  19858. const precision = Math.pow(10, precisionPoints);
  19859. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  19860. const indexAttr = geometry.getIndex();
  19861. const positionAttr = geometry.getAttribute('position');
  19862. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  19863. const indexArr = [0, 0, 0];
  19864. const vertKeys = ['a', 'b', 'c'];
  19865. const hashes = new Array(3);
  19866. const edgeData = {};
  19867. const vertices = [];
  19868. for (let i = 0; i < indexCount; i += 3) {
  19869. if (indexAttr) {
  19870. indexArr[0] = indexAttr.getX(i);
  19871. indexArr[1] = indexAttr.getX(i + 1);
  19872. indexArr[2] = indexAttr.getX(i + 2);
  19873. } else {
  19874. indexArr[0] = i;
  19875. indexArr[1] = i + 1;
  19876. indexArr[2] = i + 2;
  19877. }
  19878. const {
  19879. a,
  19880. b,
  19881. c
  19882. } = _triangle;
  19883. a.fromBufferAttribute(positionAttr, indexArr[0]);
  19884. b.fromBufferAttribute(positionAttr, indexArr[1]);
  19885. c.fromBufferAttribute(positionAttr, indexArr[2]);
  19886. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  19887. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  19888. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  19889. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  19890. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  19891. continue;
  19892. } // iterate over every edge
  19893. for (let j = 0; j < 3; j++) {
  19894. // get the first and next vertex making up the edge
  19895. const jNext = (j + 1) % 3;
  19896. const vecHash0 = hashes[j];
  19897. const vecHash1 = hashes[jNext];
  19898. const v0 = _triangle[vertKeys[j]];
  19899. const v1 = _triangle[vertKeys[jNext]];
  19900. const hash = `${vecHash0}_${vecHash1}`;
  19901. const reverseHash = `${vecHash1}_${vecHash0}`;
  19902. if (reverseHash in edgeData && edgeData[reverseHash]) {
  19903. // if we found a sibling edge add it into the vertex array if
  19904. // it meets the angle threshold and delete the edge from the map.
  19905. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  19906. vertices.push(v0.x, v0.y, v0.z);
  19907. vertices.push(v1.x, v1.y, v1.z);
  19908. }
  19909. edgeData[reverseHash] = null;
  19910. } else if (!(hash in edgeData)) {
  19911. // if we've already got an edge here then skip adding a new one
  19912. edgeData[hash] = {
  19913. index0: indexArr[j],
  19914. index1: indexArr[jNext],
  19915. normal: _normal.clone()
  19916. };
  19917. }
  19918. }
  19919. } // iterate over all remaining, unmatched edges and add them to the vertex array
  19920. for (const key in edgeData) {
  19921. if (edgeData[key]) {
  19922. const {
  19923. index0,
  19924. index1
  19925. } = edgeData[key];
  19926. _v0.fromBufferAttribute(positionAttr, index0);
  19927. _v1$1.fromBufferAttribute(positionAttr, index1);
  19928. vertices.push(_v0.x, _v0.y, _v0.z);
  19929. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  19930. }
  19931. }
  19932. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19933. }
  19934. }
  19935. }
  19936. class Shape extends Path {
  19937. constructor(points) {
  19938. super(points);
  19939. this.uuid = generateUUID();
  19940. this.type = 'Shape';
  19941. this.holes = [];
  19942. }
  19943. getPointsHoles(divisions) {
  19944. const holesPts = [];
  19945. for (let i = 0, l = this.holes.length; i < l; i++) {
  19946. holesPts[i] = this.holes[i].getPoints(divisions);
  19947. }
  19948. return holesPts;
  19949. } // get points of shape and holes (keypoints based on segments parameter)
  19950. extractPoints(divisions) {
  19951. return {
  19952. shape: this.getPoints(divisions),
  19953. holes: this.getPointsHoles(divisions)
  19954. };
  19955. }
  19956. copy(source) {
  19957. super.copy(source);
  19958. this.holes = [];
  19959. for (let i = 0, l = source.holes.length; i < l; i++) {
  19960. const hole = source.holes[i];
  19961. this.holes.push(hole.clone());
  19962. }
  19963. return this;
  19964. }
  19965. toJSON() {
  19966. const data = super.toJSON();
  19967. data.uuid = this.uuid;
  19968. data.holes = [];
  19969. for (let i = 0, l = this.holes.length; i < l; i++) {
  19970. const hole = this.holes[i];
  19971. data.holes.push(hole.toJSON());
  19972. }
  19973. return data;
  19974. }
  19975. fromJSON(json) {
  19976. super.fromJSON(json);
  19977. this.uuid = json.uuid;
  19978. this.holes = [];
  19979. for (let i = 0, l = json.holes.length; i < l; i++) {
  19980. const hole = json.holes[i];
  19981. this.holes.push(new Path().fromJSON(hole));
  19982. }
  19983. return this;
  19984. }
  19985. }
  19986. /**
  19987. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19988. */
  19989. const Earcut = {
  19990. triangulate: function (data, holeIndices, dim = 2) {
  19991. const hasHoles = holeIndices && holeIndices.length;
  19992. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  19993. let outerNode = linkedList(data, 0, outerLen, dim, true);
  19994. const triangles = [];
  19995. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  19996. let minX, minY, maxX, maxY, x, y, invSize;
  19997. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  19998. if (data.length > 80 * dim) {
  19999. minX = maxX = data[0];
  20000. minY = maxY = data[1];
  20001. for (let i = dim; i < outerLen; i += dim) {
  20002. x = data[i];
  20003. y = data[i + 1];
  20004. if (x < minX) minX = x;
  20005. if (y < minY) minY = y;
  20006. if (x > maxX) maxX = x;
  20007. if (y > maxY) maxY = y;
  20008. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20009. invSize = Math.max(maxX - minX, maxY - minY);
  20010. invSize = invSize !== 0 ? 1 / invSize : 0;
  20011. }
  20012. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  20013. return triangles;
  20014. }
  20015. }; // create a circular doubly linked list from polygon points in the specified winding order
  20016. function linkedList(data, start, end, dim, clockwise) {
  20017. let i, last;
  20018. if (clockwise === signedArea(data, start, end, dim) > 0) {
  20019. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  20020. } else {
  20021. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  20022. }
  20023. if (last && equals(last, last.next)) {
  20024. removeNode(last);
  20025. last = last.next;
  20026. }
  20027. return last;
  20028. } // eliminate colinear or duplicate points
  20029. function filterPoints(start, end) {
  20030. if (!start) return start;
  20031. if (!end) end = start;
  20032. let p = start,
  20033. again;
  20034. do {
  20035. again = false;
  20036. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  20037. removeNode(p);
  20038. p = end = p.prev;
  20039. if (p === p.next) break;
  20040. again = true;
  20041. } else {
  20042. p = p.next;
  20043. }
  20044. } while (again || p !== end);
  20045. return end;
  20046. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  20047. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  20048. if (!ear) return; // interlink polygon nodes in z-order
  20049. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  20050. let stop = ear,
  20051. prev,
  20052. next; // iterate through ears, slicing them one by one
  20053. while (ear.prev !== ear.next) {
  20054. prev = ear.prev;
  20055. next = ear.next;
  20056. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  20057. // cut off the triangle
  20058. triangles.push(prev.i / dim);
  20059. triangles.push(ear.i / dim);
  20060. triangles.push(next.i / dim);
  20061. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  20062. ear = next.next;
  20063. stop = next.next;
  20064. continue;
  20065. }
  20066. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  20067. if (ear === stop) {
  20068. // try filtering points and slicing again
  20069. if (!pass) {
  20070. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  20071. } else if (pass === 1) {
  20072. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  20073. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  20074. } else if (pass === 2) {
  20075. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  20076. }
  20077. break;
  20078. }
  20079. }
  20080. } // check whether a polygon node forms a valid ear with adjacent nodes
  20081. function isEar(ear) {
  20082. const a = ear.prev,
  20083. b = ear,
  20084. c = ear.next;
  20085. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20086. // now make sure we don't have other points inside the potential ear
  20087. let p = ear.next.next;
  20088. while (p !== ear.prev) {
  20089. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20090. p = p.next;
  20091. }
  20092. return true;
  20093. }
  20094. function isEarHashed(ear, minX, minY, invSize) {
  20095. const a = ear.prev,
  20096. b = ear,
  20097. c = ear.next;
  20098. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20099. // triangle bbox; min & max are calculated like this for speed
  20100. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  20101. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  20102. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  20103. maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
  20104. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  20105. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  20106. let p = ear.prevZ,
  20107. n = ear.nextZ; // look for points inside the triangle in both directions
  20108. while (p && p.z >= minZ && n && n.z <= maxZ) {
  20109. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20110. p = p.prevZ;
  20111. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  20112. n = n.nextZ;
  20113. } // look for remaining points in decreasing z-order
  20114. while (p && p.z >= minZ) {
  20115. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20116. p = p.prevZ;
  20117. } // look for remaining points in increasing z-order
  20118. while (n && n.z <= maxZ) {
  20119. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  20120. n = n.nextZ;
  20121. }
  20122. return true;
  20123. } // go through all polygon nodes and cure small local self-intersections
  20124. function cureLocalIntersections(start, triangles, dim) {
  20125. let p = start;
  20126. do {
  20127. const a = p.prev,
  20128. b = p.next.next;
  20129. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  20130. triangles.push(a.i / dim);
  20131. triangles.push(p.i / dim);
  20132. triangles.push(b.i / dim); // remove two nodes involved
  20133. removeNode(p);
  20134. removeNode(p.next);
  20135. p = start = b;
  20136. }
  20137. p = p.next;
  20138. } while (p !== start);
  20139. return filterPoints(p);
  20140. } // try splitting polygon into two and triangulate them independently
  20141. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  20142. // look for a valid diagonal that divides the polygon into two
  20143. let a = start;
  20144. do {
  20145. let b = a.next.next;
  20146. while (b !== a.prev) {
  20147. if (a.i !== b.i && isValidDiagonal(a, b)) {
  20148. // split the polygon in two by the diagonal
  20149. let c = splitPolygon(a, b); // filter colinear points around the cuts
  20150. a = filterPoints(a, a.next);
  20151. c = filterPoints(c, c.next); // run earcut on each half
  20152. earcutLinked(a, triangles, dim, minX, minY, invSize);
  20153. earcutLinked(c, triangles, dim, minX, minY, invSize);
  20154. return;
  20155. }
  20156. b = b.next;
  20157. }
  20158. a = a.next;
  20159. } while (a !== start);
  20160. } // link every hole into the outer loop, producing a single-ring polygon without holes
  20161. function eliminateHoles(data, holeIndices, outerNode, dim) {
  20162. const queue = [];
  20163. let i, len, start, end, list;
  20164. for (i = 0, len = holeIndices.length; i < len; i++) {
  20165. start = holeIndices[i] * dim;
  20166. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  20167. list = linkedList(data, start, end, dim, false);
  20168. if (list === list.next) list.steiner = true;
  20169. queue.push(getLeftmost(list));
  20170. }
  20171. queue.sort(compareX); // process holes from left to right
  20172. for (i = 0; i < queue.length; i++) {
  20173. eliminateHole(queue[i], outerNode);
  20174. outerNode = filterPoints(outerNode, outerNode.next);
  20175. }
  20176. return outerNode;
  20177. }
  20178. function compareX(a, b) {
  20179. return a.x - b.x;
  20180. } // find a bridge between vertices that connects hole with an outer ring and link it
  20181. function eliminateHole(hole, outerNode) {
  20182. outerNode = findHoleBridge(hole, outerNode);
  20183. if (outerNode) {
  20184. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  20185. filterPoints(outerNode, outerNode.next);
  20186. filterPoints(b, b.next);
  20187. }
  20188. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20189. function findHoleBridge(hole, outerNode) {
  20190. let p = outerNode;
  20191. const hx = hole.x;
  20192. const hy = hole.y;
  20193. let qx = -Infinity,
  20194. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  20195. // segment's endpoint with lesser x will be potential connection point
  20196. do {
  20197. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  20198. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  20199. if (x <= hx && x > qx) {
  20200. qx = x;
  20201. if (x === hx) {
  20202. if (hy === p.y) return p;
  20203. if (hy === p.next.y) return p.next;
  20204. }
  20205. m = p.x < p.next.x ? p : p.next;
  20206. }
  20207. }
  20208. p = p.next;
  20209. } while (p !== outerNode);
  20210. if (!m) return null;
  20211. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  20212. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20213. // if there are no points found, we have a valid connection;
  20214. // otherwise choose the point of the minimum angle with the ray as connection point
  20215. const stop = m,
  20216. mx = m.x,
  20217. my = m.y;
  20218. let tanMin = Infinity,
  20219. tan;
  20220. p = m;
  20221. do {
  20222. 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)) {
  20223. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  20224. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  20225. m = p;
  20226. tanMin = tan;
  20227. }
  20228. }
  20229. p = p.next;
  20230. } while (p !== stop);
  20231. return m;
  20232. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  20233. function sectorContainsSector(m, p) {
  20234. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  20235. } // interlink polygon nodes in z-order
  20236. function indexCurve(start, minX, minY, invSize) {
  20237. let p = start;
  20238. do {
  20239. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  20240. p.prevZ = p.prev;
  20241. p.nextZ = p.next;
  20242. p = p.next;
  20243. } while (p !== start);
  20244. p.prevZ.nextZ = null;
  20245. p.prevZ = null;
  20246. sortLinked(p);
  20247. } // Simon Tatham's linked list merge sort algorithm
  20248. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20249. function sortLinked(list) {
  20250. let i,
  20251. p,
  20252. q,
  20253. e,
  20254. tail,
  20255. numMerges,
  20256. pSize,
  20257. qSize,
  20258. inSize = 1;
  20259. do {
  20260. p = list;
  20261. list = null;
  20262. tail = null;
  20263. numMerges = 0;
  20264. while (p) {
  20265. numMerges++;
  20266. q = p;
  20267. pSize = 0;
  20268. for (i = 0; i < inSize; i++) {
  20269. pSize++;
  20270. q = q.nextZ;
  20271. if (!q) break;
  20272. }
  20273. qSize = inSize;
  20274. while (pSize > 0 || qSize > 0 && q) {
  20275. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  20276. e = p;
  20277. p = p.nextZ;
  20278. pSize--;
  20279. } else {
  20280. e = q;
  20281. q = q.nextZ;
  20282. qSize--;
  20283. }
  20284. if (tail) tail.nextZ = e;else list = e;
  20285. e.prevZ = tail;
  20286. tail = e;
  20287. }
  20288. p = q;
  20289. }
  20290. tail.nextZ = null;
  20291. inSize *= 2;
  20292. } while (numMerges > 1);
  20293. return list;
  20294. } // z-order of a point given coords and inverse of the longer side of data bbox
  20295. function zOrder(x, y, minX, minY, invSize) {
  20296. // coords are transformed into non-negative 15-bit integer range
  20297. x = 32767 * (x - minX) * invSize;
  20298. y = 32767 * (y - minY) * invSize;
  20299. x = (x | x << 8) & 0x00FF00FF;
  20300. x = (x | x << 4) & 0x0F0F0F0F;
  20301. x = (x | x << 2) & 0x33333333;
  20302. x = (x | x << 1) & 0x55555555;
  20303. y = (y | y << 8) & 0x00FF00FF;
  20304. y = (y | y << 4) & 0x0F0F0F0F;
  20305. y = (y | y << 2) & 0x33333333;
  20306. y = (y | y << 1) & 0x55555555;
  20307. return x | y << 1;
  20308. } // find the leftmost node of a polygon ring
  20309. function getLeftmost(start) {
  20310. let p = start,
  20311. leftmost = start;
  20312. do {
  20313. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  20314. p = p.next;
  20315. } while (p !== start);
  20316. return leftmost;
  20317. } // check if a point lies within a convex triangle
  20318. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  20319. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  20320. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20321. function isValidDiagonal(a, b) {
  20322. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // doesn't intersect other edges
  20323. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  20324. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  20325. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  20326. } // signed area of a triangle
  20327. function area(p, q, r) {
  20328. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  20329. } // check if two points are equal
  20330. function equals(p1, p2) {
  20331. return p1.x === p2.x && p1.y === p2.y;
  20332. } // check if two segments intersect
  20333. function intersects(p1, q1, p2, q2) {
  20334. const o1 = sign(area(p1, q1, p2));
  20335. const o2 = sign(area(p1, q1, q2));
  20336. const o3 = sign(area(p2, q2, p1));
  20337. const o4 = sign(area(p2, q2, q1));
  20338. if (o1 !== o2 && o3 !== o4) return true; // general case
  20339. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20340. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20341. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20342. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20343. return false;
  20344. } // for collinear points p, q, r, check if point q lies on segment pr
  20345. function onSegment(p, q, r) {
  20346. 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);
  20347. }
  20348. function sign(num) {
  20349. return num > 0 ? 1 : num < 0 ? -1 : 0;
  20350. } // check if a polygon diagonal intersects any polygon segments
  20351. function intersectsPolygon(a, b) {
  20352. let p = a;
  20353. do {
  20354. 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;
  20355. p = p.next;
  20356. } while (p !== a);
  20357. return false;
  20358. } // check if a polygon diagonal is locally inside the polygon
  20359. function locallyInside(a, b) {
  20360. 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;
  20361. } // check if the middle point of a polygon diagonal is inside the polygon
  20362. function middleInside(a, b) {
  20363. let p = a,
  20364. inside = false;
  20365. const px = (a.x + b.x) / 2,
  20366. py = (a.y + b.y) / 2;
  20367. do {
  20368. 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;
  20369. p = p.next;
  20370. } while (p !== a);
  20371. return inside;
  20372. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20373. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20374. function splitPolygon(a, b) {
  20375. const a2 = new Node(a.i, a.x, a.y),
  20376. b2 = new Node(b.i, b.x, b.y),
  20377. an = a.next,
  20378. bp = b.prev;
  20379. a.next = b;
  20380. b.prev = a;
  20381. a2.next = an;
  20382. an.prev = a2;
  20383. b2.next = a2;
  20384. a2.prev = b2;
  20385. bp.next = b2;
  20386. b2.prev = bp;
  20387. return b2;
  20388. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  20389. function insertNode(i, x, y, last) {
  20390. const p = new Node(i, x, y);
  20391. if (!last) {
  20392. p.prev = p;
  20393. p.next = p;
  20394. } else {
  20395. p.next = last.next;
  20396. p.prev = last;
  20397. last.next.prev = p;
  20398. last.next = p;
  20399. }
  20400. return p;
  20401. }
  20402. function removeNode(p) {
  20403. p.next.prev = p.prev;
  20404. p.prev.next = p.next;
  20405. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  20406. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  20407. }
  20408. function Node(i, x, y) {
  20409. // vertex index in coordinates array
  20410. this.i = i; // vertex coordinates
  20411. this.x = x;
  20412. this.y = y; // previous and next vertex nodes in a polygon ring
  20413. this.prev = null;
  20414. this.next = null; // z-order curve value
  20415. this.z = null; // previous and next nodes in z-order
  20416. this.prevZ = null;
  20417. this.nextZ = null; // indicates whether this is a steiner point
  20418. this.steiner = false;
  20419. }
  20420. function signedArea(data, start, end, dim) {
  20421. let sum = 0;
  20422. for (let i = start, j = end - dim; i < end; i += dim) {
  20423. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  20424. j = i;
  20425. }
  20426. return sum;
  20427. }
  20428. class ShapeUtils {
  20429. // calculate area of the contour polygon
  20430. static area(contour) {
  20431. const n = contour.length;
  20432. let a = 0.0;
  20433. for (let p = n - 1, q = 0; q < n; p = q++) {
  20434. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  20435. }
  20436. return a * 0.5;
  20437. }
  20438. static isClockWise(pts) {
  20439. return ShapeUtils.area(pts) < 0;
  20440. }
  20441. static triangulateShape(contour, holes) {
  20442. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20443. const holeIndices = []; // array of hole indices
  20444. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20445. removeDupEndPts(contour);
  20446. addContour(vertices, contour); //
  20447. let holeIndex = contour.length;
  20448. holes.forEach(removeDupEndPts);
  20449. for (let i = 0; i < holes.length; i++) {
  20450. holeIndices.push(holeIndex);
  20451. holeIndex += holes[i].length;
  20452. addContour(vertices, holes[i]);
  20453. } //
  20454. const triangles = Earcut.triangulate(vertices, holeIndices); //
  20455. for (let i = 0; i < triangles.length; i += 3) {
  20456. faces.push(triangles.slice(i, i + 3));
  20457. }
  20458. return faces;
  20459. }
  20460. }
  20461. function removeDupEndPts(points) {
  20462. const l = points.length;
  20463. if (l > 2 && points[l - 1].equals(points[0])) {
  20464. points.pop();
  20465. }
  20466. }
  20467. function addContour(vertices, contour) {
  20468. for (let i = 0; i < contour.length; i++) {
  20469. vertices.push(contour[i].x);
  20470. vertices.push(contour[i].y);
  20471. }
  20472. }
  20473. /**
  20474. * Creates extruded geometry from a path shape.
  20475. *
  20476. * parameters = {
  20477. *
  20478. * curveSegments: <int>, // number of points on the curves
  20479. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20480. * depth: <float>, // Depth to extrude the shape
  20481. *
  20482. * bevelEnabled: <bool>, // turn on bevel
  20483. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20484. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20485. * bevelOffset: <float>, // how far from shape outline does bevel start
  20486. * bevelSegments: <int>, // number of bevel layers
  20487. *
  20488. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20489. *
  20490. * UVGenerator: <Object> // object that provides UV generator functions
  20491. *
  20492. * }
  20493. */
  20494. class ExtrudeGeometry extends BufferGeometry {
  20495. 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 = {}) {
  20496. super();
  20497. this.type = 'ExtrudeGeometry';
  20498. this.parameters = {
  20499. shapes: shapes,
  20500. options: options
  20501. };
  20502. shapes = Array.isArray(shapes) ? shapes : [shapes];
  20503. const scope = this;
  20504. const verticesArray = [];
  20505. const uvArray = [];
  20506. for (let i = 0, l = shapes.length; i < l; i++) {
  20507. const shape = shapes[i];
  20508. addShape(shape);
  20509. } // build geometry
  20510. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  20511. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  20512. this.computeVertexNormals(); // functions
  20513. function addShape(shape) {
  20514. const placeholder = []; // options
  20515. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20516. const steps = options.steps !== undefined ? options.steps : 1;
  20517. const depth = options.depth !== undefined ? options.depth : 1;
  20518. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20519. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20520. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20521. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20522. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20523. const extrudePath = options.extrudePath;
  20524. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; //
  20525. let extrudePts,
  20526. extrudeByPath = false;
  20527. let splineTube, binormal, normal, position2;
  20528. if (extrudePath) {
  20529. extrudePts = extrudePath.getSpacedPoints(steps);
  20530. extrudeByPath = true;
  20531. bevelEnabled = false; // bevels not supported for path extrusion
  20532. // SETUP TNB variables
  20533. // TODO1 - have a .isClosed in spline?
  20534. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20535. binormal = new Vector3();
  20536. normal = new Vector3();
  20537. position2 = new Vector3();
  20538. } // Safeguards if bevels are not enabled
  20539. if (!bevelEnabled) {
  20540. bevelSegments = 0;
  20541. bevelThickness = 0;
  20542. bevelSize = 0;
  20543. bevelOffset = 0;
  20544. } // Variables initialization
  20545. const shapePoints = shape.extractPoints(curveSegments);
  20546. let vertices = shapePoints.shape;
  20547. const holes = shapePoints.holes;
  20548. const reverse = !ShapeUtils.isClockWise(vertices);
  20549. if (reverse) {
  20550. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20551. for (let h = 0, hl = holes.length; h < hl; h++) {
  20552. const ahole = holes[h];
  20553. if (ShapeUtils.isClockWise(ahole)) {
  20554. holes[h] = ahole.reverse();
  20555. }
  20556. }
  20557. }
  20558. const faces = ShapeUtils.triangulateShape(vertices, holes);
  20559. /* Vertices */
  20560. const contour = vertices; // vertices has all points but contour has only points of circumference
  20561. for (let h = 0, hl = holes.length; h < hl; h++) {
  20562. const ahole = holes[h];
  20563. vertices = vertices.concat(ahole);
  20564. }
  20565. function scalePt2(pt, vec, size) {
  20566. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  20567. return vec.clone().multiplyScalar(size).add(pt);
  20568. }
  20569. const vlen = vertices.length,
  20570. flen = faces.length; // Find directions for point movement
  20571. function getBevelVec(inPt, inPrev, inNext) {
  20572. // computes for inPt the corresponding point inPt' on a new contour
  20573. // shifted by 1 unit (length of normalized vector) to the left
  20574. // if we walk along contour clockwise, this new contour is outside the old one
  20575. //
  20576. // inPt' is the intersection of the two lines parallel to the two
  20577. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20578. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20579. // good reading for geometry algorithms (here: line-line intersection)
  20580. // http://geomalgorithms.com/a05-_intersect-1.html
  20581. const v_prev_x = inPt.x - inPrev.x,
  20582. v_prev_y = inPt.y - inPrev.y;
  20583. const v_next_x = inNext.x - inPt.x,
  20584. v_next_y = inNext.y - inPt.y;
  20585. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  20586. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  20587. if (Math.abs(collinear0) > Number.EPSILON) {
  20588. // not collinear
  20589. // length of vectors for normalizing
  20590. const v_prev_len = Math.sqrt(v_prev_lensq);
  20591. const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  20592. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  20593. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  20594. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  20595. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  20596. 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); // vector from inPt to intersection point
  20597. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  20598. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  20599. // but prevent crazy spikes
  20600. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  20601. if (v_trans_lensq <= 2) {
  20602. return new Vector2(v_trans_x, v_trans_y);
  20603. } else {
  20604. shrink_by = Math.sqrt(v_trans_lensq / 2);
  20605. }
  20606. } else {
  20607. // handle special case of collinear edges
  20608. let direction_eq = false; // assumes: opposite
  20609. if (v_prev_x > Number.EPSILON) {
  20610. if (v_next_x > Number.EPSILON) {
  20611. direction_eq = true;
  20612. }
  20613. } else {
  20614. if (v_prev_x < -Number.EPSILON) {
  20615. if (v_next_x < -Number.EPSILON) {
  20616. direction_eq = true;
  20617. }
  20618. } else {
  20619. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  20620. direction_eq = true;
  20621. }
  20622. }
  20623. }
  20624. if (direction_eq) {
  20625. // console.log("Warning: lines are a straight sequence");
  20626. v_trans_x = -v_prev_y;
  20627. v_trans_y = v_prev_x;
  20628. shrink_by = Math.sqrt(v_prev_lensq);
  20629. } else {
  20630. // console.log("Warning: lines are a straight spike");
  20631. v_trans_x = v_prev_x;
  20632. v_trans_y = v_prev_y;
  20633. shrink_by = Math.sqrt(v_prev_lensq / 2);
  20634. }
  20635. }
  20636. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  20637. }
  20638. const contourMovements = [];
  20639. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20640. if (j === il) j = 0;
  20641. if (k === il) k = 0; // (j)---(i)---(k)
  20642. // console.log('i,j,k', i, j , k)
  20643. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  20644. }
  20645. const holesMovements = [];
  20646. let oneHoleMovements,
  20647. verticesMovements = contourMovements.concat();
  20648. for (let h = 0, hl = holes.length; h < hl; h++) {
  20649. const ahole = holes[h];
  20650. oneHoleMovements = [];
  20651. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20652. if (j === il) j = 0;
  20653. if (k === il) k = 0; // (j)---(i)---(k)
  20654. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  20655. }
  20656. holesMovements.push(oneHoleMovements);
  20657. verticesMovements = verticesMovements.concat(oneHoleMovements);
  20658. } // Loop bevelSegments, 1 for the front, 1 for the back
  20659. for (let b = 0; b < bevelSegments; b++) {
  20660. //for ( b = bevelSegments; b > 0; b -- ) {
  20661. const t = b / bevelSegments;
  20662. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20663. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20664. for (let i = 0, il = contour.length; i < il; i++) {
  20665. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20666. v(vert.x, vert.y, -z);
  20667. } // expand holes
  20668. for (let h = 0, hl = holes.length; h < hl; h++) {
  20669. const ahole = holes[h];
  20670. oneHoleMovements = holesMovements[h];
  20671. for (let i = 0, il = ahole.length; i < il; i++) {
  20672. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20673. v(vert.x, vert.y, -z);
  20674. }
  20675. }
  20676. }
  20677. const bs = bevelSize + bevelOffset; // Back facing vertices
  20678. for (let i = 0; i < vlen; i++) {
  20679. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20680. if (!extrudeByPath) {
  20681. v(vert.x, vert.y, 0);
  20682. } else {
  20683. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20684. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  20685. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  20686. position2.copy(extrudePts[0]).add(normal).add(binormal);
  20687. v(position2.x, position2.y, position2.z);
  20688. }
  20689. } // Add stepped vertices...
  20690. // Including front facing vertices
  20691. for (let s = 1; s <= steps; s++) {
  20692. for (let i = 0; i < vlen; i++) {
  20693. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20694. if (!extrudeByPath) {
  20695. v(vert.x, vert.y, depth / steps * s);
  20696. } else {
  20697. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20698. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  20699. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  20700. position2.copy(extrudePts[s]).add(normal).add(binormal);
  20701. v(position2.x, position2.y, position2.z);
  20702. }
  20703. }
  20704. } // Add bevel segments planes
  20705. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20706. for (let b = bevelSegments - 1; b >= 0; b--) {
  20707. const t = b / bevelSegments;
  20708. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20709. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20710. for (let i = 0, il = contour.length; i < il; i++) {
  20711. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20712. v(vert.x, vert.y, depth + z);
  20713. } // expand holes
  20714. for (let h = 0, hl = holes.length; h < hl; h++) {
  20715. const ahole = holes[h];
  20716. oneHoleMovements = holesMovements[h];
  20717. for (let i = 0, il = ahole.length; i < il; i++) {
  20718. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20719. if (!extrudeByPath) {
  20720. v(vert.x, vert.y, depth + z);
  20721. } else {
  20722. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  20723. }
  20724. }
  20725. }
  20726. }
  20727. /* Faces */
  20728. // Top and bottom faces
  20729. buildLidFaces(); // Sides faces
  20730. buildSideFaces(); ///// Internal functions
  20731. function buildLidFaces() {
  20732. const start = verticesArray.length / 3;
  20733. if (bevelEnabled) {
  20734. let layer = 0; // steps + 1
  20735. let offset = vlen * layer; // Bottom faces
  20736. for (let i = 0; i < flen; i++) {
  20737. const face = faces[i];
  20738. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  20739. }
  20740. layer = steps + bevelSegments * 2;
  20741. offset = vlen * layer; // Top faces
  20742. for (let i = 0; i < flen; i++) {
  20743. const face = faces[i];
  20744. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  20745. }
  20746. } else {
  20747. // Bottom faces
  20748. for (let i = 0; i < flen; i++) {
  20749. const face = faces[i];
  20750. f3(face[2], face[1], face[0]);
  20751. } // Top faces
  20752. for (let i = 0; i < flen; i++) {
  20753. const face = faces[i];
  20754. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  20755. }
  20756. }
  20757. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  20758. } // Create faces for the z-sides of the shape
  20759. function buildSideFaces() {
  20760. const start = verticesArray.length / 3;
  20761. let layeroffset = 0;
  20762. sidewalls(contour, layeroffset);
  20763. layeroffset += contour.length;
  20764. for (let h = 0, hl = holes.length; h < hl; h++) {
  20765. const ahole = holes[h];
  20766. sidewalls(ahole, layeroffset); //, true
  20767. layeroffset += ahole.length;
  20768. }
  20769. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  20770. }
  20771. function sidewalls(contour, layeroffset) {
  20772. let i = contour.length;
  20773. while (--i >= 0) {
  20774. const j = i;
  20775. let k = i - 1;
  20776. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  20777. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  20778. const slen1 = vlen * s;
  20779. const slen2 = vlen * (s + 1);
  20780. const a = layeroffset + j + slen1,
  20781. b = layeroffset + k + slen1,
  20782. c = layeroffset + k + slen2,
  20783. d = layeroffset + j + slen2;
  20784. f4(a, b, c, d);
  20785. }
  20786. }
  20787. }
  20788. function v(x, y, z) {
  20789. placeholder.push(x);
  20790. placeholder.push(y);
  20791. placeholder.push(z);
  20792. }
  20793. function f3(a, b, c) {
  20794. addVertex(a);
  20795. addVertex(b);
  20796. addVertex(c);
  20797. const nextIndex = verticesArray.length / 3;
  20798. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20799. addUV(uvs[0]);
  20800. addUV(uvs[1]);
  20801. addUV(uvs[2]);
  20802. }
  20803. function f4(a, b, c, d) {
  20804. addVertex(a);
  20805. addVertex(b);
  20806. addVertex(d);
  20807. addVertex(b);
  20808. addVertex(c);
  20809. addVertex(d);
  20810. const nextIndex = verticesArray.length / 3;
  20811. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20812. addUV(uvs[0]);
  20813. addUV(uvs[1]);
  20814. addUV(uvs[3]);
  20815. addUV(uvs[1]);
  20816. addUV(uvs[2]);
  20817. addUV(uvs[3]);
  20818. }
  20819. function addVertex(index) {
  20820. verticesArray.push(placeholder[index * 3 + 0]);
  20821. verticesArray.push(placeholder[index * 3 + 1]);
  20822. verticesArray.push(placeholder[index * 3 + 2]);
  20823. }
  20824. function addUV(vector2) {
  20825. uvArray.push(vector2.x);
  20826. uvArray.push(vector2.y);
  20827. }
  20828. }
  20829. }
  20830. toJSON() {
  20831. const data = super.toJSON();
  20832. const shapes = this.parameters.shapes;
  20833. const options = this.parameters.options;
  20834. return toJSON$1(shapes, options, data);
  20835. }
  20836. static fromJSON(data, shapes) {
  20837. const geometryShapes = [];
  20838. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20839. const shape = shapes[data.shapes[j]];
  20840. geometryShapes.push(shape);
  20841. }
  20842. const extrudePath = data.options.extrudePath;
  20843. if (extrudePath !== undefined) {
  20844. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  20845. }
  20846. return new ExtrudeGeometry(geometryShapes, data.options);
  20847. }
  20848. }
  20849. const WorldUVGenerator = {
  20850. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  20851. const a_x = vertices[indexA * 3];
  20852. const a_y = vertices[indexA * 3 + 1];
  20853. const b_x = vertices[indexB * 3];
  20854. const b_y = vertices[indexB * 3 + 1];
  20855. const c_x = vertices[indexC * 3];
  20856. const c_y = vertices[indexC * 3 + 1];
  20857. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  20858. },
  20859. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  20860. const a_x = vertices[indexA * 3];
  20861. const a_y = vertices[indexA * 3 + 1];
  20862. const a_z = vertices[indexA * 3 + 2];
  20863. const b_x = vertices[indexB * 3];
  20864. const b_y = vertices[indexB * 3 + 1];
  20865. const b_z = vertices[indexB * 3 + 2];
  20866. const c_x = vertices[indexC * 3];
  20867. const c_y = vertices[indexC * 3 + 1];
  20868. const c_z = vertices[indexC * 3 + 2];
  20869. const d_x = vertices[indexD * 3];
  20870. const d_y = vertices[indexD * 3 + 1];
  20871. const d_z = vertices[indexD * 3 + 2];
  20872. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  20873. 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)];
  20874. } else {
  20875. 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)];
  20876. }
  20877. }
  20878. };
  20879. function toJSON$1(shapes, options, data) {
  20880. data.shapes = [];
  20881. if (Array.isArray(shapes)) {
  20882. for (let i = 0, l = shapes.length; i < l; i++) {
  20883. const shape = shapes[i];
  20884. data.shapes.push(shape.uuid);
  20885. }
  20886. } else {
  20887. data.shapes.push(shapes.uuid);
  20888. }
  20889. data.options = Object.assign({}, options);
  20890. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  20891. return data;
  20892. }
  20893. class IcosahedronGeometry extends PolyhedronGeometry {
  20894. constructor(radius = 1, detail = 0) {
  20895. const t = (1 + Math.sqrt(5)) / 2;
  20896. 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];
  20897. 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];
  20898. super(vertices, indices, radius, detail);
  20899. this.type = 'IcosahedronGeometry';
  20900. this.parameters = {
  20901. radius: radius,
  20902. detail: detail
  20903. };
  20904. }
  20905. static fromJSON(data) {
  20906. return new IcosahedronGeometry(data.radius, data.detail);
  20907. }
  20908. }
  20909. class OctahedronGeometry extends PolyhedronGeometry {
  20910. constructor(radius = 1, detail = 0) {
  20911. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  20912. 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];
  20913. super(vertices, indices, radius, detail);
  20914. this.type = 'OctahedronGeometry';
  20915. this.parameters = {
  20916. radius: radius,
  20917. detail: detail
  20918. };
  20919. }
  20920. static fromJSON(data) {
  20921. return new OctahedronGeometry(data.radius, data.detail);
  20922. }
  20923. }
  20924. class RingGeometry extends BufferGeometry {
  20925. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  20926. super();
  20927. this.type = 'RingGeometry';
  20928. this.parameters = {
  20929. innerRadius: innerRadius,
  20930. outerRadius: outerRadius,
  20931. thetaSegments: thetaSegments,
  20932. phiSegments: phiSegments,
  20933. thetaStart: thetaStart,
  20934. thetaLength: thetaLength
  20935. };
  20936. thetaSegments = Math.max(3, thetaSegments);
  20937. phiSegments = Math.max(1, phiSegments); // buffers
  20938. const indices = [];
  20939. const vertices = [];
  20940. const normals = [];
  20941. const uvs = []; // some helper variables
  20942. let radius = innerRadius;
  20943. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  20944. const vertex = new Vector3();
  20945. const uv = new Vector2(); // generate vertices, normals and uvs
  20946. for (let j = 0; j <= phiSegments; j++) {
  20947. for (let i = 0; i <= thetaSegments; i++) {
  20948. // values are generate from the inside of the ring to the outside
  20949. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  20950. vertex.x = radius * Math.cos(segment);
  20951. vertex.y = radius * Math.sin(segment);
  20952. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20953. normals.push(0, 0, 1); // uv
  20954. uv.x = (vertex.x / outerRadius + 1) / 2;
  20955. uv.y = (vertex.y / outerRadius + 1) / 2;
  20956. uvs.push(uv.x, uv.y);
  20957. } // increase the radius for next row of vertices
  20958. radius += radiusStep;
  20959. } // indices
  20960. for (let j = 0; j < phiSegments; j++) {
  20961. const thetaSegmentLevel = j * (thetaSegments + 1);
  20962. for (let i = 0; i < thetaSegments; i++) {
  20963. const segment = i + thetaSegmentLevel;
  20964. const a = segment;
  20965. const b = segment + thetaSegments + 1;
  20966. const c = segment + thetaSegments + 2;
  20967. const d = segment + 1; // faces
  20968. indices.push(a, b, d);
  20969. indices.push(b, c, d);
  20970. }
  20971. } // build geometry
  20972. this.setIndex(indices);
  20973. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20974. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20975. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20976. }
  20977. static fromJSON(data) {
  20978. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  20979. }
  20980. }
  20981. class ShapeGeometry extends BufferGeometry {
  20982. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  20983. super();
  20984. this.type = 'ShapeGeometry';
  20985. this.parameters = {
  20986. shapes: shapes,
  20987. curveSegments: curveSegments
  20988. }; // buffers
  20989. const indices = [];
  20990. const vertices = [];
  20991. const normals = [];
  20992. const uvs = []; // helper variables
  20993. let groupStart = 0;
  20994. let groupCount = 0; // allow single and array values for "shapes" parameter
  20995. if (Array.isArray(shapes) === false) {
  20996. addShape(shapes);
  20997. } else {
  20998. for (let i = 0; i < shapes.length; i++) {
  20999. addShape(shapes[i]);
  21000. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  21001. groupStart += groupCount;
  21002. groupCount = 0;
  21003. }
  21004. } // build geometry
  21005. this.setIndex(indices);
  21006. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21007. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21008. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  21009. function addShape(shape) {
  21010. const indexOffset = vertices.length / 3;
  21011. const points = shape.extractPoints(curveSegments);
  21012. let shapeVertices = points.shape;
  21013. const shapeHoles = points.holes; // check direction of vertices
  21014. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  21015. shapeVertices = shapeVertices.reverse();
  21016. }
  21017. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21018. const shapeHole = shapeHoles[i];
  21019. if (ShapeUtils.isClockWise(shapeHole) === true) {
  21020. shapeHoles[i] = shapeHole.reverse();
  21021. }
  21022. }
  21023. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  21024. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21025. const shapeHole = shapeHoles[i];
  21026. shapeVertices = shapeVertices.concat(shapeHole);
  21027. } // vertices, normals, uvs
  21028. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  21029. const vertex = shapeVertices[i];
  21030. vertices.push(vertex.x, vertex.y, 0);
  21031. normals.push(0, 0, 1);
  21032. uvs.push(vertex.x, vertex.y); // world uvs
  21033. } // incides
  21034. for (let i = 0, l = faces.length; i < l; i++) {
  21035. const face = faces[i];
  21036. const a = face[0] + indexOffset;
  21037. const b = face[1] + indexOffset;
  21038. const c = face[2] + indexOffset;
  21039. indices.push(a, b, c);
  21040. groupCount += 3;
  21041. }
  21042. }
  21043. }
  21044. toJSON() {
  21045. const data = super.toJSON();
  21046. const shapes = this.parameters.shapes;
  21047. return toJSON(shapes, data);
  21048. }
  21049. static fromJSON(data, shapes) {
  21050. const geometryShapes = [];
  21051. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  21052. const shape = shapes[data.shapes[j]];
  21053. geometryShapes.push(shape);
  21054. }
  21055. return new ShapeGeometry(geometryShapes, data.curveSegments);
  21056. }
  21057. }
  21058. function toJSON(shapes, data) {
  21059. data.shapes = [];
  21060. if (Array.isArray(shapes)) {
  21061. for (let i = 0, l = shapes.length; i < l; i++) {
  21062. const shape = shapes[i];
  21063. data.shapes.push(shape.uuid);
  21064. }
  21065. } else {
  21066. data.shapes.push(shapes.uuid);
  21067. }
  21068. return data;
  21069. }
  21070. class SphereGeometry extends BufferGeometry {
  21071. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  21072. super();
  21073. this.type = 'SphereGeometry';
  21074. this.parameters = {
  21075. radius: radius,
  21076. widthSegments: widthSegments,
  21077. heightSegments: heightSegments,
  21078. phiStart: phiStart,
  21079. phiLength: phiLength,
  21080. thetaStart: thetaStart,
  21081. thetaLength: thetaLength
  21082. };
  21083. widthSegments = Math.max(3, Math.floor(widthSegments));
  21084. heightSegments = Math.max(2, Math.floor(heightSegments));
  21085. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  21086. let index = 0;
  21087. const grid = [];
  21088. const vertex = new Vector3();
  21089. const normal = new Vector3(); // buffers
  21090. const indices = [];
  21091. const vertices = [];
  21092. const normals = [];
  21093. const uvs = []; // generate vertices, normals and uvs
  21094. for (let iy = 0; iy <= heightSegments; iy++) {
  21095. const verticesRow = [];
  21096. const v = iy / heightSegments; // special case for the poles
  21097. let uOffset = 0;
  21098. if (iy == 0 && thetaStart == 0) {
  21099. uOffset = 0.5 / widthSegments;
  21100. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  21101. uOffset = -0.5 / widthSegments;
  21102. }
  21103. for (let ix = 0; ix <= widthSegments; ix++) {
  21104. const u = ix / widthSegments; // vertex
  21105. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21106. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  21107. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21108. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  21109. normal.copy(vertex).normalize();
  21110. normals.push(normal.x, normal.y, normal.z); // uv
  21111. uvs.push(u + uOffset, 1 - v);
  21112. verticesRow.push(index++);
  21113. }
  21114. grid.push(verticesRow);
  21115. } // indices
  21116. for (let iy = 0; iy < heightSegments; iy++) {
  21117. for (let ix = 0; ix < widthSegments; ix++) {
  21118. const a = grid[iy][ix + 1];
  21119. const b = grid[iy][ix];
  21120. const c = grid[iy + 1][ix];
  21121. const d = grid[iy + 1][ix + 1];
  21122. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  21123. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  21124. }
  21125. } // build geometry
  21126. this.setIndex(indices);
  21127. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21128. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21129. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21130. }
  21131. static fromJSON(data) {
  21132. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  21133. }
  21134. }
  21135. class TetrahedronGeometry extends PolyhedronGeometry {
  21136. constructor(radius = 1, detail = 0) {
  21137. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  21138. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  21139. super(vertices, indices, radius, detail);
  21140. this.type = 'TetrahedronGeometry';
  21141. this.parameters = {
  21142. radius: radius,
  21143. detail: detail
  21144. };
  21145. }
  21146. static fromJSON(data) {
  21147. return new TetrahedronGeometry(data.radius, data.detail);
  21148. }
  21149. }
  21150. class TorusGeometry extends BufferGeometry {
  21151. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  21152. super();
  21153. this.type = 'TorusGeometry';
  21154. this.parameters = {
  21155. radius: radius,
  21156. tube: tube,
  21157. radialSegments: radialSegments,
  21158. tubularSegments: tubularSegments,
  21159. arc: arc
  21160. };
  21161. radialSegments = Math.floor(radialSegments);
  21162. tubularSegments = Math.floor(tubularSegments); // buffers
  21163. const indices = [];
  21164. const vertices = [];
  21165. const normals = [];
  21166. const uvs = []; // helper variables
  21167. const center = new Vector3();
  21168. const vertex = new Vector3();
  21169. const normal = new Vector3(); // generate vertices, normals and uvs
  21170. for (let j = 0; j <= radialSegments; j++) {
  21171. for (let i = 0; i <= tubularSegments; i++) {
  21172. const u = i / tubularSegments * arc;
  21173. const v = j / radialSegments * Math.PI * 2; // vertex
  21174. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  21175. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  21176. vertex.z = tube * Math.sin(v);
  21177. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  21178. center.x = radius * Math.cos(u);
  21179. center.y = radius * Math.sin(u);
  21180. normal.subVectors(vertex, center).normalize();
  21181. normals.push(normal.x, normal.y, normal.z); // uv
  21182. uvs.push(i / tubularSegments);
  21183. uvs.push(j / radialSegments);
  21184. }
  21185. } // generate indices
  21186. for (let j = 1; j <= radialSegments; j++) {
  21187. for (let i = 1; i <= tubularSegments; i++) {
  21188. // indices
  21189. const a = (tubularSegments + 1) * j + i - 1;
  21190. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  21191. const c = (tubularSegments + 1) * (j - 1) + i;
  21192. const d = (tubularSegments + 1) * j + i; // faces
  21193. indices.push(a, b, d);
  21194. indices.push(b, c, d);
  21195. }
  21196. } // build geometry
  21197. this.setIndex(indices);
  21198. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21199. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21200. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21201. }
  21202. static fromJSON(data) {
  21203. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  21204. }
  21205. }
  21206. class TorusKnotGeometry extends BufferGeometry {
  21207. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  21208. super();
  21209. this.type = 'TorusKnotGeometry';
  21210. this.parameters = {
  21211. radius: radius,
  21212. tube: tube,
  21213. tubularSegments: tubularSegments,
  21214. radialSegments: radialSegments,
  21215. p: p,
  21216. q: q
  21217. };
  21218. tubularSegments = Math.floor(tubularSegments);
  21219. radialSegments = Math.floor(radialSegments); // buffers
  21220. const indices = [];
  21221. const vertices = [];
  21222. const normals = [];
  21223. const uvs = []; // helper variables
  21224. const vertex = new Vector3();
  21225. const normal = new Vector3();
  21226. const P1 = new Vector3();
  21227. const P2 = new Vector3();
  21228. const B = new Vector3();
  21229. const T = new Vector3();
  21230. const N = new Vector3(); // generate vertices, normals and uvs
  21231. for (let i = 0; i <= tubularSegments; ++i) {
  21232. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21233. const u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21234. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21235. calculatePositionOnCurve(u, p, q, radius, P1);
  21236. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  21237. T.subVectors(P2, P1);
  21238. N.addVectors(P2, P1);
  21239. B.crossVectors(T, N);
  21240. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  21241. B.normalize();
  21242. N.normalize();
  21243. for (let j = 0; j <= radialSegments; ++j) {
  21244. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21245. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21246. const v = j / radialSegments * Math.PI * 2;
  21247. const cx = -tube * Math.cos(v);
  21248. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  21249. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21250. vertex.x = P1.x + (cx * N.x + cy * B.x);
  21251. vertex.y = P1.y + (cx * N.y + cy * B.y);
  21252. vertex.z = P1.z + (cx * N.z + cy * B.z);
  21253. vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21254. normal.subVectors(vertex, P1).normalize();
  21255. normals.push(normal.x, normal.y, normal.z); // uv
  21256. uvs.push(i / tubularSegments);
  21257. uvs.push(j / radialSegments);
  21258. }
  21259. } // generate indices
  21260. for (let j = 1; j <= tubularSegments; j++) {
  21261. for (let i = 1; i <= radialSegments; i++) {
  21262. // indices
  21263. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  21264. const b = (radialSegments + 1) * j + (i - 1);
  21265. const c = (radialSegments + 1) * j + i;
  21266. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21267. indices.push(a, b, d);
  21268. indices.push(b, c, d);
  21269. }
  21270. } // build geometry
  21271. this.setIndex(indices);
  21272. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21273. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21274. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  21275. function calculatePositionOnCurve(u, p, q, radius, position) {
  21276. const cu = Math.cos(u);
  21277. const su = Math.sin(u);
  21278. const quOverP = q / p * u;
  21279. const cs = Math.cos(quOverP);
  21280. position.x = radius * (2 + cs) * 0.5 * cu;
  21281. position.y = radius * (2 + cs) * su * 0.5;
  21282. position.z = radius * Math.sin(quOverP) * 0.5;
  21283. }
  21284. }
  21285. static fromJSON(data) {
  21286. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  21287. }
  21288. }
  21289. class TubeGeometry extends BufferGeometry {
  21290. 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) {
  21291. super();
  21292. this.type = 'TubeGeometry';
  21293. this.parameters = {
  21294. path: path,
  21295. tubularSegments: tubularSegments,
  21296. radius: radius,
  21297. radialSegments: radialSegments,
  21298. closed: closed
  21299. };
  21300. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  21301. this.tangents = frames.tangents;
  21302. this.normals = frames.normals;
  21303. this.binormals = frames.binormals; // helper variables
  21304. const vertex = new Vector3();
  21305. const normal = new Vector3();
  21306. const uv = new Vector2();
  21307. let P = new Vector3(); // buffer
  21308. const vertices = [];
  21309. const normals = [];
  21310. const uvs = [];
  21311. const indices = []; // create buffer data
  21312. generateBufferData(); // build geometry
  21313. this.setIndex(indices);
  21314. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21315. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21316. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  21317. function generateBufferData() {
  21318. for (let i = 0; i < tubularSegments; i++) {
  21319. generateSegment(i);
  21320. } // if the geometry is not closed, generate the last row of vertices and normals
  21321. // at the regular position on the given path
  21322. //
  21323. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21324. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  21325. // this makes it easy compute correct values for closed geometries
  21326. generateUVs(); // finally create faces
  21327. generateIndices();
  21328. }
  21329. function generateSegment(i) {
  21330. // we use getPointAt to sample evenly distributed points from the given path
  21331. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  21332. const N = frames.normals[i];
  21333. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  21334. for (let j = 0; j <= radialSegments; j++) {
  21335. const v = j / radialSegments * Math.PI * 2;
  21336. const sin = Math.sin(v);
  21337. const cos = -Math.cos(v); // normal
  21338. normal.x = cos * N.x + sin * B.x;
  21339. normal.y = cos * N.y + sin * B.y;
  21340. normal.z = cos * N.z + sin * B.z;
  21341. normal.normalize();
  21342. normals.push(normal.x, normal.y, normal.z); // vertex
  21343. vertex.x = P.x + radius * normal.x;
  21344. vertex.y = P.y + radius * normal.y;
  21345. vertex.z = P.z + radius * normal.z;
  21346. vertices.push(vertex.x, vertex.y, vertex.z);
  21347. }
  21348. }
  21349. function generateIndices() {
  21350. for (let j = 1; j <= tubularSegments; j++) {
  21351. for (let i = 1; i <= radialSegments; i++) {
  21352. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  21353. const b = (radialSegments + 1) * j + (i - 1);
  21354. const c = (radialSegments + 1) * j + i;
  21355. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21356. indices.push(a, b, d);
  21357. indices.push(b, c, d);
  21358. }
  21359. }
  21360. }
  21361. function generateUVs() {
  21362. for (let i = 0; i <= tubularSegments; i++) {
  21363. for (let j = 0; j <= radialSegments; j++) {
  21364. uv.x = i / tubularSegments;
  21365. uv.y = j / radialSegments;
  21366. uvs.push(uv.x, uv.y);
  21367. }
  21368. }
  21369. }
  21370. }
  21371. toJSON() {
  21372. const data = super.toJSON();
  21373. data.path = this.parameters.path.toJSON();
  21374. return data;
  21375. }
  21376. static fromJSON(data) {
  21377. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21378. // User defined curves or instances of CurvePath will not be deserialized.
  21379. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  21380. }
  21381. }
  21382. class WireframeGeometry extends BufferGeometry {
  21383. constructor(geometry = null) {
  21384. super();
  21385. this.type = 'WireframeGeometry';
  21386. this.parameters = {
  21387. geometry: geometry
  21388. };
  21389. if (geometry !== null) {
  21390. // buffer
  21391. const vertices = [];
  21392. const edges = new Set(); // helper variables
  21393. const start = new Vector3();
  21394. const end = new Vector3();
  21395. if (geometry.index !== null) {
  21396. // indexed BufferGeometry
  21397. const position = geometry.attributes.position;
  21398. const indices = geometry.index;
  21399. let groups = geometry.groups;
  21400. if (groups.length === 0) {
  21401. groups = [{
  21402. start: 0,
  21403. count: indices.count,
  21404. materialIndex: 0
  21405. }];
  21406. } // create a data structure that contains all edges without duplicates
  21407. for (let o = 0, ol = groups.length; o < ol; ++o) {
  21408. const group = groups[o];
  21409. const groupStart = group.start;
  21410. const groupCount = group.count;
  21411. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  21412. for (let j = 0; j < 3; j++) {
  21413. const index1 = indices.getX(i + j);
  21414. const index2 = indices.getX(i + (j + 1) % 3);
  21415. start.fromBufferAttribute(position, index1);
  21416. end.fromBufferAttribute(position, index2);
  21417. if (isUniqueEdge(start, end, edges) === true) {
  21418. vertices.push(start.x, start.y, start.z);
  21419. vertices.push(end.x, end.y, end.z);
  21420. }
  21421. }
  21422. }
  21423. }
  21424. } else {
  21425. // non-indexed BufferGeometry
  21426. const position = geometry.attributes.position;
  21427. for (let i = 0, l = position.count / 3; i < l; i++) {
  21428. for (let j = 0; j < 3; j++) {
  21429. // three edges per triangle, an edge is represented as (index1, index2)
  21430. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21431. const index1 = 3 * i + j;
  21432. const index2 = 3 * i + (j + 1) % 3;
  21433. start.fromBufferAttribute(position, index1);
  21434. end.fromBufferAttribute(position, index2);
  21435. if (isUniqueEdge(start, end, edges) === true) {
  21436. vertices.push(start.x, start.y, start.z);
  21437. vertices.push(end.x, end.y, end.z);
  21438. }
  21439. }
  21440. }
  21441. } // build geometry
  21442. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21443. }
  21444. }
  21445. }
  21446. function isUniqueEdge(start, end, edges) {
  21447. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21448. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21449. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  21450. return false;
  21451. } else {
  21452. edges.add(hash1);
  21453. edges.add(hash2);
  21454. return true;
  21455. }
  21456. }
  21457. var Geometries = /*#__PURE__*/Object.freeze({
  21458. __proto__: null,
  21459. BoxGeometry: BoxGeometry,
  21460. CapsuleGeometry: CapsuleGeometry,
  21461. CircleGeometry: CircleGeometry,
  21462. ConeGeometry: ConeGeometry,
  21463. CylinderGeometry: CylinderGeometry,
  21464. DodecahedronGeometry: DodecahedronGeometry,
  21465. EdgesGeometry: EdgesGeometry,
  21466. ExtrudeGeometry: ExtrudeGeometry,
  21467. IcosahedronGeometry: IcosahedronGeometry,
  21468. LatheGeometry: LatheGeometry,
  21469. OctahedronGeometry: OctahedronGeometry,
  21470. PlaneGeometry: PlaneGeometry,
  21471. PolyhedronGeometry: PolyhedronGeometry,
  21472. RingGeometry: RingGeometry,
  21473. ShapeGeometry: ShapeGeometry,
  21474. SphereGeometry: SphereGeometry,
  21475. TetrahedronGeometry: TetrahedronGeometry,
  21476. TorusGeometry: TorusGeometry,
  21477. TorusKnotGeometry: TorusKnotGeometry,
  21478. TubeGeometry: TubeGeometry,
  21479. WireframeGeometry: WireframeGeometry
  21480. });
  21481. class ShadowMaterial extends Material {
  21482. constructor(parameters) {
  21483. super();
  21484. this.isShadowMaterial = true;
  21485. this.type = 'ShadowMaterial';
  21486. this.color = new Color(0x000000);
  21487. this.transparent = true;
  21488. this.fog = true;
  21489. this.setValues(parameters);
  21490. }
  21491. copy(source) {
  21492. super.copy(source);
  21493. this.color.copy(source.color);
  21494. this.fog = source.fog;
  21495. return this;
  21496. }
  21497. }
  21498. class RawShaderMaterial extends ShaderMaterial {
  21499. constructor(parameters) {
  21500. super(parameters);
  21501. this.isRawShaderMaterial = true;
  21502. this.type = 'RawShaderMaterial';
  21503. }
  21504. }
  21505. class MeshStandardMaterial extends Material {
  21506. constructor(parameters) {
  21507. super();
  21508. this.isMeshStandardMaterial = true;
  21509. this.defines = {
  21510. 'STANDARD': ''
  21511. };
  21512. this.type = 'MeshStandardMaterial';
  21513. this.color = new Color(0xffffff); // diffuse
  21514. this.roughness = 1.0;
  21515. this.metalness = 0.0;
  21516. this.map = null;
  21517. this.lightMap = null;
  21518. this.lightMapIntensity = 1.0;
  21519. this.aoMap = null;
  21520. this.aoMapIntensity = 1.0;
  21521. this.emissive = new Color(0x000000);
  21522. this.emissiveIntensity = 1.0;
  21523. this.emissiveMap = null;
  21524. this.bumpMap = null;
  21525. this.bumpScale = 1;
  21526. this.normalMap = null;
  21527. this.normalMapType = TangentSpaceNormalMap;
  21528. this.normalScale = new Vector2(1, 1);
  21529. this.displacementMap = null;
  21530. this.displacementScale = 1;
  21531. this.displacementBias = 0;
  21532. this.roughnessMap = null;
  21533. this.metalnessMap = null;
  21534. this.alphaMap = null;
  21535. this.envMap = null;
  21536. this.envMapIntensity = 1.0;
  21537. this.wireframe = false;
  21538. this.wireframeLinewidth = 1;
  21539. this.wireframeLinecap = 'round';
  21540. this.wireframeLinejoin = 'round';
  21541. this.flatShading = false;
  21542. this.fog = true;
  21543. this.setValues(parameters);
  21544. }
  21545. copy(source) {
  21546. super.copy(source);
  21547. this.defines = {
  21548. 'STANDARD': ''
  21549. };
  21550. this.color.copy(source.color);
  21551. this.roughness = source.roughness;
  21552. this.metalness = source.metalness;
  21553. this.map = source.map;
  21554. this.lightMap = source.lightMap;
  21555. this.lightMapIntensity = source.lightMapIntensity;
  21556. this.aoMap = source.aoMap;
  21557. this.aoMapIntensity = source.aoMapIntensity;
  21558. this.emissive.copy(source.emissive);
  21559. this.emissiveMap = source.emissiveMap;
  21560. this.emissiveIntensity = source.emissiveIntensity;
  21561. this.bumpMap = source.bumpMap;
  21562. this.bumpScale = source.bumpScale;
  21563. this.normalMap = source.normalMap;
  21564. this.normalMapType = source.normalMapType;
  21565. this.normalScale.copy(source.normalScale);
  21566. this.displacementMap = source.displacementMap;
  21567. this.displacementScale = source.displacementScale;
  21568. this.displacementBias = source.displacementBias;
  21569. this.roughnessMap = source.roughnessMap;
  21570. this.metalnessMap = source.metalnessMap;
  21571. this.alphaMap = source.alphaMap;
  21572. this.envMap = source.envMap;
  21573. this.envMapIntensity = source.envMapIntensity;
  21574. this.wireframe = source.wireframe;
  21575. this.wireframeLinewidth = source.wireframeLinewidth;
  21576. this.wireframeLinecap = source.wireframeLinecap;
  21577. this.wireframeLinejoin = source.wireframeLinejoin;
  21578. this.flatShading = source.flatShading;
  21579. this.fog = source.fog;
  21580. return this;
  21581. }
  21582. }
  21583. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21584. constructor(parameters) {
  21585. super();
  21586. this.isMeshPhysicalMaterial = true;
  21587. this.defines = {
  21588. 'STANDARD': '',
  21589. 'PHYSICAL': ''
  21590. };
  21591. this.type = 'MeshPhysicalMaterial';
  21592. this.clearcoatMap = null;
  21593. this.clearcoatRoughness = 0.0;
  21594. this.clearcoatRoughnessMap = null;
  21595. this.clearcoatNormalScale = new Vector2(1, 1);
  21596. this.clearcoatNormalMap = null;
  21597. this.ior = 1.5;
  21598. Object.defineProperty(this, 'reflectivity', {
  21599. get: function () {
  21600. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  21601. },
  21602. set: function (reflectivity) {
  21603. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  21604. }
  21605. });
  21606. this.iridescenceMap = null;
  21607. this.iridescenceIOR = 1.3;
  21608. this.iridescenceThicknessRange = [100, 400];
  21609. this.iridescenceThicknessMap = null;
  21610. this.sheenColor = new Color(0x000000);
  21611. this.sheenColorMap = null;
  21612. this.sheenRoughness = 1.0;
  21613. this.sheenRoughnessMap = null;
  21614. this.transmissionMap = null;
  21615. this.thickness = 0;
  21616. this.thicknessMap = null;
  21617. this.attenuationDistance = 0.0;
  21618. this.attenuationColor = new Color(1, 1, 1);
  21619. this.specularIntensity = 1.0;
  21620. this.specularIntensityMap = null;
  21621. this.specularColor = new Color(1, 1, 1);
  21622. this.specularColorMap = null;
  21623. this._sheen = 0.0;
  21624. this._clearcoat = 0;
  21625. this._iridescence = 0;
  21626. this._transmission = 0;
  21627. this.setValues(parameters);
  21628. }
  21629. get sheen() {
  21630. return this._sheen;
  21631. }
  21632. set sheen(value) {
  21633. if (this._sheen > 0 !== value > 0) {
  21634. this.version++;
  21635. }
  21636. this._sheen = value;
  21637. }
  21638. get clearcoat() {
  21639. return this._clearcoat;
  21640. }
  21641. set clearcoat(value) {
  21642. if (this._clearcoat > 0 !== value > 0) {
  21643. this.version++;
  21644. }
  21645. this._clearcoat = value;
  21646. }
  21647. get iridescence() {
  21648. return this._iridescence;
  21649. }
  21650. set iridescence(value) {
  21651. if (this._iridescence > 0 !== value > 0) {
  21652. this.version++;
  21653. }
  21654. this._iridescence = value;
  21655. }
  21656. get transmission() {
  21657. return this._transmission;
  21658. }
  21659. set transmission(value) {
  21660. if (this._transmission > 0 !== value > 0) {
  21661. this.version++;
  21662. }
  21663. this._transmission = value;
  21664. }
  21665. copy(source) {
  21666. super.copy(source);
  21667. this.defines = {
  21668. 'STANDARD': '',
  21669. 'PHYSICAL': ''
  21670. };
  21671. this.clearcoat = source.clearcoat;
  21672. this.clearcoatMap = source.clearcoatMap;
  21673. this.clearcoatRoughness = source.clearcoatRoughness;
  21674. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21675. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21676. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  21677. this.ior = source.ior;
  21678. this.iridescence = source.iridescence;
  21679. this.iridescenceMap = source.iridescenceMap;
  21680. this.iridescenceIOR = source.iridescenceIOR;
  21681. this.iridescenceThicknessRange = [...source.iridescenceThicknessRange];
  21682. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  21683. this.sheen = source.sheen;
  21684. this.sheenColor.copy(source.sheenColor);
  21685. this.sheenColorMap = source.sheenColorMap;
  21686. this.sheenRoughness = source.sheenRoughness;
  21687. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21688. this.transmission = source.transmission;
  21689. this.transmissionMap = source.transmissionMap;
  21690. this.thickness = source.thickness;
  21691. this.thicknessMap = source.thicknessMap;
  21692. this.attenuationDistance = source.attenuationDistance;
  21693. this.attenuationColor.copy(source.attenuationColor);
  21694. this.specularIntensity = source.specularIntensity;
  21695. this.specularIntensityMap = source.specularIntensityMap;
  21696. this.specularColor.copy(source.specularColor);
  21697. this.specularColorMap = source.specularColorMap;
  21698. return this;
  21699. }
  21700. }
  21701. class MeshPhongMaterial extends Material {
  21702. constructor(parameters) {
  21703. super();
  21704. this.isMeshPhongMaterial = true;
  21705. this.type = 'MeshPhongMaterial';
  21706. this.color = new Color(0xffffff); // diffuse
  21707. this.specular = new Color(0x111111);
  21708. this.shininess = 30;
  21709. this.map = null;
  21710. this.lightMap = null;
  21711. this.lightMapIntensity = 1.0;
  21712. this.aoMap = null;
  21713. this.aoMapIntensity = 1.0;
  21714. this.emissive = new Color(0x000000);
  21715. this.emissiveIntensity = 1.0;
  21716. this.emissiveMap = null;
  21717. this.bumpMap = null;
  21718. this.bumpScale = 1;
  21719. this.normalMap = null;
  21720. this.normalMapType = TangentSpaceNormalMap;
  21721. this.normalScale = new Vector2(1, 1);
  21722. this.displacementMap = null;
  21723. this.displacementScale = 1;
  21724. this.displacementBias = 0;
  21725. this.specularMap = null;
  21726. this.alphaMap = null;
  21727. this.envMap = null;
  21728. this.combine = MultiplyOperation;
  21729. this.reflectivity = 1;
  21730. this.refractionRatio = 0.98;
  21731. this.wireframe = false;
  21732. this.wireframeLinewidth = 1;
  21733. this.wireframeLinecap = 'round';
  21734. this.wireframeLinejoin = 'round';
  21735. this.flatShading = false;
  21736. this.fog = true;
  21737. this.setValues(parameters);
  21738. }
  21739. copy(source) {
  21740. super.copy(source);
  21741. this.color.copy(source.color);
  21742. this.specular.copy(source.specular);
  21743. this.shininess = source.shininess;
  21744. this.map = source.map;
  21745. this.lightMap = source.lightMap;
  21746. this.lightMapIntensity = source.lightMapIntensity;
  21747. this.aoMap = source.aoMap;
  21748. this.aoMapIntensity = source.aoMapIntensity;
  21749. this.emissive.copy(source.emissive);
  21750. this.emissiveMap = source.emissiveMap;
  21751. this.emissiveIntensity = source.emissiveIntensity;
  21752. this.bumpMap = source.bumpMap;
  21753. this.bumpScale = source.bumpScale;
  21754. this.normalMap = source.normalMap;
  21755. this.normalMapType = source.normalMapType;
  21756. this.normalScale.copy(source.normalScale);
  21757. this.displacementMap = source.displacementMap;
  21758. this.displacementScale = source.displacementScale;
  21759. this.displacementBias = source.displacementBias;
  21760. this.specularMap = source.specularMap;
  21761. this.alphaMap = source.alphaMap;
  21762. this.envMap = source.envMap;
  21763. this.combine = source.combine;
  21764. this.reflectivity = source.reflectivity;
  21765. this.refractionRatio = source.refractionRatio;
  21766. this.wireframe = source.wireframe;
  21767. this.wireframeLinewidth = source.wireframeLinewidth;
  21768. this.wireframeLinecap = source.wireframeLinecap;
  21769. this.wireframeLinejoin = source.wireframeLinejoin;
  21770. this.flatShading = source.flatShading;
  21771. this.fog = source.fog;
  21772. return this;
  21773. }
  21774. }
  21775. class MeshToonMaterial extends Material {
  21776. constructor(parameters) {
  21777. super();
  21778. this.isMeshToonMaterial = true;
  21779. this.defines = {
  21780. 'TOON': ''
  21781. };
  21782. this.type = 'MeshToonMaterial';
  21783. this.color = new Color(0xffffff);
  21784. this.map = null;
  21785. this.gradientMap = null;
  21786. this.lightMap = null;
  21787. this.lightMapIntensity = 1.0;
  21788. this.aoMap = null;
  21789. this.aoMapIntensity = 1.0;
  21790. this.emissive = new Color(0x000000);
  21791. this.emissiveIntensity = 1.0;
  21792. this.emissiveMap = null;
  21793. this.bumpMap = null;
  21794. this.bumpScale = 1;
  21795. this.normalMap = null;
  21796. this.normalMapType = TangentSpaceNormalMap;
  21797. this.normalScale = new Vector2(1, 1);
  21798. this.displacementMap = null;
  21799. this.displacementScale = 1;
  21800. this.displacementBias = 0;
  21801. this.alphaMap = null;
  21802. this.wireframe = false;
  21803. this.wireframeLinewidth = 1;
  21804. this.wireframeLinecap = 'round';
  21805. this.wireframeLinejoin = 'round';
  21806. this.fog = true;
  21807. this.setValues(parameters);
  21808. }
  21809. copy(source) {
  21810. super.copy(source);
  21811. this.color.copy(source.color);
  21812. this.map = source.map;
  21813. this.gradientMap = source.gradientMap;
  21814. this.lightMap = source.lightMap;
  21815. this.lightMapIntensity = source.lightMapIntensity;
  21816. this.aoMap = source.aoMap;
  21817. this.aoMapIntensity = source.aoMapIntensity;
  21818. this.emissive.copy(source.emissive);
  21819. this.emissiveMap = source.emissiveMap;
  21820. this.emissiveIntensity = source.emissiveIntensity;
  21821. this.bumpMap = source.bumpMap;
  21822. this.bumpScale = source.bumpScale;
  21823. this.normalMap = source.normalMap;
  21824. this.normalMapType = source.normalMapType;
  21825. this.normalScale.copy(source.normalScale);
  21826. this.displacementMap = source.displacementMap;
  21827. this.displacementScale = source.displacementScale;
  21828. this.displacementBias = source.displacementBias;
  21829. this.alphaMap = source.alphaMap;
  21830. this.wireframe = source.wireframe;
  21831. this.wireframeLinewidth = source.wireframeLinewidth;
  21832. this.wireframeLinecap = source.wireframeLinecap;
  21833. this.wireframeLinejoin = source.wireframeLinejoin;
  21834. this.fog = source.fog;
  21835. return this;
  21836. }
  21837. }
  21838. class MeshNormalMaterial extends Material {
  21839. constructor(parameters) {
  21840. super();
  21841. this.isMeshNormalMaterial = true;
  21842. this.type = 'MeshNormalMaterial';
  21843. this.bumpMap = null;
  21844. this.bumpScale = 1;
  21845. this.normalMap = null;
  21846. this.normalMapType = TangentSpaceNormalMap;
  21847. this.normalScale = new Vector2(1, 1);
  21848. this.displacementMap = null;
  21849. this.displacementScale = 1;
  21850. this.displacementBias = 0;
  21851. this.wireframe = false;
  21852. this.wireframeLinewidth = 1;
  21853. this.flatShading = false;
  21854. this.setValues(parameters);
  21855. }
  21856. copy(source) {
  21857. super.copy(source);
  21858. this.bumpMap = source.bumpMap;
  21859. this.bumpScale = source.bumpScale;
  21860. this.normalMap = source.normalMap;
  21861. this.normalMapType = source.normalMapType;
  21862. this.normalScale.copy(source.normalScale);
  21863. this.displacementMap = source.displacementMap;
  21864. this.displacementScale = source.displacementScale;
  21865. this.displacementBias = source.displacementBias;
  21866. this.wireframe = source.wireframe;
  21867. this.wireframeLinewidth = source.wireframeLinewidth;
  21868. this.flatShading = source.flatShading;
  21869. return this;
  21870. }
  21871. }
  21872. class MeshLambertMaterial extends Material {
  21873. constructor(parameters) {
  21874. super();
  21875. this.isMeshLambertMaterial = true;
  21876. this.type = 'MeshLambertMaterial';
  21877. this.color = new Color(0xffffff); // diffuse
  21878. this.map = null;
  21879. this.lightMap = null;
  21880. this.lightMapIntensity = 1.0;
  21881. this.aoMap = null;
  21882. this.aoMapIntensity = 1.0;
  21883. this.emissive = new Color(0x000000);
  21884. this.emissiveIntensity = 1.0;
  21885. this.emissiveMap = null;
  21886. this.bumpMap = null;
  21887. this.bumpScale = 1;
  21888. this.normalMap = null;
  21889. this.normalMapType = TangentSpaceNormalMap;
  21890. this.normalScale = new Vector2(1, 1);
  21891. this.displacementMap = null;
  21892. this.displacementScale = 1;
  21893. this.displacementBias = 0;
  21894. this.specularMap = null;
  21895. this.alphaMap = null;
  21896. this.envMap = null;
  21897. this.combine = MultiplyOperation;
  21898. this.reflectivity = 1;
  21899. this.refractionRatio = 0.98;
  21900. this.wireframe = false;
  21901. this.wireframeLinewidth = 1;
  21902. this.wireframeLinecap = 'round';
  21903. this.wireframeLinejoin = 'round';
  21904. this.flatShading = false;
  21905. this.fog = true;
  21906. this.setValues(parameters);
  21907. }
  21908. copy(source) {
  21909. super.copy(source);
  21910. this.color.copy(source.color);
  21911. this.map = source.map;
  21912. this.lightMap = source.lightMap;
  21913. this.lightMapIntensity = source.lightMapIntensity;
  21914. this.aoMap = source.aoMap;
  21915. this.aoMapIntensity = source.aoMapIntensity;
  21916. this.emissive.copy(source.emissive);
  21917. this.emissiveMap = source.emissiveMap;
  21918. this.emissiveIntensity = source.emissiveIntensity;
  21919. this.bumpMap = source.bumpMap;
  21920. this.bumpScale = source.bumpScale;
  21921. this.normalMap = source.normalMap;
  21922. this.normalMapType = source.normalMapType;
  21923. this.normalScale.copy(source.normalScale);
  21924. this.displacementMap = source.displacementMap;
  21925. this.displacementScale = source.displacementScale;
  21926. this.displacementBias = source.displacementBias;
  21927. this.specularMap = source.specularMap;
  21928. this.alphaMap = source.alphaMap;
  21929. this.envMap = source.envMap;
  21930. this.combine = source.combine;
  21931. this.reflectivity = source.reflectivity;
  21932. this.refractionRatio = source.refractionRatio;
  21933. this.wireframe = source.wireframe;
  21934. this.wireframeLinewidth = source.wireframeLinewidth;
  21935. this.wireframeLinecap = source.wireframeLinecap;
  21936. this.wireframeLinejoin = source.wireframeLinejoin;
  21937. this.flatShading = source.flatShading;
  21938. this.fog = source.fog;
  21939. return this;
  21940. }
  21941. }
  21942. class MeshMatcapMaterial extends Material {
  21943. constructor(parameters) {
  21944. super();
  21945. this.isMeshMatcapMaterial = true;
  21946. this.defines = {
  21947. 'MATCAP': ''
  21948. };
  21949. this.type = 'MeshMatcapMaterial';
  21950. this.color = new Color(0xffffff); // diffuse
  21951. this.matcap = null;
  21952. this.map = null;
  21953. this.bumpMap = null;
  21954. this.bumpScale = 1;
  21955. this.normalMap = null;
  21956. this.normalMapType = TangentSpaceNormalMap;
  21957. this.normalScale = new Vector2(1, 1);
  21958. this.displacementMap = null;
  21959. this.displacementScale = 1;
  21960. this.displacementBias = 0;
  21961. this.alphaMap = null;
  21962. this.flatShading = false;
  21963. this.fog = true;
  21964. this.setValues(parameters);
  21965. }
  21966. copy(source) {
  21967. super.copy(source);
  21968. this.defines = {
  21969. 'MATCAP': ''
  21970. };
  21971. this.color.copy(source.color);
  21972. this.matcap = source.matcap;
  21973. this.map = source.map;
  21974. this.bumpMap = source.bumpMap;
  21975. this.bumpScale = source.bumpScale;
  21976. this.normalMap = source.normalMap;
  21977. this.normalMapType = source.normalMapType;
  21978. this.normalScale.copy(source.normalScale);
  21979. this.displacementMap = source.displacementMap;
  21980. this.displacementScale = source.displacementScale;
  21981. this.displacementBias = source.displacementBias;
  21982. this.alphaMap = source.alphaMap;
  21983. this.flatShading = source.flatShading;
  21984. this.fog = source.fog;
  21985. return this;
  21986. }
  21987. }
  21988. class LineDashedMaterial extends LineBasicMaterial {
  21989. constructor(parameters) {
  21990. super();
  21991. this.isLineDashedMaterial = true;
  21992. this.type = 'LineDashedMaterial';
  21993. this.scale = 1;
  21994. this.dashSize = 3;
  21995. this.gapSize = 1;
  21996. this.setValues(parameters);
  21997. }
  21998. copy(source) {
  21999. super.copy(source);
  22000. this.scale = source.scale;
  22001. this.dashSize = source.dashSize;
  22002. this.gapSize = source.gapSize;
  22003. return this;
  22004. }
  22005. }
  22006. function arraySlice(array, from, to) {
  22007. if (isTypedArray(array)) {
  22008. // in ios9 array.subarray(from, undefined) will return empty array
  22009. // but array.subarray(from) or array.subarray(from, len) is correct
  22010. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  22011. }
  22012. return array.slice(from, to);
  22013. } // converts an array to a specific type
  22014. function convertArray(array, type, forceClone) {
  22015. if (!array || // let 'undefined' and 'null' pass
  22016. !forceClone && array.constructor === type) return array;
  22017. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  22018. return new type(array); // create typed array
  22019. }
  22020. return Array.prototype.slice.call(array); // create Array
  22021. }
  22022. function isTypedArray(object) {
  22023. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  22024. } // returns an array by which times and values can be sorted
  22025. function getKeyframeOrder(times) {
  22026. function compareTime(i, j) {
  22027. return times[i] - times[j];
  22028. }
  22029. const n = times.length;
  22030. const result = new Array(n);
  22031. for (let i = 0; i !== n; ++i) result[i] = i;
  22032. result.sort(compareTime);
  22033. return result;
  22034. } // uses the array previously returned by 'getKeyframeOrder' to sort data
  22035. function sortedArray(values, stride, order) {
  22036. const nValues = values.length;
  22037. const result = new values.constructor(nValues);
  22038. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  22039. const srcOffset = order[i] * stride;
  22040. for (let j = 0; j !== stride; ++j) {
  22041. result[dstOffset++] = values[srcOffset + j];
  22042. }
  22043. }
  22044. return result;
  22045. } // function for parsing AOS keyframe formats
  22046. function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  22047. let i = 1,
  22048. key = jsonKeys[0];
  22049. while (key !== undefined && key[valuePropertyName] === undefined) {
  22050. key = jsonKeys[i++];
  22051. }
  22052. if (key === undefined) return; // no data
  22053. let value = key[valuePropertyName];
  22054. if (value === undefined) return; // no data
  22055. if (Array.isArray(value)) {
  22056. do {
  22057. value = key[valuePropertyName];
  22058. if (value !== undefined) {
  22059. times.push(key.time);
  22060. values.push.apply(values, value); // push all elements
  22061. }
  22062. key = jsonKeys[i++];
  22063. } while (key !== undefined);
  22064. } else if (value.toArray !== undefined) {
  22065. // ...assume THREE.Math-ish
  22066. do {
  22067. value = key[valuePropertyName];
  22068. if (value !== undefined) {
  22069. times.push(key.time);
  22070. value.toArray(values, values.length);
  22071. }
  22072. key = jsonKeys[i++];
  22073. } while (key !== undefined);
  22074. } else {
  22075. // otherwise push as-is
  22076. do {
  22077. value = key[valuePropertyName];
  22078. if (value !== undefined) {
  22079. times.push(key.time);
  22080. values.push(value);
  22081. }
  22082. key = jsonKeys[i++];
  22083. } while (key !== undefined);
  22084. }
  22085. }
  22086. function subclip(sourceClip, name, startFrame, endFrame, fps = 30) {
  22087. const clip = sourceClip.clone();
  22088. clip.name = name;
  22089. const tracks = [];
  22090. for (let i = 0; i < clip.tracks.length; ++i) {
  22091. const track = clip.tracks[i];
  22092. const valueSize = track.getValueSize();
  22093. const times = [];
  22094. const values = [];
  22095. for (let j = 0; j < track.times.length; ++j) {
  22096. const frame = track.times[j] * fps;
  22097. if (frame < startFrame || frame >= endFrame) continue;
  22098. times.push(track.times[j]);
  22099. for (let k = 0; k < valueSize; ++k) {
  22100. values.push(track.values[j * valueSize + k]);
  22101. }
  22102. }
  22103. if (times.length === 0) continue;
  22104. track.times = convertArray(times, track.times.constructor);
  22105. track.values = convertArray(values, track.values.constructor);
  22106. tracks.push(track);
  22107. }
  22108. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  22109. let minStartTime = Infinity;
  22110. for (let i = 0; i < clip.tracks.length; ++i) {
  22111. if (minStartTime > clip.tracks[i].times[0]) {
  22112. minStartTime = clip.tracks[i].times[0];
  22113. }
  22114. } // shift all tracks such that clip begins at t=0
  22115. for (let i = 0; i < clip.tracks.length; ++i) {
  22116. clip.tracks[i].shift(-1 * minStartTime);
  22117. }
  22118. clip.resetDuration();
  22119. return clip;
  22120. }
  22121. function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  22122. if (fps <= 0) fps = 30;
  22123. const numTracks = referenceClip.tracks.length;
  22124. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  22125. for (let i = 0; i < numTracks; ++i) {
  22126. const referenceTrack = referenceClip.tracks[i];
  22127. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  22128. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  22129. const targetTrack = targetClip.tracks.find(function (track) {
  22130. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  22131. });
  22132. if (targetTrack === undefined) continue;
  22133. let referenceOffset = 0;
  22134. const referenceValueSize = referenceTrack.getValueSize();
  22135. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22136. referenceOffset = referenceValueSize / 3;
  22137. }
  22138. let targetOffset = 0;
  22139. const targetValueSize = targetTrack.getValueSize();
  22140. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22141. targetOffset = targetValueSize / 3;
  22142. }
  22143. const lastIndex = referenceTrack.times.length - 1;
  22144. let referenceValue; // Find the value to subtract out of the track
  22145. if (referenceTime <= referenceTrack.times[0]) {
  22146. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22147. const startIndex = referenceOffset;
  22148. const endIndex = referenceValueSize - referenceOffset;
  22149. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  22150. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  22151. // Reference frame is after the last keyframe, so just use the last keyframe
  22152. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22153. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22154. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  22155. } else {
  22156. // Interpolate to the reference value
  22157. const interpolant = referenceTrack.createInterpolant();
  22158. const startIndex = referenceOffset;
  22159. const endIndex = referenceValueSize - referenceOffset;
  22160. interpolant.evaluate(referenceTime);
  22161. referenceValue = arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  22162. } // Conjugate the quaternion
  22163. if (referenceTrackType === 'quaternion') {
  22164. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  22165. referenceQuat.toArray(referenceValue);
  22166. } // Subtract the reference value from all of the track values
  22167. const numTimes = targetTrack.times.length;
  22168. for (let j = 0; j < numTimes; ++j) {
  22169. const valueStart = j * targetValueSize + targetOffset;
  22170. if (referenceTrackType === 'quaternion') {
  22171. // Multiply the conjugate for quaternion track types
  22172. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  22173. } else {
  22174. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  22175. for (let k = 0; k < valueEnd; ++k) {
  22176. targetTrack.values[valueStart + k] -= referenceValue[k];
  22177. }
  22178. }
  22179. }
  22180. }
  22181. targetClip.blendMode = AdditiveAnimationBlendMode;
  22182. return targetClip;
  22183. }
  22184. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22185. __proto__: null,
  22186. arraySlice: arraySlice,
  22187. convertArray: convertArray,
  22188. isTypedArray: isTypedArray,
  22189. getKeyframeOrder: getKeyframeOrder,
  22190. sortedArray: sortedArray,
  22191. flattenJSON: flattenJSON,
  22192. subclip: subclip,
  22193. makeClipAdditive: makeClipAdditive
  22194. });
  22195. /**
  22196. * Abstract base class of interpolants over parametric samples.
  22197. *
  22198. * The parameter domain is one dimensional, typically the time or a path
  22199. * along a curve defined by the data.
  22200. *
  22201. * The sample values can have any dimensionality and derived classes may
  22202. * apply special interpretations to the data.
  22203. *
  22204. * This class provides the interval seek in a Template Method, deferring
  22205. * the actual interpolation to derived classes.
  22206. *
  22207. * Time complexity is O(1) for linear access crossing at most two points
  22208. * and O(log N) for random access, where N is the number of positions.
  22209. *
  22210. * References:
  22211. *
  22212. * http://www.oodesign.com/template-method-pattern.html
  22213. *
  22214. */
  22215. class Interpolant {
  22216. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22217. this.parameterPositions = parameterPositions;
  22218. this._cachedIndex = 0;
  22219. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  22220. this.sampleValues = sampleValues;
  22221. this.valueSize = sampleSize;
  22222. this.settings = null;
  22223. this.DefaultSettings_ = {};
  22224. }
  22225. evaluate(t) {
  22226. const pp = this.parameterPositions;
  22227. let i1 = this._cachedIndex,
  22228. t1 = pp[i1],
  22229. t0 = pp[i1 - 1];
  22230. validate_interval: {
  22231. seek: {
  22232. let right;
  22233. linear_scan: {
  22234. //- See http://jsperf.com/comparison-to-undefined/3
  22235. //- slower code:
  22236. //-
  22237. //- if ( t >= t1 || t1 === undefined ) {
  22238. forward_scan: if (!(t < t1)) {
  22239. for (let giveUpAt = i1 + 2;;) {
  22240. if (t1 === undefined) {
  22241. if (t < t0) break forward_scan; // after end
  22242. i1 = pp.length;
  22243. this._cachedIndex = i1;
  22244. return this.copySampleValue_(i1 - 1);
  22245. }
  22246. if (i1 === giveUpAt) break; // this loop
  22247. t0 = t1;
  22248. t1 = pp[++i1];
  22249. if (t < t1) {
  22250. // we have arrived at the sought interval
  22251. break seek;
  22252. }
  22253. } // prepare binary search on the right side of the index
  22254. right = pp.length;
  22255. break linear_scan;
  22256. } //- slower code:
  22257. //- if ( t < t0 || t0 === undefined ) {
  22258. if (!(t >= t0)) {
  22259. // looping?
  22260. const t1global = pp[1];
  22261. if (t < t1global) {
  22262. i1 = 2; // + 1, using the scan for the details
  22263. t0 = t1global;
  22264. } // linear reverse scan
  22265. for (let giveUpAt = i1 - 2;;) {
  22266. if (t0 === undefined) {
  22267. // before start
  22268. this._cachedIndex = 0;
  22269. return this.copySampleValue_(0);
  22270. }
  22271. if (i1 === giveUpAt) break; // this loop
  22272. t1 = t0;
  22273. t0 = pp[--i1 - 1];
  22274. if (t >= t0) {
  22275. // we have arrived at the sought interval
  22276. break seek;
  22277. }
  22278. } // prepare binary search on the left side of the index
  22279. right = i1;
  22280. i1 = 0;
  22281. break linear_scan;
  22282. } // the interval is valid
  22283. break validate_interval;
  22284. } // linear scan
  22285. // binary search
  22286. while (i1 < right) {
  22287. const mid = i1 + right >>> 1;
  22288. if (t < pp[mid]) {
  22289. right = mid;
  22290. } else {
  22291. i1 = mid + 1;
  22292. }
  22293. }
  22294. t1 = pp[i1];
  22295. t0 = pp[i1 - 1]; // check boundary cases, again
  22296. if (t0 === undefined) {
  22297. this._cachedIndex = 0;
  22298. return this.copySampleValue_(0);
  22299. }
  22300. if (t1 === undefined) {
  22301. i1 = pp.length;
  22302. this._cachedIndex = i1;
  22303. return this.copySampleValue_(i1 - 1);
  22304. }
  22305. } // seek
  22306. this._cachedIndex = i1;
  22307. this.intervalChanged_(i1, t0, t1);
  22308. } // validate_interval
  22309. return this.interpolate_(i1, t0, t, t1);
  22310. }
  22311. getSettings_() {
  22312. return this.settings || this.DefaultSettings_;
  22313. }
  22314. copySampleValue_(index) {
  22315. // copies a sample value to the result buffer
  22316. const result = this.resultBuffer,
  22317. values = this.sampleValues,
  22318. stride = this.valueSize,
  22319. offset = index * stride;
  22320. for (let i = 0; i !== stride; ++i) {
  22321. result[i] = values[offset + i];
  22322. }
  22323. return result;
  22324. } // Template methods for derived classes:
  22325. interpolate_() {
  22326. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  22327. }
  22328. intervalChanged_() {// empty
  22329. }
  22330. }
  22331. /**
  22332. * Fast and simple cubic spline interpolant.
  22333. *
  22334. * It was derived from a Hermitian construction setting the first derivative
  22335. * at each sample position to the linear slope between neighboring positions
  22336. * over their parameter interval.
  22337. */
  22338. class CubicInterpolant extends Interpolant {
  22339. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22340. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22341. this._weightPrev = -0;
  22342. this._offsetPrev = -0;
  22343. this._weightNext = -0;
  22344. this._offsetNext = -0;
  22345. this.DefaultSettings_ = {
  22346. endingStart: ZeroCurvatureEnding,
  22347. endingEnd: ZeroCurvatureEnding
  22348. };
  22349. }
  22350. intervalChanged_(i1, t0, t1) {
  22351. const pp = this.parameterPositions;
  22352. let iPrev = i1 - 2,
  22353. iNext = i1 + 1,
  22354. tPrev = pp[iPrev],
  22355. tNext = pp[iNext];
  22356. if (tPrev === undefined) {
  22357. switch (this.getSettings_().endingStart) {
  22358. case ZeroSlopeEnding:
  22359. // f'(t0) = 0
  22360. iPrev = i1;
  22361. tPrev = 2 * t0 - t1;
  22362. break;
  22363. case WrapAroundEnding:
  22364. // use the other end of the curve
  22365. iPrev = pp.length - 2;
  22366. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  22367. break;
  22368. default:
  22369. // ZeroCurvatureEnding
  22370. // f''(t0) = 0 a.k.a. Natural Spline
  22371. iPrev = i1;
  22372. tPrev = t1;
  22373. }
  22374. }
  22375. if (tNext === undefined) {
  22376. switch (this.getSettings_().endingEnd) {
  22377. case ZeroSlopeEnding:
  22378. // f'(tN) = 0
  22379. iNext = i1;
  22380. tNext = 2 * t1 - t0;
  22381. break;
  22382. case WrapAroundEnding:
  22383. // use the other end of the curve
  22384. iNext = 1;
  22385. tNext = t1 + pp[1] - pp[0];
  22386. break;
  22387. default:
  22388. // ZeroCurvatureEnding
  22389. // f''(tN) = 0, a.k.a. Natural Spline
  22390. iNext = i1 - 1;
  22391. tNext = t0;
  22392. }
  22393. }
  22394. const halfDt = (t1 - t0) * 0.5,
  22395. stride = this.valueSize;
  22396. this._weightPrev = halfDt / (t0 - tPrev);
  22397. this._weightNext = halfDt / (tNext - t1);
  22398. this._offsetPrev = iPrev * stride;
  22399. this._offsetNext = iNext * stride;
  22400. }
  22401. interpolate_(i1, t0, t, t1) {
  22402. const result = this.resultBuffer,
  22403. values = this.sampleValues,
  22404. stride = this.valueSize,
  22405. o1 = i1 * stride,
  22406. o0 = o1 - stride,
  22407. oP = this._offsetPrev,
  22408. oN = this._offsetNext,
  22409. wP = this._weightPrev,
  22410. wN = this._weightNext,
  22411. p = (t - t0) / (t1 - t0),
  22412. pp = p * p,
  22413. ppp = pp * p; // evaluate polynomials
  22414. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  22415. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  22416. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  22417. const sN = wN * ppp - wN * pp; // combine data linearly
  22418. for (let i = 0; i !== stride; ++i) {
  22419. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  22420. }
  22421. return result;
  22422. }
  22423. }
  22424. class LinearInterpolant extends Interpolant {
  22425. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22426. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22427. }
  22428. interpolate_(i1, t0, t, t1) {
  22429. const result = this.resultBuffer,
  22430. values = this.sampleValues,
  22431. stride = this.valueSize,
  22432. offset1 = i1 * stride,
  22433. offset0 = offset1 - stride,
  22434. weight1 = (t - t0) / (t1 - t0),
  22435. weight0 = 1 - weight1;
  22436. for (let i = 0; i !== stride; ++i) {
  22437. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  22438. }
  22439. return result;
  22440. }
  22441. }
  22442. /**
  22443. *
  22444. * Interpolant that evaluates to the sample value at the position preceding
  22445. * the parameter.
  22446. */
  22447. class DiscreteInterpolant extends Interpolant {
  22448. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22449. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22450. }
  22451. interpolate_(i1
  22452. /*, t0, t, t1 */
  22453. ) {
  22454. return this.copySampleValue_(i1 - 1);
  22455. }
  22456. }
  22457. class KeyframeTrack {
  22458. constructor(name, times, values, interpolation) {
  22459. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  22460. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  22461. this.name = name;
  22462. this.times = convertArray(times, this.TimeBufferType);
  22463. this.values = convertArray(values, this.ValueBufferType);
  22464. this.setInterpolation(interpolation || this.DefaultInterpolation);
  22465. } // Serialization (in static context, because of constructor invocation
  22466. // and automatic invocation of .toJSON):
  22467. static toJSON(track) {
  22468. const trackType = track.constructor;
  22469. let json; // derived classes can define a static toJSON method
  22470. if (trackType.toJSON !== this.toJSON) {
  22471. json = trackType.toJSON(track);
  22472. } else {
  22473. // by default, we assume the data can be serialized as-is
  22474. json = {
  22475. 'name': track.name,
  22476. 'times': convertArray(track.times, Array),
  22477. 'values': convertArray(track.values, Array)
  22478. };
  22479. const interpolation = track.getInterpolation();
  22480. if (interpolation !== track.DefaultInterpolation) {
  22481. json.interpolation = interpolation;
  22482. }
  22483. }
  22484. json.type = track.ValueTypeName; // mandatory
  22485. return json;
  22486. }
  22487. InterpolantFactoryMethodDiscrete(result) {
  22488. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  22489. }
  22490. InterpolantFactoryMethodLinear(result) {
  22491. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22492. }
  22493. InterpolantFactoryMethodSmooth(result) {
  22494. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  22495. }
  22496. setInterpolation(interpolation) {
  22497. let factoryMethod;
  22498. switch (interpolation) {
  22499. case InterpolateDiscrete:
  22500. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22501. break;
  22502. case InterpolateLinear:
  22503. factoryMethod = this.InterpolantFactoryMethodLinear;
  22504. break;
  22505. case InterpolateSmooth:
  22506. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22507. break;
  22508. }
  22509. if (factoryMethod === undefined) {
  22510. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  22511. if (this.createInterpolant === undefined) {
  22512. // fall back to default, unless the default itself is messed up
  22513. if (interpolation !== this.DefaultInterpolation) {
  22514. this.setInterpolation(this.DefaultInterpolation);
  22515. } else {
  22516. throw new Error(message); // fatal, in this case
  22517. }
  22518. }
  22519. console.warn('THREE.KeyframeTrack:', message);
  22520. return this;
  22521. }
  22522. this.createInterpolant = factoryMethod;
  22523. return this;
  22524. }
  22525. getInterpolation() {
  22526. switch (this.createInterpolant) {
  22527. case this.InterpolantFactoryMethodDiscrete:
  22528. return InterpolateDiscrete;
  22529. case this.InterpolantFactoryMethodLinear:
  22530. return InterpolateLinear;
  22531. case this.InterpolantFactoryMethodSmooth:
  22532. return InterpolateSmooth;
  22533. }
  22534. }
  22535. getValueSize() {
  22536. return this.values.length / this.times.length;
  22537. } // move all keyframes either forwards or backwards in time
  22538. shift(timeOffset) {
  22539. if (timeOffset !== 0.0) {
  22540. const times = this.times;
  22541. for (let i = 0, n = times.length; i !== n; ++i) {
  22542. times[i] += timeOffset;
  22543. }
  22544. }
  22545. return this;
  22546. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22547. scale(timeScale) {
  22548. if (timeScale !== 1.0) {
  22549. const times = this.times;
  22550. for (let i = 0, n = times.length; i !== n; ++i) {
  22551. times[i] *= timeScale;
  22552. }
  22553. }
  22554. return this;
  22555. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22556. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22557. trim(startTime, endTime) {
  22558. const times = this.times,
  22559. nKeys = times.length;
  22560. let from = 0,
  22561. to = nKeys - 1;
  22562. while (from !== nKeys && times[from] < startTime) {
  22563. ++from;
  22564. }
  22565. while (to !== -1 && times[to] > endTime) {
  22566. --to;
  22567. }
  22568. ++to; // inclusive -> exclusive bound
  22569. if (from !== 0 || to !== nKeys) {
  22570. // empty tracks are forbidden, so keep at least one keyframe
  22571. if (from >= to) {
  22572. to = Math.max(to, 1);
  22573. from = to - 1;
  22574. }
  22575. const stride = this.getValueSize();
  22576. this.times = arraySlice(times, from, to);
  22577. this.values = arraySlice(this.values, from * stride, to * stride);
  22578. }
  22579. return this;
  22580. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22581. validate() {
  22582. let valid = true;
  22583. const valueSize = this.getValueSize();
  22584. if (valueSize - Math.floor(valueSize) !== 0) {
  22585. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  22586. valid = false;
  22587. }
  22588. const times = this.times,
  22589. values = this.values,
  22590. nKeys = times.length;
  22591. if (nKeys === 0) {
  22592. console.error('THREE.KeyframeTrack: Track is empty.', this);
  22593. valid = false;
  22594. }
  22595. let prevTime = null;
  22596. for (let i = 0; i !== nKeys; i++) {
  22597. const currTime = times[i];
  22598. if (typeof currTime === 'number' && isNaN(currTime)) {
  22599. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  22600. valid = false;
  22601. break;
  22602. }
  22603. if (prevTime !== null && prevTime > currTime) {
  22604. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  22605. valid = false;
  22606. break;
  22607. }
  22608. prevTime = currTime;
  22609. }
  22610. if (values !== undefined) {
  22611. if (isTypedArray(values)) {
  22612. for (let i = 0, n = values.length; i !== n; ++i) {
  22613. const value = values[i];
  22614. if (isNaN(value)) {
  22615. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  22616. valid = false;
  22617. break;
  22618. }
  22619. }
  22620. }
  22621. }
  22622. return valid;
  22623. } // removes equivalent sequential keys as common in morph target sequences
  22624. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22625. optimize() {
  22626. // times or values may be shared with other tracks, so overwriting is unsafe
  22627. const times = arraySlice(this.times),
  22628. values = arraySlice(this.values),
  22629. stride = this.getValueSize(),
  22630. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22631. lastIndex = times.length - 1;
  22632. let writeIndex = 1;
  22633. for (let i = 1; i < lastIndex; ++i) {
  22634. let keep = false;
  22635. const time = times[i];
  22636. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  22637. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  22638. if (!smoothInterpolation) {
  22639. // remove unnecessary keyframes same as their neighbors
  22640. const offset = i * stride,
  22641. offsetP = offset - stride,
  22642. offsetN = offset + stride;
  22643. for (let j = 0; j !== stride; ++j) {
  22644. const value = values[offset + j];
  22645. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  22646. keep = true;
  22647. break;
  22648. }
  22649. }
  22650. } else {
  22651. keep = true;
  22652. }
  22653. } // in-place compaction
  22654. if (keep) {
  22655. if (i !== writeIndex) {
  22656. times[writeIndex] = times[i];
  22657. const readOffset = i * stride,
  22658. writeOffset = writeIndex * stride;
  22659. for (let j = 0; j !== stride; ++j) {
  22660. values[writeOffset + j] = values[readOffset + j];
  22661. }
  22662. }
  22663. ++writeIndex;
  22664. }
  22665. } // flush last keyframe (compaction looks ahead)
  22666. if (lastIndex > 0) {
  22667. times[writeIndex] = times[lastIndex];
  22668. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  22669. values[writeOffset + j] = values[readOffset + j];
  22670. }
  22671. ++writeIndex;
  22672. }
  22673. if (writeIndex !== times.length) {
  22674. this.times = arraySlice(times, 0, writeIndex);
  22675. this.values = arraySlice(values, 0, writeIndex * stride);
  22676. } else {
  22677. this.times = times;
  22678. this.values = values;
  22679. }
  22680. return this;
  22681. }
  22682. clone() {
  22683. const times = arraySlice(this.times, 0);
  22684. const values = arraySlice(this.values, 0);
  22685. const TypedKeyframeTrack = this.constructor;
  22686. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22687. track.createInterpolant = this.createInterpolant;
  22688. return track;
  22689. }
  22690. }
  22691. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22692. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22693. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22694. /**
  22695. * A Track of Boolean keyframe values.
  22696. */
  22697. class BooleanKeyframeTrack extends KeyframeTrack {}
  22698. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22699. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22700. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22701. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22702. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  22703. /**
  22704. * A Track of keyframe values that represent color.
  22705. */
  22706. class ColorKeyframeTrack extends KeyframeTrack {}
  22707. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  22708. /**
  22709. * A Track of numeric keyframe values.
  22710. */
  22711. class NumberKeyframeTrack extends KeyframeTrack {}
  22712. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  22713. /**
  22714. * Spherical linear unit quaternion interpolant.
  22715. */
  22716. class QuaternionLinearInterpolant extends Interpolant {
  22717. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22718. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22719. }
  22720. interpolate_(i1, t0, t, t1) {
  22721. const result = this.resultBuffer,
  22722. values = this.sampleValues,
  22723. stride = this.valueSize,
  22724. alpha = (t - t0) / (t1 - t0);
  22725. let offset = i1 * stride;
  22726. for (let end = offset + stride; offset !== end; offset += 4) {
  22727. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  22728. }
  22729. return result;
  22730. }
  22731. }
  22732. /**
  22733. * A Track of quaternion keyframe values.
  22734. */
  22735. class QuaternionKeyframeTrack extends KeyframeTrack {
  22736. InterpolantFactoryMethodLinear(result) {
  22737. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22738. }
  22739. }
  22740. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  22741. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22742. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22743. /**
  22744. * A Track that interpolates Strings
  22745. */
  22746. class StringKeyframeTrack extends KeyframeTrack {}
  22747. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22748. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22749. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22750. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22751. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22752. /**
  22753. * A Track of vectored keyframe values.
  22754. */
  22755. class VectorKeyframeTrack extends KeyframeTrack {}
  22756. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  22757. class AnimationClip {
  22758. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  22759. this.name = name;
  22760. this.tracks = tracks;
  22761. this.duration = duration;
  22762. this.blendMode = blendMode;
  22763. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  22764. if (this.duration < 0) {
  22765. this.resetDuration();
  22766. }
  22767. }
  22768. static parse(json) {
  22769. const tracks = [],
  22770. jsonTracks = json.tracks,
  22771. frameTime = 1.0 / (json.fps || 1.0);
  22772. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  22773. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22774. }
  22775. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22776. clip.uuid = json.uuid;
  22777. return clip;
  22778. }
  22779. static toJSON(clip) {
  22780. const tracks = [],
  22781. clipTracks = clip.tracks;
  22782. const json = {
  22783. 'name': clip.name,
  22784. 'duration': clip.duration,
  22785. 'tracks': tracks,
  22786. 'uuid': clip.uuid,
  22787. 'blendMode': clip.blendMode
  22788. };
  22789. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22790. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22791. }
  22792. return json;
  22793. }
  22794. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22795. const numMorphTargets = morphTargetSequence.length;
  22796. const tracks = [];
  22797. for (let i = 0; i < numMorphTargets; i++) {
  22798. let times = [];
  22799. let values = [];
  22800. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22801. values.push(0, 1, 0);
  22802. const order = getKeyframeOrder(times);
  22803. times = sortedArray(times, 1, order);
  22804. values = sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22805. // last frame as well for perfect loop.
  22806. if (!noLoop && times[0] === 0) {
  22807. times.push(numMorphTargets);
  22808. values.push(values[0]);
  22809. }
  22810. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22811. }
  22812. return new this(name, -1, tracks);
  22813. }
  22814. static findByName(objectOrClipArray, name) {
  22815. let clipArray = objectOrClipArray;
  22816. if (!Array.isArray(objectOrClipArray)) {
  22817. const o = objectOrClipArray;
  22818. clipArray = o.geometry && o.geometry.animations || o.animations;
  22819. }
  22820. for (let i = 0; i < clipArray.length; i++) {
  22821. if (clipArray[i].name === name) {
  22822. return clipArray[i];
  22823. }
  22824. }
  22825. return null;
  22826. }
  22827. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22828. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22829. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22830. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22831. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22832. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22833. const morphTarget = morphTargets[i];
  22834. const parts = morphTarget.name.match(pattern);
  22835. if (parts && parts.length > 1) {
  22836. const name = parts[1];
  22837. let animationMorphTargets = animationToMorphTargets[name];
  22838. if (!animationMorphTargets) {
  22839. animationToMorphTargets[name] = animationMorphTargets = [];
  22840. }
  22841. animationMorphTargets.push(morphTarget);
  22842. }
  22843. }
  22844. const clips = [];
  22845. for (const name in animationToMorphTargets) {
  22846. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22847. }
  22848. return clips;
  22849. } // parse the animation.hierarchy format
  22850. static parseAnimation(animation, bones) {
  22851. if (!animation) {
  22852. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22853. return null;
  22854. }
  22855. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22856. // only return track if there are actually keys.
  22857. if (animationKeys.length !== 0) {
  22858. const times = [];
  22859. const values = [];
  22860. flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22861. if (times.length !== 0) {
  22862. destTracks.push(new trackType(trackName, times, values));
  22863. }
  22864. }
  22865. };
  22866. const tracks = [];
  22867. const clipName = animation.name || 'default';
  22868. const fps = animation.fps || 30;
  22869. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22870. let duration = animation.length || -1;
  22871. const hierarchyTracks = animation.hierarchy || [];
  22872. for (let h = 0; h < hierarchyTracks.length; h++) {
  22873. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22874. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22875. if (animationKeys[0].morphTargets) {
  22876. // figure out all morph targets used in this track
  22877. const morphTargetNames = {};
  22878. let k;
  22879. for (k = 0; k < animationKeys.length; k++) {
  22880. if (animationKeys[k].morphTargets) {
  22881. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22882. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22883. }
  22884. }
  22885. } // create a track for each morph target with all zero
  22886. // morphTargetInfluences except for the keys in which
  22887. // the morphTarget is named.
  22888. for (const morphTargetName in morphTargetNames) {
  22889. const times = [];
  22890. const values = [];
  22891. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22892. const animationKey = animationKeys[k];
  22893. times.push(animationKey.time);
  22894. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22895. }
  22896. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22897. }
  22898. duration = morphTargetNames.length * fps;
  22899. } else {
  22900. // ...assume skeletal animation
  22901. const boneName = '.bones[' + bones[h].name + ']';
  22902. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22903. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22904. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22905. }
  22906. }
  22907. if (tracks.length === 0) {
  22908. return null;
  22909. }
  22910. const clip = new this(clipName, duration, tracks, blendMode);
  22911. return clip;
  22912. }
  22913. resetDuration() {
  22914. const tracks = this.tracks;
  22915. let duration = 0;
  22916. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22917. const track = this.tracks[i];
  22918. duration = Math.max(duration, track.times[track.times.length - 1]);
  22919. }
  22920. this.duration = duration;
  22921. return this;
  22922. }
  22923. trim() {
  22924. for (let i = 0; i < this.tracks.length; i++) {
  22925. this.tracks[i].trim(0, this.duration);
  22926. }
  22927. return this;
  22928. }
  22929. validate() {
  22930. let valid = true;
  22931. for (let i = 0; i < this.tracks.length; i++) {
  22932. valid = valid && this.tracks[i].validate();
  22933. }
  22934. return valid;
  22935. }
  22936. optimize() {
  22937. for (let i = 0; i < this.tracks.length; i++) {
  22938. this.tracks[i].optimize();
  22939. }
  22940. return this;
  22941. }
  22942. clone() {
  22943. const tracks = [];
  22944. for (let i = 0; i < this.tracks.length; i++) {
  22945. tracks.push(this.tracks[i].clone());
  22946. }
  22947. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22948. }
  22949. toJSON() {
  22950. return this.constructor.toJSON(this);
  22951. }
  22952. }
  22953. function getTrackTypeForValueTypeName(typeName) {
  22954. switch (typeName.toLowerCase()) {
  22955. case 'scalar':
  22956. case 'double':
  22957. case 'float':
  22958. case 'number':
  22959. case 'integer':
  22960. return NumberKeyframeTrack;
  22961. case 'vector':
  22962. case 'vector2':
  22963. case 'vector3':
  22964. case 'vector4':
  22965. return VectorKeyframeTrack;
  22966. case 'color':
  22967. return ColorKeyframeTrack;
  22968. case 'quaternion':
  22969. return QuaternionKeyframeTrack;
  22970. case 'bool':
  22971. case 'boolean':
  22972. return BooleanKeyframeTrack;
  22973. case 'string':
  22974. return StringKeyframeTrack;
  22975. }
  22976. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22977. }
  22978. function parseKeyframeTrack(json) {
  22979. if (json.type === undefined) {
  22980. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22981. }
  22982. const trackType = getTrackTypeForValueTypeName(json.type);
  22983. if (json.times === undefined) {
  22984. const times = [],
  22985. values = [];
  22986. flattenJSON(json.keys, times, values, 'value');
  22987. json.times = times;
  22988. json.values = values;
  22989. } // derived classes can define a static parse method
  22990. if (trackType.parse !== undefined) {
  22991. return trackType.parse(json);
  22992. } else {
  22993. // by default, we assume a constructor compatible with the base
  22994. return new trackType(json.name, json.times, json.values, json.interpolation);
  22995. }
  22996. }
  22997. const Cache = {
  22998. enabled: false,
  22999. files: {},
  23000. add: function (key, file) {
  23001. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  23002. this.files[key] = file;
  23003. },
  23004. get: function (key) {
  23005. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  23006. return this.files[key];
  23007. },
  23008. remove: function (key) {
  23009. delete this.files[key];
  23010. },
  23011. clear: function () {
  23012. this.files = {};
  23013. }
  23014. };
  23015. class LoadingManager {
  23016. constructor(onLoad, onProgress, onError) {
  23017. const scope = this;
  23018. let isLoading = false;
  23019. let itemsLoaded = 0;
  23020. let itemsTotal = 0;
  23021. let urlModifier = undefined;
  23022. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  23023. // in the constructor
  23024. this.onStart = undefined;
  23025. this.onLoad = onLoad;
  23026. this.onProgress = onProgress;
  23027. this.onError = onError;
  23028. this.itemStart = function (url) {
  23029. itemsTotal++;
  23030. if (isLoading === false) {
  23031. if (scope.onStart !== undefined) {
  23032. scope.onStart(url, itemsLoaded, itemsTotal);
  23033. }
  23034. }
  23035. isLoading = true;
  23036. };
  23037. this.itemEnd = function (url) {
  23038. itemsLoaded++;
  23039. if (scope.onProgress !== undefined) {
  23040. scope.onProgress(url, itemsLoaded, itemsTotal);
  23041. }
  23042. if (itemsLoaded === itemsTotal) {
  23043. isLoading = false;
  23044. if (scope.onLoad !== undefined) {
  23045. scope.onLoad();
  23046. }
  23047. }
  23048. };
  23049. this.itemError = function (url) {
  23050. if (scope.onError !== undefined) {
  23051. scope.onError(url);
  23052. }
  23053. };
  23054. this.resolveURL = function (url) {
  23055. if (urlModifier) {
  23056. return urlModifier(url);
  23057. }
  23058. return url;
  23059. };
  23060. this.setURLModifier = function (transform) {
  23061. urlModifier = transform;
  23062. return this;
  23063. };
  23064. this.addHandler = function (regex, loader) {
  23065. handlers.push(regex, loader);
  23066. return this;
  23067. };
  23068. this.removeHandler = function (regex) {
  23069. const index = handlers.indexOf(regex);
  23070. if (index !== -1) {
  23071. handlers.splice(index, 2);
  23072. }
  23073. return this;
  23074. };
  23075. this.getHandler = function (file) {
  23076. for (let i = 0, l = handlers.length; i < l; i += 2) {
  23077. const regex = handlers[i];
  23078. const loader = handlers[i + 1];
  23079. if (regex.global) regex.lastIndex = 0; // see #17920
  23080. if (regex.test(file)) {
  23081. return loader;
  23082. }
  23083. }
  23084. return null;
  23085. };
  23086. }
  23087. }
  23088. const DefaultLoadingManager = /*@__PURE__*/new LoadingManager();
  23089. class Loader {
  23090. constructor(manager) {
  23091. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  23092. this.crossOrigin = 'anonymous';
  23093. this.withCredentials = false;
  23094. this.path = '';
  23095. this.resourcePath = '';
  23096. this.requestHeader = {};
  23097. }
  23098. load() {}
  23099. loadAsync(url, onProgress) {
  23100. const scope = this;
  23101. return new Promise(function (resolve, reject) {
  23102. scope.load(url, resolve, onProgress, reject);
  23103. });
  23104. }
  23105. parse() {}
  23106. setCrossOrigin(crossOrigin) {
  23107. this.crossOrigin = crossOrigin;
  23108. return this;
  23109. }
  23110. setWithCredentials(value) {
  23111. this.withCredentials = value;
  23112. return this;
  23113. }
  23114. setPath(path) {
  23115. this.path = path;
  23116. return this;
  23117. }
  23118. setResourcePath(resourcePath) {
  23119. this.resourcePath = resourcePath;
  23120. return this;
  23121. }
  23122. setRequestHeader(requestHeader) {
  23123. this.requestHeader = requestHeader;
  23124. return this;
  23125. }
  23126. }
  23127. const loading = {};
  23128. class HttpError extends Error {
  23129. constructor(message, response) {
  23130. super(message);
  23131. this.response = response;
  23132. }
  23133. }
  23134. class FileLoader extends Loader {
  23135. constructor(manager) {
  23136. super(manager);
  23137. }
  23138. load(url, onLoad, onProgress, onError) {
  23139. if (url === undefined) url = '';
  23140. if (this.path !== undefined) url = this.path + url;
  23141. url = this.manager.resolveURL(url);
  23142. const cached = Cache.get(url);
  23143. if (cached !== undefined) {
  23144. this.manager.itemStart(url);
  23145. setTimeout(() => {
  23146. if (onLoad) onLoad(cached);
  23147. this.manager.itemEnd(url);
  23148. }, 0);
  23149. return cached;
  23150. } // Check if request is duplicate
  23151. if (loading[url] !== undefined) {
  23152. loading[url].push({
  23153. onLoad: onLoad,
  23154. onProgress: onProgress,
  23155. onError: onError
  23156. });
  23157. return;
  23158. } // Initialise array for duplicate requests
  23159. loading[url] = [];
  23160. loading[url].push({
  23161. onLoad: onLoad,
  23162. onProgress: onProgress,
  23163. onError: onError
  23164. }); // create request
  23165. const req = new Request(url, {
  23166. headers: new Headers(this.requestHeader),
  23167. credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
  23168. }); // record states ( avoid data race )
  23169. const mimeType = this.mimeType;
  23170. const responseType = this.responseType; // start the fetch
  23171. fetch(req).then(response => {
  23172. if (response.status === 200 || response.status === 0) {
  23173. // Some browsers return HTTP Status 0 when using non-http protocol
  23174. // e.g. 'file://' or 'data://'. Handle as success.
  23175. if (response.status === 0) {
  23176. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  23177. } // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23178. if (typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined) {
  23179. return response;
  23180. }
  23181. const callbacks = loading[url];
  23182. const reader = response.body.getReader();
  23183. const contentLength = response.headers.get('Content-Length');
  23184. const total = contentLength ? parseInt(contentLength) : 0;
  23185. const lengthComputable = total !== 0;
  23186. let loaded = 0; // periodically read data into the new stream tracking while download progress
  23187. const stream = new ReadableStream({
  23188. start(controller) {
  23189. readData();
  23190. function readData() {
  23191. reader.read().then(({
  23192. done,
  23193. value
  23194. }) => {
  23195. if (done) {
  23196. controller.close();
  23197. } else {
  23198. loaded += value.byteLength;
  23199. const event = new ProgressEvent('progress', {
  23200. lengthComputable,
  23201. loaded,
  23202. total
  23203. });
  23204. for (let i = 0, il = callbacks.length; i < il; i++) {
  23205. const callback = callbacks[i];
  23206. if (callback.onProgress) callback.onProgress(event);
  23207. }
  23208. controller.enqueue(value);
  23209. readData();
  23210. }
  23211. });
  23212. }
  23213. }
  23214. });
  23215. return new Response(stream);
  23216. } else {
  23217. throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response);
  23218. }
  23219. }).then(response => {
  23220. switch (responseType) {
  23221. case 'arraybuffer':
  23222. return response.arrayBuffer();
  23223. case 'blob':
  23224. return response.blob();
  23225. case 'document':
  23226. return response.text().then(text => {
  23227. const parser = new DOMParser();
  23228. return parser.parseFromString(text, mimeType);
  23229. });
  23230. case 'json':
  23231. return response.json();
  23232. default:
  23233. if (mimeType === undefined) {
  23234. return response.text();
  23235. } else {
  23236. // sniff encoding
  23237. const re = /charset="?([^;"\s]*)"?/i;
  23238. const exec = re.exec(mimeType);
  23239. const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
  23240. const decoder = new TextDecoder(label);
  23241. return response.arrayBuffer().then(ab => decoder.decode(ab));
  23242. }
  23243. }
  23244. }).then(data => {
  23245. // Add to cache only on HTTP success, so that we do not cache
  23246. // error response bodies as proper responses to requests.
  23247. Cache.add(url, data);
  23248. const callbacks = loading[url];
  23249. delete loading[url];
  23250. for (let i = 0, il = callbacks.length; i < il; i++) {
  23251. const callback = callbacks[i];
  23252. if (callback.onLoad) callback.onLoad(data);
  23253. }
  23254. }).catch(err => {
  23255. // Abort errors and other errors are handled the same
  23256. const callbacks = loading[url];
  23257. if (callbacks === undefined) {
  23258. // When onLoad was called and url was deleted in `loading`
  23259. this.manager.itemError(url);
  23260. throw err;
  23261. }
  23262. delete loading[url];
  23263. for (let i = 0, il = callbacks.length; i < il; i++) {
  23264. const callback = callbacks[i];
  23265. if (callback.onError) callback.onError(err);
  23266. }
  23267. this.manager.itemError(url);
  23268. }).finally(() => {
  23269. this.manager.itemEnd(url);
  23270. });
  23271. this.manager.itemStart(url);
  23272. }
  23273. setResponseType(value) {
  23274. this.responseType = value;
  23275. return this;
  23276. }
  23277. setMimeType(value) {
  23278. this.mimeType = value;
  23279. return this;
  23280. }
  23281. }
  23282. class AnimationLoader extends Loader {
  23283. constructor(manager) {
  23284. super(manager);
  23285. }
  23286. load(url, onLoad, onProgress, onError) {
  23287. const scope = this;
  23288. const loader = new FileLoader(this.manager);
  23289. loader.setPath(this.path);
  23290. loader.setRequestHeader(this.requestHeader);
  23291. loader.setWithCredentials(this.withCredentials);
  23292. loader.load(url, function (text) {
  23293. try {
  23294. onLoad(scope.parse(JSON.parse(text)));
  23295. } catch (e) {
  23296. if (onError) {
  23297. onError(e);
  23298. } else {
  23299. console.error(e);
  23300. }
  23301. scope.manager.itemError(url);
  23302. }
  23303. }, onProgress, onError);
  23304. }
  23305. parse(json) {
  23306. const animations = [];
  23307. for (let i = 0; i < json.length; i++) {
  23308. const clip = AnimationClip.parse(json[i]);
  23309. animations.push(clip);
  23310. }
  23311. return animations;
  23312. }
  23313. }
  23314. /**
  23315. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23316. *
  23317. * Sub classes have to implement the parse() method which will be used in load().
  23318. */
  23319. class CompressedTextureLoader extends Loader {
  23320. constructor(manager) {
  23321. super(manager);
  23322. }
  23323. load(url, onLoad, onProgress, onError) {
  23324. const scope = this;
  23325. const images = [];
  23326. const texture = new CompressedTexture();
  23327. const loader = new FileLoader(this.manager);
  23328. loader.setPath(this.path);
  23329. loader.setResponseType('arraybuffer');
  23330. loader.setRequestHeader(this.requestHeader);
  23331. loader.setWithCredentials(scope.withCredentials);
  23332. let loaded = 0;
  23333. function loadTexture(i) {
  23334. loader.load(url[i], function (buffer) {
  23335. const texDatas = scope.parse(buffer, true);
  23336. images[i] = {
  23337. width: texDatas.width,
  23338. height: texDatas.height,
  23339. format: texDatas.format,
  23340. mipmaps: texDatas.mipmaps
  23341. };
  23342. loaded += 1;
  23343. if (loaded === 6) {
  23344. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  23345. texture.image = images;
  23346. texture.format = texDatas.format;
  23347. texture.needsUpdate = true;
  23348. if (onLoad) onLoad(texture);
  23349. }
  23350. }, onProgress, onError);
  23351. }
  23352. if (Array.isArray(url)) {
  23353. for (let i = 0, il = url.length; i < il; ++i) {
  23354. loadTexture(i);
  23355. }
  23356. } else {
  23357. // compressed cubemap texture stored in a single DDS file
  23358. loader.load(url, function (buffer) {
  23359. const texDatas = scope.parse(buffer, true);
  23360. if (texDatas.isCubemap) {
  23361. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23362. for (let f = 0; f < faces; f++) {
  23363. images[f] = {
  23364. mipmaps: []
  23365. };
  23366. for (let i = 0; i < texDatas.mipmapCount; i++) {
  23367. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  23368. images[f].format = texDatas.format;
  23369. images[f].width = texDatas.width;
  23370. images[f].height = texDatas.height;
  23371. }
  23372. }
  23373. texture.image = images;
  23374. } else {
  23375. texture.image.width = texDatas.width;
  23376. texture.image.height = texDatas.height;
  23377. texture.mipmaps = texDatas.mipmaps;
  23378. }
  23379. if (texDatas.mipmapCount === 1) {
  23380. texture.minFilter = LinearFilter;
  23381. }
  23382. texture.format = texDatas.format;
  23383. texture.needsUpdate = true;
  23384. if (onLoad) onLoad(texture);
  23385. }, onProgress, onError);
  23386. }
  23387. return texture;
  23388. }
  23389. }
  23390. class ImageLoader extends Loader {
  23391. constructor(manager) {
  23392. super(manager);
  23393. }
  23394. load(url, onLoad, onProgress, onError) {
  23395. if (this.path !== undefined) url = this.path + url;
  23396. url = this.manager.resolveURL(url);
  23397. const scope = this;
  23398. const cached = Cache.get(url);
  23399. if (cached !== undefined) {
  23400. scope.manager.itemStart(url);
  23401. setTimeout(function () {
  23402. if (onLoad) onLoad(cached);
  23403. scope.manager.itemEnd(url);
  23404. }, 0);
  23405. return cached;
  23406. }
  23407. const image = createElementNS('img');
  23408. function onImageLoad() {
  23409. removeEventListeners();
  23410. Cache.add(url, this);
  23411. if (onLoad) onLoad(this);
  23412. scope.manager.itemEnd(url);
  23413. }
  23414. function onImageError(event) {
  23415. removeEventListeners();
  23416. if (onError) onError(event);
  23417. scope.manager.itemError(url);
  23418. scope.manager.itemEnd(url);
  23419. }
  23420. function removeEventListeners() {
  23421. image.removeEventListener('load', onImageLoad, false);
  23422. image.removeEventListener('error', onImageError, false);
  23423. }
  23424. image.addEventListener('load', onImageLoad, false);
  23425. image.addEventListener('error', onImageError, false);
  23426. if (url.slice(0, 5) !== 'data:') {
  23427. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  23428. }
  23429. scope.manager.itemStart(url);
  23430. image.src = url;
  23431. return image;
  23432. }
  23433. }
  23434. class CubeTextureLoader extends Loader {
  23435. constructor(manager) {
  23436. super(manager);
  23437. }
  23438. load(urls, onLoad, onProgress, onError) {
  23439. const texture = new CubeTexture();
  23440. const loader = new ImageLoader(this.manager);
  23441. loader.setCrossOrigin(this.crossOrigin);
  23442. loader.setPath(this.path);
  23443. let loaded = 0;
  23444. function loadTexture(i) {
  23445. loader.load(urls[i], function (image) {
  23446. texture.images[i] = image;
  23447. loaded++;
  23448. if (loaded === 6) {
  23449. texture.needsUpdate = true;
  23450. if (onLoad) onLoad(texture);
  23451. }
  23452. }, undefined, onError);
  23453. }
  23454. for (let i = 0; i < urls.length; ++i) {
  23455. loadTexture(i);
  23456. }
  23457. return texture;
  23458. }
  23459. }
  23460. /**
  23461. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23462. *
  23463. * Sub classes have to implement the parse() method which will be used in load().
  23464. */
  23465. class DataTextureLoader extends Loader {
  23466. constructor(manager) {
  23467. super(manager);
  23468. }
  23469. load(url, onLoad, onProgress, onError) {
  23470. const scope = this;
  23471. const texture = new DataTexture();
  23472. const loader = new FileLoader(this.manager);
  23473. loader.setResponseType('arraybuffer');
  23474. loader.setRequestHeader(this.requestHeader);
  23475. loader.setPath(this.path);
  23476. loader.setWithCredentials(scope.withCredentials);
  23477. loader.load(url, function (buffer) {
  23478. const texData = scope.parse(buffer);
  23479. if (!texData) return;
  23480. if (texData.image !== undefined) {
  23481. texture.image = texData.image;
  23482. } else if (texData.data !== undefined) {
  23483. texture.image.width = texData.width;
  23484. texture.image.height = texData.height;
  23485. texture.image.data = texData.data;
  23486. }
  23487. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23488. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23489. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23490. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23491. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23492. if (texData.encoding !== undefined) {
  23493. texture.encoding = texData.encoding;
  23494. }
  23495. if (texData.flipY !== undefined) {
  23496. texture.flipY = texData.flipY;
  23497. }
  23498. if (texData.format !== undefined) {
  23499. texture.format = texData.format;
  23500. }
  23501. if (texData.type !== undefined) {
  23502. texture.type = texData.type;
  23503. }
  23504. if (texData.mipmaps !== undefined) {
  23505. texture.mipmaps = texData.mipmaps;
  23506. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23507. }
  23508. if (texData.mipmapCount === 1) {
  23509. texture.minFilter = LinearFilter;
  23510. }
  23511. if (texData.generateMipmaps !== undefined) {
  23512. texture.generateMipmaps = texData.generateMipmaps;
  23513. }
  23514. texture.needsUpdate = true;
  23515. if (onLoad) onLoad(texture, texData);
  23516. }, onProgress, onError);
  23517. return texture;
  23518. }
  23519. }
  23520. class TextureLoader extends Loader {
  23521. constructor(manager) {
  23522. super(manager);
  23523. }
  23524. load(url, onLoad, onProgress, onError) {
  23525. const texture = new Texture();
  23526. const loader = new ImageLoader(this.manager);
  23527. loader.setCrossOrigin(this.crossOrigin);
  23528. loader.setPath(this.path);
  23529. loader.load(url, function (image) {
  23530. texture.image = image;
  23531. texture.needsUpdate = true;
  23532. if (onLoad !== undefined) {
  23533. onLoad(texture);
  23534. }
  23535. }, onProgress, onError);
  23536. return texture;
  23537. }
  23538. }
  23539. class Light extends Object3D {
  23540. constructor(color, intensity = 1) {
  23541. super();
  23542. this.isLight = true;
  23543. this.type = 'Light';
  23544. this.color = new Color(color);
  23545. this.intensity = intensity;
  23546. }
  23547. dispose() {// Empty here in base class; some subclasses override.
  23548. }
  23549. copy(source, recursive) {
  23550. super.copy(source, recursive);
  23551. this.color.copy(source.color);
  23552. this.intensity = source.intensity;
  23553. return this;
  23554. }
  23555. toJSON(meta) {
  23556. const data = super.toJSON(meta);
  23557. data.object.color = this.color.getHex();
  23558. data.object.intensity = this.intensity;
  23559. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23560. if (this.distance !== undefined) data.object.distance = this.distance;
  23561. if (this.angle !== undefined) data.object.angle = this.angle;
  23562. if (this.decay !== undefined) data.object.decay = this.decay;
  23563. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23564. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23565. return data;
  23566. }
  23567. }
  23568. class HemisphereLight extends Light {
  23569. constructor(skyColor, groundColor, intensity) {
  23570. super(skyColor, intensity);
  23571. this.isHemisphereLight = true;
  23572. this.type = 'HemisphereLight';
  23573. this.position.copy(Object3D.DefaultUp);
  23574. this.updateMatrix();
  23575. this.groundColor = new Color(groundColor);
  23576. }
  23577. copy(source, recursive) {
  23578. super.copy(source, recursive);
  23579. this.groundColor.copy(source.groundColor);
  23580. return this;
  23581. }
  23582. }
  23583. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23584. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23585. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23586. class LightShadow {
  23587. constructor(camera) {
  23588. this.camera = camera;
  23589. this.bias = 0;
  23590. this.normalBias = 0;
  23591. this.radius = 1;
  23592. this.blurSamples = 8;
  23593. this.mapSize = new Vector2(512, 512);
  23594. this.map = null;
  23595. this.mapPass = null;
  23596. this.matrix = new Matrix4();
  23597. this.autoUpdate = true;
  23598. this.needsUpdate = false;
  23599. this._frustum = new Frustum();
  23600. this._frameExtents = new Vector2(1, 1);
  23601. this._viewportCount = 1;
  23602. this._viewports = [new Vector4(0, 0, 1, 1)];
  23603. }
  23604. getViewportCount() {
  23605. return this._viewportCount;
  23606. }
  23607. getFrustum() {
  23608. return this._frustum;
  23609. }
  23610. updateMatrices(light) {
  23611. const shadowCamera = this.camera;
  23612. const shadowMatrix = this.matrix;
  23613. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23614. shadowCamera.position.copy(_lightPositionWorld$1);
  23615. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23616. shadowCamera.lookAt(_lookTarget$1);
  23617. shadowCamera.updateMatrixWorld();
  23618. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23619. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23620. 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);
  23621. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23622. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23623. }
  23624. getViewport(viewportIndex) {
  23625. return this._viewports[viewportIndex];
  23626. }
  23627. getFrameExtents() {
  23628. return this._frameExtents;
  23629. }
  23630. dispose() {
  23631. if (this.map) {
  23632. this.map.dispose();
  23633. }
  23634. if (this.mapPass) {
  23635. this.mapPass.dispose();
  23636. }
  23637. }
  23638. copy(source) {
  23639. this.camera = source.camera.clone();
  23640. this.bias = source.bias;
  23641. this.radius = source.radius;
  23642. this.mapSize.copy(source.mapSize);
  23643. return this;
  23644. }
  23645. clone() {
  23646. return new this.constructor().copy(this);
  23647. }
  23648. toJSON() {
  23649. const object = {};
  23650. if (this.bias !== 0) object.bias = this.bias;
  23651. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23652. if (this.radius !== 1) object.radius = this.radius;
  23653. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23654. object.camera = this.camera.toJSON(false).object;
  23655. delete object.camera.matrix;
  23656. return object;
  23657. }
  23658. }
  23659. class SpotLightShadow extends LightShadow {
  23660. constructor() {
  23661. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23662. this.isSpotLightShadow = true;
  23663. this.focus = 1;
  23664. }
  23665. updateMatrices(light) {
  23666. const camera = this.camera;
  23667. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23668. const aspect = this.mapSize.width / this.mapSize.height;
  23669. const far = light.distance || camera.far;
  23670. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23671. camera.fov = fov;
  23672. camera.aspect = aspect;
  23673. camera.far = far;
  23674. camera.updateProjectionMatrix();
  23675. }
  23676. super.updateMatrices(light);
  23677. }
  23678. copy(source) {
  23679. super.copy(source);
  23680. this.focus = source.focus;
  23681. return this;
  23682. }
  23683. }
  23684. class SpotLight extends Light {
  23685. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23686. super(color, intensity);
  23687. this.isSpotLight = true;
  23688. this.type = 'SpotLight';
  23689. this.position.copy(Object3D.DefaultUp);
  23690. this.updateMatrix();
  23691. this.target = new Object3D();
  23692. this.distance = distance;
  23693. this.angle = angle;
  23694. this.penumbra = penumbra;
  23695. this.decay = decay; // for physically correct lights, should be 2.
  23696. this.shadow = new SpotLightShadow();
  23697. }
  23698. get power() {
  23699. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23700. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23701. return this.intensity * Math.PI;
  23702. }
  23703. set power(power) {
  23704. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23705. this.intensity = power / Math.PI;
  23706. }
  23707. dispose() {
  23708. this.shadow.dispose();
  23709. }
  23710. copy(source, recursive) {
  23711. super.copy(source, recursive);
  23712. this.distance = source.distance;
  23713. this.angle = source.angle;
  23714. this.penumbra = source.penumbra;
  23715. this.decay = source.decay;
  23716. this.target = source.target.clone();
  23717. this.shadow = source.shadow.clone();
  23718. return this;
  23719. }
  23720. }
  23721. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23722. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23723. const _lookTarget = /*@__PURE__*/new Vector3();
  23724. class PointLightShadow extends LightShadow {
  23725. constructor() {
  23726. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23727. this.isPointLightShadow = true;
  23728. this._frameExtents = new Vector2(4, 2);
  23729. this._viewportCount = 6;
  23730. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23731. // following orientation:
  23732. //
  23733. // xzXZ
  23734. // y Y
  23735. //
  23736. // X - Positive x direction
  23737. // x - Negative x direction
  23738. // Y - Positive y direction
  23739. // y - Negative y direction
  23740. // Z - Positive z direction
  23741. // z - Negative z direction
  23742. // positive X
  23743. new Vector4(2, 1, 1, 1), // negative X
  23744. new Vector4(0, 1, 1, 1), // positive Z
  23745. new Vector4(3, 1, 1, 1), // negative Z
  23746. new Vector4(1, 1, 1, 1), // positive Y
  23747. new Vector4(3, 0, 1, 1), // negative Y
  23748. new Vector4(1, 0, 1, 1)];
  23749. 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)];
  23750. 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)];
  23751. }
  23752. updateMatrices(light, viewportIndex = 0) {
  23753. const camera = this.camera;
  23754. const shadowMatrix = this.matrix;
  23755. const far = light.distance || camera.far;
  23756. if (far !== camera.far) {
  23757. camera.far = far;
  23758. camera.updateProjectionMatrix();
  23759. }
  23760. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23761. camera.position.copy(_lightPositionWorld);
  23762. _lookTarget.copy(camera.position);
  23763. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23764. camera.up.copy(this._cubeUps[viewportIndex]);
  23765. camera.lookAt(_lookTarget);
  23766. camera.updateMatrixWorld();
  23767. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23768. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23769. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23770. }
  23771. }
  23772. class PointLight extends Light {
  23773. constructor(color, intensity, distance = 0, decay = 1) {
  23774. super(color, intensity);
  23775. this.isPointLight = true;
  23776. this.type = 'PointLight';
  23777. this.distance = distance;
  23778. this.decay = decay; // for physically correct lights, should be 2.
  23779. this.shadow = new PointLightShadow();
  23780. }
  23781. get power() {
  23782. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23783. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23784. return this.intensity * 4 * Math.PI;
  23785. }
  23786. set power(power) {
  23787. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23788. this.intensity = power / (4 * Math.PI);
  23789. }
  23790. dispose() {
  23791. this.shadow.dispose();
  23792. }
  23793. copy(source, recursive) {
  23794. super.copy(source, recursive);
  23795. this.distance = source.distance;
  23796. this.decay = source.decay;
  23797. this.shadow = source.shadow.clone();
  23798. return this;
  23799. }
  23800. }
  23801. class DirectionalLightShadow extends LightShadow {
  23802. constructor() {
  23803. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23804. this.isDirectionalLightShadow = true;
  23805. }
  23806. }
  23807. class DirectionalLight extends Light {
  23808. constructor(color, intensity) {
  23809. super(color, intensity);
  23810. this.isDirectionalLight = true;
  23811. this.type = 'DirectionalLight';
  23812. this.position.copy(Object3D.DefaultUp);
  23813. this.updateMatrix();
  23814. this.target = new Object3D();
  23815. this.shadow = new DirectionalLightShadow();
  23816. }
  23817. dispose() {
  23818. this.shadow.dispose();
  23819. }
  23820. copy(source) {
  23821. super.copy(source);
  23822. this.target = source.target.clone();
  23823. this.shadow = source.shadow.clone();
  23824. return this;
  23825. }
  23826. }
  23827. class AmbientLight extends Light {
  23828. constructor(color, intensity) {
  23829. super(color, intensity);
  23830. this.isAmbientLight = true;
  23831. this.type = 'AmbientLight';
  23832. }
  23833. }
  23834. class RectAreaLight extends Light {
  23835. constructor(color, intensity, width = 10, height = 10) {
  23836. super(color, intensity);
  23837. this.isRectAreaLight = true;
  23838. this.type = 'RectAreaLight';
  23839. this.width = width;
  23840. this.height = height;
  23841. }
  23842. get power() {
  23843. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23844. return this.intensity * this.width * this.height * Math.PI;
  23845. }
  23846. set power(power) {
  23847. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23848. this.intensity = power / (this.width * this.height * Math.PI);
  23849. }
  23850. copy(source) {
  23851. super.copy(source);
  23852. this.width = source.width;
  23853. this.height = source.height;
  23854. return this;
  23855. }
  23856. toJSON(meta) {
  23857. const data = super.toJSON(meta);
  23858. data.object.width = this.width;
  23859. data.object.height = this.height;
  23860. return data;
  23861. }
  23862. }
  23863. /**
  23864. * Primary reference:
  23865. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23866. *
  23867. * Secondary reference:
  23868. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23869. */
  23870. // 3-band SH defined by 9 coefficients
  23871. class SphericalHarmonics3 {
  23872. constructor() {
  23873. this.isSphericalHarmonics3 = true;
  23874. this.coefficients = [];
  23875. for (let i = 0; i < 9; i++) {
  23876. this.coefficients.push(new Vector3());
  23877. }
  23878. }
  23879. set(coefficients) {
  23880. for (let i = 0; i < 9; i++) {
  23881. this.coefficients[i].copy(coefficients[i]);
  23882. }
  23883. return this;
  23884. }
  23885. zero() {
  23886. for (let i = 0; i < 9; i++) {
  23887. this.coefficients[i].set(0, 0, 0);
  23888. }
  23889. return this;
  23890. } // get the radiance in the direction of the normal
  23891. // target is a Vector3
  23892. getAt(normal, target) {
  23893. // normal is assumed to be unit length
  23894. const x = normal.x,
  23895. y = normal.y,
  23896. z = normal.z;
  23897. const coeff = this.coefficients; // band 0
  23898. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23899. target.addScaledVector(coeff[1], 0.488603 * y);
  23900. target.addScaledVector(coeff[2], 0.488603 * z);
  23901. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23902. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23903. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23904. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23905. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23906. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23907. return target;
  23908. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23909. // target is a Vector3
  23910. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23911. getIrradianceAt(normal, target) {
  23912. // normal is assumed to be unit length
  23913. const x = normal.x,
  23914. y = normal.y,
  23915. z = normal.z;
  23916. const coeff = this.coefficients; // band 0
  23917. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23918. // band 1
  23919. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23920. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23921. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23922. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23923. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23924. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23925. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23926. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23927. return target;
  23928. }
  23929. add(sh) {
  23930. for (let i = 0; i < 9; i++) {
  23931. this.coefficients[i].add(sh.coefficients[i]);
  23932. }
  23933. return this;
  23934. }
  23935. addScaledSH(sh, s) {
  23936. for (let i = 0; i < 9; i++) {
  23937. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23938. }
  23939. return this;
  23940. }
  23941. scale(s) {
  23942. for (let i = 0; i < 9; i++) {
  23943. this.coefficients[i].multiplyScalar(s);
  23944. }
  23945. return this;
  23946. }
  23947. lerp(sh, alpha) {
  23948. for (let i = 0; i < 9; i++) {
  23949. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23950. }
  23951. return this;
  23952. }
  23953. equals(sh) {
  23954. for (let i = 0; i < 9; i++) {
  23955. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23956. return false;
  23957. }
  23958. }
  23959. return true;
  23960. }
  23961. copy(sh) {
  23962. return this.set(sh.coefficients);
  23963. }
  23964. clone() {
  23965. return new this.constructor().copy(this);
  23966. }
  23967. fromArray(array, offset = 0) {
  23968. const coefficients = this.coefficients;
  23969. for (let i = 0; i < 9; i++) {
  23970. coefficients[i].fromArray(array, offset + i * 3);
  23971. }
  23972. return this;
  23973. }
  23974. toArray(array = [], offset = 0) {
  23975. const coefficients = this.coefficients;
  23976. for (let i = 0; i < 9; i++) {
  23977. coefficients[i].toArray(array, offset + i * 3);
  23978. }
  23979. return array;
  23980. } // evaluate the basis functions
  23981. // shBasis is an Array[ 9 ]
  23982. static getBasisAt(normal, shBasis) {
  23983. // normal is assumed to be unit length
  23984. const x = normal.x,
  23985. y = normal.y,
  23986. z = normal.z; // band 0
  23987. shBasis[0] = 0.282095; // band 1
  23988. shBasis[1] = 0.488603 * y;
  23989. shBasis[2] = 0.488603 * z;
  23990. shBasis[3] = 0.488603 * x; // band 2
  23991. shBasis[4] = 1.092548 * x * y;
  23992. shBasis[5] = 1.092548 * y * z;
  23993. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23994. shBasis[7] = 1.092548 * x * z;
  23995. shBasis[8] = 0.546274 * (x * x - y * y);
  23996. }
  23997. }
  23998. class LightProbe extends Light {
  23999. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  24000. super(undefined, intensity);
  24001. this.isLightProbe = true;
  24002. this.sh = sh;
  24003. }
  24004. copy(source) {
  24005. super.copy(source);
  24006. this.sh.copy(source.sh);
  24007. return this;
  24008. }
  24009. fromJSON(json) {
  24010. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24011. this.sh.fromArray(json.sh);
  24012. return this;
  24013. }
  24014. toJSON(meta) {
  24015. const data = super.toJSON(meta);
  24016. data.object.sh = this.sh.toArray();
  24017. return data;
  24018. }
  24019. }
  24020. class MaterialLoader extends Loader {
  24021. constructor(manager) {
  24022. super(manager);
  24023. this.textures = {};
  24024. }
  24025. load(url, onLoad, onProgress, onError) {
  24026. const scope = this;
  24027. const loader = new FileLoader(scope.manager);
  24028. loader.setPath(scope.path);
  24029. loader.setRequestHeader(scope.requestHeader);
  24030. loader.setWithCredentials(scope.withCredentials);
  24031. loader.load(url, function (text) {
  24032. try {
  24033. onLoad(scope.parse(JSON.parse(text)));
  24034. } catch (e) {
  24035. if (onError) {
  24036. onError(e);
  24037. } else {
  24038. console.error(e);
  24039. }
  24040. scope.manager.itemError(url);
  24041. }
  24042. }, onProgress, onError);
  24043. }
  24044. parse(json) {
  24045. const textures = this.textures;
  24046. function getTexture(name) {
  24047. if (textures[name] === undefined) {
  24048. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24049. }
  24050. return textures[name];
  24051. }
  24052. const material = MaterialLoader.createMaterialFromType(json.type);
  24053. if (json.uuid !== undefined) material.uuid = json.uuid;
  24054. if (json.name !== undefined) material.name = json.name;
  24055. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  24056. if (json.roughness !== undefined) material.roughness = json.roughness;
  24057. if (json.metalness !== undefined) material.metalness = json.metalness;
  24058. if (json.sheen !== undefined) material.sheen = json.sheen;
  24059. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  24060. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  24061. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  24062. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  24063. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  24064. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  24065. if (json.shininess !== undefined) material.shininess = json.shininess;
  24066. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24067. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24068. if (json.iridescence !== undefined) material.iridescence = json.iridescence;
  24069. if (json.iridescenceIOR !== undefined) material.iridescenceIOR = json.iridescenceIOR;
  24070. if (json.iridescenceThicknessRange !== undefined) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24071. if (json.transmission !== undefined) material.transmission = json.transmission;
  24072. if (json.thickness !== undefined) material.thickness = json.thickness;
  24073. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  24074. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  24075. if (json.fog !== undefined) material.fog = json.fog;
  24076. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24077. if (json.blending !== undefined) material.blending = json.blending;
  24078. if (json.combine !== undefined) material.combine = json.combine;
  24079. if (json.side !== undefined) material.side = json.side;
  24080. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  24081. if (json.opacity !== undefined) material.opacity = json.opacity;
  24082. if (json.transparent !== undefined) material.transparent = json.transparent;
  24083. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24084. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24085. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24086. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24087. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24088. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24089. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24090. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24091. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24092. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24093. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24094. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24095. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24096. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24097. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24098. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24099. if (json.rotation !== undefined) material.rotation = json.rotation;
  24100. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24101. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24102. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24103. if (json.scale !== undefined) material.scale = json.scale;
  24104. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24105. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24106. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24107. if (json.dithering !== undefined) material.dithering = json.dithering;
  24108. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  24109. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  24110. if (json.visible !== undefined) material.visible = json.visible;
  24111. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24112. if (json.userData !== undefined) material.userData = json.userData;
  24113. if (json.vertexColors !== undefined) {
  24114. if (typeof json.vertexColors === 'number') {
  24115. material.vertexColors = json.vertexColors > 0 ? true : false;
  24116. } else {
  24117. material.vertexColors = json.vertexColors;
  24118. }
  24119. } // Shader Material
  24120. if (json.uniforms !== undefined) {
  24121. for (const name in json.uniforms) {
  24122. const uniform = json.uniforms[name];
  24123. material.uniforms[name] = {};
  24124. switch (uniform.type) {
  24125. case 't':
  24126. material.uniforms[name].value = getTexture(uniform.value);
  24127. break;
  24128. case 'c':
  24129. material.uniforms[name].value = new Color().setHex(uniform.value);
  24130. break;
  24131. case 'v2':
  24132. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24133. break;
  24134. case 'v3':
  24135. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24136. break;
  24137. case 'v4':
  24138. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24139. break;
  24140. case 'm3':
  24141. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24142. break;
  24143. case 'm4':
  24144. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24145. break;
  24146. default:
  24147. material.uniforms[name].value = uniform.value;
  24148. }
  24149. }
  24150. }
  24151. if (json.defines !== undefined) material.defines = json.defines;
  24152. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24153. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24154. if (json.glslVersion !== undefined) material.glslVersion = json.glslVersion;
  24155. if (json.extensions !== undefined) {
  24156. for (const key in json.extensions) {
  24157. material.extensions[key] = json.extensions[key];
  24158. }
  24159. } // for PointsMaterial
  24160. if (json.size !== undefined) material.size = json.size;
  24161. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24162. if (json.map !== undefined) material.map = getTexture(json.map);
  24163. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24164. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  24165. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24166. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24167. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24168. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24169. if (json.normalScale !== undefined) {
  24170. let normalScale = json.normalScale;
  24171. if (Array.isArray(normalScale) === false) {
  24172. // Blender exporter used to export a scalar. See #7459
  24173. normalScale = [normalScale, normalScale];
  24174. }
  24175. material.normalScale = new Vector2().fromArray(normalScale);
  24176. }
  24177. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24178. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24179. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24180. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24181. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24182. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24183. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24184. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24185. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  24186. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  24187. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24188. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24189. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24190. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24191. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24192. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24193. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24194. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24195. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24196. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  24197. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  24198. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24199. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24200. if (json.iridescenceMap !== undefined) material.iridescenceMap = getTexture(json.iridescenceMap);
  24201. if (json.iridescenceThicknessMap !== undefined) material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap);
  24202. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  24203. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  24204. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  24205. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  24206. return material;
  24207. }
  24208. setTextures(value) {
  24209. this.textures = value;
  24210. return this;
  24211. }
  24212. static createMaterialFromType(type) {
  24213. const materialLib = {
  24214. ShadowMaterial,
  24215. SpriteMaterial,
  24216. RawShaderMaterial,
  24217. ShaderMaterial,
  24218. PointsMaterial,
  24219. MeshPhysicalMaterial,
  24220. MeshStandardMaterial,
  24221. MeshPhongMaterial,
  24222. MeshToonMaterial,
  24223. MeshNormalMaterial,
  24224. MeshLambertMaterial,
  24225. MeshDepthMaterial,
  24226. MeshDistanceMaterial,
  24227. MeshBasicMaterial,
  24228. MeshMatcapMaterial,
  24229. LineDashedMaterial,
  24230. LineBasicMaterial,
  24231. Material
  24232. };
  24233. return new materialLib[type]();
  24234. }
  24235. }
  24236. class LoaderUtils {
  24237. static decodeText(array) {
  24238. if (typeof TextDecoder !== 'undefined') {
  24239. return new TextDecoder().decode(array);
  24240. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24241. // throws a "maximum call stack size exceeded" error for large arrays.
  24242. let s = '';
  24243. for (let i = 0, il = array.length; i < il; i++) {
  24244. // Implicitly assumes little-endian.
  24245. s += String.fromCharCode(array[i]);
  24246. }
  24247. try {
  24248. // merges multi-byte utf-8 characters.
  24249. return decodeURIComponent(escape(s));
  24250. } catch (e) {
  24251. // see #16358
  24252. return s;
  24253. }
  24254. }
  24255. static extractUrlBase(url) {
  24256. const index = url.lastIndexOf('/');
  24257. if (index === -1) return './';
  24258. return url.slice(0, index + 1);
  24259. }
  24260. static resolveURL(url, path) {
  24261. // Invalid URL
  24262. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  24263. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  24264. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  24265. } // Absolute URL http://,https://,//
  24266. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  24267. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  24268. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  24269. return path + url;
  24270. }
  24271. }
  24272. class InstancedBufferGeometry extends BufferGeometry {
  24273. constructor() {
  24274. super();
  24275. this.isInstancedBufferGeometry = true;
  24276. this.type = 'InstancedBufferGeometry';
  24277. this.instanceCount = Infinity;
  24278. }
  24279. copy(source) {
  24280. super.copy(source);
  24281. this.instanceCount = source.instanceCount;
  24282. return this;
  24283. }
  24284. clone() {
  24285. return new this.constructor().copy(this);
  24286. }
  24287. toJSON() {
  24288. const data = super.toJSON(this);
  24289. data.instanceCount = this.instanceCount;
  24290. data.isInstancedBufferGeometry = true;
  24291. return data;
  24292. }
  24293. }
  24294. class BufferGeometryLoader extends Loader {
  24295. constructor(manager) {
  24296. super(manager);
  24297. }
  24298. load(url, onLoad, onProgress, onError) {
  24299. const scope = this;
  24300. const loader = new FileLoader(scope.manager);
  24301. loader.setPath(scope.path);
  24302. loader.setRequestHeader(scope.requestHeader);
  24303. loader.setWithCredentials(scope.withCredentials);
  24304. loader.load(url, function (text) {
  24305. try {
  24306. onLoad(scope.parse(JSON.parse(text)));
  24307. } catch (e) {
  24308. if (onError) {
  24309. onError(e);
  24310. } else {
  24311. console.error(e);
  24312. }
  24313. scope.manager.itemError(url);
  24314. }
  24315. }, onProgress, onError);
  24316. }
  24317. parse(json) {
  24318. const interleavedBufferMap = {};
  24319. const arrayBufferMap = {};
  24320. function getInterleavedBuffer(json, uuid) {
  24321. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24322. const interleavedBuffers = json.interleavedBuffers;
  24323. const interleavedBuffer = interleavedBuffers[uuid];
  24324. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24325. const array = getTypedArray(interleavedBuffer.type, buffer);
  24326. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24327. ib.uuid = interleavedBuffer.uuid;
  24328. interleavedBufferMap[uuid] = ib;
  24329. return ib;
  24330. }
  24331. function getArrayBuffer(json, uuid) {
  24332. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24333. const arrayBuffers = json.arrayBuffers;
  24334. const arrayBuffer = arrayBuffers[uuid];
  24335. const ab = new Uint32Array(arrayBuffer).buffer;
  24336. arrayBufferMap[uuid] = ab;
  24337. return ab;
  24338. }
  24339. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24340. const index = json.data.index;
  24341. if (index !== undefined) {
  24342. const typedArray = getTypedArray(index.type, index.array);
  24343. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24344. }
  24345. const attributes = json.data.attributes;
  24346. for (const key in attributes) {
  24347. const attribute = attributes[key];
  24348. let bufferAttribute;
  24349. if (attribute.isInterleavedBufferAttribute) {
  24350. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24351. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24352. } else {
  24353. const typedArray = getTypedArray(attribute.type, attribute.array);
  24354. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24355. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24356. }
  24357. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24358. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  24359. if (attribute.updateRange !== undefined) {
  24360. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24361. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24362. }
  24363. geometry.setAttribute(key, bufferAttribute);
  24364. }
  24365. const morphAttributes = json.data.morphAttributes;
  24366. if (morphAttributes) {
  24367. for (const key in morphAttributes) {
  24368. const attributeArray = morphAttributes[key];
  24369. const array = [];
  24370. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24371. const attribute = attributeArray[i];
  24372. let bufferAttribute;
  24373. if (attribute.isInterleavedBufferAttribute) {
  24374. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24375. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24376. } else {
  24377. const typedArray = getTypedArray(attribute.type, attribute.array);
  24378. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24379. }
  24380. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24381. array.push(bufferAttribute);
  24382. }
  24383. geometry.morphAttributes[key] = array;
  24384. }
  24385. }
  24386. const morphTargetsRelative = json.data.morphTargetsRelative;
  24387. if (morphTargetsRelative) {
  24388. geometry.morphTargetsRelative = true;
  24389. }
  24390. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24391. if (groups !== undefined) {
  24392. for (let i = 0, n = groups.length; i !== n; ++i) {
  24393. const group = groups[i];
  24394. geometry.addGroup(group.start, group.count, group.materialIndex);
  24395. }
  24396. }
  24397. const boundingSphere = json.data.boundingSphere;
  24398. if (boundingSphere !== undefined) {
  24399. const center = new Vector3();
  24400. if (boundingSphere.center !== undefined) {
  24401. center.fromArray(boundingSphere.center);
  24402. }
  24403. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24404. }
  24405. if (json.name) geometry.name = json.name;
  24406. if (json.userData) geometry.userData = json.userData;
  24407. return geometry;
  24408. }
  24409. }
  24410. class ObjectLoader extends Loader {
  24411. constructor(manager) {
  24412. super(manager);
  24413. }
  24414. load(url, onLoad, onProgress, onError) {
  24415. const scope = this;
  24416. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24417. this.resourcePath = this.resourcePath || path;
  24418. const loader = new FileLoader(this.manager);
  24419. loader.setPath(this.path);
  24420. loader.setRequestHeader(this.requestHeader);
  24421. loader.setWithCredentials(this.withCredentials);
  24422. loader.load(url, function (text) {
  24423. let json = null;
  24424. try {
  24425. json = JSON.parse(text);
  24426. } catch (error) {
  24427. if (onError !== undefined) onError(error);
  24428. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24429. return;
  24430. }
  24431. const metadata = json.metadata;
  24432. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24433. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24434. return;
  24435. }
  24436. scope.parse(json, onLoad);
  24437. }, onProgress, onError);
  24438. }
  24439. async loadAsync(url, onProgress) {
  24440. const scope = this;
  24441. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24442. this.resourcePath = this.resourcePath || path;
  24443. const loader = new FileLoader(this.manager);
  24444. loader.setPath(this.path);
  24445. loader.setRequestHeader(this.requestHeader);
  24446. loader.setWithCredentials(this.withCredentials);
  24447. const text = await loader.loadAsync(url, onProgress);
  24448. const json = JSON.parse(text);
  24449. const metadata = json.metadata;
  24450. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24451. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  24452. }
  24453. return await scope.parseAsync(json);
  24454. }
  24455. parse(json, onLoad) {
  24456. const animations = this.parseAnimations(json.animations);
  24457. const shapes = this.parseShapes(json.shapes);
  24458. const geometries = this.parseGeometries(json.geometries, shapes);
  24459. const images = this.parseImages(json.images, function () {
  24460. if (onLoad !== undefined) onLoad(object);
  24461. });
  24462. const textures = this.parseTextures(json.textures, images);
  24463. const materials = this.parseMaterials(json.materials, textures);
  24464. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24465. const skeletons = this.parseSkeletons(json.skeletons, object);
  24466. this.bindSkeletons(object, skeletons); //
  24467. if (onLoad !== undefined) {
  24468. let hasImages = false;
  24469. for (const uuid in images) {
  24470. if (images[uuid].data instanceof HTMLImageElement) {
  24471. hasImages = true;
  24472. break;
  24473. }
  24474. }
  24475. if (hasImages === false) onLoad(object);
  24476. }
  24477. return object;
  24478. }
  24479. async parseAsync(json) {
  24480. const animations = this.parseAnimations(json.animations);
  24481. const shapes = this.parseShapes(json.shapes);
  24482. const geometries = this.parseGeometries(json.geometries, shapes);
  24483. const images = await this.parseImagesAsync(json.images);
  24484. const textures = this.parseTextures(json.textures, images);
  24485. const materials = this.parseMaterials(json.materials, textures);
  24486. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24487. const skeletons = this.parseSkeletons(json.skeletons, object);
  24488. this.bindSkeletons(object, skeletons);
  24489. return object;
  24490. }
  24491. parseShapes(json) {
  24492. const shapes = {};
  24493. if (json !== undefined) {
  24494. for (let i = 0, l = json.length; i < l; i++) {
  24495. const shape = new Shape().fromJSON(json[i]);
  24496. shapes[shape.uuid] = shape;
  24497. }
  24498. }
  24499. return shapes;
  24500. }
  24501. parseSkeletons(json, object) {
  24502. const skeletons = {};
  24503. const bones = {}; // generate bone lookup table
  24504. object.traverse(function (child) {
  24505. if (child.isBone) bones[child.uuid] = child;
  24506. }); // create skeletons
  24507. if (json !== undefined) {
  24508. for (let i = 0, l = json.length; i < l; i++) {
  24509. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24510. skeletons[skeleton.uuid] = skeleton;
  24511. }
  24512. }
  24513. return skeletons;
  24514. }
  24515. parseGeometries(json, shapes) {
  24516. const geometries = {};
  24517. if (json !== undefined) {
  24518. const bufferGeometryLoader = new BufferGeometryLoader();
  24519. for (let i = 0, l = json.length; i < l; i++) {
  24520. let geometry;
  24521. const data = json[i];
  24522. switch (data.type) {
  24523. case 'BufferGeometry':
  24524. case 'InstancedBufferGeometry':
  24525. geometry = bufferGeometryLoader.parse(data);
  24526. break;
  24527. default:
  24528. if (data.type in Geometries) {
  24529. geometry = Geometries[data.type].fromJSON(data, shapes);
  24530. } else {
  24531. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  24532. }
  24533. }
  24534. geometry.uuid = data.uuid;
  24535. if (data.name !== undefined) geometry.name = data.name;
  24536. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24537. geometries[data.uuid] = geometry;
  24538. }
  24539. }
  24540. return geometries;
  24541. }
  24542. parseMaterials(json, textures) {
  24543. const cache = {}; // MultiMaterial
  24544. const materials = {};
  24545. if (json !== undefined) {
  24546. const loader = new MaterialLoader();
  24547. loader.setTextures(textures);
  24548. for (let i = 0, l = json.length; i < l; i++) {
  24549. const data = json[i];
  24550. if (cache[data.uuid] === undefined) {
  24551. cache[data.uuid] = loader.parse(data);
  24552. }
  24553. materials[data.uuid] = cache[data.uuid];
  24554. }
  24555. }
  24556. return materials;
  24557. }
  24558. parseAnimations(json) {
  24559. const animations = {};
  24560. if (json !== undefined) {
  24561. for (let i = 0; i < json.length; i++) {
  24562. const data = json[i];
  24563. const clip = AnimationClip.parse(data);
  24564. animations[clip.uuid] = clip;
  24565. }
  24566. }
  24567. return animations;
  24568. }
  24569. parseImages(json, onLoad) {
  24570. const scope = this;
  24571. const images = {};
  24572. let loader;
  24573. function loadImage(url) {
  24574. scope.manager.itemStart(url);
  24575. return loader.load(url, function () {
  24576. scope.manager.itemEnd(url);
  24577. }, undefined, function () {
  24578. scope.manager.itemError(url);
  24579. scope.manager.itemEnd(url);
  24580. });
  24581. }
  24582. function deserializeImage(image) {
  24583. if (typeof image === 'string') {
  24584. const url = image;
  24585. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24586. return loadImage(path);
  24587. } else {
  24588. if (image.data) {
  24589. return {
  24590. data: getTypedArray(image.type, image.data),
  24591. width: image.width,
  24592. height: image.height
  24593. };
  24594. } else {
  24595. return null;
  24596. }
  24597. }
  24598. }
  24599. if (json !== undefined && json.length > 0) {
  24600. const manager = new LoadingManager(onLoad);
  24601. loader = new ImageLoader(manager);
  24602. loader.setCrossOrigin(this.crossOrigin);
  24603. for (let i = 0, il = json.length; i < il; i++) {
  24604. const image = json[i];
  24605. const url = image.url;
  24606. if (Array.isArray(url)) {
  24607. // load array of images e.g CubeTexture
  24608. const imageArray = [];
  24609. for (let j = 0, jl = url.length; j < jl; j++) {
  24610. const currentUrl = url[j];
  24611. const deserializedImage = deserializeImage(currentUrl);
  24612. if (deserializedImage !== null) {
  24613. if (deserializedImage instanceof HTMLImageElement) {
  24614. imageArray.push(deserializedImage);
  24615. } else {
  24616. // special case: handle array of data textures for cube textures
  24617. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24618. }
  24619. }
  24620. }
  24621. images[image.uuid] = new Source(imageArray);
  24622. } else {
  24623. // load single image
  24624. const deserializedImage = deserializeImage(image.url);
  24625. images[image.uuid] = new Source(deserializedImage);
  24626. }
  24627. }
  24628. }
  24629. return images;
  24630. }
  24631. async parseImagesAsync(json) {
  24632. const scope = this;
  24633. const images = {};
  24634. let loader;
  24635. async function deserializeImage(image) {
  24636. if (typeof image === 'string') {
  24637. const url = image;
  24638. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24639. return await loader.loadAsync(path);
  24640. } else {
  24641. if (image.data) {
  24642. return {
  24643. data: getTypedArray(image.type, image.data),
  24644. width: image.width,
  24645. height: image.height
  24646. };
  24647. } else {
  24648. return null;
  24649. }
  24650. }
  24651. }
  24652. if (json !== undefined && json.length > 0) {
  24653. loader = new ImageLoader(this.manager);
  24654. loader.setCrossOrigin(this.crossOrigin);
  24655. for (let i = 0, il = json.length; i < il; i++) {
  24656. const image = json[i];
  24657. const url = image.url;
  24658. if (Array.isArray(url)) {
  24659. // load array of images e.g CubeTexture
  24660. const imageArray = [];
  24661. for (let j = 0, jl = url.length; j < jl; j++) {
  24662. const currentUrl = url[j];
  24663. const deserializedImage = await deserializeImage(currentUrl);
  24664. if (deserializedImage !== null) {
  24665. if (deserializedImage instanceof HTMLImageElement) {
  24666. imageArray.push(deserializedImage);
  24667. } else {
  24668. // special case: handle array of data textures for cube textures
  24669. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24670. }
  24671. }
  24672. }
  24673. images[image.uuid] = new Source(imageArray);
  24674. } else {
  24675. // load single image
  24676. const deserializedImage = await deserializeImage(image.url);
  24677. images[image.uuid] = new Source(deserializedImage);
  24678. }
  24679. }
  24680. }
  24681. return images;
  24682. }
  24683. parseTextures(json, images) {
  24684. function parseConstant(value, type) {
  24685. if (typeof value === 'number') return value;
  24686. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24687. return type[value];
  24688. }
  24689. const textures = {};
  24690. if (json !== undefined) {
  24691. for (let i = 0, l = json.length; i < l; i++) {
  24692. const data = json[i];
  24693. if (data.image === undefined) {
  24694. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24695. }
  24696. if (images[data.image] === undefined) {
  24697. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24698. }
  24699. const source = images[data.image];
  24700. const image = source.data;
  24701. let texture;
  24702. if (Array.isArray(image)) {
  24703. texture = new CubeTexture();
  24704. if (image.length === 6) texture.needsUpdate = true;
  24705. } else {
  24706. if (image && image.data) {
  24707. texture = new DataTexture();
  24708. } else {
  24709. texture = new Texture();
  24710. }
  24711. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24712. }
  24713. texture.source = source;
  24714. texture.uuid = data.uuid;
  24715. if (data.name !== undefined) texture.name = data.name;
  24716. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24717. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24718. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24719. if (data.center !== undefined) texture.center.fromArray(data.center);
  24720. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24721. if (data.wrap !== undefined) {
  24722. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24723. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24724. }
  24725. if (data.format !== undefined) texture.format = data.format;
  24726. if (data.type !== undefined) texture.type = data.type;
  24727. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24728. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24729. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24730. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24731. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24732. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24733. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24734. if (data.userData !== undefined) texture.userData = data.userData;
  24735. textures[data.uuid] = texture;
  24736. }
  24737. }
  24738. return textures;
  24739. }
  24740. parseObject(data, geometries, materials, textures, animations) {
  24741. let object;
  24742. function getGeometry(name) {
  24743. if (geometries[name] === undefined) {
  24744. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24745. }
  24746. return geometries[name];
  24747. }
  24748. function getMaterial(name) {
  24749. if (name === undefined) return undefined;
  24750. if (Array.isArray(name)) {
  24751. const array = [];
  24752. for (let i = 0, l = name.length; i < l; i++) {
  24753. const uuid = name[i];
  24754. if (materials[uuid] === undefined) {
  24755. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24756. }
  24757. array.push(materials[uuid]);
  24758. }
  24759. return array;
  24760. }
  24761. if (materials[name] === undefined) {
  24762. console.warn('THREE.ObjectLoader: Undefined material', name);
  24763. }
  24764. return materials[name];
  24765. }
  24766. function getTexture(uuid) {
  24767. if (textures[uuid] === undefined) {
  24768. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24769. }
  24770. return textures[uuid];
  24771. }
  24772. let geometry, material;
  24773. switch (data.type) {
  24774. case 'Scene':
  24775. object = new Scene();
  24776. if (data.background !== undefined) {
  24777. if (Number.isInteger(data.background)) {
  24778. object.background = new Color(data.background);
  24779. } else {
  24780. object.background = getTexture(data.background);
  24781. }
  24782. }
  24783. if (data.environment !== undefined) {
  24784. object.environment = getTexture(data.environment);
  24785. }
  24786. if (data.fog !== undefined) {
  24787. if (data.fog.type === 'Fog') {
  24788. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24789. } else if (data.fog.type === 'FogExp2') {
  24790. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24791. }
  24792. }
  24793. break;
  24794. case 'PerspectiveCamera':
  24795. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24796. if (data.focus !== undefined) object.focus = data.focus;
  24797. if (data.zoom !== undefined) object.zoom = data.zoom;
  24798. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24799. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24800. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24801. break;
  24802. case 'OrthographicCamera':
  24803. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24804. if (data.zoom !== undefined) object.zoom = data.zoom;
  24805. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24806. break;
  24807. case 'AmbientLight':
  24808. object = new AmbientLight(data.color, data.intensity);
  24809. break;
  24810. case 'DirectionalLight':
  24811. object = new DirectionalLight(data.color, data.intensity);
  24812. break;
  24813. case 'PointLight':
  24814. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24815. break;
  24816. case 'RectAreaLight':
  24817. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24818. break;
  24819. case 'SpotLight':
  24820. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24821. break;
  24822. case 'HemisphereLight':
  24823. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24824. break;
  24825. case 'LightProbe':
  24826. object = new LightProbe().fromJSON(data);
  24827. break;
  24828. case 'SkinnedMesh':
  24829. geometry = getGeometry(data.geometry);
  24830. material = getMaterial(data.material);
  24831. object = new SkinnedMesh(geometry, material);
  24832. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24833. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24834. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24835. break;
  24836. case 'Mesh':
  24837. geometry = getGeometry(data.geometry);
  24838. material = getMaterial(data.material);
  24839. object = new Mesh(geometry, material);
  24840. break;
  24841. case 'InstancedMesh':
  24842. geometry = getGeometry(data.geometry);
  24843. material = getMaterial(data.material);
  24844. const count = data.count;
  24845. const instanceMatrix = data.instanceMatrix;
  24846. const instanceColor = data.instanceColor;
  24847. object = new InstancedMesh(geometry, material, count);
  24848. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24849. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24850. break;
  24851. case 'LOD':
  24852. object = new LOD();
  24853. break;
  24854. case 'Line':
  24855. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24856. break;
  24857. case 'LineLoop':
  24858. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24859. break;
  24860. case 'LineSegments':
  24861. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24862. break;
  24863. case 'PointCloud':
  24864. case 'Points':
  24865. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24866. break;
  24867. case 'Sprite':
  24868. object = new Sprite(getMaterial(data.material));
  24869. break;
  24870. case 'Group':
  24871. object = new Group();
  24872. break;
  24873. case 'Bone':
  24874. object = new Bone();
  24875. break;
  24876. default:
  24877. object = new Object3D();
  24878. }
  24879. object.uuid = data.uuid;
  24880. if (data.name !== undefined) object.name = data.name;
  24881. if (data.matrix !== undefined) {
  24882. object.matrix.fromArray(data.matrix);
  24883. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24884. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24885. } else {
  24886. if (data.position !== undefined) object.position.fromArray(data.position);
  24887. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24888. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24889. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24890. }
  24891. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24892. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24893. if (data.shadow) {
  24894. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24895. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24896. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24897. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24898. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24899. }
  24900. if (data.visible !== undefined) object.visible = data.visible;
  24901. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24902. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24903. if (data.userData !== undefined) object.userData = data.userData;
  24904. if (data.layers !== undefined) object.layers.mask = data.layers;
  24905. if (data.children !== undefined) {
  24906. const children = data.children;
  24907. for (let i = 0; i < children.length; i++) {
  24908. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24909. }
  24910. }
  24911. if (data.animations !== undefined) {
  24912. const objectAnimations = data.animations;
  24913. for (let i = 0; i < objectAnimations.length; i++) {
  24914. const uuid = objectAnimations[i];
  24915. object.animations.push(animations[uuid]);
  24916. }
  24917. }
  24918. if (data.type === 'LOD') {
  24919. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24920. const levels = data.levels;
  24921. for (let l = 0; l < levels.length; l++) {
  24922. const level = levels[l];
  24923. const child = object.getObjectByProperty('uuid', level.object);
  24924. if (child !== undefined) {
  24925. object.addLevel(child, level.distance);
  24926. }
  24927. }
  24928. }
  24929. return object;
  24930. }
  24931. bindSkeletons(object, skeletons) {
  24932. if (Object.keys(skeletons).length === 0) return;
  24933. object.traverse(function (child) {
  24934. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24935. const skeleton = skeletons[child.skeleton];
  24936. if (skeleton === undefined) {
  24937. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24938. } else {
  24939. child.bind(skeleton, child.bindMatrix);
  24940. }
  24941. }
  24942. });
  24943. }
  24944. }
  24945. const TEXTURE_MAPPING = {
  24946. UVMapping: UVMapping,
  24947. CubeReflectionMapping: CubeReflectionMapping,
  24948. CubeRefractionMapping: CubeRefractionMapping,
  24949. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24950. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24951. CubeUVReflectionMapping: CubeUVReflectionMapping
  24952. };
  24953. const TEXTURE_WRAPPING = {
  24954. RepeatWrapping: RepeatWrapping,
  24955. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24956. MirroredRepeatWrapping: MirroredRepeatWrapping
  24957. };
  24958. const TEXTURE_FILTER = {
  24959. NearestFilter: NearestFilter,
  24960. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24961. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24962. LinearFilter: LinearFilter,
  24963. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24964. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24965. };
  24966. class ImageBitmapLoader extends Loader {
  24967. constructor(manager) {
  24968. super(manager);
  24969. this.isImageBitmapLoader = true;
  24970. if (typeof createImageBitmap === 'undefined') {
  24971. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24972. }
  24973. if (typeof fetch === 'undefined') {
  24974. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24975. }
  24976. this.options = {
  24977. premultiplyAlpha: 'none'
  24978. };
  24979. }
  24980. setOptions(options) {
  24981. this.options = options;
  24982. return this;
  24983. }
  24984. load(url, onLoad, onProgress, onError) {
  24985. if (url === undefined) url = '';
  24986. if (this.path !== undefined) url = this.path + url;
  24987. url = this.manager.resolveURL(url);
  24988. const scope = this;
  24989. const cached = Cache.get(url);
  24990. if (cached !== undefined) {
  24991. scope.manager.itemStart(url);
  24992. setTimeout(function () {
  24993. if (onLoad) onLoad(cached);
  24994. scope.manager.itemEnd(url);
  24995. }, 0);
  24996. return cached;
  24997. }
  24998. const fetchOptions = {};
  24999. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  25000. fetchOptions.headers = this.requestHeader;
  25001. fetch(url, fetchOptions).then(function (res) {
  25002. return res.blob();
  25003. }).then(function (blob) {
  25004. return createImageBitmap(blob, Object.assign(scope.options, {
  25005. colorSpaceConversion: 'none'
  25006. }));
  25007. }).then(function (imageBitmap) {
  25008. Cache.add(url, imageBitmap);
  25009. if (onLoad) onLoad(imageBitmap);
  25010. scope.manager.itemEnd(url);
  25011. }).catch(function (e) {
  25012. if (onError) onError(e);
  25013. scope.manager.itemError(url);
  25014. scope.manager.itemEnd(url);
  25015. });
  25016. scope.manager.itemStart(url);
  25017. }
  25018. }
  25019. let _context;
  25020. const AudioContext = {
  25021. getContext: function () {
  25022. if (_context === undefined) {
  25023. _context = new (window.AudioContext || window.webkitAudioContext)();
  25024. }
  25025. return _context;
  25026. },
  25027. setContext: function (value) {
  25028. _context = value;
  25029. }
  25030. };
  25031. class AudioLoader extends Loader {
  25032. constructor(manager) {
  25033. super(manager);
  25034. }
  25035. load(url, onLoad, onProgress, onError) {
  25036. const scope = this;
  25037. const loader = new FileLoader(this.manager);
  25038. loader.setResponseType('arraybuffer');
  25039. loader.setPath(this.path);
  25040. loader.setRequestHeader(this.requestHeader);
  25041. loader.setWithCredentials(this.withCredentials);
  25042. loader.load(url, function (buffer) {
  25043. try {
  25044. // Create a copy of the buffer. The `decodeAudioData` method
  25045. // detaches the buffer when complete, preventing reuse.
  25046. const bufferCopy = buffer.slice(0);
  25047. const context = AudioContext.getContext();
  25048. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25049. onLoad(audioBuffer);
  25050. });
  25051. } catch (e) {
  25052. if (onError) {
  25053. onError(e);
  25054. } else {
  25055. console.error(e);
  25056. }
  25057. scope.manager.itemError(url);
  25058. }
  25059. }, onProgress, onError);
  25060. }
  25061. }
  25062. class HemisphereLightProbe extends LightProbe {
  25063. constructor(skyColor, groundColor, intensity = 1) {
  25064. super(undefined, intensity);
  25065. this.isHemisphereLightProbe = true;
  25066. const color1 = new Color().set(skyColor);
  25067. const color2 = new Color().set(groundColor);
  25068. const sky = new Vector3(color1.r, color1.g, color1.b);
  25069. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25070. const c0 = Math.sqrt(Math.PI);
  25071. const c1 = c0 * Math.sqrt(0.75);
  25072. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25073. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25074. }
  25075. }
  25076. class AmbientLightProbe extends LightProbe {
  25077. constructor(color, intensity = 1) {
  25078. super(undefined, intensity);
  25079. this.isAmbientLightProbe = true;
  25080. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25081. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25082. }
  25083. }
  25084. const _eyeRight = /*@__PURE__*/new Matrix4();
  25085. const _eyeLeft = /*@__PURE__*/new Matrix4();
  25086. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  25087. class StereoCamera {
  25088. constructor() {
  25089. this.type = 'StereoCamera';
  25090. this.aspect = 1;
  25091. this.eyeSep = 0.064;
  25092. this.cameraL = new PerspectiveCamera();
  25093. this.cameraL.layers.enable(1);
  25094. this.cameraL.matrixAutoUpdate = false;
  25095. this.cameraR = new PerspectiveCamera();
  25096. this.cameraR.layers.enable(2);
  25097. this.cameraR.matrixAutoUpdate = false;
  25098. this._cache = {
  25099. focus: null,
  25100. fov: null,
  25101. aspect: null,
  25102. near: null,
  25103. far: null,
  25104. zoom: null,
  25105. eyeSep: null
  25106. };
  25107. }
  25108. update(camera) {
  25109. const cache = this._cache;
  25110. 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;
  25111. if (needsUpdate) {
  25112. cache.focus = camera.focus;
  25113. cache.fov = camera.fov;
  25114. cache.aspect = camera.aspect * this.aspect;
  25115. cache.near = camera.near;
  25116. cache.far = camera.far;
  25117. cache.zoom = camera.zoom;
  25118. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25119. // http://paulbourke.net/stereographics/stereorender/
  25120. _projectionMatrix.copy(camera.projectionMatrix);
  25121. const eyeSepHalf = cache.eyeSep / 2;
  25122. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25123. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25124. let xmin, xmax; // translate xOffset
  25125. _eyeLeft.elements[12] = -eyeSepHalf;
  25126. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25127. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25128. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25129. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25130. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25131. this.cameraL.projectionMatrix.copy(_projectionMatrix); // for right eye
  25132. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25133. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25134. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25135. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25136. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  25137. }
  25138. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25139. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25140. }
  25141. }
  25142. class Clock {
  25143. constructor(autoStart = true) {
  25144. this.autoStart = autoStart;
  25145. this.startTime = 0;
  25146. this.oldTime = 0;
  25147. this.elapsedTime = 0;
  25148. this.running = false;
  25149. }
  25150. start() {
  25151. this.startTime = now();
  25152. this.oldTime = this.startTime;
  25153. this.elapsedTime = 0;
  25154. this.running = true;
  25155. }
  25156. stop() {
  25157. this.getElapsedTime();
  25158. this.running = false;
  25159. this.autoStart = false;
  25160. }
  25161. getElapsedTime() {
  25162. this.getDelta();
  25163. return this.elapsedTime;
  25164. }
  25165. getDelta() {
  25166. let diff = 0;
  25167. if (this.autoStart && !this.running) {
  25168. this.start();
  25169. return 0;
  25170. }
  25171. if (this.running) {
  25172. const newTime = now();
  25173. diff = (newTime - this.oldTime) / 1000;
  25174. this.oldTime = newTime;
  25175. this.elapsedTime += diff;
  25176. }
  25177. return diff;
  25178. }
  25179. }
  25180. function now() {
  25181. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25182. }
  25183. const _position$1 = /*@__PURE__*/new Vector3();
  25184. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  25185. const _scale$1 = /*@__PURE__*/new Vector3();
  25186. const _orientation$1 = /*@__PURE__*/new Vector3();
  25187. class AudioListener extends Object3D {
  25188. constructor() {
  25189. super();
  25190. this.type = 'AudioListener';
  25191. this.context = AudioContext.getContext();
  25192. this.gain = this.context.createGain();
  25193. this.gain.connect(this.context.destination);
  25194. this.filter = null;
  25195. this.timeDelta = 0; // private
  25196. this._clock = new Clock();
  25197. }
  25198. getInput() {
  25199. return this.gain;
  25200. }
  25201. removeFilter() {
  25202. if (this.filter !== null) {
  25203. this.gain.disconnect(this.filter);
  25204. this.filter.disconnect(this.context.destination);
  25205. this.gain.connect(this.context.destination);
  25206. this.filter = null;
  25207. }
  25208. return this;
  25209. }
  25210. getFilter() {
  25211. return this.filter;
  25212. }
  25213. setFilter(value) {
  25214. if (this.filter !== null) {
  25215. this.gain.disconnect(this.filter);
  25216. this.filter.disconnect(this.context.destination);
  25217. } else {
  25218. this.gain.disconnect(this.context.destination);
  25219. }
  25220. this.filter = value;
  25221. this.gain.connect(this.filter);
  25222. this.filter.connect(this.context.destination);
  25223. return this;
  25224. }
  25225. getMasterVolume() {
  25226. return this.gain.gain.value;
  25227. }
  25228. setMasterVolume(value) {
  25229. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25230. return this;
  25231. }
  25232. updateMatrixWorld(force) {
  25233. super.updateMatrixWorld(force);
  25234. const listener = this.context.listener;
  25235. const up = this.up;
  25236. this.timeDelta = this._clock.getDelta();
  25237. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  25238. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  25239. if (listener.positionX) {
  25240. // code path for Chrome (see #14393)
  25241. const endTime = this.context.currentTime + this.timeDelta;
  25242. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  25243. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  25244. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  25245. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25246. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25247. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25248. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25249. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25250. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25251. } else {
  25252. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  25253. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  25254. }
  25255. }
  25256. }
  25257. class Audio extends Object3D {
  25258. constructor(listener) {
  25259. super();
  25260. this.type = 'Audio';
  25261. this.listener = listener;
  25262. this.context = listener.context;
  25263. this.gain = this.context.createGain();
  25264. this.gain.connect(listener.getInput());
  25265. this.autoplay = false;
  25266. this.buffer = null;
  25267. this.detune = 0;
  25268. this.loop = false;
  25269. this.loopStart = 0;
  25270. this.loopEnd = 0;
  25271. this.offset = 0;
  25272. this.duration = undefined;
  25273. this.playbackRate = 1;
  25274. this.isPlaying = false;
  25275. this.hasPlaybackControl = true;
  25276. this.source = null;
  25277. this.sourceType = 'empty';
  25278. this._startedAt = 0;
  25279. this._progress = 0;
  25280. this._connected = false;
  25281. this.filters = [];
  25282. }
  25283. getOutput() {
  25284. return this.gain;
  25285. }
  25286. setNodeSource(audioNode) {
  25287. this.hasPlaybackControl = false;
  25288. this.sourceType = 'audioNode';
  25289. this.source = audioNode;
  25290. this.connect();
  25291. return this;
  25292. }
  25293. setMediaElementSource(mediaElement) {
  25294. this.hasPlaybackControl = false;
  25295. this.sourceType = 'mediaNode';
  25296. this.source = this.context.createMediaElementSource(mediaElement);
  25297. this.connect();
  25298. return this;
  25299. }
  25300. setMediaStreamSource(mediaStream) {
  25301. this.hasPlaybackControl = false;
  25302. this.sourceType = 'mediaStreamNode';
  25303. this.source = this.context.createMediaStreamSource(mediaStream);
  25304. this.connect();
  25305. return this;
  25306. }
  25307. setBuffer(audioBuffer) {
  25308. this.buffer = audioBuffer;
  25309. this.sourceType = 'buffer';
  25310. if (this.autoplay) this.play();
  25311. return this;
  25312. }
  25313. play(delay = 0) {
  25314. if (this.isPlaying === true) {
  25315. console.warn('THREE.Audio: Audio is already playing.');
  25316. return;
  25317. }
  25318. if (this.hasPlaybackControl === false) {
  25319. console.warn('THREE.Audio: this Audio has no playback control.');
  25320. return;
  25321. }
  25322. this._startedAt = this.context.currentTime + delay;
  25323. const source = this.context.createBufferSource();
  25324. source.buffer = this.buffer;
  25325. source.loop = this.loop;
  25326. source.loopStart = this.loopStart;
  25327. source.loopEnd = this.loopEnd;
  25328. source.onended = this.onEnded.bind(this);
  25329. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25330. this.isPlaying = true;
  25331. this.source = source;
  25332. this.setDetune(this.detune);
  25333. this.setPlaybackRate(this.playbackRate);
  25334. return this.connect();
  25335. }
  25336. pause() {
  25337. if (this.hasPlaybackControl === false) {
  25338. console.warn('THREE.Audio: this Audio has no playback control.');
  25339. return;
  25340. }
  25341. if (this.isPlaying === true) {
  25342. // update current progress
  25343. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25344. if (this.loop === true) {
  25345. // ensure _progress does not exceed duration with looped audios
  25346. this._progress = this._progress % (this.duration || this.buffer.duration);
  25347. }
  25348. this.source.stop();
  25349. this.source.onended = null;
  25350. this.isPlaying = false;
  25351. }
  25352. return this;
  25353. }
  25354. stop() {
  25355. if (this.hasPlaybackControl === false) {
  25356. console.warn('THREE.Audio: this Audio has no playback control.');
  25357. return;
  25358. }
  25359. this._progress = 0;
  25360. this.source.stop();
  25361. this.source.onended = null;
  25362. this.isPlaying = false;
  25363. return this;
  25364. }
  25365. connect() {
  25366. if (this.filters.length > 0) {
  25367. this.source.connect(this.filters[0]);
  25368. for (let i = 1, l = this.filters.length; i < l; i++) {
  25369. this.filters[i - 1].connect(this.filters[i]);
  25370. }
  25371. this.filters[this.filters.length - 1].connect(this.getOutput());
  25372. } else {
  25373. this.source.connect(this.getOutput());
  25374. }
  25375. this._connected = true;
  25376. return this;
  25377. }
  25378. disconnect() {
  25379. if (this.filters.length > 0) {
  25380. this.source.disconnect(this.filters[0]);
  25381. for (let i = 1, l = this.filters.length; i < l; i++) {
  25382. this.filters[i - 1].disconnect(this.filters[i]);
  25383. }
  25384. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25385. } else {
  25386. this.source.disconnect(this.getOutput());
  25387. }
  25388. this._connected = false;
  25389. return this;
  25390. }
  25391. getFilters() {
  25392. return this.filters;
  25393. }
  25394. setFilters(value) {
  25395. if (!value) value = [];
  25396. if (this._connected === true) {
  25397. this.disconnect();
  25398. this.filters = value.slice();
  25399. this.connect();
  25400. } else {
  25401. this.filters = value.slice();
  25402. }
  25403. return this;
  25404. }
  25405. setDetune(value) {
  25406. this.detune = value;
  25407. if (this.source.detune === undefined) return; // only set detune when available
  25408. if (this.isPlaying === true) {
  25409. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25410. }
  25411. return this;
  25412. }
  25413. getDetune() {
  25414. return this.detune;
  25415. }
  25416. getFilter() {
  25417. return this.getFilters()[0];
  25418. }
  25419. setFilter(filter) {
  25420. return this.setFilters(filter ? [filter] : []);
  25421. }
  25422. setPlaybackRate(value) {
  25423. if (this.hasPlaybackControl === false) {
  25424. console.warn('THREE.Audio: this Audio has no playback control.');
  25425. return;
  25426. }
  25427. this.playbackRate = value;
  25428. if (this.isPlaying === true) {
  25429. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25430. }
  25431. return this;
  25432. }
  25433. getPlaybackRate() {
  25434. return this.playbackRate;
  25435. }
  25436. onEnded() {
  25437. this.isPlaying = false;
  25438. }
  25439. getLoop() {
  25440. if (this.hasPlaybackControl === false) {
  25441. console.warn('THREE.Audio: this Audio has no playback control.');
  25442. return false;
  25443. }
  25444. return this.loop;
  25445. }
  25446. setLoop(value) {
  25447. if (this.hasPlaybackControl === false) {
  25448. console.warn('THREE.Audio: this Audio has no playback control.');
  25449. return;
  25450. }
  25451. this.loop = value;
  25452. if (this.isPlaying === true) {
  25453. this.source.loop = this.loop;
  25454. }
  25455. return this;
  25456. }
  25457. setLoopStart(value) {
  25458. this.loopStart = value;
  25459. return this;
  25460. }
  25461. setLoopEnd(value) {
  25462. this.loopEnd = value;
  25463. return this;
  25464. }
  25465. getVolume() {
  25466. return this.gain.gain.value;
  25467. }
  25468. setVolume(value) {
  25469. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25470. return this;
  25471. }
  25472. }
  25473. const _position = /*@__PURE__*/new Vector3();
  25474. const _quaternion = /*@__PURE__*/new Quaternion();
  25475. const _scale = /*@__PURE__*/new Vector3();
  25476. const _orientation = /*@__PURE__*/new Vector3();
  25477. class PositionalAudio extends Audio {
  25478. constructor(listener) {
  25479. super(listener);
  25480. this.panner = this.context.createPanner();
  25481. this.panner.panningModel = 'HRTF';
  25482. this.panner.connect(this.gain);
  25483. }
  25484. disconnect() {
  25485. super.disconnect();
  25486. this.panner.disconnect(this.gain);
  25487. }
  25488. getOutput() {
  25489. return this.panner;
  25490. }
  25491. getRefDistance() {
  25492. return this.panner.refDistance;
  25493. }
  25494. setRefDistance(value) {
  25495. this.panner.refDistance = value;
  25496. return this;
  25497. }
  25498. getRolloffFactor() {
  25499. return this.panner.rolloffFactor;
  25500. }
  25501. setRolloffFactor(value) {
  25502. this.panner.rolloffFactor = value;
  25503. return this;
  25504. }
  25505. getDistanceModel() {
  25506. return this.panner.distanceModel;
  25507. }
  25508. setDistanceModel(value) {
  25509. this.panner.distanceModel = value;
  25510. return this;
  25511. }
  25512. getMaxDistance() {
  25513. return this.panner.maxDistance;
  25514. }
  25515. setMaxDistance(value) {
  25516. this.panner.maxDistance = value;
  25517. return this;
  25518. }
  25519. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25520. this.panner.coneInnerAngle = coneInnerAngle;
  25521. this.panner.coneOuterAngle = coneOuterAngle;
  25522. this.panner.coneOuterGain = coneOuterGain;
  25523. return this;
  25524. }
  25525. updateMatrixWorld(force) {
  25526. super.updateMatrixWorld(force);
  25527. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25528. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25529. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25530. const panner = this.panner;
  25531. if (panner.positionX) {
  25532. // code path for Chrome and Firefox (see #14393)
  25533. const endTime = this.context.currentTime + this.listener.timeDelta;
  25534. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25535. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25536. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25537. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25538. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25539. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25540. } else {
  25541. panner.setPosition(_position.x, _position.y, _position.z);
  25542. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25543. }
  25544. }
  25545. }
  25546. class AudioAnalyser {
  25547. constructor(audio, fftSize = 2048) {
  25548. this.analyser = audio.context.createAnalyser();
  25549. this.analyser.fftSize = fftSize;
  25550. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25551. audio.getOutput().connect(this.analyser);
  25552. }
  25553. getFrequencyData() {
  25554. this.analyser.getByteFrequencyData(this.data);
  25555. return this.data;
  25556. }
  25557. getAverageFrequency() {
  25558. let value = 0;
  25559. const data = this.getFrequencyData();
  25560. for (let i = 0; i < data.length; i++) {
  25561. value += data[i];
  25562. }
  25563. return value / data.length;
  25564. }
  25565. }
  25566. class PropertyMixer {
  25567. constructor(binding, typeName, valueSize) {
  25568. this.binding = binding;
  25569. this.valueSize = valueSize;
  25570. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25571. //
  25572. // interpolators can use .buffer as their .result
  25573. // the data then goes to 'incoming'
  25574. //
  25575. // 'accu0' and 'accu1' are used frame-interleaved for
  25576. // the cumulative result and are compared to detect
  25577. // changes
  25578. //
  25579. // 'orig' stores the original state of the property
  25580. //
  25581. // 'add' is used for additive cumulative results
  25582. //
  25583. // 'work' is optional and is only present for quaternion types. It is used
  25584. // to store intermediate quaternion multiplication results
  25585. switch (typeName) {
  25586. case 'quaternion':
  25587. mixFunction = this._slerp;
  25588. mixFunctionAdditive = this._slerpAdditive;
  25589. setIdentity = this._setAdditiveIdentityQuaternion;
  25590. this.buffer = new Float64Array(valueSize * 6);
  25591. this._workIndex = 5;
  25592. break;
  25593. case 'string':
  25594. case 'bool':
  25595. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25596. // additive is not relevant for non-numeric types
  25597. mixFunctionAdditive = this._select;
  25598. setIdentity = this._setAdditiveIdentityOther;
  25599. this.buffer = new Array(valueSize * 5);
  25600. break;
  25601. default:
  25602. mixFunction = this._lerp;
  25603. mixFunctionAdditive = this._lerpAdditive;
  25604. setIdentity = this._setAdditiveIdentityNumeric;
  25605. this.buffer = new Float64Array(valueSize * 5);
  25606. }
  25607. this._mixBufferRegion = mixFunction;
  25608. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25609. this._setIdentity = setIdentity;
  25610. this._origIndex = 3;
  25611. this._addIndex = 4;
  25612. this.cumulativeWeight = 0;
  25613. this.cumulativeWeightAdditive = 0;
  25614. this.useCount = 0;
  25615. this.referenceCount = 0;
  25616. } // accumulate data in the 'incoming' region into 'accu<i>'
  25617. accumulate(accuIndex, weight) {
  25618. // note: happily accumulating nothing when weight = 0, the caller knows
  25619. // the weight and shouldn't have made the call in the first place
  25620. const buffer = this.buffer,
  25621. stride = this.valueSize,
  25622. offset = accuIndex * stride + stride;
  25623. let currentWeight = this.cumulativeWeight;
  25624. if (currentWeight === 0) {
  25625. // accuN := incoming * weight
  25626. for (let i = 0; i !== stride; ++i) {
  25627. buffer[offset + i] = buffer[i];
  25628. }
  25629. currentWeight = weight;
  25630. } else {
  25631. // accuN := accuN + incoming * weight
  25632. currentWeight += weight;
  25633. const mix = weight / currentWeight;
  25634. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25635. }
  25636. this.cumulativeWeight = currentWeight;
  25637. } // accumulate data in the 'incoming' region into 'add'
  25638. accumulateAdditive(weight) {
  25639. const buffer = this.buffer,
  25640. stride = this.valueSize,
  25641. offset = stride * this._addIndex;
  25642. if (this.cumulativeWeightAdditive === 0) {
  25643. // add = identity
  25644. this._setIdentity();
  25645. } // add := add + incoming * weight
  25646. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25647. this.cumulativeWeightAdditive += weight;
  25648. } // apply the state of 'accu<i>' to the binding when accus differ
  25649. apply(accuIndex) {
  25650. const stride = this.valueSize,
  25651. buffer = this.buffer,
  25652. offset = accuIndex * stride + stride,
  25653. weight = this.cumulativeWeight,
  25654. weightAdditive = this.cumulativeWeightAdditive,
  25655. binding = this.binding;
  25656. this.cumulativeWeight = 0;
  25657. this.cumulativeWeightAdditive = 0;
  25658. if (weight < 1) {
  25659. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25660. const originalValueOffset = stride * this._origIndex;
  25661. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25662. }
  25663. if (weightAdditive > 0) {
  25664. // accuN := accuN + additive accuN
  25665. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25666. }
  25667. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25668. if (buffer[i] !== buffer[i + stride]) {
  25669. // value has changed -> update scene graph
  25670. binding.setValue(buffer, offset);
  25671. break;
  25672. }
  25673. }
  25674. } // remember the state of the bound property and copy it to both accus
  25675. saveOriginalState() {
  25676. const binding = this.binding;
  25677. const buffer = this.buffer,
  25678. stride = this.valueSize,
  25679. originalValueOffset = stride * this._origIndex;
  25680. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25681. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25682. buffer[i] = buffer[originalValueOffset + i % stride];
  25683. } // Add to identity for additive
  25684. this._setIdentity();
  25685. this.cumulativeWeight = 0;
  25686. this.cumulativeWeightAdditive = 0;
  25687. } // apply the state previously taken via 'saveOriginalState' to the binding
  25688. restoreOriginalState() {
  25689. const originalValueOffset = this.valueSize * 3;
  25690. this.binding.setValue(this.buffer, originalValueOffset);
  25691. }
  25692. _setAdditiveIdentityNumeric() {
  25693. const startIndex = this._addIndex * this.valueSize;
  25694. const endIndex = startIndex + this.valueSize;
  25695. for (let i = startIndex; i < endIndex; i++) {
  25696. this.buffer[i] = 0;
  25697. }
  25698. }
  25699. _setAdditiveIdentityQuaternion() {
  25700. this._setAdditiveIdentityNumeric();
  25701. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25702. }
  25703. _setAdditiveIdentityOther() {
  25704. const startIndex = this._origIndex * this.valueSize;
  25705. const targetIndex = this._addIndex * this.valueSize;
  25706. for (let i = 0; i < this.valueSize; i++) {
  25707. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25708. }
  25709. } // mix functions
  25710. _select(buffer, dstOffset, srcOffset, t, stride) {
  25711. if (t >= 0.5) {
  25712. for (let i = 0; i !== stride; ++i) {
  25713. buffer[dstOffset + i] = buffer[srcOffset + i];
  25714. }
  25715. }
  25716. }
  25717. _slerp(buffer, dstOffset, srcOffset, t) {
  25718. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25719. }
  25720. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25721. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25722. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25723. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25724. }
  25725. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25726. const s = 1 - t;
  25727. for (let i = 0; i !== stride; ++i) {
  25728. const j = dstOffset + i;
  25729. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25730. }
  25731. }
  25732. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25733. for (let i = 0; i !== stride; ++i) {
  25734. const j = dstOffset + i;
  25735. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25736. }
  25737. }
  25738. }
  25739. // Characters [].:/ are reserved for track binding syntax.
  25740. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25741. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25742. // only latin characters, and the unicode \p{L} is not yet supported. So
  25743. // instead, we exclude reserved characters and match everything else.
  25744. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25745. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25746. // be matched to parse the rest of the track name.
  25747. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25748. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25749. // characters. Accessor may contain any character except closing bracket.
  25750. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25751. // contain any non-bracket characters.
  25752. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25753. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25754. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25755. class Composite {
  25756. constructor(targetGroup, path, optionalParsedPath) {
  25757. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25758. this._targetGroup = targetGroup;
  25759. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25760. }
  25761. getValue(array, offset) {
  25762. this.bind(); // bind all binding
  25763. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25764. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25765. if (binding !== undefined) binding.getValue(array, offset);
  25766. }
  25767. setValue(array, offset) {
  25768. const bindings = this._bindings;
  25769. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25770. bindings[i].setValue(array, offset);
  25771. }
  25772. }
  25773. bind() {
  25774. const bindings = this._bindings;
  25775. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25776. bindings[i].bind();
  25777. }
  25778. }
  25779. unbind() {
  25780. const bindings = this._bindings;
  25781. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25782. bindings[i].unbind();
  25783. }
  25784. }
  25785. } // Note: This class uses a State pattern on a per-method basis:
  25786. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25787. // prototype version of these methods with one that represents
  25788. // the bound state. When the property is not found, the methods
  25789. // become no-ops.
  25790. class PropertyBinding {
  25791. constructor(rootNode, path, parsedPath) {
  25792. this.path = path;
  25793. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25794. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25795. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25796. this.getValue = this._getValue_unbound;
  25797. this.setValue = this._setValue_unbound;
  25798. }
  25799. static create(root, path, parsedPath) {
  25800. if (!(root && root.isAnimationObjectGroup)) {
  25801. return new PropertyBinding(root, path, parsedPath);
  25802. } else {
  25803. return new PropertyBinding.Composite(root, path, parsedPath);
  25804. }
  25805. }
  25806. /**
  25807. * Replaces spaces with underscores and removes unsupported characters from
  25808. * node names, to ensure compatibility with parseTrackName().
  25809. *
  25810. * @param {string} name Node name to be sanitized.
  25811. * @return {string}
  25812. */
  25813. static sanitizeNodeName(name) {
  25814. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25815. }
  25816. static parseTrackName(trackName) {
  25817. const matches = _trackRe.exec(trackName);
  25818. if (matches === null) {
  25819. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25820. }
  25821. const results = {
  25822. // directoryName: matches[ 1 ], // (tschw) currently unused
  25823. nodeName: matches[2],
  25824. objectName: matches[3],
  25825. objectIndex: matches[4],
  25826. propertyName: matches[5],
  25827. // required
  25828. propertyIndex: matches[6]
  25829. };
  25830. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25831. if (lastDot !== undefined && lastDot !== -1) {
  25832. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25833. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25834. // 'bar' could be the objectName, or part of a nodeName (which can
  25835. // include '.' characters).
  25836. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25837. results.nodeName = results.nodeName.substring(0, lastDot);
  25838. results.objectName = objectName;
  25839. }
  25840. }
  25841. if (results.propertyName === null || results.propertyName.length === 0) {
  25842. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25843. }
  25844. return results;
  25845. }
  25846. static findNode(root, nodeName) {
  25847. if (nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25848. return root;
  25849. } // search into skeleton bones.
  25850. if (root.skeleton) {
  25851. const bone = root.skeleton.getBoneByName(nodeName);
  25852. if (bone !== undefined) {
  25853. return bone;
  25854. }
  25855. } // search into node subtree.
  25856. if (root.children) {
  25857. const searchNodeSubtree = function (children) {
  25858. for (let i = 0; i < children.length; i++) {
  25859. const childNode = children[i];
  25860. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25861. return childNode;
  25862. }
  25863. const result = searchNodeSubtree(childNode.children);
  25864. if (result) return result;
  25865. }
  25866. return null;
  25867. };
  25868. const subTreeNode = searchNodeSubtree(root.children);
  25869. if (subTreeNode) {
  25870. return subTreeNode;
  25871. }
  25872. }
  25873. return null;
  25874. } // these are used to "bind" a nonexistent property
  25875. _getValue_unavailable() {}
  25876. _setValue_unavailable() {} // Getters
  25877. _getValue_direct(buffer, offset) {
  25878. buffer[offset] = this.targetObject[this.propertyName];
  25879. }
  25880. _getValue_array(buffer, offset) {
  25881. const source = this.resolvedProperty;
  25882. for (let i = 0, n = source.length; i !== n; ++i) {
  25883. buffer[offset++] = source[i];
  25884. }
  25885. }
  25886. _getValue_arrayElement(buffer, offset) {
  25887. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25888. }
  25889. _getValue_toArray(buffer, offset) {
  25890. this.resolvedProperty.toArray(buffer, offset);
  25891. } // Direct
  25892. _setValue_direct(buffer, offset) {
  25893. this.targetObject[this.propertyName] = buffer[offset];
  25894. }
  25895. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25896. this.targetObject[this.propertyName] = buffer[offset];
  25897. this.targetObject.needsUpdate = true;
  25898. }
  25899. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25900. this.targetObject[this.propertyName] = buffer[offset];
  25901. this.targetObject.matrixWorldNeedsUpdate = true;
  25902. } // EntireArray
  25903. _setValue_array(buffer, offset) {
  25904. const dest = this.resolvedProperty;
  25905. for (let i = 0, n = dest.length; i !== n; ++i) {
  25906. dest[i] = buffer[offset++];
  25907. }
  25908. }
  25909. _setValue_array_setNeedsUpdate(buffer, offset) {
  25910. const dest = this.resolvedProperty;
  25911. for (let i = 0, n = dest.length; i !== n; ++i) {
  25912. dest[i] = buffer[offset++];
  25913. }
  25914. this.targetObject.needsUpdate = true;
  25915. }
  25916. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25917. const dest = this.resolvedProperty;
  25918. for (let i = 0, n = dest.length; i !== n; ++i) {
  25919. dest[i] = buffer[offset++];
  25920. }
  25921. this.targetObject.matrixWorldNeedsUpdate = true;
  25922. } // ArrayElement
  25923. _setValue_arrayElement(buffer, offset) {
  25924. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25925. }
  25926. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25927. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25928. this.targetObject.needsUpdate = true;
  25929. }
  25930. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25931. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25932. this.targetObject.matrixWorldNeedsUpdate = true;
  25933. } // HasToFromArray
  25934. _setValue_fromArray(buffer, offset) {
  25935. this.resolvedProperty.fromArray(buffer, offset);
  25936. }
  25937. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25938. this.resolvedProperty.fromArray(buffer, offset);
  25939. this.targetObject.needsUpdate = true;
  25940. }
  25941. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25942. this.resolvedProperty.fromArray(buffer, offset);
  25943. this.targetObject.matrixWorldNeedsUpdate = true;
  25944. }
  25945. _getValue_unbound(targetArray, offset) {
  25946. this.bind();
  25947. this.getValue(targetArray, offset);
  25948. }
  25949. _setValue_unbound(sourceArray, offset) {
  25950. this.bind();
  25951. this.setValue(sourceArray, offset);
  25952. } // create getter / setter pair for a property in the scene graph
  25953. bind() {
  25954. let targetObject = this.node;
  25955. const parsedPath = this.parsedPath;
  25956. const objectName = parsedPath.objectName;
  25957. const propertyName = parsedPath.propertyName;
  25958. let propertyIndex = parsedPath.propertyIndex;
  25959. if (!targetObject) {
  25960. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25961. this.node = targetObject;
  25962. } // set fail state so we can just 'return' on error
  25963. this.getValue = this._getValue_unavailable;
  25964. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25965. if (!targetObject) {
  25966. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25967. return;
  25968. }
  25969. if (objectName) {
  25970. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25971. switch (objectName) {
  25972. case 'materials':
  25973. if (!targetObject.material) {
  25974. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25975. return;
  25976. }
  25977. if (!targetObject.material.materials) {
  25978. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25979. return;
  25980. }
  25981. targetObject = targetObject.material.materials;
  25982. break;
  25983. case 'bones':
  25984. if (!targetObject.skeleton) {
  25985. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25986. return;
  25987. } // potential future optimization: skip this if propertyIndex is already an integer
  25988. // and convert the integer string to a true integer.
  25989. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25990. for (let i = 0; i < targetObject.length; i++) {
  25991. if (targetObject[i].name === objectIndex) {
  25992. objectIndex = i;
  25993. break;
  25994. }
  25995. }
  25996. break;
  25997. default:
  25998. if (targetObject[objectName] === undefined) {
  25999. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26000. return;
  26001. }
  26002. targetObject = targetObject[objectName];
  26003. }
  26004. if (objectIndex !== undefined) {
  26005. if (targetObject[objectIndex] === undefined) {
  26006. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26007. return;
  26008. }
  26009. targetObject = targetObject[objectIndex];
  26010. }
  26011. } // resolve property
  26012. const nodeProperty = targetObject[propertyName];
  26013. if (nodeProperty === undefined) {
  26014. const nodeName = parsedPath.nodeName;
  26015. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26016. return;
  26017. } // determine versioning scheme
  26018. let versioning = this.Versioning.None;
  26019. this.targetObject = targetObject;
  26020. if (targetObject.needsUpdate !== undefined) {
  26021. // material
  26022. versioning = this.Versioning.NeedsUpdate;
  26023. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26024. // node transform
  26025. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26026. } // determine how the property gets bound
  26027. let bindingType = this.BindingType.Direct;
  26028. if (propertyIndex !== undefined) {
  26029. // access a sub element of the property array (only primitives are supported right now)
  26030. if (propertyName === 'morphTargetInfluences') {
  26031. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26032. // support resolving morphTarget names into indices.
  26033. if (!targetObject.geometry) {
  26034. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26035. return;
  26036. }
  26037. if (!targetObject.geometry.morphAttributes) {
  26038. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26039. return;
  26040. }
  26041. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  26042. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  26043. }
  26044. }
  26045. bindingType = this.BindingType.ArrayElement;
  26046. this.resolvedProperty = nodeProperty;
  26047. this.propertyIndex = propertyIndex;
  26048. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26049. // must use copy for Object3D.Euler/Quaternion
  26050. bindingType = this.BindingType.HasFromToArray;
  26051. this.resolvedProperty = nodeProperty;
  26052. } else if (Array.isArray(nodeProperty)) {
  26053. bindingType = this.BindingType.EntireArray;
  26054. this.resolvedProperty = nodeProperty;
  26055. } else {
  26056. this.propertyName = propertyName;
  26057. } // select getter / setter
  26058. this.getValue = this.GetterByBindingType[bindingType];
  26059. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26060. }
  26061. unbind() {
  26062. this.node = null; // back to the prototype version of getValue / setValue
  26063. // note: avoiding to mutate the shape of 'this' via 'delete'
  26064. this.getValue = this._getValue_unbound;
  26065. this.setValue = this._setValue_unbound;
  26066. }
  26067. }
  26068. PropertyBinding.Composite = Composite;
  26069. PropertyBinding.prototype.BindingType = {
  26070. Direct: 0,
  26071. EntireArray: 1,
  26072. ArrayElement: 2,
  26073. HasFromToArray: 3
  26074. };
  26075. PropertyBinding.prototype.Versioning = {
  26076. None: 0,
  26077. NeedsUpdate: 1,
  26078. MatrixWorldNeedsUpdate: 2
  26079. };
  26080. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  26081. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  26082. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  26083. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  26084. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  26085. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  26086. /**
  26087. *
  26088. * A group of objects that receives a shared animation state.
  26089. *
  26090. * Usage:
  26091. *
  26092. * - Add objects you would otherwise pass as 'root' to the
  26093. * constructor or the .clipAction method of AnimationMixer.
  26094. *
  26095. * - Instead pass this object as 'root'.
  26096. *
  26097. * - You can also add and remove objects later when the mixer
  26098. * is running.
  26099. *
  26100. * Note:
  26101. *
  26102. * Objects of this class appear as one object to the mixer,
  26103. * so cache control of the individual objects must be done
  26104. * on the group.
  26105. *
  26106. * Limitation:
  26107. *
  26108. * - The animated properties must be compatible among the
  26109. * all objects in the group.
  26110. *
  26111. * - A single property can either be controlled through a
  26112. * target group or directly, but not both.
  26113. */
  26114. class AnimationObjectGroup {
  26115. constructor() {
  26116. this.isAnimationObjectGroup = true;
  26117. this.uuid = generateUUID(); // cached objects followed by the active ones
  26118. this._objects = Array.prototype.slice.call(arguments);
  26119. this.nCachedObjects_ = 0; // threshold
  26120. // note: read by PropertyBinding.Composite
  26121. const indices = {};
  26122. this._indicesByUUID = indices; // for bookkeeping
  26123. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26124. indices[arguments[i].uuid] = i;
  26125. }
  26126. this._paths = []; // inside: string
  26127. this._parsedPaths = []; // inside: { we don't care, here }
  26128. this._bindings = []; // inside: Array< PropertyBinding >
  26129. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26130. const scope = this;
  26131. this.stats = {
  26132. objects: {
  26133. get total() {
  26134. return scope._objects.length;
  26135. },
  26136. get inUse() {
  26137. return this.total - scope.nCachedObjects_;
  26138. }
  26139. },
  26140. get bindingsPerObject() {
  26141. return scope._bindings.length;
  26142. }
  26143. };
  26144. }
  26145. add() {
  26146. const objects = this._objects,
  26147. indicesByUUID = this._indicesByUUID,
  26148. paths = this._paths,
  26149. parsedPaths = this._parsedPaths,
  26150. bindings = this._bindings,
  26151. nBindings = bindings.length;
  26152. let knownObject = undefined,
  26153. nObjects = objects.length,
  26154. nCachedObjects = this.nCachedObjects_;
  26155. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26156. const object = arguments[i],
  26157. uuid = object.uuid;
  26158. let index = indicesByUUID[uuid];
  26159. if (index === undefined) {
  26160. // unknown object -> add it to the ACTIVE region
  26161. index = nObjects++;
  26162. indicesByUUID[uuid] = index;
  26163. objects.push(object); // accounting is done, now do the same for all bindings
  26164. for (let j = 0, m = nBindings; j !== m; ++j) {
  26165. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26166. }
  26167. } else if (index < nCachedObjects) {
  26168. knownObject = objects[index]; // move existing object to the ACTIVE region
  26169. const firstActiveIndex = --nCachedObjects,
  26170. lastCachedObject = objects[firstActiveIndex];
  26171. indicesByUUID[lastCachedObject.uuid] = index;
  26172. objects[index] = lastCachedObject;
  26173. indicesByUUID[uuid] = firstActiveIndex;
  26174. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26175. for (let j = 0, m = nBindings; j !== m; ++j) {
  26176. const bindingsForPath = bindings[j],
  26177. lastCached = bindingsForPath[firstActiveIndex];
  26178. let binding = bindingsForPath[index];
  26179. bindingsForPath[index] = lastCached;
  26180. if (binding === undefined) {
  26181. // since we do not bother to create new bindings
  26182. // for objects that are cached, the binding may
  26183. // or may not exist
  26184. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26185. }
  26186. bindingsForPath[firstActiveIndex] = binding;
  26187. }
  26188. } else if (objects[index] !== knownObject) {
  26189. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26190. } // else the object is already where we want it to be
  26191. } // for arguments
  26192. this.nCachedObjects_ = nCachedObjects;
  26193. }
  26194. remove() {
  26195. const objects = this._objects,
  26196. indicesByUUID = this._indicesByUUID,
  26197. bindings = this._bindings,
  26198. nBindings = bindings.length;
  26199. let nCachedObjects = this.nCachedObjects_;
  26200. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26201. const object = arguments[i],
  26202. uuid = object.uuid,
  26203. index = indicesByUUID[uuid];
  26204. if (index !== undefined && index >= nCachedObjects) {
  26205. // move existing object into the CACHED region
  26206. const lastCachedIndex = nCachedObjects++,
  26207. firstActiveObject = objects[lastCachedIndex];
  26208. indicesByUUID[firstActiveObject.uuid] = index;
  26209. objects[index] = firstActiveObject;
  26210. indicesByUUID[uuid] = lastCachedIndex;
  26211. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26212. for (let j = 0, m = nBindings; j !== m; ++j) {
  26213. const bindingsForPath = bindings[j],
  26214. firstActive = bindingsForPath[lastCachedIndex],
  26215. binding = bindingsForPath[index];
  26216. bindingsForPath[index] = firstActive;
  26217. bindingsForPath[lastCachedIndex] = binding;
  26218. }
  26219. }
  26220. } // for arguments
  26221. this.nCachedObjects_ = nCachedObjects;
  26222. } // remove & forget
  26223. uncache() {
  26224. const objects = this._objects,
  26225. indicesByUUID = this._indicesByUUID,
  26226. bindings = this._bindings,
  26227. nBindings = bindings.length;
  26228. let nCachedObjects = this.nCachedObjects_,
  26229. nObjects = objects.length;
  26230. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26231. const object = arguments[i],
  26232. uuid = object.uuid,
  26233. index = indicesByUUID[uuid];
  26234. if (index !== undefined) {
  26235. delete indicesByUUID[uuid];
  26236. if (index < nCachedObjects) {
  26237. // object is cached, shrink the CACHED region
  26238. const firstActiveIndex = --nCachedObjects,
  26239. lastCachedObject = objects[firstActiveIndex],
  26240. lastIndex = --nObjects,
  26241. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26242. indicesByUUID[lastCachedObject.uuid] = index;
  26243. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26244. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26245. objects[firstActiveIndex] = lastObject;
  26246. objects.pop(); // accounting is done, now do the same for all bindings
  26247. for (let j = 0, m = nBindings; j !== m; ++j) {
  26248. const bindingsForPath = bindings[j],
  26249. lastCached = bindingsForPath[firstActiveIndex],
  26250. last = bindingsForPath[lastIndex];
  26251. bindingsForPath[index] = lastCached;
  26252. bindingsForPath[firstActiveIndex] = last;
  26253. bindingsForPath.pop();
  26254. }
  26255. } else {
  26256. // object is active, just swap with the last and pop
  26257. const lastIndex = --nObjects,
  26258. lastObject = objects[lastIndex];
  26259. if (lastIndex > 0) {
  26260. indicesByUUID[lastObject.uuid] = index;
  26261. }
  26262. objects[index] = lastObject;
  26263. objects.pop(); // accounting is done, now do the same for all bindings
  26264. for (let j = 0, m = nBindings; j !== m; ++j) {
  26265. const bindingsForPath = bindings[j];
  26266. bindingsForPath[index] = bindingsForPath[lastIndex];
  26267. bindingsForPath.pop();
  26268. }
  26269. } // cached or active
  26270. } // if object is known
  26271. } // for arguments
  26272. this.nCachedObjects_ = nCachedObjects;
  26273. } // Internal interface used by befriended PropertyBinding.Composite:
  26274. subscribe_(path, parsedPath) {
  26275. // returns an array of bindings for the given path that is changed
  26276. // according to the contained objects in the group
  26277. const indicesByPath = this._bindingsIndicesByPath;
  26278. let index = indicesByPath[path];
  26279. const bindings = this._bindings;
  26280. if (index !== undefined) return bindings[index];
  26281. const paths = this._paths,
  26282. parsedPaths = this._parsedPaths,
  26283. objects = this._objects,
  26284. nObjects = objects.length,
  26285. nCachedObjects = this.nCachedObjects_,
  26286. bindingsForPath = new Array(nObjects);
  26287. index = bindings.length;
  26288. indicesByPath[path] = index;
  26289. paths.push(path);
  26290. parsedPaths.push(parsedPath);
  26291. bindings.push(bindingsForPath);
  26292. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26293. const object = objects[i];
  26294. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26295. }
  26296. return bindingsForPath;
  26297. }
  26298. unsubscribe_(path) {
  26299. // tells the group to forget about a property path and no longer
  26300. // update the array previously obtained with 'subscribe_'
  26301. const indicesByPath = this._bindingsIndicesByPath,
  26302. index = indicesByPath[path];
  26303. if (index !== undefined) {
  26304. const paths = this._paths,
  26305. parsedPaths = this._parsedPaths,
  26306. bindings = this._bindings,
  26307. lastBindingsIndex = bindings.length - 1,
  26308. lastBindings = bindings[lastBindingsIndex],
  26309. lastBindingsPath = path[lastBindingsIndex];
  26310. indicesByPath[lastBindingsPath] = index;
  26311. bindings[index] = lastBindings;
  26312. bindings.pop();
  26313. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26314. parsedPaths.pop();
  26315. paths[index] = paths[lastBindingsIndex];
  26316. paths.pop();
  26317. }
  26318. }
  26319. }
  26320. class AnimationAction {
  26321. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26322. this._mixer = mixer;
  26323. this._clip = clip;
  26324. this._localRoot = localRoot;
  26325. this.blendMode = blendMode;
  26326. const tracks = clip.tracks,
  26327. nTracks = tracks.length,
  26328. interpolants = new Array(nTracks);
  26329. const interpolantSettings = {
  26330. endingStart: ZeroCurvatureEnding,
  26331. endingEnd: ZeroCurvatureEnding
  26332. };
  26333. for (let i = 0; i !== nTracks; ++i) {
  26334. const interpolant = tracks[i].createInterpolant(null);
  26335. interpolants[i] = interpolant;
  26336. interpolant.settings = interpolantSettings;
  26337. }
  26338. this._interpolantSettings = interpolantSettings;
  26339. this._interpolants = interpolants; // bound by the mixer
  26340. // inside: PropertyMixer (managed by the mixer)
  26341. this._propertyBindings = new Array(nTracks);
  26342. this._cacheIndex = null; // for the memory manager
  26343. this._byClipCacheIndex = null; // for the memory manager
  26344. this._timeScaleInterpolant = null;
  26345. this._weightInterpolant = null;
  26346. this.loop = LoopRepeat;
  26347. this._loopCount = -1; // global mixer time when the action is to be started
  26348. // it's set back to 'null' upon start of the action
  26349. this._startTime = null; // scaled local time of the action
  26350. // gets clamped or wrapped to 0..clip.duration according to loop
  26351. this.time = 0;
  26352. this.timeScale = 1;
  26353. this._effectiveTimeScale = 1;
  26354. this.weight = 1;
  26355. this._effectiveWeight = 1;
  26356. this.repetitions = Infinity; // no. of repetitions when looping
  26357. this.paused = false; // true -> zero effective time scale
  26358. this.enabled = true; // false -> zero effective weight
  26359. this.clampWhenFinished = false; // keep feeding the last frame?
  26360. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26361. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26362. } // State & Scheduling
  26363. play() {
  26364. this._mixer._activateAction(this);
  26365. return this;
  26366. }
  26367. stop() {
  26368. this._mixer._deactivateAction(this);
  26369. return this.reset();
  26370. }
  26371. reset() {
  26372. this.paused = false;
  26373. this.enabled = true;
  26374. this.time = 0; // restart clip
  26375. this._loopCount = -1; // forget previous loops
  26376. this._startTime = null; // forget scheduling
  26377. return this.stopFading().stopWarping();
  26378. }
  26379. isRunning() {
  26380. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26381. } // return true when play has been called
  26382. isScheduled() {
  26383. return this._mixer._isActiveAction(this);
  26384. }
  26385. startAt(time) {
  26386. this._startTime = time;
  26387. return this;
  26388. }
  26389. setLoop(mode, repetitions) {
  26390. this.loop = mode;
  26391. this.repetitions = repetitions;
  26392. return this;
  26393. } // Weight
  26394. // set the weight stopping any scheduled fading
  26395. // although .enabled = false yields an effective weight of zero, this
  26396. // method does *not* change .enabled, because it would be confusing
  26397. setEffectiveWeight(weight) {
  26398. this.weight = weight; // note: same logic as when updated at runtime
  26399. this._effectiveWeight = this.enabled ? weight : 0;
  26400. return this.stopFading();
  26401. } // return the weight considering fading and .enabled
  26402. getEffectiveWeight() {
  26403. return this._effectiveWeight;
  26404. }
  26405. fadeIn(duration) {
  26406. return this._scheduleFading(duration, 0, 1);
  26407. }
  26408. fadeOut(duration) {
  26409. return this._scheduleFading(duration, 1, 0);
  26410. }
  26411. crossFadeFrom(fadeOutAction, duration, warp) {
  26412. fadeOutAction.fadeOut(duration);
  26413. this.fadeIn(duration);
  26414. if (warp) {
  26415. const fadeInDuration = this._clip.duration,
  26416. fadeOutDuration = fadeOutAction._clip.duration,
  26417. startEndRatio = fadeOutDuration / fadeInDuration,
  26418. endStartRatio = fadeInDuration / fadeOutDuration;
  26419. fadeOutAction.warp(1.0, startEndRatio, duration);
  26420. this.warp(endStartRatio, 1.0, duration);
  26421. }
  26422. return this;
  26423. }
  26424. crossFadeTo(fadeInAction, duration, warp) {
  26425. return fadeInAction.crossFadeFrom(this, duration, warp);
  26426. }
  26427. stopFading() {
  26428. const weightInterpolant = this._weightInterpolant;
  26429. if (weightInterpolant !== null) {
  26430. this._weightInterpolant = null;
  26431. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26432. }
  26433. return this;
  26434. } // Time Scale Control
  26435. // set the time scale stopping any scheduled warping
  26436. // although .paused = true yields an effective time scale of zero, this
  26437. // method does *not* change .paused, because it would be confusing
  26438. setEffectiveTimeScale(timeScale) {
  26439. this.timeScale = timeScale;
  26440. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26441. return this.stopWarping();
  26442. } // return the time scale considering warping and .paused
  26443. getEffectiveTimeScale() {
  26444. return this._effectiveTimeScale;
  26445. }
  26446. setDuration(duration) {
  26447. this.timeScale = this._clip.duration / duration;
  26448. return this.stopWarping();
  26449. }
  26450. syncWith(action) {
  26451. this.time = action.time;
  26452. this.timeScale = action.timeScale;
  26453. return this.stopWarping();
  26454. }
  26455. halt(duration) {
  26456. return this.warp(this._effectiveTimeScale, 0, duration);
  26457. }
  26458. warp(startTimeScale, endTimeScale, duration) {
  26459. const mixer = this._mixer,
  26460. now = mixer.time,
  26461. timeScale = this.timeScale;
  26462. let interpolant = this._timeScaleInterpolant;
  26463. if (interpolant === null) {
  26464. interpolant = mixer._lendControlInterpolant();
  26465. this._timeScaleInterpolant = interpolant;
  26466. }
  26467. const times = interpolant.parameterPositions,
  26468. values = interpolant.sampleValues;
  26469. times[0] = now;
  26470. times[1] = now + duration;
  26471. values[0] = startTimeScale / timeScale;
  26472. values[1] = endTimeScale / timeScale;
  26473. return this;
  26474. }
  26475. stopWarping() {
  26476. const timeScaleInterpolant = this._timeScaleInterpolant;
  26477. if (timeScaleInterpolant !== null) {
  26478. this._timeScaleInterpolant = null;
  26479. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26480. }
  26481. return this;
  26482. } // Object Accessors
  26483. getMixer() {
  26484. return this._mixer;
  26485. }
  26486. getClip() {
  26487. return this._clip;
  26488. }
  26489. getRoot() {
  26490. return this._localRoot || this._mixer._root;
  26491. } // Interna
  26492. _update(time, deltaTime, timeDirection, accuIndex) {
  26493. // called by the mixer
  26494. if (!this.enabled) {
  26495. // call ._updateWeight() to update ._effectiveWeight
  26496. this._updateWeight(time);
  26497. return;
  26498. }
  26499. const startTime = this._startTime;
  26500. if (startTime !== null) {
  26501. // check for scheduled start of action
  26502. const timeRunning = (time - startTime) * timeDirection;
  26503. if (timeRunning < 0 || timeDirection === 0) {
  26504. deltaTime = 0;
  26505. } else {
  26506. this._startTime = null; // unschedule
  26507. deltaTime = timeDirection * timeRunning;
  26508. }
  26509. } // apply time scale and advance time
  26510. deltaTime *= this._updateTimeScale(time);
  26511. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26512. // an effective weight of 0
  26513. const weight = this._updateWeight(time);
  26514. if (weight > 0) {
  26515. const interpolants = this._interpolants;
  26516. const propertyMixers = this._propertyBindings;
  26517. switch (this.blendMode) {
  26518. case AdditiveAnimationBlendMode:
  26519. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26520. interpolants[j].evaluate(clipTime);
  26521. propertyMixers[j].accumulateAdditive(weight);
  26522. }
  26523. break;
  26524. case NormalAnimationBlendMode:
  26525. default:
  26526. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26527. interpolants[j].evaluate(clipTime);
  26528. propertyMixers[j].accumulate(accuIndex, weight);
  26529. }
  26530. }
  26531. }
  26532. }
  26533. _updateWeight(time) {
  26534. let weight = 0;
  26535. if (this.enabled) {
  26536. weight = this.weight;
  26537. const interpolant = this._weightInterpolant;
  26538. if (interpolant !== null) {
  26539. const interpolantValue = interpolant.evaluate(time)[0];
  26540. weight *= interpolantValue;
  26541. if (time > interpolant.parameterPositions[1]) {
  26542. this.stopFading();
  26543. if (interpolantValue === 0) {
  26544. // faded out, disable
  26545. this.enabled = false;
  26546. }
  26547. }
  26548. }
  26549. }
  26550. this._effectiveWeight = weight;
  26551. return weight;
  26552. }
  26553. _updateTimeScale(time) {
  26554. let timeScale = 0;
  26555. if (!this.paused) {
  26556. timeScale = this.timeScale;
  26557. const interpolant = this._timeScaleInterpolant;
  26558. if (interpolant !== null) {
  26559. const interpolantValue = interpolant.evaluate(time)[0];
  26560. timeScale *= interpolantValue;
  26561. if (time > interpolant.parameterPositions[1]) {
  26562. this.stopWarping();
  26563. if (timeScale === 0) {
  26564. // motion has halted, pause
  26565. this.paused = true;
  26566. } else {
  26567. // warp done - apply final time scale
  26568. this.timeScale = timeScale;
  26569. }
  26570. }
  26571. }
  26572. }
  26573. this._effectiveTimeScale = timeScale;
  26574. return timeScale;
  26575. }
  26576. _updateTime(deltaTime) {
  26577. const duration = this._clip.duration;
  26578. const loop = this.loop;
  26579. let time = this.time + deltaTime;
  26580. let loopCount = this._loopCount;
  26581. const pingPong = loop === LoopPingPong;
  26582. if (deltaTime === 0) {
  26583. if (loopCount === -1) return time;
  26584. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26585. }
  26586. if (loop === LoopOnce) {
  26587. if (loopCount === -1) {
  26588. // just started
  26589. this._loopCount = 0;
  26590. this._setEndings(true, true, false);
  26591. }
  26592. handle_stop: {
  26593. if (time >= duration) {
  26594. time = duration;
  26595. } else if (time < 0) {
  26596. time = 0;
  26597. } else {
  26598. this.time = time;
  26599. break handle_stop;
  26600. }
  26601. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26602. this.time = time;
  26603. this._mixer.dispatchEvent({
  26604. type: 'finished',
  26605. action: this,
  26606. direction: deltaTime < 0 ? -1 : 1
  26607. });
  26608. }
  26609. } else {
  26610. // repetitive Repeat or PingPong
  26611. if (loopCount === -1) {
  26612. // just started
  26613. if (deltaTime >= 0) {
  26614. loopCount = 0;
  26615. this._setEndings(true, this.repetitions === 0, pingPong);
  26616. } else {
  26617. // when looping in reverse direction, the initial
  26618. // transition through zero counts as a repetition,
  26619. // so leave loopCount at -1
  26620. this._setEndings(this.repetitions === 0, true, pingPong);
  26621. }
  26622. }
  26623. if (time >= duration || time < 0) {
  26624. // wrap around
  26625. const loopDelta = Math.floor(time / duration); // signed
  26626. time -= duration * loopDelta;
  26627. loopCount += Math.abs(loopDelta);
  26628. const pending = this.repetitions - loopCount;
  26629. if (pending <= 0) {
  26630. // have to stop (switch state, clamp time, fire event)
  26631. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26632. time = deltaTime > 0 ? duration : 0;
  26633. this.time = time;
  26634. this._mixer.dispatchEvent({
  26635. type: 'finished',
  26636. action: this,
  26637. direction: deltaTime > 0 ? 1 : -1
  26638. });
  26639. } else {
  26640. // keep running
  26641. if (pending === 1) {
  26642. // entering the last round
  26643. const atStart = deltaTime < 0;
  26644. this._setEndings(atStart, !atStart, pingPong);
  26645. } else {
  26646. this._setEndings(false, false, pingPong);
  26647. }
  26648. this._loopCount = loopCount;
  26649. this.time = time;
  26650. this._mixer.dispatchEvent({
  26651. type: 'loop',
  26652. action: this,
  26653. loopDelta: loopDelta
  26654. });
  26655. }
  26656. } else {
  26657. this.time = time;
  26658. }
  26659. if (pingPong && (loopCount & 1) === 1) {
  26660. // invert time for the "pong round"
  26661. return duration - time;
  26662. }
  26663. }
  26664. return time;
  26665. }
  26666. _setEndings(atStart, atEnd, pingPong) {
  26667. const settings = this._interpolantSettings;
  26668. if (pingPong) {
  26669. settings.endingStart = ZeroSlopeEnding;
  26670. settings.endingEnd = ZeroSlopeEnding;
  26671. } else {
  26672. // assuming for LoopOnce atStart == atEnd == true
  26673. if (atStart) {
  26674. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26675. } else {
  26676. settings.endingStart = WrapAroundEnding;
  26677. }
  26678. if (atEnd) {
  26679. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26680. } else {
  26681. settings.endingEnd = WrapAroundEnding;
  26682. }
  26683. }
  26684. }
  26685. _scheduleFading(duration, weightNow, weightThen) {
  26686. const mixer = this._mixer,
  26687. now = mixer.time;
  26688. let interpolant = this._weightInterpolant;
  26689. if (interpolant === null) {
  26690. interpolant = mixer._lendControlInterpolant();
  26691. this._weightInterpolant = interpolant;
  26692. }
  26693. const times = interpolant.parameterPositions,
  26694. values = interpolant.sampleValues;
  26695. times[0] = now;
  26696. values[0] = weightNow;
  26697. times[1] = now + duration;
  26698. values[1] = weightThen;
  26699. return this;
  26700. }
  26701. }
  26702. const _controlInterpolantsResultBuffer = new Float32Array(1);
  26703. class AnimationMixer extends EventDispatcher {
  26704. constructor(root) {
  26705. super();
  26706. this._root = root;
  26707. this._initMemoryManager();
  26708. this._accuIndex = 0;
  26709. this.time = 0;
  26710. this.timeScale = 1.0;
  26711. }
  26712. _bindAction(action, prototypeAction) {
  26713. const root = action._localRoot || this._root,
  26714. tracks = action._clip.tracks,
  26715. nTracks = tracks.length,
  26716. bindings = action._propertyBindings,
  26717. interpolants = action._interpolants,
  26718. rootUuid = root.uuid,
  26719. bindingsByRoot = this._bindingsByRootAndName;
  26720. let bindingsByName = bindingsByRoot[rootUuid];
  26721. if (bindingsByName === undefined) {
  26722. bindingsByName = {};
  26723. bindingsByRoot[rootUuid] = bindingsByName;
  26724. }
  26725. for (let i = 0; i !== nTracks; ++i) {
  26726. const track = tracks[i],
  26727. trackName = track.name;
  26728. let binding = bindingsByName[trackName];
  26729. if (binding !== undefined) {
  26730. ++binding.referenceCount;
  26731. bindings[i] = binding;
  26732. } else {
  26733. binding = bindings[i];
  26734. if (binding !== undefined) {
  26735. // existing binding, make sure the cache knows
  26736. if (binding._cacheIndex === null) {
  26737. ++binding.referenceCount;
  26738. this._addInactiveBinding(binding, rootUuid, trackName);
  26739. }
  26740. continue;
  26741. }
  26742. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26743. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26744. ++binding.referenceCount;
  26745. this._addInactiveBinding(binding, rootUuid, trackName);
  26746. bindings[i] = binding;
  26747. }
  26748. interpolants[i].resultBuffer = binding.buffer;
  26749. }
  26750. }
  26751. _activateAction(action) {
  26752. if (!this._isActiveAction(action)) {
  26753. if (action._cacheIndex === null) {
  26754. // this action has been forgotten by the cache, but the user
  26755. // appears to be still using it -> rebind
  26756. const rootUuid = (action._localRoot || this._root).uuid,
  26757. clipUuid = action._clip.uuid,
  26758. actionsForClip = this._actionsByClip[clipUuid];
  26759. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26760. this._addInactiveAction(action, clipUuid, rootUuid);
  26761. }
  26762. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26763. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26764. const binding = bindings[i];
  26765. if (binding.useCount++ === 0) {
  26766. this._lendBinding(binding);
  26767. binding.saveOriginalState();
  26768. }
  26769. }
  26770. this._lendAction(action);
  26771. }
  26772. }
  26773. _deactivateAction(action) {
  26774. if (this._isActiveAction(action)) {
  26775. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26776. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26777. const binding = bindings[i];
  26778. if (--binding.useCount === 0) {
  26779. binding.restoreOriginalState();
  26780. this._takeBackBinding(binding);
  26781. }
  26782. }
  26783. this._takeBackAction(action);
  26784. }
  26785. } // Memory manager
  26786. _initMemoryManager() {
  26787. this._actions = []; // 'nActiveActions' followed by inactive ones
  26788. this._nActiveActions = 0;
  26789. this._actionsByClip = {}; // inside:
  26790. // {
  26791. // knownActions: Array< AnimationAction > - used as prototypes
  26792. // actionByRoot: AnimationAction - lookup
  26793. // }
  26794. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26795. this._nActiveBindings = 0;
  26796. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26797. this._controlInterpolants = []; // same game as above
  26798. this._nActiveControlInterpolants = 0;
  26799. const scope = this;
  26800. this.stats = {
  26801. actions: {
  26802. get total() {
  26803. return scope._actions.length;
  26804. },
  26805. get inUse() {
  26806. return scope._nActiveActions;
  26807. }
  26808. },
  26809. bindings: {
  26810. get total() {
  26811. return scope._bindings.length;
  26812. },
  26813. get inUse() {
  26814. return scope._nActiveBindings;
  26815. }
  26816. },
  26817. controlInterpolants: {
  26818. get total() {
  26819. return scope._controlInterpolants.length;
  26820. },
  26821. get inUse() {
  26822. return scope._nActiveControlInterpolants;
  26823. }
  26824. }
  26825. };
  26826. } // Memory management for AnimationAction objects
  26827. _isActiveAction(action) {
  26828. const index = action._cacheIndex;
  26829. return index !== null && index < this._nActiveActions;
  26830. }
  26831. _addInactiveAction(action, clipUuid, rootUuid) {
  26832. const actions = this._actions,
  26833. actionsByClip = this._actionsByClip;
  26834. let actionsForClip = actionsByClip[clipUuid];
  26835. if (actionsForClip === undefined) {
  26836. actionsForClip = {
  26837. knownActions: [action],
  26838. actionByRoot: {}
  26839. };
  26840. action._byClipCacheIndex = 0;
  26841. actionsByClip[clipUuid] = actionsForClip;
  26842. } else {
  26843. const knownActions = actionsForClip.knownActions;
  26844. action._byClipCacheIndex = knownActions.length;
  26845. knownActions.push(action);
  26846. }
  26847. action._cacheIndex = actions.length;
  26848. actions.push(action);
  26849. actionsForClip.actionByRoot[rootUuid] = action;
  26850. }
  26851. _removeInactiveAction(action) {
  26852. const actions = this._actions,
  26853. lastInactiveAction = actions[actions.length - 1],
  26854. cacheIndex = action._cacheIndex;
  26855. lastInactiveAction._cacheIndex = cacheIndex;
  26856. actions[cacheIndex] = lastInactiveAction;
  26857. actions.pop();
  26858. action._cacheIndex = null;
  26859. const clipUuid = action._clip.uuid,
  26860. actionsByClip = this._actionsByClip,
  26861. actionsForClip = actionsByClip[clipUuid],
  26862. knownActionsForClip = actionsForClip.knownActions,
  26863. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26864. byClipCacheIndex = action._byClipCacheIndex;
  26865. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26866. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26867. knownActionsForClip.pop();
  26868. action._byClipCacheIndex = null;
  26869. const actionByRoot = actionsForClip.actionByRoot,
  26870. rootUuid = (action._localRoot || this._root).uuid;
  26871. delete actionByRoot[rootUuid];
  26872. if (knownActionsForClip.length === 0) {
  26873. delete actionsByClip[clipUuid];
  26874. }
  26875. this._removeInactiveBindingsForAction(action);
  26876. }
  26877. _removeInactiveBindingsForAction(action) {
  26878. const bindings = action._propertyBindings;
  26879. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26880. const binding = bindings[i];
  26881. if (--binding.referenceCount === 0) {
  26882. this._removeInactiveBinding(binding);
  26883. }
  26884. }
  26885. }
  26886. _lendAction(action) {
  26887. // [ active actions | inactive actions ]
  26888. // [ active actions >| inactive actions ]
  26889. // s a
  26890. // <-swap->
  26891. // a s
  26892. const actions = this._actions,
  26893. prevIndex = action._cacheIndex,
  26894. lastActiveIndex = this._nActiveActions++,
  26895. firstInactiveAction = actions[lastActiveIndex];
  26896. action._cacheIndex = lastActiveIndex;
  26897. actions[lastActiveIndex] = action;
  26898. firstInactiveAction._cacheIndex = prevIndex;
  26899. actions[prevIndex] = firstInactiveAction;
  26900. }
  26901. _takeBackAction(action) {
  26902. // [ active actions | inactive actions ]
  26903. // [ active actions |< inactive actions ]
  26904. // a s
  26905. // <-swap->
  26906. // s a
  26907. const actions = this._actions,
  26908. prevIndex = action._cacheIndex,
  26909. firstInactiveIndex = --this._nActiveActions,
  26910. lastActiveAction = actions[firstInactiveIndex];
  26911. action._cacheIndex = firstInactiveIndex;
  26912. actions[firstInactiveIndex] = action;
  26913. lastActiveAction._cacheIndex = prevIndex;
  26914. actions[prevIndex] = lastActiveAction;
  26915. } // Memory management for PropertyMixer objects
  26916. _addInactiveBinding(binding, rootUuid, trackName) {
  26917. const bindingsByRoot = this._bindingsByRootAndName,
  26918. bindings = this._bindings;
  26919. let bindingByName = bindingsByRoot[rootUuid];
  26920. if (bindingByName === undefined) {
  26921. bindingByName = {};
  26922. bindingsByRoot[rootUuid] = bindingByName;
  26923. }
  26924. bindingByName[trackName] = binding;
  26925. binding._cacheIndex = bindings.length;
  26926. bindings.push(binding);
  26927. }
  26928. _removeInactiveBinding(binding) {
  26929. const bindings = this._bindings,
  26930. propBinding = binding.binding,
  26931. rootUuid = propBinding.rootNode.uuid,
  26932. trackName = propBinding.path,
  26933. bindingsByRoot = this._bindingsByRootAndName,
  26934. bindingByName = bindingsByRoot[rootUuid],
  26935. lastInactiveBinding = bindings[bindings.length - 1],
  26936. cacheIndex = binding._cacheIndex;
  26937. lastInactiveBinding._cacheIndex = cacheIndex;
  26938. bindings[cacheIndex] = lastInactiveBinding;
  26939. bindings.pop();
  26940. delete bindingByName[trackName];
  26941. if (Object.keys(bindingByName).length === 0) {
  26942. delete bindingsByRoot[rootUuid];
  26943. }
  26944. }
  26945. _lendBinding(binding) {
  26946. const bindings = this._bindings,
  26947. prevIndex = binding._cacheIndex,
  26948. lastActiveIndex = this._nActiveBindings++,
  26949. firstInactiveBinding = bindings[lastActiveIndex];
  26950. binding._cacheIndex = lastActiveIndex;
  26951. bindings[lastActiveIndex] = binding;
  26952. firstInactiveBinding._cacheIndex = prevIndex;
  26953. bindings[prevIndex] = firstInactiveBinding;
  26954. }
  26955. _takeBackBinding(binding) {
  26956. const bindings = this._bindings,
  26957. prevIndex = binding._cacheIndex,
  26958. firstInactiveIndex = --this._nActiveBindings,
  26959. lastActiveBinding = bindings[firstInactiveIndex];
  26960. binding._cacheIndex = firstInactiveIndex;
  26961. bindings[firstInactiveIndex] = binding;
  26962. lastActiveBinding._cacheIndex = prevIndex;
  26963. bindings[prevIndex] = lastActiveBinding;
  26964. } // Memory management of Interpolants for weight and time scale
  26965. _lendControlInterpolant() {
  26966. const interpolants = this._controlInterpolants,
  26967. lastActiveIndex = this._nActiveControlInterpolants++;
  26968. let interpolant = interpolants[lastActiveIndex];
  26969. if (interpolant === undefined) {
  26970. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer);
  26971. interpolant.__cacheIndex = lastActiveIndex;
  26972. interpolants[lastActiveIndex] = interpolant;
  26973. }
  26974. return interpolant;
  26975. }
  26976. _takeBackControlInterpolant(interpolant) {
  26977. const interpolants = this._controlInterpolants,
  26978. prevIndex = interpolant.__cacheIndex,
  26979. firstInactiveIndex = --this._nActiveControlInterpolants,
  26980. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26981. interpolant.__cacheIndex = firstInactiveIndex;
  26982. interpolants[firstInactiveIndex] = interpolant;
  26983. lastActiveInterpolant.__cacheIndex = prevIndex;
  26984. interpolants[prevIndex] = lastActiveInterpolant;
  26985. } // return an action for a clip optionally using a custom root target
  26986. // object (this method allocates a lot of dynamic memory in case a
  26987. // previously unknown clip/root combination is specified)
  26988. clipAction(clip, optionalRoot, blendMode) {
  26989. const root = optionalRoot || this._root,
  26990. rootUuid = root.uuid;
  26991. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26992. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26993. const actionsForClip = this._actionsByClip[clipUuid];
  26994. let prototypeAction = null;
  26995. if (blendMode === undefined) {
  26996. if (clipObject !== null) {
  26997. blendMode = clipObject.blendMode;
  26998. } else {
  26999. blendMode = NormalAnimationBlendMode;
  27000. }
  27001. }
  27002. if (actionsForClip !== undefined) {
  27003. const existingAction = actionsForClip.actionByRoot[rootUuid];
  27004. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  27005. return existingAction;
  27006. } // we know the clip, so we don't have to parse all
  27007. // the bindings again but can just copy
  27008. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27009. if (clipObject === null) clipObject = prototypeAction._clip;
  27010. } // clip must be known when specified via string
  27011. if (clipObject === null) return null; // allocate all resources required to run it
  27012. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  27013. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27014. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27015. return newAction;
  27016. } // get an existing action
  27017. existingAction(clip, optionalRoot) {
  27018. const root = optionalRoot || this._root,
  27019. rootUuid = root.uuid,
  27020. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27021. clipUuid = clipObject ? clipObject.uuid : clip,
  27022. actionsForClip = this._actionsByClip[clipUuid];
  27023. if (actionsForClip !== undefined) {
  27024. return actionsForClip.actionByRoot[rootUuid] || null;
  27025. }
  27026. return null;
  27027. } // deactivates all previously scheduled actions
  27028. stopAllAction() {
  27029. const actions = this._actions,
  27030. nActions = this._nActiveActions;
  27031. for (let i = nActions - 1; i >= 0; --i) {
  27032. actions[i].stop();
  27033. }
  27034. return this;
  27035. } // advance the time and update apply the animation
  27036. update(deltaTime) {
  27037. deltaTime *= this.timeScale;
  27038. const actions = this._actions,
  27039. nActions = this._nActiveActions,
  27040. time = this.time += deltaTime,
  27041. timeDirection = Math.sign(deltaTime),
  27042. accuIndex = this._accuIndex ^= 1; // run active actions
  27043. for (let i = 0; i !== nActions; ++i) {
  27044. const action = actions[i];
  27045. action._update(time, deltaTime, timeDirection, accuIndex);
  27046. } // update scene graph
  27047. const bindings = this._bindings,
  27048. nBindings = this._nActiveBindings;
  27049. for (let i = 0; i !== nBindings; ++i) {
  27050. bindings[i].apply(accuIndex);
  27051. }
  27052. return this;
  27053. } // Allows you to seek to a specific time in an animation.
  27054. setTime(timeInSeconds) {
  27055. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27056. for (let i = 0; i < this._actions.length; i++) {
  27057. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27058. }
  27059. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27060. } // return this mixer's root target object
  27061. getRoot() {
  27062. return this._root;
  27063. } // free all resources specific to a particular clip
  27064. uncacheClip(clip) {
  27065. const actions = this._actions,
  27066. clipUuid = clip.uuid,
  27067. actionsByClip = this._actionsByClip,
  27068. actionsForClip = actionsByClip[clipUuid];
  27069. if (actionsForClip !== undefined) {
  27070. // note: just calling _removeInactiveAction would mess up the
  27071. // iteration state and also require updating the state we can
  27072. // just throw away
  27073. const actionsToRemove = actionsForClip.knownActions;
  27074. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27075. const action = actionsToRemove[i];
  27076. this._deactivateAction(action);
  27077. const cacheIndex = action._cacheIndex,
  27078. lastInactiveAction = actions[actions.length - 1];
  27079. action._cacheIndex = null;
  27080. action._byClipCacheIndex = null;
  27081. lastInactiveAction._cacheIndex = cacheIndex;
  27082. actions[cacheIndex] = lastInactiveAction;
  27083. actions.pop();
  27084. this._removeInactiveBindingsForAction(action);
  27085. }
  27086. delete actionsByClip[clipUuid];
  27087. }
  27088. } // free all resources specific to a particular root target object
  27089. uncacheRoot(root) {
  27090. const rootUuid = root.uuid,
  27091. actionsByClip = this._actionsByClip;
  27092. for (const clipUuid in actionsByClip) {
  27093. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27094. action = actionByRoot[rootUuid];
  27095. if (action !== undefined) {
  27096. this._deactivateAction(action);
  27097. this._removeInactiveAction(action);
  27098. }
  27099. }
  27100. const bindingsByRoot = this._bindingsByRootAndName,
  27101. bindingByName = bindingsByRoot[rootUuid];
  27102. if (bindingByName !== undefined) {
  27103. for (const trackName in bindingByName) {
  27104. const binding = bindingByName[trackName];
  27105. binding.restoreOriginalState();
  27106. this._removeInactiveBinding(binding);
  27107. }
  27108. }
  27109. } // remove a targeted clip from the cache
  27110. uncacheAction(clip, optionalRoot) {
  27111. const action = this.existingAction(clip, optionalRoot);
  27112. if (action !== null) {
  27113. this._deactivateAction(action);
  27114. this._removeInactiveAction(action);
  27115. }
  27116. }
  27117. }
  27118. class Uniform {
  27119. constructor(value) {
  27120. this.value = value;
  27121. }
  27122. clone() {
  27123. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27124. }
  27125. }
  27126. let id = 0;
  27127. class UniformsGroup extends EventDispatcher {
  27128. constructor() {
  27129. super();
  27130. this.isUniformsGroup = true;
  27131. Object.defineProperty(this, 'id', {
  27132. value: id++
  27133. });
  27134. this.name = '';
  27135. this.usage = StaticDrawUsage;
  27136. this.uniforms = [];
  27137. }
  27138. add(uniform) {
  27139. this.uniforms.push(uniform);
  27140. return this;
  27141. }
  27142. remove(uniform) {
  27143. const index = this.uniforms.indexOf(uniform);
  27144. if (index !== -1) this.uniforms.splice(index, 1);
  27145. return this;
  27146. }
  27147. setName(name) {
  27148. this.name = name;
  27149. return this;
  27150. }
  27151. setUsage(value) {
  27152. this.usage = value;
  27153. return this;
  27154. }
  27155. dispose() {
  27156. this.dispatchEvent({
  27157. type: 'dispose'
  27158. });
  27159. return this;
  27160. }
  27161. copy(source) {
  27162. this.name = source.name;
  27163. this.usage = source.usage;
  27164. const uniformsSource = source.uniforms;
  27165. this.uniforms.length = 0;
  27166. for (let i = 0, l = uniformsSource.length; i < l; i++) {
  27167. this.uniforms.push(uniformsSource[i].clone());
  27168. }
  27169. return this;
  27170. }
  27171. clone() {
  27172. return new this.constructor().copy(this);
  27173. }
  27174. }
  27175. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27176. constructor(array, stride, meshPerAttribute = 1) {
  27177. super(array, stride);
  27178. this.isInstancedInterleavedBuffer = true;
  27179. this.meshPerAttribute = meshPerAttribute;
  27180. }
  27181. copy(source) {
  27182. super.copy(source);
  27183. this.meshPerAttribute = source.meshPerAttribute;
  27184. return this;
  27185. }
  27186. clone(data) {
  27187. const ib = super.clone(data);
  27188. ib.meshPerAttribute = this.meshPerAttribute;
  27189. return ib;
  27190. }
  27191. toJSON(data) {
  27192. const json = super.toJSON(data);
  27193. json.isInstancedInterleavedBuffer = true;
  27194. json.meshPerAttribute = this.meshPerAttribute;
  27195. return json;
  27196. }
  27197. }
  27198. class GLBufferAttribute {
  27199. constructor(buffer, type, itemSize, elementSize, count) {
  27200. this.isGLBufferAttribute = true;
  27201. this.buffer = buffer;
  27202. this.type = type;
  27203. this.itemSize = itemSize;
  27204. this.elementSize = elementSize;
  27205. this.count = count;
  27206. this.version = 0;
  27207. }
  27208. set needsUpdate(value) {
  27209. if (value === true) this.version++;
  27210. }
  27211. setBuffer(buffer) {
  27212. this.buffer = buffer;
  27213. return this;
  27214. }
  27215. setType(type, elementSize) {
  27216. this.type = type;
  27217. this.elementSize = elementSize;
  27218. return this;
  27219. }
  27220. setItemSize(itemSize) {
  27221. this.itemSize = itemSize;
  27222. return this;
  27223. }
  27224. setCount(count) {
  27225. this.count = count;
  27226. return this;
  27227. }
  27228. }
  27229. class Raycaster {
  27230. constructor(origin, direction, near = 0, far = Infinity) {
  27231. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27232. this.near = near;
  27233. this.far = far;
  27234. this.camera = null;
  27235. this.layers = new Layers();
  27236. this.params = {
  27237. Mesh: {},
  27238. Line: {
  27239. threshold: 1
  27240. },
  27241. LOD: {},
  27242. Points: {
  27243. threshold: 1
  27244. },
  27245. Sprite: {}
  27246. };
  27247. }
  27248. set(origin, direction) {
  27249. // direction is assumed to be normalized (for accurate distance calculations)
  27250. this.ray.set(origin, direction);
  27251. }
  27252. setFromCamera(coords, camera) {
  27253. if (camera.isPerspectiveCamera) {
  27254. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27255. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27256. this.camera = camera;
  27257. } else if (camera.isOrthographicCamera) {
  27258. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27259. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27260. this.camera = camera;
  27261. } else {
  27262. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  27263. }
  27264. }
  27265. intersectObject(object, recursive = true, intersects = []) {
  27266. intersectObject(object, this, intersects, recursive);
  27267. intersects.sort(ascSort);
  27268. return intersects;
  27269. }
  27270. intersectObjects(objects, recursive = true, intersects = []) {
  27271. for (let i = 0, l = objects.length; i < l; i++) {
  27272. intersectObject(objects[i], this, intersects, recursive);
  27273. }
  27274. intersects.sort(ascSort);
  27275. return intersects;
  27276. }
  27277. }
  27278. function ascSort(a, b) {
  27279. return a.distance - b.distance;
  27280. }
  27281. function intersectObject(object, raycaster, intersects, recursive) {
  27282. if (object.layers.test(raycaster.layers)) {
  27283. object.raycast(raycaster, intersects);
  27284. }
  27285. if (recursive === true) {
  27286. const children = object.children;
  27287. for (let i = 0, l = children.length; i < l; i++) {
  27288. intersectObject(children[i], raycaster, intersects, true);
  27289. }
  27290. }
  27291. }
  27292. /**
  27293. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27294. *
  27295. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27296. * The azimuthal angle (theta) is measured from the positive z-axis.
  27297. */
  27298. class Spherical {
  27299. constructor(radius = 1, phi = 0, theta = 0) {
  27300. this.radius = radius;
  27301. this.phi = phi; // polar angle
  27302. this.theta = theta; // azimuthal angle
  27303. return this;
  27304. }
  27305. set(radius, phi, theta) {
  27306. this.radius = radius;
  27307. this.phi = phi;
  27308. this.theta = theta;
  27309. return this;
  27310. }
  27311. copy(other) {
  27312. this.radius = other.radius;
  27313. this.phi = other.phi;
  27314. this.theta = other.theta;
  27315. return this;
  27316. } // restrict phi to be between EPS and PI-EPS
  27317. makeSafe() {
  27318. const EPS = 0.000001;
  27319. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27320. return this;
  27321. }
  27322. setFromVector3(v) {
  27323. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27324. }
  27325. setFromCartesianCoords(x, y, z) {
  27326. this.radius = Math.sqrt(x * x + y * y + z * z);
  27327. if (this.radius === 0) {
  27328. this.theta = 0;
  27329. this.phi = 0;
  27330. } else {
  27331. this.theta = Math.atan2(x, z);
  27332. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27333. }
  27334. return this;
  27335. }
  27336. clone() {
  27337. return new this.constructor().copy(this);
  27338. }
  27339. }
  27340. /**
  27341. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27342. */
  27343. class Cylindrical {
  27344. constructor(radius = 1, theta = 0, y = 0) {
  27345. this.radius = radius; // distance from the origin to a point in the x-z plane
  27346. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27347. this.y = y; // height above the x-z plane
  27348. return this;
  27349. }
  27350. set(radius, theta, y) {
  27351. this.radius = radius;
  27352. this.theta = theta;
  27353. this.y = y;
  27354. return this;
  27355. }
  27356. copy(other) {
  27357. this.radius = other.radius;
  27358. this.theta = other.theta;
  27359. this.y = other.y;
  27360. return this;
  27361. }
  27362. setFromVector3(v) {
  27363. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27364. }
  27365. setFromCartesianCoords(x, y, z) {
  27366. this.radius = Math.sqrt(x * x + z * z);
  27367. this.theta = Math.atan2(x, z);
  27368. this.y = y;
  27369. return this;
  27370. }
  27371. clone() {
  27372. return new this.constructor().copy(this);
  27373. }
  27374. }
  27375. const _vector$4 = /*@__PURE__*/new Vector2();
  27376. class Box2 {
  27377. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27378. this.isBox2 = true;
  27379. this.min = min;
  27380. this.max = max;
  27381. }
  27382. set(min, max) {
  27383. this.min.copy(min);
  27384. this.max.copy(max);
  27385. return this;
  27386. }
  27387. setFromPoints(points) {
  27388. this.makeEmpty();
  27389. for (let i = 0, il = points.length; i < il; i++) {
  27390. this.expandByPoint(points[i]);
  27391. }
  27392. return this;
  27393. }
  27394. setFromCenterAndSize(center, size) {
  27395. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27396. this.min.copy(center).sub(halfSize);
  27397. this.max.copy(center).add(halfSize);
  27398. return this;
  27399. }
  27400. clone() {
  27401. return new this.constructor().copy(this);
  27402. }
  27403. copy(box) {
  27404. this.min.copy(box.min);
  27405. this.max.copy(box.max);
  27406. return this;
  27407. }
  27408. makeEmpty() {
  27409. this.min.x = this.min.y = +Infinity;
  27410. this.max.x = this.max.y = -Infinity;
  27411. return this;
  27412. }
  27413. isEmpty() {
  27414. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27415. return this.max.x < this.min.x || this.max.y < this.min.y;
  27416. }
  27417. getCenter(target) {
  27418. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27419. }
  27420. getSize(target) {
  27421. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27422. }
  27423. expandByPoint(point) {
  27424. this.min.min(point);
  27425. this.max.max(point);
  27426. return this;
  27427. }
  27428. expandByVector(vector) {
  27429. this.min.sub(vector);
  27430. this.max.add(vector);
  27431. return this;
  27432. }
  27433. expandByScalar(scalar) {
  27434. this.min.addScalar(-scalar);
  27435. this.max.addScalar(scalar);
  27436. return this;
  27437. }
  27438. containsPoint(point) {
  27439. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27440. }
  27441. containsBox(box) {
  27442. 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;
  27443. }
  27444. getParameter(point, target) {
  27445. // This can potentially have a divide by zero if the box
  27446. // has a size dimension of 0.
  27447. 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));
  27448. }
  27449. intersectsBox(box) {
  27450. // using 4 splitting planes to rule out intersections
  27451. 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;
  27452. }
  27453. clampPoint(point, target) {
  27454. return target.copy(point).clamp(this.min, this.max);
  27455. }
  27456. distanceToPoint(point) {
  27457. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27458. return clampedPoint.sub(point).length();
  27459. }
  27460. intersect(box) {
  27461. this.min.max(box.min);
  27462. this.max.min(box.max);
  27463. return this;
  27464. }
  27465. union(box) {
  27466. this.min.min(box.min);
  27467. this.max.max(box.max);
  27468. return this;
  27469. }
  27470. translate(offset) {
  27471. this.min.add(offset);
  27472. this.max.add(offset);
  27473. return this;
  27474. }
  27475. equals(box) {
  27476. return box.min.equals(this.min) && box.max.equals(this.max);
  27477. }
  27478. }
  27479. const _startP = /*@__PURE__*/new Vector3();
  27480. const _startEnd = /*@__PURE__*/new Vector3();
  27481. class Line3 {
  27482. constructor(start = new Vector3(), end = new Vector3()) {
  27483. this.start = start;
  27484. this.end = end;
  27485. }
  27486. set(start, end) {
  27487. this.start.copy(start);
  27488. this.end.copy(end);
  27489. return this;
  27490. }
  27491. copy(line) {
  27492. this.start.copy(line.start);
  27493. this.end.copy(line.end);
  27494. return this;
  27495. }
  27496. getCenter(target) {
  27497. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27498. }
  27499. delta(target) {
  27500. return target.subVectors(this.end, this.start);
  27501. }
  27502. distanceSq() {
  27503. return this.start.distanceToSquared(this.end);
  27504. }
  27505. distance() {
  27506. return this.start.distanceTo(this.end);
  27507. }
  27508. at(t, target) {
  27509. return this.delta(target).multiplyScalar(t).add(this.start);
  27510. }
  27511. closestPointToPointParameter(point, clampToLine) {
  27512. _startP.subVectors(point, this.start);
  27513. _startEnd.subVectors(this.end, this.start);
  27514. const startEnd2 = _startEnd.dot(_startEnd);
  27515. const startEnd_startP = _startEnd.dot(_startP);
  27516. let t = startEnd_startP / startEnd2;
  27517. if (clampToLine) {
  27518. t = clamp(t, 0, 1);
  27519. }
  27520. return t;
  27521. }
  27522. closestPointToPoint(point, clampToLine, target) {
  27523. const t = this.closestPointToPointParameter(point, clampToLine);
  27524. return this.delta(target).multiplyScalar(t).add(this.start);
  27525. }
  27526. applyMatrix4(matrix) {
  27527. this.start.applyMatrix4(matrix);
  27528. this.end.applyMatrix4(matrix);
  27529. return this;
  27530. }
  27531. equals(line) {
  27532. return line.start.equals(this.start) && line.end.equals(this.end);
  27533. }
  27534. clone() {
  27535. return new this.constructor().copy(this);
  27536. }
  27537. }
  27538. const _vector$3 = /*@__PURE__*/new Vector3();
  27539. class SpotLightHelper extends Object3D {
  27540. constructor(light, color) {
  27541. super();
  27542. this.light = light;
  27543. this.light.updateMatrixWorld();
  27544. this.matrix = light.matrixWorld;
  27545. this.matrixAutoUpdate = false;
  27546. this.color = color;
  27547. const geometry = new BufferGeometry();
  27548. 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];
  27549. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27550. const p1 = i / l * Math.PI * 2;
  27551. const p2 = j / l * Math.PI * 2;
  27552. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27553. }
  27554. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27555. const material = new LineBasicMaterial({
  27556. fog: false,
  27557. toneMapped: false
  27558. });
  27559. this.cone = new LineSegments(geometry, material);
  27560. this.add(this.cone);
  27561. this.update();
  27562. }
  27563. dispose() {
  27564. this.cone.geometry.dispose();
  27565. this.cone.material.dispose();
  27566. }
  27567. update() {
  27568. this.light.updateMatrixWorld();
  27569. const coneLength = this.light.distance ? this.light.distance : 1000;
  27570. const coneWidth = coneLength * Math.tan(this.light.angle);
  27571. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27572. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27573. this.cone.lookAt(_vector$3);
  27574. if (this.color !== undefined) {
  27575. this.cone.material.color.set(this.color);
  27576. } else {
  27577. this.cone.material.color.copy(this.light.color);
  27578. }
  27579. }
  27580. }
  27581. const _vector$2 = /*@__PURE__*/new Vector3();
  27582. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27583. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27584. class SkeletonHelper extends LineSegments {
  27585. constructor(object) {
  27586. const bones = getBoneList(object);
  27587. const geometry = new BufferGeometry();
  27588. const vertices = [];
  27589. const colors = [];
  27590. const color1 = new Color(0, 0, 1);
  27591. const color2 = new Color(0, 1, 0);
  27592. for (let i = 0; i < bones.length; i++) {
  27593. const bone = bones[i];
  27594. if (bone.parent && bone.parent.isBone) {
  27595. vertices.push(0, 0, 0);
  27596. vertices.push(0, 0, 0);
  27597. colors.push(color1.r, color1.g, color1.b);
  27598. colors.push(color2.r, color2.g, color2.b);
  27599. }
  27600. }
  27601. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27602. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27603. const material = new LineBasicMaterial({
  27604. vertexColors: true,
  27605. depthTest: false,
  27606. depthWrite: false,
  27607. toneMapped: false,
  27608. transparent: true
  27609. });
  27610. super(geometry, material);
  27611. this.isSkeletonHelper = true;
  27612. this.type = 'SkeletonHelper';
  27613. this.root = object;
  27614. this.bones = bones;
  27615. this.matrix = object.matrixWorld;
  27616. this.matrixAutoUpdate = false;
  27617. }
  27618. updateMatrixWorld(force) {
  27619. const bones = this.bones;
  27620. const geometry = this.geometry;
  27621. const position = geometry.getAttribute('position');
  27622. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27623. for (let i = 0, j = 0; i < bones.length; i++) {
  27624. const bone = bones[i];
  27625. if (bone.parent && bone.parent.isBone) {
  27626. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27627. _vector$2.setFromMatrixPosition(_boneMatrix);
  27628. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27629. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27630. _vector$2.setFromMatrixPosition(_boneMatrix);
  27631. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27632. j += 2;
  27633. }
  27634. }
  27635. geometry.getAttribute('position').needsUpdate = true;
  27636. super.updateMatrixWorld(force);
  27637. }
  27638. }
  27639. function getBoneList(object) {
  27640. const boneList = [];
  27641. if (object.isBone === true) {
  27642. boneList.push(object);
  27643. }
  27644. for (let i = 0; i < object.children.length; i++) {
  27645. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27646. }
  27647. return boneList;
  27648. }
  27649. class PointLightHelper extends Mesh {
  27650. constructor(light, sphereSize, color) {
  27651. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27652. const material = new MeshBasicMaterial({
  27653. wireframe: true,
  27654. fog: false,
  27655. toneMapped: false
  27656. });
  27657. super(geometry, material);
  27658. this.light = light;
  27659. this.light.updateMatrixWorld();
  27660. this.color = color;
  27661. this.type = 'PointLightHelper';
  27662. this.matrix = this.light.matrixWorld;
  27663. this.matrixAutoUpdate = false;
  27664. this.update();
  27665. /*
  27666. // TODO: delete this comment?
  27667. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  27668. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27669. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27670. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27671. const d = light.distance;
  27672. if ( d === 0.0 ) {
  27673. this.lightDistance.visible = false;
  27674. } else {
  27675. this.lightDistance.scale.set( d, d, d );
  27676. }
  27677. this.add( this.lightDistance );
  27678. */
  27679. }
  27680. dispose() {
  27681. this.geometry.dispose();
  27682. this.material.dispose();
  27683. }
  27684. update() {
  27685. if (this.color !== undefined) {
  27686. this.material.color.set(this.color);
  27687. } else {
  27688. this.material.color.copy(this.light.color);
  27689. }
  27690. /*
  27691. const d = this.light.distance;
  27692. if ( d === 0.0 ) {
  27693. this.lightDistance.visible = false;
  27694. } else {
  27695. this.lightDistance.visible = true;
  27696. this.lightDistance.scale.set( d, d, d );
  27697. }
  27698. */
  27699. }
  27700. }
  27701. const _vector$1 = /*@__PURE__*/new Vector3();
  27702. const _color1 = /*@__PURE__*/new Color();
  27703. const _color2 = /*@__PURE__*/new Color();
  27704. class HemisphereLightHelper extends Object3D {
  27705. constructor(light, size, color) {
  27706. super();
  27707. this.light = light;
  27708. this.light.updateMatrixWorld();
  27709. this.matrix = light.matrixWorld;
  27710. this.matrixAutoUpdate = false;
  27711. this.color = color;
  27712. const geometry = new OctahedronGeometry(size);
  27713. geometry.rotateY(Math.PI * 0.5);
  27714. this.material = new MeshBasicMaterial({
  27715. wireframe: true,
  27716. fog: false,
  27717. toneMapped: false
  27718. });
  27719. if (this.color === undefined) this.material.vertexColors = true;
  27720. const position = geometry.getAttribute('position');
  27721. const colors = new Float32Array(position.count * 3);
  27722. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27723. this.add(new Mesh(geometry, this.material));
  27724. this.update();
  27725. }
  27726. dispose() {
  27727. this.children[0].geometry.dispose();
  27728. this.children[0].material.dispose();
  27729. }
  27730. update() {
  27731. const mesh = this.children[0];
  27732. if (this.color !== undefined) {
  27733. this.material.color.set(this.color);
  27734. } else {
  27735. const colors = mesh.geometry.getAttribute('color');
  27736. _color1.copy(this.light.color);
  27737. _color2.copy(this.light.groundColor);
  27738. for (let i = 0, l = colors.count; i < l; i++) {
  27739. const color = i < l / 2 ? _color1 : _color2;
  27740. colors.setXYZ(i, color.r, color.g, color.b);
  27741. }
  27742. colors.needsUpdate = true;
  27743. }
  27744. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27745. }
  27746. }
  27747. class GridHelper extends LineSegments {
  27748. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27749. color1 = new Color(color1);
  27750. color2 = new Color(color2);
  27751. const center = divisions / 2;
  27752. const step = size / divisions;
  27753. const halfSize = size / 2;
  27754. const vertices = [],
  27755. colors = [];
  27756. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27757. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27758. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27759. const color = i === center ? color1 : color2;
  27760. color.toArray(colors, j);
  27761. j += 3;
  27762. color.toArray(colors, j);
  27763. j += 3;
  27764. color.toArray(colors, j);
  27765. j += 3;
  27766. color.toArray(colors, j);
  27767. j += 3;
  27768. }
  27769. const geometry = new BufferGeometry();
  27770. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27771. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27772. const material = new LineBasicMaterial({
  27773. vertexColors: true,
  27774. toneMapped: false
  27775. });
  27776. super(geometry, material);
  27777. this.type = 'GridHelper';
  27778. }
  27779. }
  27780. class PolarGridHelper extends LineSegments {
  27781. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27782. color1 = new Color(color1);
  27783. color2 = new Color(color2);
  27784. const vertices = [];
  27785. const colors = []; // create the radials
  27786. for (let i = 0; i <= radials; i++) {
  27787. const v = i / radials * (Math.PI * 2);
  27788. const x = Math.sin(v) * radius;
  27789. const z = Math.cos(v) * radius;
  27790. vertices.push(0, 0, 0);
  27791. vertices.push(x, 0, z);
  27792. const color = i & 1 ? color1 : color2;
  27793. colors.push(color.r, color.g, color.b);
  27794. colors.push(color.r, color.g, color.b);
  27795. } // create the circles
  27796. for (let i = 0; i <= circles; i++) {
  27797. const color = i & 1 ? color1 : color2;
  27798. const r = radius - radius / circles * i;
  27799. for (let j = 0; j < divisions; j++) {
  27800. // first vertex
  27801. let v = j / divisions * (Math.PI * 2);
  27802. let x = Math.sin(v) * r;
  27803. let z = Math.cos(v) * r;
  27804. vertices.push(x, 0, z);
  27805. colors.push(color.r, color.g, color.b); // second vertex
  27806. v = (j + 1) / divisions * (Math.PI * 2);
  27807. x = Math.sin(v) * r;
  27808. z = Math.cos(v) * r;
  27809. vertices.push(x, 0, z);
  27810. colors.push(color.r, color.g, color.b);
  27811. }
  27812. }
  27813. const geometry = new BufferGeometry();
  27814. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27815. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27816. const material = new LineBasicMaterial({
  27817. vertexColors: true,
  27818. toneMapped: false
  27819. });
  27820. super(geometry, material);
  27821. this.type = 'PolarGridHelper';
  27822. }
  27823. }
  27824. const _v1 = /*@__PURE__*/new Vector3();
  27825. const _v2 = /*@__PURE__*/new Vector3();
  27826. const _v3 = /*@__PURE__*/new Vector3();
  27827. class DirectionalLightHelper extends Object3D {
  27828. constructor(light, size, color) {
  27829. super();
  27830. this.light = light;
  27831. this.light.updateMatrixWorld();
  27832. this.matrix = light.matrixWorld;
  27833. this.matrixAutoUpdate = false;
  27834. this.color = color;
  27835. if (size === undefined) size = 1;
  27836. let geometry = new BufferGeometry();
  27837. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27838. const material = new LineBasicMaterial({
  27839. fog: false,
  27840. toneMapped: false
  27841. });
  27842. this.lightPlane = new Line(geometry, material);
  27843. this.add(this.lightPlane);
  27844. geometry = new BufferGeometry();
  27845. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27846. this.targetLine = new Line(geometry, material);
  27847. this.add(this.targetLine);
  27848. this.update();
  27849. }
  27850. dispose() {
  27851. this.lightPlane.geometry.dispose();
  27852. this.lightPlane.material.dispose();
  27853. this.targetLine.geometry.dispose();
  27854. this.targetLine.material.dispose();
  27855. }
  27856. update() {
  27857. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27858. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27859. _v3.subVectors(_v2, _v1);
  27860. this.lightPlane.lookAt(_v2);
  27861. if (this.color !== undefined) {
  27862. this.lightPlane.material.color.set(this.color);
  27863. this.targetLine.material.color.set(this.color);
  27864. } else {
  27865. this.lightPlane.material.color.copy(this.light.color);
  27866. this.targetLine.material.color.copy(this.light.color);
  27867. }
  27868. this.targetLine.lookAt(_v2);
  27869. this.targetLine.scale.z = _v3.length();
  27870. }
  27871. }
  27872. const _vector = /*@__PURE__*/new Vector3();
  27873. const _camera = /*@__PURE__*/new Camera();
  27874. /**
  27875. * - shows frustum, line of sight and up of the camera
  27876. * - suitable for fast updates
  27877. * - based on frustum visualization in lightgl.js shadowmap example
  27878. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  27879. */
  27880. class CameraHelper extends LineSegments {
  27881. constructor(camera) {
  27882. const geometry = new BufferGeometry();
  27883. const material = new LineBasicMaterial({
  27884. color: 0xffffff,
  27885. vertexColors: true,
  27886. toneMapped: false
  27887. });
  27888. const vertices = [];
  27889. const colors = [];
  27890. const pointMap = {}; // near
  27891. addLine('n1', 'n2');
  27892. addLine('n2', 'n4');
  27893. addLine('n4', 'n3');
  27894. addLine('n3', 'n1'); // far
  27895. addLine('f1', 'f2');
  27896. addLine('f2', 'f4');
  27897. addLine('f4', 'f3');
  27898. addLine('f3', 'f1'); // sides
  27899. addLine('n1', 'f1');
  27900. addLine('n2', 'f2');
  27901. addLine('n3', 'f3');
  27902. addLine('n4', 'f4'); // cone
  27903. addLine('p', 'n1');
  27904. addLine('p', 'n2');
  27905. addLine('p', 'n3');
  27906. addLine('p', 'n4'); // up
  27907. addLine('u1', 'u2');
  27908. addLine('u2', 'u3');
  27909. addLine('u3', 'u1'); // target
  27910. addLine('c', 't');
  27911. addLine('p', 'c'); // cross
  27912. addLine('cn1', 'cn2');
  27913. addLine('cn3', 'cn4');
  27914. addLine('cf1', 'cf2');
  27915. addLine('cf3', 'cf4');
  27916. function addLine(a, b) {
  27917. addPoint(a);
  27918. addPoint(b);
  27919. }
  27920. function addPoint(id) {
  27921. vertices.push(0, 0, 0);
  27922. colors.push(0, 0, 0);
  27923. if (pointMap[id] === undefined) {
  27924. pointMap[id] = [];
  27925. }
  27926. pointMap[id].push(vertices.length / 3 - 1);
  27927. }
  27928. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27929. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27930. super(geometry, material);
  27931. this.type = 'CameraHelper';
  27932. this.camera = camera;
  27933. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27934. this.matrix = camera.matrixWorld;
  27935. this.matrixAutoUpdate = false;
  27936. this.pointMap = pointMap;
  27937. this.update(); // colors
  27938. const colorFrustum = new Color(0xffaa00);
  27939. const colorCone = new Color(0xff0000);
  27940. const colorUp = new Color(0x00aaff);
  27941. const colorTarget = new Color(0xffffff);
  27942. const colorCross = new Color(0x333333);
  27943. this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross);
  27944. }
  27945. setColors(frustum, cone, up, target, cross) {
  27946. const geometry = this.geometry;
  27947. const colorAttribute = geometry.getAttribute('color'); // near
  27948. colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b);
  27949. colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); // n1, n2
  27950. colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b);
  27951. colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); // n2, n4
  27952. colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b);
  27953. colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); // n4, n3
  27954. colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b);
  27955. colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); // n3, n1
  27956. // far
  27957. colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b);
  27958. colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); // f1, f2
  27959. colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b);
  27960. colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); // f2, f4
  27961. colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b);
  27962. colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); // f4, f3
  27963. colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b);
  27964. colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); // f3, f1
  27965. // sides
  27966. colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b);
  27967. colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); // n1, f1
  27968. colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b);
  27969. colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); // n2, f2
  27970. colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b);
  27971. colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); // n3, f3
  27972. colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b);
  27973. colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); // n4, f4
  27974. // cone
  27975. colorAttribute.setXYZ(24, cone.r, cone.g, cone.b);
  27976. colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); // p, n1
  27977. colorAttribute.setXYZ(26, cone.r, cone.g, cone.b);
  27978. colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); // p, n2
  27979. colorAttribute.setXYZ(28, cone.r, cone.g, cone.b);
  27980. colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); // p, n3
  27981. colorAttribute.setXYZ(30, cone.r, cone.g, cone.b);
  27982. colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); // p, n4
  27983. // up
  27984. colorAttribute.setXYZ(32, up.r, up.g, up.b);
  27985. colorAttribute.setXYZ(33, up.r, up.g, up.b); // u1, u2
  27986. colorAttribute.setXYZ(34, up.r, up.g, up.b);
  27987. colorAttribute.setXYZ(35, up.r, up.g, up.b); // u2, u3
  27988. colorAttribute.setXYZ(36, up.r, up.g, up.b);
  27989. colorAttribute.setXYZ(37, up.r, up.g, up.b); // u3, u1
  27990. // target
  27991. colorAttribute.setXYZ(38, target.r, target.g, target.b);
  27992. colorAttribute.setXYZ(39, target.r, target.g, target.b); // c, t
  27993. colorAttribute.setXYZ(40, cross.r, cross.g, cross.b);
  27994. colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); // p, c
  27995. // cross
  27996. colorAttribute.setXYZ(42, cross.r, cross.g, cross.b);
  27997. colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); // cn1, cn2
  27998. colorAttribute.setXYZ(44, cross.r, cross.g, cross.b);
  27999. colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); // cn3, cn4
  28000. colorAttribute.setXYZ(46, cross.r, cross.g, cross.b);
  28001. colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); // cf1, cf2
  28002. colorAttribute.setXYZ(48, cross.r, cross.g, cross.b);
  28003. colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); // cf3, cf4
  28004. colorAttribute.needsUpdate = true;
  28005. }
  28006. update() {
  28007. const geometry = this.geometry;
  28008. const pointMap = this.pointMap;
  28009. const w = 1,
  28010. h = 1; // we need just camera projection matrix inverse
  28011. // world matrix must be identity
  28012. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28013. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28014. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28015. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28016. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28017. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28018. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28019. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28020. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28021. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28022. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28023. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28024. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28025. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28026. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28027. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28028. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28029. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28030. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28031. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28032. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28033. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28034. geometry.getAttribute('position').needsUpdate = true;
  28035. }
  28036. dispose() {
  28037. this.geometry.dispose();
  28038. this.material.dispose();
  28039. }
  28040. }
  28041. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28042. _vector.set(x, y, z).unproject(camera);
  28043. const points = pointMap[point];
  28044. if (points !== undefined) {
  28045. const position = geometry.getAttribute('position');
  28046. for (let i = 0, l = points.length; i < l; i++) {
  28047. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  28048. }
  28049. }
  28050. }
  28051. const _box = /*@__PURE__*/new Box3();
  28052. class BoxHelper extends LineSegments {
  28053. constructor(object, color = 0xffff00) {
  28054. 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]);
  28055. const positions = new Float32Array(8 * 3);
  28056. const geometry = new BufferGeometry();
  28057. geometry.setIndex(new BufferAttribute(indices, 1));
  28058. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  28059. super(geometry, new LineBasicMaterial({
  28060. color: color,
  28061. toneMapped: false
  28062. }));
  28063. this.object = object;
  28064. this.type = 'BoxHelper';
  28065. this.matrixAutoUpdate = false;
  28066. this.update();
  28067. }
  28068. update(object) {
  28069. if (object !== undefined) {
  28070. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28071. }
  28072. if (this.object !== undefined) {
  28073. _box.setFromObject(this.object);
  28074. }
  28075. if (_box.isEmpty()) return;
  28076. const min = _box.min;
  28077. const max = _box.max;
  28078. /*
  28079. 5____4
  28080. 1/___0/|
  28081. | 6__|_7
  28082. 2/___3/
  28083. 0: max.x, max.y, max.z
  28084. 1: min.x, max.y, max.z
  28085. 2: min.x, min.y, max.z
  28086. 3: max.x, min.y, max.z
  28087. 4: max.x, max.y, min.z
  28088. 5: min.x, max.y, min.z
  28089. 6: min.x, min.y, min.z
  28090. 7: max.x, min.y, min.z
  28091. */
  28092. const position = this.geometry.attributes.position;
  28093. const array = position.array;
  28094. array[0] = max.x;
  28095. array[1] = max.y;
  28096. array[2] = max.z;
  28097. array[3] = min.x;
  28098. array[4] = max.y;
  28099. array[5] = max.z;
  28100. array[6] = min.x;
  28101. array[7] = min.y;
  28102. array[8] = max.z;
  28103. array[9] = max.x;
  28104. array[10] = min.y;
  28105. array[11] = max.z;
  28106. array[12] = max.x;
  28107. array[13] = max.y;
  28108. array[14] = min.z;
  28109. array[15] = min.x;
  28110. array[16] = max.y;
  28111. array[17] = min.z;
  28112. array[18] = min.x;
  28113. array[19] = min.y;
  28114. array[20] = min.z;
  28115. array[21] = max.x;
  28116. array[22] = min.y;
  28117. array[23] = min.z;
  28118. position.needsUpdate = true;
  28119. this.geometry.computeBoundingSphere();
  28120. }
  28121. setFromObject(object) {
  28122. this.object = object;
  28123. this.update();
  28124. return this;
  28125. }
  28126. copy(source, recursive) {
  28127. super.copy(source, recursive);
  28128. this.object = source.object;
  28129. return this;
  28130. }
  28131. }
  28132. class Box3Helper extends LineSegments {
  28133. constructor(box, color = 0xffff00) {
  28134. 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]);
  28135. 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];
  28136. const geometry = new BufferGeometry();
  28137. geometry.setIndex(new BufferAttribute(indices, 1));
  28138. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28139. super(geometry, new LineBasicMaterial({
  28140. color: color,
  28141. toneMapped: false
  28142. }));
  28143. this.box = box;
  28144. this.type = 'Box3Helper';
  28145. this.geometry.computeBoundingSphere();
  28146. }
  28147. updateMatrixWorld(force) {
  28148. const box = this.box;
  28149. if (box.isEmpty()) return;
  28150. box.getCenter(this.position);
  28151. box.getSize(this.scale);
  28152. this.scale.multiplyScalar(0.5);
  28153. super.updateMatrixWorld(force);
  28154. }
  28155. }
  28156. class PlaneHelper extends Line {
  28157. constructor(plane, size = 1, hex = 0xffff00) {
  28158. const color = hex;
  28159. 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];
  28160. const geometry = new BufferGeometry();
  28161. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28162. geometry.computeBoundingSphere();
  28163. super(geometry, new LineBasicMaterial({
  28164. color: color,
  28165. toneMapped: false
  28166. }));
  28167. this.type = 'PlaneHelper';
  28168. this.plane = plane;
  28169. this.size = size;
  28170. const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28171. const geometry2 = new BufferGeometry();
  28172. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28173. geometry2.computeBoundingSphere();
  28174. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28175. color: color,
  28176. opacity: 0.2,
  28177. transparent: true,
  28178. depthWrite: false,
  28179. toneMapped: false
  28180. })));
  28181. }
  28182. updateMatrixWorld(force) {
  28183. this.position.set(0, 0, 0);
  28184. this.scale.set(0.5 * this.size, 0.5 * this.size, 1);
  28185. this.lookAt(this.plane.normal);
  28186. this.translateZ(-this.plane.constant);
  28187. super.updateMatrixWorld(force);
  28188. }
  28189. }
  28190. const _axis = /*@__PURE__*/new Vector3();
  28191. let _lineGeometry, _coneGeometry;
  28192. class ArrowHelper extends Object3D {
  28193. // dir is assumed to be normalized
  28194. 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) {
  28195. super();
  28196. this.type = 'ArrowHelper';
  28197. if (_lineGeometry === undefined) {
  28198. _lineGeometry = new BufferGeometry();
  28199. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28200. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  28201. _coneGeometry.translate(0, -0.5, 0);
  28202. }
  28203. this.position.copy(origin);
  28204. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28205. color: color,
  28206. toneMapped: false
  28207. }));
  28208. this.line.matrixAutoUpdate = false;
  28209. this.add(this.line);
  28210. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28211. color: color,
  28212. toneMapped: false
  28213. }));
  28214. this.cone.matrixAutoUpdate = false;
  28215. this.add(this.cone);
  28216. this.setDirection(dir);
  28217. this.setLength(length, headLength, headWidth);
  28218. }
  28219. setDirection(dir) {
  28220. // dir is assumed to be normalized
  28221. if (dir.y > 0.99999) {
  28222. this.quaternion.set(0, 0, 0, 1);
  28223. } else if (dir.y < -0.99999) {
  28224. this.quaternion.set(1, 0, 0, 0);
  28225. } else {
  28226. _axis.set(dir.z, 0, -dir.x).normalize();
  28227. const radians = Math.acos(dir.y);
  28228. this.quaternion.setFromAxisAngle(_axis, radians);
  28229. }
  28230. }
  28231. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  28232. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28233. this.line.updateMatrix();
  28234. this.cone.scale.set(headWidth, headLength, headWidth);
  28235. this.cone.position.y = length;
  28236. this.cone.updateMatrix();
  28237. }
  28238. setColor(color) {
  28239. this.line.material.color.set(color);
  28240. this.cone.material.color.set(color);
  28241. }
  28242. copy(source) {
  28243. super.copy(source, false);
  28244. this.line.copy(source.line);
  28245. this.cone.copy(source.cone);
  28246. return this;
  28247. }
  28248. }
  28249. class AxesHelper extends LineSegments {
  28250. constructor(size = 1) {
  28251. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28252. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28253. const geometry = new BufferGeometry();
  28254. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28255. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28256. const material = new LineBasicMaterial({
  28257. vertexColors: true,
  28258. toneMapped: false
  28259. });
  28260. super(geometry, material);
  28261. this.type = 'AxesHelper';
  28262. }
  28263. setColors(xAxisColor, yAxisColor, zAxisColor) {
  28264. const color = new Color();
  28265. const array = this.geometry.attributes.color.array;
  28266. color.set(xAxisColor);
  28267. color.toArray(array, 0);
  28268. color.toArray(array, 3);
  28269. color.set(yAxisColor);
  28270. color.toArray(array, 6);
  28271. color.toArray(array, 9);
  28272. color.set(zAxisColor);
  28273. color.toArray(array, 12);
  28274. color.toArray(array, 15);
  28275. this.geometry.attributes.color.needsUpdate = true;
  28276. return this;
  28277. }
  28278. dispose() {
  28279. this.geometry.dispose();
  28280. this.material.dispose();
  28281. }
  28282. }
  28283. class ShapePath {
  28284. constructor() {
  28285. this.type = 'ShapePath';
  28286. this.color = new Color();
  28287. this.subPaths = [];
  28288. this.currentPath = null;
  28289. }
  28290. moveTo(x, y) {
  28291. this.currentPath = new Path();
  28292. this.subPaths.push(this.currentPath);
  28293. this.currentPath.moveTo(x, y);
  28294. return this;
  28295. }
  28296. lineTo(x, y) {
  28297. this.currentPath.lineTo(x, y);
  28298. return this;
  28299. }
  28300. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  28301. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  28302. return this;
  28303. }
  28304. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  28305. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  28306. return this;
  28307. }
  28308. splineThru(pts) {
  28309. this.currentPath.splineThru(pts);
  28310. return this;
  28311. }
  28312. toShapes(isCCW, noHoles) {
  28313. function toShapesNoHoles(inSubpaths) {
  28314. const shapes = [];
  28315. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  28316. const tmpPath = inSubpaths[i];
  28317. const tmpShape = new Shape();
  28318. tmpShape.curves = tmpPath.curves;
  28319. shapes.push(tmpShape);
  28320. }
  28321. return shapes;
  28322. }
  28323. function isPointInsidePolygon(inPt, inPolygon) {
  28324. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  28325. // toggling of inside/outside at every single! intersection point of an edge
  28326. // with the horizontal line through inPt, left of inPt
  28327. // not counting lowerY endpoints of edges and whole edges on that line
  28328. let inside = false;
  28329. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  28330. let edgeLowPt = inPolygon[p];
  28331. let edgeHighPt = inPolygon[q];
  28332. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28333. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28334. if (Math.abs(edgeDy) > Number.EPSILON) {
  28335. // not parallel
  28336. if (edgeDy < 0) {
  28337. edgeLowPt = inPolygon[q];
  28338. edgeDx = -edgeDx;
  28339. edgeHighPt = inPolygon[p];
  28340. edgeDy = -edgeDy;
  28341. }
  28342. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  28343. if (inPt.y === edgeLowPt.y) {
  28344. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  28345. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28346. } else {
  28347. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  28348. if (perpEdge === 0) return true; // inPt is on contour ?
  28349. if (perpEdge < 0) continue;
  28350. inside = !inside; // true intersection left of inPt
  28351. }
  28352. } else {
  28353. // parallel or collinear
  28354. if (inPt.y !== edgeLowPt.y) continue; // parallel
  28355. // edge lies on the same horizontal line as inPt
  28356. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  28357. // continue;
  28358. }
  28359. }
  28360. return inside;
  28361. }
  28362. const isClockWise = ShapeUtils.isClockWise;
  28363. const subPaths = this.subPaths;
  28364. if (subPaths.length === 0) return [];
  28365. if (noHoles === true) return toShapesNoHoles(subPaths);
  28366. let solid, tmpPath, tmpShape;
  28367. const shapes = [];
  28368. if (subPaths.length === 1) {
  28369. tmpPath = subPaths[0];
  28370. tmpShape = new Shape();
  28371. tmpShape.curves = tmpPath.curves;
  28372. shapes.push(tmpShape);
  28373. return shapes;
  28374. }
  28375. let holesFirst = !isClockWise(subPaths[0].getPoints());
  28376. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  28377. const betterShapeHoles = [];
  28378. const newShapes = [];
  28379. let newShapeHoles = [];
  28380. let mainIdx = 0;
  28381. let tmpPoints;
  28382. newShapes[mainIdx] = undefined;
  28383. newShapeHoles[mainIdx] = [];
  28384. for (let i = 0, l = subPaths.length; i < l; i++) {
  28385. tmpPath = subPaths[i];
  28386. tmpPoints = tmpPath.getPoints();
  28387. solid = isClockWise(tmpPoints);
  28388. solid = isCCW ? !solid : solid;
  28389. if (solid) {
  28390. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  28391. newShapes[mainIdx] = {
  28392. s: new Shape(),
  28393. p: tmpPoints
  28394. };
  28395. newShapes[mainIdx].s.curves = tmpPath.curves;
  28396. if (holesFirst) mainIdx++;
  28397. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  28398. } else {
  28399. newShapeHoles[mainIdx].push({
  28400. h: tmpPath,
  28401. p: tmpPoints[0]
  28402. }); //console.log('ccw', i);
  28403. }
  28404. } // only Holes? -> probably all Shapes with wrong orientation
  28405. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  28406. if (newShapes.length > 1) {
  28407. let ambiguous = false;
  28408. let toChange = 0;
  28409. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28410. betterShapeHoles[sIdx] = [];
  28411. }
  28412. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28413. const sho = newShapeHoles[sIdx];
  28414. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  28415. const ho = sho[hIdx];
  28416. let hole_unassigned = true;
  28417. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  28418. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  28419. if (sIdx !== s2Idx) toChange++;
  28420. if (hole_unassigned) {
  28421. hole_unassigned = false;
  28422. betterShapeHoles[s2Idx].push(ho);
  28423. } else {
  28424. ambiguous = true;
  28425. }
  28426. }
  28427. }
  28428. if (hole_unassigned) {
  28429. betterShapeHoles[sIdx].push(ho);
  28430. }
  28431. }
  28432. }
  28433. if (toChange > 0 && ambiguous === false) {
  28434. newShapeHoles = betterShapeHoles;
  28435. }
  28436. }
  28437. let tmpHoles;
  28438. for (let i = 0, il = newShapes.length; i < il; i++) {
  28439. tmpShape = newShapes[i].s;
  28440. shapes.push(tmpShape);
  28441. tmpHoles = newShapeHoles[i];
  28442. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  28443. tmpShape.holes.push(tmpHoles[j].h);
  28444. }
  28445. } //console.log("shape", shapes);
  28446. return shapes;
  28447. }
  28448. }
  28449. const _tables = /*@__PURE__*/_generateTables();
  28450. function _generateTables() {
  28451. // float32 to float16 helpers
  28452. const buffer = new ArrayBuffer(4);
  28453. const floatView = new Float32Array(buffer);
  28454. const uint32View = new Uint32Array(buffer);
  28455. const baseTable = new Uint32Array(512);
  28456. const shiftTable = new Uint32Array(512);
  28457. for (let i = 0; i < 256; ++i) {
  28458. const e = i - 127; // very small number (0, -0)
  28459. if (e < -27) {
  28460. baseTable[i] = 0x0000;
  28461. baseTable[i | 0x100] = 0x8000;
  28462. shiftTable[i] = 24;
  28463. shiftTable[i | 0x100] = 24; // small number (denorm)
  28464. } else if (e < -14) {
  28465. baseTable[i] = 0x0400 >> -e - 14;
  28466. baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
  28467. shiftTable[i] = -e - 1;
  28468. shiftTable[i | 0x100] = -e - 1; // normal number
  28469. } else if (e <= 15) {
  28470. baseTable[i] = e + 15 << 10;
  28471. baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
  28472. shiftTable[i] = 13;
  28473. shiftTable[i | 0x100] = 13; // large number (Infinity, -Infinity)
  28474. } else if (e < 128) {
  28475. baseTable[i] = 0x7c00;
  28476. baseTable[i | 0x100] = 0xfc00;
  28477. shiftTable[i] = 24;
  28478. shiftTable[i | 0x100] = 24; // stay (NaN, Infinity, -Infinity)
  28479. } else {
  28480. baseTable[i] = 0x7c00;
  28481. baseTable[i | 0x100] = 0xfc00;
  28482. shiftTable[i] = 13;
  28483. shiftTable[i | 0x100] = 13;
  28484. }
  28485. } // float16 to float32 helpers
  28486. const mantissaTable = new Uint32Array(2048);
  28487. const exponentTable = new Uint32Array(64);
  28488. const offsetTable = new Uint32Array(64);
  28489. for (let i = 1; i < 1024; ++i) {
  28490. let m = i << 13; // zero pad mantissa bits
  28491. let e = 0; // zero exponent
  28492. // normalized
  28493. while ((m & 0x00800000) === 0) {
  28494. m <<= 1;
  28495. e -= 0x00800000; // decrement exponent
  28496. }
  28497. m &= ~0x00800000; // clear leading 1 bit
  28498. e += 0x38800000; // adjust bias
  28499. mantissaTable[i] = m | e;
  28500. }
  28501. for (let i = 1024; i < 2048; ++i) {
  28502. mantissaTable[i] = 0x38000000 + (i - 1024 << 13);
  28503. }
  28504. for (let i = 1; i < 31; ++i) {
  28505. exponentTable[i] = i << 23;
  28506. }
  28507. exponentTable[31] = 0x47800000;
  28508. exponentTable[32] = 0x80000000;
  28509. for (let i = 33; i < 63; ++i) {
  28510. exponentTable[i] = 0x80000000 + (i - 32 << 23);
  28511. }
  28512. exponentTable[63] = 0xc7800000;
  28513. for (let i = 1; i < 64; ++i) {
  28514. if (i !== 32) {
  28515. offsetTable[i] = 1024;
  28516. }
  28517. }
  28518. return {
  28519. floatView: floatView,
  28520. uint32View: uint32View,
  28521. baseTable: baseTable,
  28522. shiftTable: shiftTable,
  28523. mantissaTable: mantissaTable,
  28524. exponentTable: exponentTable,
  28525. offsetTable: offsetTable
  28526. };
  28527. } // float32 to float16
  28528. function toHalfFloat(val) {
  28529. if (Math.abs(val) > 65504) console.warn('THREE.DataUtils.toHalfFloat(): Value out of range.');
  28530. val = clamp(val, -65504, 65504);
  28531. _tables.floatView[0] = val;
  28532. const f = _tables.uint32View[0];
  28533. const e = f >> 23 & 0x1ff;
  28534. return _tables.baseTable[e] + ((f & 0x007fffff) >> _tables.shiftTable[e]);
  28535. } // float16 to float32
  28536. function fromHalfFloat(val) {
  28537. const m = val >> 10;
  28538. _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 0x3ff)] + _tables.exponentTable[m];
  28539. return _tables.floatView[0];
  28540. }
  28541. var DataUtils = /*#__PURE__*/Object.freeze({
  28542. __proto__: null,
  28543. toHalfFloat: toHalfFloat,
  28544. fromHalfFloat: fromHalfFloat
  28545. });
  28546. function ImmediateRenderObject() {
  28547. console.error('THREE.ImmediateRenderObject has been removed.');
  28548. } // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  28549. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  28550. constructor(width, height, options) {
  28551. console.error('THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.');
  28552. super(width, height, options);
  28553. this.samples = 4;
  28554. }
  28555. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28556. class DataTexture2DArray extends DataArrayTexture {
  28557. constructor(data, width, height, depth) {
  28558. console.warn('THREE.DataTexture2DArray has been renamed to DataArrayTexture.');
  28559. super(data, width, height, depth);
  28560. }
  28561. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28562. class DataTexture3D extends Data3DTexture {
  28563. constructor(data, width, height, depth) {
  28564. console.warn('THREE.DataTexture3D has been renamed to Data3DTexture.');
  28565. super(data, width, height, depth);
  28566. }
  28567. } // r144
  28568. class BoxBufferGeometry extends BoxGeometry {
  28569. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  28570. console.warn('THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.');
  28571. super(width, height, depth, widthSegments, heightSegments, depthSegments);
  28572. }
  28573. } // r144
  28574. class CapsuleBufferGeometry extends CapsuleGeometry {
  28575. constructor(radius, length, capSegments, radialSegments) {
  28576. console.warn('THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.');
  28577. super(radius, length, capSegments, radialSegments);
  28578. }
  28579. } // r144
  28580. class CircleBufferGeometry extends CircleGeometry {
  28581. constructor(radius, segments, thetaStart, thetaLength) {
  28582. console.warn('THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.');
  28583. super(radius, segments, thetaStart, thetaLength);
  28584. }
  28585. } // r144
  28586. class ConeBufferGeometry extends ConeGeometry {
  28587. constructor(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  28588. console.warn('THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.');
  28589. super(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  28590. }
  28591. } // r144
  28592. class CylinderBufferGeometry extends CylinderGeometry {
  28593. constructor(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  28594. console.warn('THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.');
  28595. super(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  28596. }
  28597. } // r144
  28598. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  28599. constructor(radius, detail) {
  28600. console.warn('THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.');
  28601. super(radius, detail);
  28602. }
  28603. } // r144
  28604. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  28605. constructor(shapes, options) {
  28606. console.warn('THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.');
  28607. super(shapes, options);
  28608. }
  28609. } // r144
  28610. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  28611. constructor(radius, detail) {
  28612. console.warn('THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.');
  28613. super(radius, detail);
  28614. }
  28615. } // r144
  28616. class LatheBufferGeometry extends LatheGeometry {
  28617. constructor(points, segments, phiStart, phiLength) {
  28618. console.warn('THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.');
  28619. super(points, segments, phiStart, phiLength);
  28620. }
  28621. } // r144
  28622. class OctahedronBufferGeometry extends OctahedronGeometry {
  28623. constructor(radius, detail) {
  28624. console.warn('THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.');
  28625. super(radius, detail);
  28626. }
  28627. } // r144
  28628. class PlaneBufferGeometry extends PlaneGeometry {
  28629. constructor(width, height, widthSegments, heightSegments) {
  28630. console.warn('THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.');
  28631. super(width, height, widthSegments, heightSegments);
  28632. }
  28633. } // r144
  28634. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  28635. constructor(vertices, indices, radius, detail) {
  28636. console.warn('THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.');
  28637. super(vertices, indices, radius, detail);
  28638. }
  28639. } // r144
  28640. class RingBufferGeometry extends RingGeometry {
  28641. constructor(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  28642. console.warn('THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.');
  28643. super(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength);
  28644. }
  28645. } // r144
  28646. class ShapeBufferGeometry extends ShapeGeometry {
  28647. constructor(shapes, curveSegments) {
  28648. console.warn('THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.');
  28649. super(shapes, curveSegments);
  28650. }
  28651. } // r144
  28652. class SphereBufferGeometry extends SphereGeometry {
  28653. constructor(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  28654. console.warn('THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.');
  28655. super(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength);
  28656. }
  28657. } // r144
  28658. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  28659. constructor(radius, detail) {
  28660. console.warn('THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.');
  28661. super(radius, detail);
  28662. }
  28663. } // r144
  28664. class TorusBufferGeometry extends TorusGeometry {
  28665. constructor(radius, tube, radialSegments, tubularSegments, arc) {
  28666. console.warn('THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.');
  28667. super(radius, tube, radialSegments, tubularSegments, arc);
  28668. }
  28669. } // r144
  28670. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  28671. constructor(radius, tube, tubularSegments, radialSegments, p, q) {
  28672. console.warn('THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.');
  28673. super(radius, tube, tubularSegments, radialSegments, p, q);
  28674. }
  28675. } // r144
  28676. class TubeBufferGeometry extends TubeGeometry {
  28677. constructor(path, tubularSegments, radius, radialSegments, closed) {
  28678. console.warn('THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.');
  28679. super(path, tubularSegments, radius, radialSegments, closed);
  28680. }
  28681. }
  28682. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28683. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28684. detail: {
  28685. revision: REVISION
  28686. }
  28687. }));
  28688. }
  28689. if (typeof window !== 'undefined') {
  28690. if (window.__THREE__) {
  28691. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28692. } else {
  28693. window.__THREE__ = REVISION;
  28694. }
  28695. }
  28696. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28697. exports.AddEquation = AddEquation;
  28698. exports.AddOperation = AddOperation;
  28699. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28700. exports.AdditiveBlending = AdditiveBlending;
  28701. exports.AlphaFormat = AlphaFormat;
  28702. exports.AlwaysDepth = AlwaysDepth;
  28703. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28704. exports.AmbientLight = AmbientLight;
  28705. exports.AmbientLightProbe = AmbientLightProbe;
  28706. exports.AnimationClip = AnimationClip;
  28707. exports.AnimationLoader = AnimationLoader;
  28708. exports.AnimationMixer = AnimationMixer;
  28709. exports.AnimationObjectGroup = AnimationObjectGroup;
  28710. exports.AnimationUtils = AnimationUtils;
  28711. exports.ArcCurve = ArcCurve;
  28712. exports.ArrayCamera = ArrayCamera;
  28713. exports.ArrowHelper = ArrowHelper;
  28714. exports.Audio = Audio;
  28715. exports.AudioAnalyser = AudioAnalyser;
  28716. exports.AudioContext = AudioContext;
  28717. exports.AudioListener = AudioListener;
  28718. exports.AudioLoader = AudioLoader;
  28719. exports.AxesHelper = AxesHelper;
  28720. exports.BackSide = BackSide;
  28721. exports.BasicDepthPacking = BasicDepthPacking;
  28722. exports.BasicShadowMap = BasicShadowMap;
  28723. exports.Bone = Bone;
  28724. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28725. exports.Box2 = Box2;
  28726. exports.Box3 = Box3;
  28727. exports.Box3Helper = Box3Helper;
  28728. exports.BoxBufferGeometry = BoxBufferGeometry;
  28729. exports.BoxGeometry = BoxGeometry;
  28730. exports.BoxHelper = BoxHelper;
  28731. exports.BufferAttribute = BufferAttribute;
  28732. exports.BufferGeometry = BufferGeometry;
  28733. exports.BufferGeometryLoader = BufferGeometryLoader;
  28734. exports.ByteType = ByteType;
  28735. exports.Cache = Cache;
  28736. exports.Camera = Camera;
  28737. exports.CameraHelper = CameraHelper;
  28738. exports.CanvasTexture = CanvasTexture;
  28739. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  28740. exports.CapsuleGeometry = CapsuleGeometry;
  28741. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28742. exports.CineonToneMapping = CineonToneMapping;
  28743. exports.CircleBufferGeometry = CircleBufferGeometry;
  28744. exports.CircleGeometry = CircleGeometry;
  28745. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28746. exports.Clock = Clock;
  28747. exports.Color = Color;
  28748. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28749. exports.ColorManagement = ColorManagement;
  28750. exports.CompressedTexture = CompressedTexture;
  28751. exports.CompressedTextureLoader = CompressedTextureLoader;
  28752. exports.ConeBufferGeometry = ConeBufferGeometry;
  28753. exports.ConeGeometry = ConeGeometry;
  28754. exports.CubeCamera = CubeCamera;
  28755. exports.CubeReflectionMapping = CubeReflectionMapping;
  28756. exports.CubeRefractionMapping = CubeRefractionMapping;
  28757. exports.CubeTexture = CubeTexture;
  28758. exports.CubeTextureLoader = CubeTextureLoader;
  28759. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28760. exports.CubicBezierCurve = CubicBezierCurve;
  28761. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28762. exports.CubicInterpolant = CubicInterpolant;
  28763. exports.CullFaceBack = CullFaceBack;
  28764. exports.CullFaceFront = CullFaceFront;
  28765. exports.CullFaceFrontBack = CullFaceFrontBack;
  28766. exports.CullFaceNone = CullFaceNone;
  28767. exports.Curve = Curve;
  28768. exports.CurvePath = CurvePath;
  28769. exports.CustomBlending = CustomBlending;
  28770. exports.CustomToneMapping = CustomToneMapping;
  28771. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  28772. exports.CylinderGeometry = CylinderGeometry;
  28773. exports.Cylindrical = Cylindrical;
  28774. exports.Data3DTexture = Data3DTexture;
  28775. exports.DataArrayTexture = DataArrayTexture;
  28776. exports.DataTexture = DataTexture;
  28777. exports.DataTexture2DArray = DataTexture2DArray;
  28778. exports.DataTexture3D = DataTexture3D;
  28779. exports.DataTextureLoader = DataTextureLoader;
  28780. exports.DataUtils = DataUtils;
  28781. exports.DecrementStencilOp = DecrementStencilOp;
  28782. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28783. exports.DefaultLoadingManager = DefaultLoadingManager;
  28784. exports.DepthFormat = DepthFormat;
  28785. exports.DepthStencilFormat = DepthStencilFormat;
  28786. exports.DepthTexture = DepthTexture;
  28787. exports.DirectionalLight = DirectionalLight;
  28788. exports.DirectionalLightHelper = DirectionalLightHelper;
  28789. exports.DiscreteInterpolant = DiscreteInterpolant;
  28790. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  28791. exports.DodecahedronGeometry = DodecahedronGeometry;
  28792. exports.DoubleSide = DoubleSide;
  28793. exports.DstAlphaFactor = DstAlphaFactor;
  28794. exports.DstColorFactor = DstColorFactor;
  28795. exports.DynamicCopyUsage = DynamicCopyUsage;
  28796. exports.DynamicDrawUsage = DynamicDrawUsage;
  28797. exports.DynamicReadUsage = DynamicReadUsage;
  28798. exports.EdgesGeometry = EdgesGeometry;
  28799. exports.EllipseCurve = EllipseCurve;
  28800. exports.EqualDepth = EqualDepth;
  28801. exports.EqualStencilFunc = EqualStencilFunc;
  28802. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28803. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28804. exports.Euler = Euler;
  28805. exports.EventDispatcher = EventDispatcher;
  28806. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  28807. exports.ExtrudeGeometry = ExtrudeGeometry;
  28808. exports.FileLoader = FileLoader;
  28809. exports.Float16BufferAttribute = Float16BufferAttribute;
  28810. exports.Float32BufferAttribute = Float32BufferAttribute;
  28811. exports.Float64BufferAttribute = Float64BufferAttribute;
  28812. exports.FloatType = FloatType;
  28813. exports.Fog = Fog;
  28814. exports.FogExp2 = FogExp2;
  28815. exports.FramebufferTexture = FramebufferTexture;
  28816. exports.FrontSide = FrontSide;
  28817. exports.Frustum = Frustum;
  28818. exports.GLBufferAttribute = GLBufferAttribute;
  28819. exports.GLSL1 = GLSL1;
  28820. exports.GLSL3 = GLSL3;
  28821. exports.GreaterDepth = GreaterDepth;
  28822. exports.GreaterEqualDepth = GreaterEqualDepth;
  28823. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28824. exports.GreaterStencilFunc = GreaterStencilFunc;
  28825. exports.GridHelper = GridHelper;
  28826. exports.Group = Group;
  28827. exports.HalfFloatType = HalfFloatType;
  28828. exports.HemisphereLight = HemisphereLight;
  28829. exports.HemisphereLightHelper = HemisphereLightHelper;
  28830. exports.HemisphereLightProbe = HemisphereLightProbe;
  28831. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  28832. exports.IcosahedronGeometry = IcosahedronGeometry;
  28833. exports.ImageBitmapLoader = ImageBitmapLoader;
  28834. exports.ImageLoader = ImageLoader;
  28835. exports.ImageUtils = ImageUtils;
  28836. exports.ImmediateRenderObject = ImmediateRenderObject;
  28837. exports.IncrementStencilOp = IncrementStencilOp;
  28838. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  28839. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  28840. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  28841. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  28842. exports.InstancedMesh = InstancedMesh;
  28843. exports.Int16BufferAttribute = Int16BufferAttribute;
  28844. exports.Int32BufferAttribute = Int32BufferAttribute;
  28845. exports.Int8BufferAttribute = Int8BufferAttribute;
  28846. exports.IntType = IntType;
  28847. exports.InterleavedBuffer = InterleavedBuffer;
  28848. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  28849. exports.Interpolant = Interpolant;
  28850. exports.InterpolateDiscrete = InterpolateDiscrete;
  28851. exports.InterpolateLinear = InterpolateLinear;
  28852. exports.InterpolateSmooth = InterpolateSmooth;
  28853. exports.InvertStencilOp = InvertStencilOp;
  28854. exports.KeepStencilOp = KeepStencilOp;
  28855. exports.KeyframeTrack = KeyframeTrack;
  28856. exports.LOD = LOD;
  28857. exports.LatheBufferGeometry = LatheBufferGeometry;
  28858. exports.LatheGeometry = LatheGeometry;
  28859. exports.Layers = Layers;
  28860. exports.LessDepth = LessDepth;
  28861. exports.LessEqualDepth = LessEqualDepth;
  28862. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  28863. exports.LessStencilFunc = LessStencilFunc;
  28864. exports.Light = Light;
  28865. exports.LightProbe = LightProbe;
  28866. exports.Line = Line;
  28867. exports.Line3 = Line3;
  28868. exports.LineBasicMaterial = LineBasicMaterial;
  28869. exports.LineCurve = LineCurve;
  28870. exports.LineCurve3 = LineCurve3;
  28871. exports.LineDashedMaterial = LineDashedMaterial;
  28872. exports.LineLoop = LineLoop;
  28873. exports.LineSegments = LineSegments;
  28874. exports.LinearEncoding = LinearEncoding;
  28875. exports.LinearFilter = LinearFilter;
  28876. exports.LinearInterpolant = LinearInterpolant;
  28877. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  28878. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  28879. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  28880. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  28881. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  28882. exports.LinearToneMapping = LinearToneMapping;
  28883. exports.Loader = Loader;
  28884. exports.LoaderUtils = LoaderUtils;
  28885. exports.LoadingManager = LoadingManager;
  28886. exports.LoopOnce = LoopOnce;
  28887. exports.LoopPingPong = LoopPingPong;
  28888. exports.LoopRepeat = LoopRepeat;
  28889. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  28890. exports.LuminanceFormat = LuminanceFormat;
  28891. exports.MOUSE = MOUSE;
  28892. exports.Material = Material;
  28893. exports.MaterialLoader = MaterialLoader;
  28894. exports.MathUtils = MathUtils;
  28895. exports.Matrix3 = Matrix3;
  28896. exports.Matrix4 = Matrix4;
  28897. exports.MaxEquation = MaxEquation;
  28898. exports.Mesh = Mesh;
  28899. exports.MeshBasicMaterial = MeshBasicMaterial;
  28900. exports.MeshDepthMaterial = MeshDepthMaterial;
  28901. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  28902. exports.MeshLambertMaterial = MeshLambertMaterial;
  28903. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  28904. exports.MeshNormalMaterial = MeshNormalMaterial;
  28905. exports.MeshPhongMaterial = MeshPhongMaterial;
  28906. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  28907. exports.MeshStandardMaterial = MeshStandardMaterial;
  28908. exports.MeshToonMaterial = MeshToonMaterial;
  28909. exports.MinEquation = MinEquation;
  28910. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  28911. exports.MixOperation = MixOperation;
  28912. exports.MultiplyBlending = MultiplyBlending;
  28913. exports.MultiplyOperation = MultiplyOperation;
  28914. exports.NearestFilter = NearestFilter;
  28915. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  28916. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  28917. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  28918. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  28919. exports.NeverDepth = NeverDepth;
  28920. exports.NeverStencilFunc = NeverStencilFunc;
  28921. exports.NoBlending = NoBlending;
  28922. exports.NoColorSpace = NoColorSpace;
  28923. exports.NoToneMapping = NoToneMapping;
  28924. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  28925. exports.NormalBlending = NormalBlending;
  28926. exports.NotEqualDepth = NotEqualDepth;
  28927. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  28928. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  28929. exports.Object3D = Object3D;
  28930. exports.ObjectLoader = ObjectLoader;
  28931. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  28932. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  28933. exports.OctahedronGeometry = OctahedronGeometry;
  28934. exports.OneFactor = OneFactor;
  28935. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  28936. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  28937. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  28938. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  28939. exports.OrthographicCamera = OrthographicCamera;
  28940. exports.PCFShadowMap = PCFShadowMap;
  28941. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  28942. exports.PMREMGenerator = PMREMGenerator;
  28943. exports.Path = Path;
  28944. exports.PerspectiveCamera = PerspectiveCamera;
  28945. exports.Plane = Plane;
  28946. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  28947. exports.PlaneGeometry = PlaneGeometry;
  28948. exports.PlaneHelper = PlaneHelper;
  28949. exports.PointLight = PointLight;
  28950. exports.PointLightHelper = PointLightHelper;
  28951. exports.Points = Points;
  28952. exports.PointsMaterial = PointsMaterial;
  28953. exports.PolarGridHelper = PolarGridHelper;
  28954. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  28955. exports.PolyhedronGeometry = PolyhedronGeometry;
  28956. exports.PositionalAudio = PositionalAudio;
  28957. exports.PropertyBinding = PropertyBinding;
  28958. exports.PropertyMixer = PropertyMixer;
  28959. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  28960. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  28961. exports.Quaternion = Quaternion;
  28962. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  28963. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  28964. exports.REVISION = REVISION;
  28965. exports.RGBADepthPacking = RGBADepthPacking;
  28966. exports.RGBAFormat = RGBAFormat;
  28967. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  28968. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  28969. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  28970. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  28971. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  28972. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  28973. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  28974. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  28975. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  28976. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  28977. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  28978. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  28979. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  28980. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  28981. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  28982. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  28983. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  28984. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  28985. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  28986. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  28987. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  28988. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  28989. exports.RGBFormat = RGBFormat;
  28990. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  28991. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  28992. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  28993. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  28994. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  28995. exports.RGFormat = RGFormat;
  28996. exports.RGIntegerFormat = RGIntegerFormat;
  28997. exports.RawShaderMaterial = RawShaderMaterial;
  28998. exports.Ray = Ray;
  28999. exports.Raycaster = Raycaster;
  29000. exports.RectAreaLight = RectAreaLight;
  29001. exports.RedFormat = RedFormat;
  29002. exports.RedIntegerFormat = RedIntegerFormat;
  29003. exports.ReinhardToneMapping = ReinhardToneMapping;
  29004. exports.RepeatWrapping = RepeatWrapping;
  29005. exports.ReplaceStencilOp = ReplaceStencilOp;
  29006. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29007. exports.RingBufferGeometry = RingBufferGeometry;
  29008. exports.RingGeometry = RingGeometry;
  29009. exports.SRGBColorSpace = SRGBColorSpace;
  29010. exports.Scene = Scene;
  29011. exports.ShaderChunk = ShaderChunk;
  29012. exports.ShaderLib = ShaderLib;
  29013. exports.ShaderMaterial = ShaderMaterial;
  29014. exports.ShadowMaterial = ShadowMaterial;
  29015. exports.Shape = Shape;
  29016. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  29017. exports.ShapeGeometry = ShapeGeometry;
  29018. exports.ShapePath = ShapePath;
  29019. exports.ShapeUtils = ShapeUtils;
  29020. exports.ShortType = ShortType;
  29021. exports.Skeleton = Skeleton;
  29022. exports.SkeletonHelper = SkeletonHelper;
  29023. exports.SkinnedMesh = SkinnedMesh;
  29024. exports.Source = Source;
  29025. exports.Sphere = Sphere;
  29026. exports.SphereBufferGeometry = SphereBufferGeometry;
  29027. exports.SphereGeometry = SphereGeometry;
  29028. exports.Spherical = Spherical;
  29029. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29030. exports.SplineCurve = SplineCurve;
  29031. exports.SpotLight = SpotLight;
  29032. exports.SpotLightHelper = SpotLightHelper;
  29033. exports.Sprite = Sprite;
  29034. exports.SpriteMaterial = SpriteMaterial;
  29035. exports.SrcAlphaFactor = SrcAlphaFactor;
  29036. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29037. exports.SrcColorFactor = SrcColorFactor;
  29038. exports.StaticCopyUsage = StaticCopyUsage;
  29039. exports.StaticDrawUsage = StaticDrawUsage;
  29040. exports.StaticReadUsage = StaticReadUsage;
  29041. exports.StereoCamera = StereoCamera;
  29042. exports.StreamCopyUsage = StreamCopyUsage;
  29043. exports.StreamDrawUsage = StreamDrawUsage;
  29044. exports.StreamReadUsage = StreamReadUsage;
  29045. exports.StringKeyframeTrack = StringKeyframeTrack;
  29046. exports.SubtractEquation = SubtractEquation;
  29047. exports.SubtractiveBlending = SubtractiveBlending;
  29048. exports.TOUCH = TOUCH;
  29049. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29050. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  29051. exports.TetrahedronGeometry = TetrahedronGeometry;
  29052. exports.Texture = Texture;
  29053. exports.TextureLoader = TextureLoader;
  29054. exports.TorusBufferGeometry = TorusBufferGeometry;
  29055. exports.TorusGeometry = TorusGeometry;
  29056. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  29057. exports.TorusKnotGeometry = TorusKnotGeometry;
  29058. exports.Triangle = Triangle;
  29059. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29060. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29061. exports.TrianglesDrawMode = TrianglesDrawMode;
  29062. exports.TubeBufferGeometry = TubeBufferGeometry;
  29063. exports.TubeGeometry = TubeGeometry;
  29064. exports.UVMapping = UVMapping;
  29065. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29066. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29067. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29068. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29069. exports.Uniform = Uniform;
  29070. exports.UniformsGroup = UniformsGroup;
  29071. exports.UniformsLib = UniformsLib;
  29072. exports.UniformsUtils = UniformsUtils;
  29073. exports.UnsignedByteType = UnsignedByteType;
  29074. exports.UnsignedInt248Type = UnsignedInt248Type;
  29075. exports.UnsignedIntType = UnsignedIntType;
  29076. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29077. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29078. exports.UnsignedShortType = UnsignedShortType;
  29079. exports.VSMShadowMap = VSMShadowMap;
  29080. exports.Vector2 = Vector2;
  29081. exports.Vector3 = Vector3;
  29082. exports.Vector4 = Vector4;
  29083. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29084. exports.VideoTexture = VideoTexture;
  29085. exports.WebGL1Renderer = WebGL1Renderer;
  29086. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  29087. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  29088. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29089. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29090. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29091. exports.WebGLRenderTarget = WebGLRenderTarget;
  29092. exports.WebGLRenderer = WebGLRenderer;
  29093. exports.WebGLUtils = WebGLUtils;
  29094. exports.WireframeGeometry = WireframeGeometry;
  29095. exports.WrapAroundEnding = WrapAroundEnding;
  29096. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29097. exports.ZeroFactor = ZeroFactor;
  29098. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29099. exports.ZeroStencilOp = ZeroStencilOp;
  29100. exports._SRGBAFormat = _SRGBAFormat;
  29101. exports.sRGBEncoding = sRGBEncoding;