three.cjs 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849
  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 = '143';
  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 FlatShading = 1;
  35. const SmoothShading = 2;
  36. const NoBlending = 0;
  37. const NormalBlending = 1;
  38. const AdditiveBlending = 2;
  39. const SubtractiveBlending = 3;
  40. const MultiplyBlending = 4;
  41. const CustomBlending = 5;
  42. const AddEquation = 100;
  43. const SubtractEquation = 101;
  44. const ReverseSubtractEquation = 102;
  45. const MinEquation = 103;
  46. const MaxEquation = 104;
  47. const ZeroFactor = 200;
  48. const OneFactor = 201;
  49. const SrcColorFactor = 202;
  50. const OneMinusSrcColorFactor = 203;
  51. const SrcAlphaFactor = 204;
  52. const OneMinusSrcAlphaFactor = 205;
  53. const DstAlphaFactor = 206;
  54. const OneMinusDstAlphaFactor = 207;
  55. const DstColorFactor = 208;
  56. const OneMinusDstColorFactor = 209;
  57. const SrcAlphaSaturateFactor = 210;
  58. const NeverDepth = 0;
  59. const AlwaysDepth = 1;
  60. const LessDepth = 2;
  61. const LessEqualDepth = 3;
  62. const EqualDepth = 4;
  63. const GreaterEqualDepth = 5;
  64. const GreaterDepth = 6;
  65. const NotEqualDepth = 7;
  66. const MultiplyOperation = 0;
  67. const MixOperation = 1;
  68. const AddOperation = 2;
  69. const NoToneMapping = 0;
  70. const LinearToneMapping = 1;
  71. const ReinhardToneMapping = 2;
  72. const CineonToneMapping = 3;
  73. const ACESFilmicToneMapping = 4;
  74. const CustomToneMapping = 5;
  75. const UVMapping = 300;
  76. const CubeReflectionMapping = 301;
  77. const CubeRefractionMapping = 302;
  78. const EquirectangularReflectionMapping = 303;
  79. const EquirectangularRefractionMapping = 304;
  80. const CubeUVReflectionMapping = 306;
  81. const RepeatWrapping = 1000;
  82. const ClampToEdgeWrapping = 1001;
  83. const MirroredRepeatWrapping = 1002;
  84. const NearestFilter = 1003;
  85. const NearestMipmapNearestFilter = 1004;
  86. const NearestMipMapNearestFilter = 1004;
  87. const NearestMipmapLinearFilter = 1005;
  88. const NearestMipMapLinearFilter = 1005;
  89. const LinearFilter = 1006;
  90. const LinearMipmapNearestFilter = 1007;
  91. const LinearMipMapNearestFilter = 1007;
  92. const LinearMipmapLinearFilter = 1008;
  93. const LinearMipMapLinearFilter = 1008;
  94. const UnsignedByteType = 1009;
  95. const ByteType = 1010;
  96. const ShortType = 1011;
  97. const UnsignedShortType = 1012;
  98. const IntType = 1013;
  99. const UnsignedIntType = 1014;
  100. const FloatType = 1015;
  101. const HalfFloatType = 1016;
  102. const UnsignedShort4444Type = 1017;
  103. const UnsignedShort5551Type = 1018;
  104. const UnsignedInt248Type = 1020;
  105. const AlphaFormat = 1021;
  106. const RGBFormat = 1022;
  107. const RGBAFormat = 1023;
  108. const LuminanceFormat = 1024;
  109. const LuminanceAlphaFormat = 1025;
  110. const DepthFormat = 1026;
  111. const DepthStencilFormat = 1027;
  112. const RedFormat = 1028;
  113. const RedIntegerFormat = 1029;
  114. const RGFormat = 1030;
  115. const RGIntegerFormat = 1031;
  116. const RGBAIntegerFormat = 1033;
  117. const RGB_S3TC_DXT1_Format = 33776;
  118. const RGBA_S3TC_DXT1_Format = 33777;
  119. const RGBA_S3TC_DXT3_Format = 33778;
  120. const RGBA_S3TC_DXT5_Format = 33779;
  121. const RGB_PVRTC_4BPPV1_Format = 35840;
  122. const RGB_PVRTC_2BPPV1_Format = 35841;
  123. const RGBA_PVRTC_4BPPV1_Format = 35842;
  124. const RGBA_PVRTC_2BPPV1_Format = 35843;
  125. const RGB_ETC1_Format = 36196;
  126. const RGB_ETC2_Format = 37492;
  127. const RGBA_ETC2_EAC_Format = 37496;
  128. const RGBA_ASTC_4x4_Format = 37808;
  129. const RGBA_ASTC_5x4_Format = 37809;
  130. const RGBA_ASTC_5x5_Format = 37810;
  131. const RGBA_ASTC_6x5_Format = 37811;
  132. const RGBA_ASTC_6x6_Format = 37812;
  133. const RGBA_ASTC_8x5_Format = 37813;
  134. const RGBA_ASTC_8x6_Format = 37814;
  135. const RGBA_ASTC_8x8_Format = 37815;
  136. const RGBA_ASTC_10x5_Format = 37816;
  137. const RGBA_ASTC_10x6_Format = 37817;
  138. const RGBA_ASTC_10x8_Format = 37818;
  139. const RGBA_ASTC_10x10_Format = 37819;
  140. const RGBA_ASTC_12x10_Format = 37820;
  141. const RGBA_ASTC_12x12_Format = 37821;
  142. const RGBA_BPTC_Format = 36492;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const LinearEncoding = 3000;
  158. const sRGBEncoding = 3001;
  159. const BasicDepthPacking = 3200;
  160. const RGBADepthPacking = 3201;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1; // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  163. const NoColorSpace = '';
  164. const SRGBColorSpace = 'srgb';
  165. const LinearSRGBColorSpace = 'srgb-linear';
  166. const ZeroStencilOp = 0;
  167. const KeepStencilOp = 7680;
  168. const ReplaceStencilOp = 7681;
  169. const IncrementStencilOp = 7682;
  170. const DecrementStencilOp = 7683;
  171. const IncrementWrapStencilOp = 34055;
  172. const DecrementWrapStencilOp = 34056;
  173. const InvertStencilOp = 5386;
  174. const NeverStencilFunc = 512;
  175. const LessStencilFunc = 513;
  176. const EqualStencilFunc = 514;
  177. const LessEqualStencilFunc = 515;
  178. const GreaterStencilFunc = 516;
  179. const NotEqualStencilFunc = 517;
  180. const GreaterEqualStencilFunc = 518;
  181. const AlwaysStencilFunc = 519;
  182. const StaticDrawUsage = 35044;
  183. const DynamicDrawUsage = 35048;
  184. const StreamDrawUsage = 35040;
  185. const StaticReadUsage = 35045;
  186. const DynamicReadUsage = 35049;
  187. const StreamReadUsage = 35041;
  188. const StaticCopyUsage = 35046;
  189. const DynamicCopyUsage = 35050;
  190. const StreamCopyUsage = 35042;
  191. const GLSL1 = '100';
  192. const GLSL3 = '300 es';
  193. const _SRGBAFormat = 1035; // fallback for WebGL 1
  194. /**
  195. * https://github.com/mrdoob/eventdispatcher.js/
  196. */
  197. class EventDispatcher {
  198. addEventListener(type, listener) {
  199. if (this._listeners === undefined) this._listeners = {};
  200. const listeners = this._listeners;
  201. if (listeners[type] === undefined) {
  202. listeners[type] = [];
  203. }
  204. if (listeners[type].indexOf(listener) === -1) {
  205. listeners[type].push(listener);
  206. }
  207. }
  208. hasEventListener(type, listener) {
  209. if (this._listeners === undefined) return false;
  210. const listeners = this._listeners;
  211. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  212. }
  213. removeEventListener(type, listener) {
  214. if (this._listeners === undefined) return;
  215. const listeners = this._listeners;
  216. const listenerArray = listeners[type];
  217. if (listenerArray !== undefined) {
  218. const index = listenerArray.indexOf(listener);
  219. if (index !== -1) {
  220. listenerArray.splice(index, 1);
  221. }
  222. }
  223. }
  224. dispatchEvent(event) {
  225. if (this._listeners === undefined) return;
  226. const listeners = this._listeners;
  227. const listenerArray = listeners[event.type];
  228. if (listenerArray !== undefined) {
  229. event.target = this; // Make a copy, in case listeners are removed while iterating.
  230. const array = listenerArray.slice(0);
  231. for (let i = 0, l = array.length; i < l; i++) {
  232. array[i].call(this, event);
  233. }
  234. event.target = null;
  235. }
  236. }
  237. }
  238. const _lut = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff'];
  239. let _seed = 1234567;
  240. const DEG2RAD = Math.PI / 180;
  241. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  242. function generateUUID() {
  243. const d0 = Math.random() * 0xffffffff | 0;
  244. const d1 = Math.random() * 0xffffffff | 0;
  245. const d2 = Math.random() * 0xffffffff | 0;
  246. const d3 = Math.random() * 0xffffffff | 0;
  247. 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.
  248. return uuid.toLowerCase();
  249. }
  250. function clamp(value, min, max) {
  251. return Math.max(min, Math.min(max, value));
  252. } // compute euclidean modulo of m % n
  253. // https://en.wikipedia.org/wiki/Modulo_operation
  254. function euclideanModulo(n, m) {
  255. return (n % m + m) % m;
  256. } // Linear mapping from range <a1, a2> to range <b1, b2>
  257. function mapLinear(x, a1, a2, b1, b2) {
  258. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  259. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  260. function inverseLerp(x, y, value) {
  261. if (x !== y) {
  262. return (value - x) / (y - x);
  263. } else {
  264. return 0;
  265. }
  266. } // https://en.wikipedia.org/wiki/Linear_interpolation
  267. function lerp(x, y, t) {
  268. return (1 - t) * x + t * y;
  269. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  270. function damp(x, y, lambda, dt) {
  271. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  272. } // https://www.desmos.com/calculator/vcsjnyz7x4
  273. function pingpong(x, length = 1) {
  274. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  275. } // http://en.wikipedia.org/wiki/Smoothstep
  276. function smoothstep(x, min, max) {
  277. if (x <= min) return 0;
  278. if (x >= max) return 1;
  279. x = (x - min) / (max - min);
  280. return x * x * (3 - 2 * x);
  281. }
  282. function smootherstep(x, min, max) {
  283. if (x <= min) return 0;
  284. if (x >= max) return 1;
  285. x = (x - min) / (max - min);
  286. return x * x * x * (x * (x * 6 - 15) + 10);
  287. } // Random integer from <low, high> interval
  288. function randInt(low, high) {
  289. return low + Math.floor(Math.random() * (high - low + 1));
  290. } // Random float from <low, high> interval
  291. function randFloat(low, high) {
  292. return low + Math.random() * (high - low);
  293. } // Random float from <-range/2, range/2> interval
  294. function randFloatSpread(range) {
  295. return range * (0.5 - Math.random());
  296. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  297. function seededRandom(s) {
  298. if (s !== undefined) _seed = s; // Mulberry32 generator
  299. let t = _seed += 0x6D2B79F5;
  300. t = Math.imul(t ^ t >>> 15, t | 1);
  301. t ^= t + Math.imul(t ^ t >>> 7, t | 61);
  302. return ((t ^ t >>> 14) >>> 0) / 4294967296;
  303. }
  304. function degToRad(degrees) {
  305. return degrees * DEG2RAD;
  306. }
  307. function radToDeg(radians) {
  308. return radians * RAD2DEG;
  309. }
  310. function isPowerOfTwo(value) {
  311. return (value & value - 1) === 0 && value !== 0;
  312. }
  313. function ceilPowerOfTwo(value) {
  314. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  315. }
  316. function floorPowerOfTwo(value) {
  317. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  318. }
  319. function setQuaternionFromProperEuler(q, a, b, c, order) {
  320. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  321. // rotations are applied to the axes in the order specified by 'order'
  322. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  323. // angles are in radians
  324. const cos = Math.cos;
  325. const sin = Math.sin;
  326. const c2 = cos(b / 2);
  327. const s2 = sin(b / 2);
  328. const c13 = cos((a + c) / 2);
  329. const s13 = sin((a + c) / 2);
  330. const c1_3 = cos((a - c) / 2);
  331. const s1_3 = sin((a - c) / 2);
  332. const c3_1 = cos((c - a) / 2);
  333. const s3_1 = sin((c - a) / 2);
  334. switch (order) {
  335. case 'XYX':
  336. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  337. break;
  338. case 'YZY':
  339. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  340. break;
  341. case 'ZXZ':
  342. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  343. break;
  344. case 'XZX':
  345. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  346. break;
  347. case 'YXY':
  348. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  349. break;
  350. case 'ZYZ':
  351. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  352. break;
  353. default:
  354. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  355. }
  356. }
  357. function denormalize$1(value, array) {
  358. switch (array.constructor) {
  359. case Float32Array:
  360. return value;
  361. case Uint16Array:
  362. return value / 65535.0;
  363. case Uint8Array:
  364. return value / 255.0;
  365. case Int16Array:
  366. return Math.max(value / 32767.0, -1.0);
  367. case Int8Array:
  368. return Math.max(value / 127.0, -1.0);
  369. default:
  370. throw new Error('Invalid component type.');
  371. }
  372. }
  373. function normalize(value, array) {
  374. switch (array.constructor) {
  375. case Float32Array:
  376. return value;
  377. case Uint16Array:
  378. return Math.round(value * 65535.0);
  379. case Uint8Array:
  380. return Math.round(value * 255.0);
  381. case Int16Array:
  382. return Math.round(value * 32767.0);
  383. case Int8Array:
  384. return Math.round(value * 127.0);
  385. default:
  386. throw new Error('Invalid component type.');
  387. }
  388. }
  389. var MathUtils = /*#__PURE__*/Object.freeze({
  390. __proto__: null,
  391. DEG2RAD: DEG2RAD,
  392. RAD2DEG: RAD2DEG,
  393. generateUUID: generateUUID,
  394. clamp: clamp,
  395. euclideanModulo: euclideanModulo,
  396. mapLinear: mapLinear,
  397. inverseLerp: inverseLerp,
  398. lerp: lerp,
  399. damp: damp,
  400. pingpong: pingpong,
  401. smoothstep: smoothstep,
  402. smootherstep: smootherstep,
  403. randInt: randInt,
  404. randFloat: randFloat,
  405. randFloatSpread: randFloatSpread,
  406. seededRandom: seededRandom,
  407. degToRad: degToRad,
  408. radToDeg: radToDeg,
  409. isPowerOfTwo: isPowerOfTwo,
  410. ceilPowerOfTwo: ceilPowerOfTwo,
  411. floorPowerOfTwo: floorPowerOfTwo,
  412. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  413. normalize: normalize,
  414. denormalize: denormalize$1
  415. });
  416. class Vector2 {
  417. constructor(x = 0, y = 0) {
  418. Vector2.prototype.isVector2 = true;
  419. this.x = x;
  420. this.y = y;
  421. }
  422. get width() {
  423. return this.x;
  424. }
  425. set width(value) {
  426. this.x = value;
  427. }
  428. get height() {
  429. return this.y;
  430. }
  431. set height(value) {
  432. this.y = value;
  433. }
  434. set(x, y) {
  435. this.x = x;
  436. this.y = y;
  437. return this;
  438. }
  439. setScalar(scalar) {
  440. this.x = scalar;
  441. this.y = scalar;
  442. return this;
  443. }
  444. setX(x) {
  445. this.x = x;
  446. return this;
  447. }
  448. setY(y) {
  449. this.y = y;
  450. return this;
  451. }
  452. setComponent(index, value) {
  453. switch (index) {
  454. case 0:
  455. this.x = value;
  456. break;
  457. case 1:
  458. this.y = value;
  459. break;
  460. default:
  461. throw new Error('index is out of range: ' + index);
  462. }
  463. return this;
  464. }
  465. getComponent(index) {
  466. switch (index) {
  467. case 0:
  468. return this.x;
  469. case 1:
  470. return this.y;
  471. default:
  472. throw new Error('index is out of range: ' + index);
  473. }
  474. }
  475. clone() {
  476. return new this.constructor(this.x, this.y);
  477. }
  478. copy(v) {
  479. this.x = v.x;
  480. this.y = v.y;
  481. return this;
  482. }
  483. add(v) {
  484. this.x += v.x;
  485. this.y += v.y;
  486. return this;
  487. }
  488. addScalar(s) {
  489. this.x += s;
  490. this.y += s;
  491. return this;
  492. }
  493. addVectors(a, b) {
  494. this.x = a.x + b.x;
  495. this.y = a.y + b.y;
  496. return this;
  497. }
  498. addScaledVector(v, s) {
  499. this.x += v.x * s;
  500. this.y += v.y * s;
  501. return this;
  502. }
  503. sub(v) {
  504. this.x -= v.x;
  505. this.y -= v.y;
  506. return this;
  507. }
  508. subScalar(s) {
  509. this.x -= s;
  510. this.y -= s;
  511. return this;
  512. }
  513. subVectors(a, b) {
  514. this.x = a.x - b.x;
  515. this.y = a.y - b.y;
  516. return this;
  517. }
  518. multiply(v) {
  519. this.x *= v.x;
  520. this.y *= v.y;
  521. return this;
  522. }
  523. multiplyScalar(scalar) {
  524. this.x *= scalar;
  525. this.y *= scalar;
  526. return this;
  527. }
  528. divide(v) {
  529. this.x /= v.x;
  530. this.y /= v.y;
  531. return this;
  532. }
  533. divideScalar(scalar) {
  534. return this.multiplyScalar(1 / scalar);
  535. }
  536. applyMatrix3(m) {
  537. const x = this.x,
  538. y = this.y;
  539. const e = m.elements;
  540. this.x = e[0] * x + e[3] * y + e[6];
  541. this.y = e[1] * x + e[4] * y + e[7];
  542. return this;
  543. }
  544. min(v) {
  545. this.x = Math.min(this.x, v.x);
  546. this.y = Math.min(this.y, v.y);
  547. return this;
  548. }
  549. max(v) {
  550. this.x = Math.max(this.x, v.x);
  551. this.y = Math.max(this.y, v.y);
  552. return this;
  553. }
  554. clamp(min, max) {
  555. // assumes min < max, componentwise
  556. this.x = Math.max(min.x, Math.min(max.x, this.x));
  557. this.y = Math.max(min.y, Math.min(max.y, this.y));
  558. return this;
  559. }
  560. clampScalar(minVal, maxVal) {
  561. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  562. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  563. return this;
  564. }
  565. clampLength(min, max) {
  566. const length = this.length();
  567. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  568. }
  569. floor() {
  570. this.x = Math.floor(this.x);
  571. this.y = Math.floor(this.y);
  572. return this;
  573. }
  574. ceil() {
  575. this.x = Math.ceil(this.x);
  576. this.y = Math.ceil(this.y);
  577. return this;
  578. }
  579. round() {
  580. this.x = Math.round(this.x);
  581. this.y = Math.round(this.y);
  582. return this;
  583. }
  584. roundToZero() {
  585. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  586. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  587. return this;
  588. }
  589. negate() {
  590. this.x = -this.x;
  591. this.y = -this.y;
  592. return this;
  593. }
  594. dot(v) {
  595. return this.x * v.x + this.y * v.y;
  596. }
  597. cross(v) {
  598. return this.x * v.y - this.y * v.x;
  599. }
  600. lengthSq() {
  601. return this.x * this.x + this.y * this.y;
  602. }
  603. length() {
  604. return Math.sqrt(this.x * this.x + this.y * this.y);
  605. }
  606. manhattanLength() {
  607. return Math.abs(this.x) + Math.abs(this.y);
  608. }
  609. normalize() {
  610. return this.divideScalar(this.length() || 1);
  611. }
  612. angle() {
  613. // computes the angle in radians with respect to the positive x-axis
  614. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  615. return angle;
  616. }
  617. distanceTo(v) {
  618. return Math.sqrt(this.distanceToSquared(v));
  619. }
  620. distanceToSquared(v) {
  621. const dx = this.x - v.x,
  622. dy = this.y - v.y;
  623. return dx * dx + dy * dy;
  624. }
  625. manhattanDistanceTo(v) {
  626. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  627. }
  628. setLength(length) {
  629. return this.normalize().multiplyScalar(length);
  630. }
  631. lerp(v, alpha) {
  632. this.x += (v.x - this.x) * alpha;
  633. this.y += (v.y - this.y) * alpha;
  634. return this;
  635. }
  636. lerpVectors(v1, v2, alpha) {
  637. this.x = v1.x + (v2.x - v1.x) * alpha;
  638. this.y = v1.y + (v2.y - v1.y) * alpha;
  639. return this;
  640. }
  641. equals(v) {
  642. return v.x === this.x && v.y === this.y;
  643. }
  644. fromArray(array, offset = 0) {
  645. this.x = array[offset];
  646. this.y = array[offset + 1];
  647. return this;
  648. }
  649. toArray(array = [], offset = 0) {
  650. array[offset] = this.x;
  651. array[offset + 1] = this.y;
  652. return array;
  653. }
  654. fromBufferAttribute(attribute, index) {
  655. this.x = attribute.getX(index);
  656. this.y = attribute.getY(index);
  657. return this;
  658. }
  659. rotateAround(center, angle) {
  660. const c = Math.cos(angle),
  661. s = Math.sin(angle);
  662. const x = this.x - center.x;
  663. const y = this.y - center.y;
  664. this.x = x * c - y * s + center.x;
  665. this.y = x * s + y * c + center.y;
  666. return this;
  667. }
  668. random() {
  669. this.x = Math.random();
  670. this.y = Math.random();
  671. return this;
  672. }
  673. *[Symbol.iterator]() {
  674. yield this.x;
  675. yield this.y;
  676. }
  677. }
  678. class Matrix3 {
  679. constructor() {
  680. Matrix3.prototype.isMatrix3 = true;
  681. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  682. }
  683. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  684. const te = this.elements;
  685. te[0] = n11;
  686. te[1] = n21;
  687. te[2] = n31;
  688. te[3] = n12;
  689. te[4] = n22;
  690. te[5] = n32;
  691. te[6] = n13;
  692. te[7] = n23;
  693. te[8] = n33;
  694. return this;
  695. }
  696. identity() {
  697. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  698. return this;
  699. }
  700. copy(m) {
  701. const te = this.elements;
  702. const me = m.elements;
  703. te[0] = me[0];
  704. te[1] = me[1];
  705. te[2] = me[2];
  706. te[3] = me[3];
  707. te[4] = me[4];
  708. te[5] = me[5];
  709. te[6] = me[6];
  710. te[7] = me[7];
  711. te[8] = me[8];
  712. return this;
  713. }
  714. extractBasis(xAxis, yAxis, zAxis) {
  715. xAxis.setFromMatrix3Column(this, 0);
  716. yAxis.setFromMatrix3Column(this, 1);
  717. zAxis.setFromMatrix3Column(this, 2);
  718. return this;
  719. }
  720. setFromMatrix4(m) {
  721. const me = m.elements;
  722. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  723. return this;
  724. }
  725. multiply(m) {
  726. return this.multiplyMatrices(this, m);
  727. }
  728. premultiply(m) {
  729. return this.multiplyMatrices(m, this);
  730. }
  731. multiplyMatrices(a, b) {
  732. const ae = a.elements;
  733. const be = b.elements;
  734. const te = this.elements;
  735. const a11 = ae[0],
  736. a12 = ae[3],
  737. a13 = ae[6];
  738. const a21 = ae[1],
  739. a22 = ae[4],
  740. a23 = ae[7];
  741. const a31 = ae[2],
  742. a32 = ae[5],
  743. a33 = ae[8];
  744. const b11 = be[0],
  745. b12 = be[3],
  746. b13 = be[6];
  747. const b21 = be[1],
  748. b22 = be[4],
  749. b23 = be[7];
  750. const b31 = be[2],
  751. b32 = be[5],
  752. b33 = be[8];
  753. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  754. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  755. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  756. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  757. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  758. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  759. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  760. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  761. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  762. return this;
  763. }
  764. multiplyScalar(s) {
  765. const te = this.elements;
  766. te[0] *= s;
  767. te[3] *= s;
  768. te[6] *= s;
  769. te[1] *= s;
  770. te[4] *= s;
  771. te[7] *= s;
  772. te[2] *= s;
  773. te[5] *= s;
  774. te[8] *= s;
  775. return this;
  776. }
  777. determinant() {
  778. const te = this.elements;
  779. const a = te[0],
  780. b = te[1],
  781. c = te[2],
  782. d = te[3],
  783. e = te[4],
  784. f = te[5],
  785. g = te[6],
  786. h = te[7],
  787. i = te[8];
  788. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  789. }
  790. invert() {
  791. const te = this.elements,
  792. n11 = te[0],
  793. n21 = te[1],
  794. n31 = te[2],
  795. n12 = te[3],
  796. n22 = te[4],
  797. n32 = te[5],
  798. n13 = te[6],
  799. n23 = te[7],
  800. n33 = te[8],
  801. t11 = n33 * n22 - n32 * n23,
  802. t12 = n32 * n13 - n33 * n12,
  803. t13 = n23 * n12 - n22 * n13,
  804. det = n11 * t11 + n21 * t12 + n31 * t13;
  805. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  806. const detInv = 1 / det;
  807. te[0] = t11 * detInv;
  808. te[1] = (n31 * n23 - n33 * n21) * detInv;
  809. te[2] = (n32 * n21 - n31 * n22) * detInv;
  810. te[3] = t12 * detInv;
  811. te[4] = (n33 * n11 - n31 * n13) * detInv;
  812. te[5] = (n31 * n12 - n32 * n11) * detInv;
  813. te[6] = t13 * detInv;
  814. te[7] = (n21 * n13 - n23 * n11) * detInv;
  815. te[8] = (n22 * n11 - n21 * n12) * detInv;
  816. return this;
  817. }
  818. transpose() {
  819. let tmp;
  820. const m = this.elements;
  821. tmp = m[1];
  822. m[1] = m[3];
  823. m[3] = tmp;
  824. tmp = m[2];
  825. m[2] = m[6];
  826. m[6] = tmp;
  827. tmp = m[5];
  828. m[5] = m[7];
  829. m[7] = tmp;
  830. return this;
  831. }
  832. getNormalMatrix(matrix4) {
  833. return this.setFromMatrix4(matrix4).invert().transpose();
  834. }
  835. transposeIntoArray(r) {
  836. const m = this.elements;
  837. r[0] = m[0];
  838. r[1] = m[3];
  839. r[2] = m[6];
  840. r[3] = m[1];
  841. r[4] = m[4];
  842. r[5] = m[7];
  843. r[6] = m[2];
  844. r[7] = m[5];
  845. r[8] = m[8];
  846. return this;
  847. }
  848. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  849. const c = Math.cos(rotation);
  850. const s = Math.sin(rotation);
  851. 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);
  852. return this;
  853. }
  854. scale(sx, sy) {
  855. const te = this.elements;
  856. te[0] *= sx;
  857. te[3] *= sx;
  858. te[6] *= sx;
  859. te[1] *= sy;
  860. te[4] *= sy;
  861. te[7] *= sy;
  862. return this;
  863. }
  864. rotate(theta) {
  865. const c = Math.cos(theta);
  866. const s = Math.sin(theta);
  867. const te = this.elements;
  868. const a11 = te[0],
  869. a12 = te[3],
  870. a13 = te[6];
  871. const a21 = te[1],
  872. a22 = te[4],
  873. a23 = te[7];
  874. te[0] = c * a11 + s * a21;
  875. te[3] = c * a12 + s * a22;
  876. te[6] = c * a13 + s * a23;
  877. te[1] = -s * a11 + c * a21;
  878. te[4] = -s * a12 + c * a22;
  879. te[7] = -s * a13 + c * a23;
  880. return this;
  881. }
  882. translate(tx, ty) {
  883. const te = this.elements;
  884. te[0] += tx * te[2];
  885. te[3] += tx * te[5];
  886. te[6] += tx * te[8];
  887. te[1] += ty * te[2];
  888. te[4] += ty * te[5];
  889. te[7] += ty * te[8];
  890. return this;
  891. }
  892. equals(matrix) {
  893. const te = this.elements;
  894. const me = matrix.elements;
  895. for (let i = 0; i < 9; i++) {
  896. if (te[i] !== me[i]) return false;
  897. }
  898. return true;
  899. }
  900. fromArray(array, offset = 0) {
  901. for (let i = 0; i < 9; i++) {
  902. this.elements[i] = array[i + offset];
  903. }
  904. return this;
  905. }
  906. toArray(array = [], offset = 0) {
  907. const te = this.elements;
  908. array[offset] = te[0];
  909. array[offset + 1] = te[1];
  910. array[offset + 2] = te[2];
  911. array[offset + 3] = te[3];
  912. array[offset + 4] = te[4];
  913. array[offset + 5] = te[5];
  914. array[offset + 6] = te[6];
  915. array[offset + 7] = te[7];
  916. array[offset + 8] = te[8];
  917. return array;
  918. }
  919. clone() {
  920. return new this.constructor().fromArray(this.elements);
  921. }
  922. }
  923. function arrayNeedsUint32(array) {
  924. // assumes larger values usually on last
  925. for (let i = array.length - 1; i >= 0; --i) {
  926. if (array[i] > 65535) return true;
  927. }
  928. return false;
  929. }
  930. const TYPED_ARRAYS = {
  931. Int8Array: Int8Array,
  932. Uint8Array: Uint8Array,
  933. Uint8ClampedArray: Uint8ClampedArray,
  934. Int16Array: Int16Array,
  935. Uint16Array: Uint16Array,
  936. Int32Array: Int32Array,
  937. Uint32Array: Uint32Array,
  938. Float32Array: Float32Array,
  939. Float64Array: Float64Array
  940. };
  941. function getTypedArray(type, buffer) {
  942. return new TYPED_ARRAYS[type](buffer);
  943. }
  944. function createElementNS(name) {
  945. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  946. }
  947. function SRGBToLinear(c) {
  948. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  949. }
  950. function LinearToSRGB(c) {
  951. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  952. } // JavaScript RGB-to-RGB transforms, defined as
  953. // FN[InputColorSpace][OutputColorSpace] callback functions.
  954. const FN = {
  955. [SRGBColorSpace]: {
  956. [LinearSRGBColorSpace]: SRGBToLinear
  957. },
  958. [LinearSRGBColorSpace]: {
  959. [SRGBColorSpace]: LinearToSRGB
  960. }
  961. };
  962. const ColorManagement = {
  963. legacyMode: true,
  964. get workingColorSpace() {
  965. return LinearSRGBColorSpace;
  966. },
  967. set workingColorSpace(colorSpace) {
  968. console.warn('THREE.ColorManagement: .workingColorSpace is readonly.');
  969. },
  970. convert: function (color, sourceColorSpace, targetColorSpace) {
  971. if (this.legacyMode || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) {
  972. return color;
  973. }
  974. if (FN[sourceColorSpace] && FN[sourceColorSpace][targetColorSpace] !== undefined) {
  975. const fn = FN[sourceColorSpace][targetColorSpace];
  976. color.r = fn(color.r);
  977. color.g = fn(color.g);
  978. color.b = fn(color.b);
  979. return color;
  980. }
  981. throw new Error('Unsupported color space conversion.');
  982. },
  983. fromWorkingColorSpace: function (color, targetColorSpace) {
  984. return this.convert(color, this.workingColorSpace, targetColorSpace);
  985. },
  986. toWorkingColorSpace: function (color, sourceColorSpace) {
  987. return this.convert(color, sourceColorSpace, this.workingColorSpace);
  988. }
  989. };
  990. const _colorKeywords = {
  991. 'aliceblue': 0xF0F8FF,
  992. 'antiquewhite': 0xFAEBD7,
  993. 'aqua': 0x00FFFF,
  994. 'aquamarine': 0x7FFFD4,
  995. 'azure': 0xF0FFFF,
  996. 'beige': 0xF5F5DC,
  997. 'bisque': 0xFFE4C4,
  998. 'black': 0x000000,
  999. 'blanchedalmond': 0xFFEBCD,
  1000. 'blue': 0x0000FF,
  1001. 'blueviolet': 0x8A2BE2,
  1002. 'brown': 0xA52A2A,
  1003. 'burlywood': 0xDEB887,
  1004. 'cadetblue': 0x5F9EA0,
  1005. 'chartreuse': 0x7FFF00,
  1006. 'chocolate': 0xD2691E,
  1007. 'coral': 0xFF7F50,
  1008. 'cornflowerblue': 0x6495ED,
  1009. 'cornsilk': 0xFFF8DC,
  1010. 'crimson': 0xDC143C,
  1011. 'cyan': 0x00FFFF,
  1012. 'darkblue': 0x00008B,
  1013. 'darkcyan': 0x008B8B,
  1014. 'darkgoldenrod': 0xB8860B,
  1015. 'darkgray': 0xA9A9A9,
  1016. 'darkgreen': 0x006400,
  1017. 'darkgrey': 0xA9A9A9,
  1018. 'darkkhaki': 0xBDB76B,
  1019. 'darkmagenta': 0x8B008B,
  1020. 'darkolivegreen': 0x556B2F,
  1021. 'darkorange': 0xFF8C00,
  1022. 'darkorchid': 0x9932CC,
  1023. 'darkred': 0x8B0000,
  1024. 'darksalmon': 0xE9967A,
  1025. 'darkseagreen': 0x8FBC8F,
  1026. 'darkslateblue': 0x483D8B,
  1027. 'darkslategray': 0x2F4F4F,
  1028. 'darkslategrey': 0x2F4F4F,
  1029. 'darkturquoise': 0x00CED1,
  1030. 'darkviolet': 0x9400D3,
  1031. 'deeppink': 0xFF1493,
  1032. 'deepskyblue': 0x00BFFF,
  1033. 'dimgray': 0x696969,
  1034. 'dimgrey': 0x696969,
  1035. 'dodgerblue': 0x1E90FF,
  1036. 'firebrick': 0xB22222,
  1037. 'floralwhite': 0xFFFAF0,
  1038. 'forestgreen': 0x228B22,
  1039. 'fuchsia': 0xFF00FF,
  1040. 'gainsboro': 0xDCDCDC,
  1041. 'ghostwhite': 0xF8F8FF,
  1042. 'gold': 0xFFD700,
  1043. 'goldenrod': 0xDAA520,
  1044. 'gray': 0x808080,
  1045. 'green': 0x008000,
  1046. 'greenyellow': 0xADFF2F,
  1047. 'grey': 0x808080,
  1048. 'honeydew': 0xF0FFF0,
  1049. 'hotpink': 0xFF69B4,
  1050. 'indianred': 0xCD5C5C,
  1051. 'indigo': 0x4B0082,
  1052. 'ivory': 0xFFFFF0,
  1053. 'khaki': 0xF0E68C,
  1054. 'lavender': 0xE6E6FA,
  1055. 'lavenderblush': 0xFFF0F5,
  1056. 'lawngreen': 0x7CFC00,
  1057. 'lemonchiffon': 0xFFFACD,
  1058. 'lightblue': 0xADD8E6,
  1059. 'lightcoral': 0xF08080,
  1060. 'lightcyan': 0xE0FFFF,
  1061. 'lightgoldenrodyellow': 0xFAFAD2,
  1062. 'lightgray': 0xD3D3D3,
  1063. 'lightgreen': 0x90EE90,
  1064. 'lightgrey': 0xD3D3D3,
  1065. 'lightpink': 0xFFB6C1,
  1066. 'lightsalmon': 0xFFA07A,
  1067. 'lightseagreen': 0x20B2AA,
  1068. 'lightskyblue': 0x87CEFA,
  1069. 'lightslategray': 0x778899,
  1070. 'lightslategrey': 0x778899,
  1071. 'lightsteelblue': 0xB0C4DE,
  1072. 'lightyellow': 0xFFFFE0,
  1073. 'lime': 0x00FF00,
  1074. 'limegreen': 0x32CD32,
  1075. 'linen': 0xFAF0E6,
  1076. 'magenta': 0xFF00FF,
  1077. 'maroon': 0x800000,
  1078. 'mediumaquamarine': 0x66CDAA,
  1079. 'mediumblue': 0x0000CD,
  1080. 'mediumorchid': 0xBA55D3,
  1081. 'mediumpurple': 0x9370DB,
  1082. 'mediumseagreen': 0x3CB371,
  1083. 'mediumslateblue': 0x7B68EE,
  1084. 'mediumspringgreen': 0x00FA9A,
  1085. 'mediumturquoise': 0x48D1CC,
  1086. 'mediumvioletred': 0xC71585,
  1087. 'midnightblue': 0x191970,
  1088. 'mintcream': 0xF5FFFA,
  1089. 'mistyrose': 0xFFE4E1,
  1090. 'moccasin': 0xFFE4B5,
  1091. 'navajowhite': 0xFFDEAD,
  1092. 'navy': 0x000080,
  1093. 'oldlace': 0xFDF5E6,
  1094. 'olive': 0x808000,
  1095. 'olivedrab': 0x6B8E23,
  1096. 'orange': 0xFFA500,
  1097. 'orangered': 0xFF4500,
  1098. 'orchid': 0xDA70D6,
  1099. 'palegoldenrod': 0xEEE8AA,
  1100. 'palegreen': 0x98FB98,
  1101. 'paleturquoise': 0xAFEEEE,
  1102. 'palevioletred': 0xDB7093,
  1103. 'papayawhip': 0xFFEFD5,
  1104. 'peachpuff': 0xFFDAB9,
  1105. 'peru': 0xCD853F,
  1106. 'pink': 0xFFC0CB,
  1107. 'plum': 0xDDA0DD,
  1108. 'powderblue': 0xB0E0E6,
  1109. 'purple': 0x800080,
  1110. 'rebeccapurple': 0x663399,
  1111. 'red': 0xFF0000,
  1112. 'rosybrown': 0xBC8F8F,
  1113. 'royalblue': 0x4169E1,
  1114. 'saddlebrown': 0x8B4513,
  1115. 'salmon': 0xFA8072,
  1116. 'sandybrown': 0xF4A460,
  1117. 'seagreen': 0x2E8B57,
  1118. 'seashell': 0xFFF5EE,
  1119. 'sienna': 0xA0522D,
  1120. 'silver': 0xC0C0C0,
  1121. 'skyblue': 0x87CEEB,
  1122. 'slateblue': 0x6A5ACD,
  1123. 'slategray': 0x708090,
  1124. 'slategrey': 0x708090,
  1125. 'snow': 0xFFFAFA,
  1126. 'springgreen': 0x00FF7F,
  1127. 'steelblue': 0x4682B4,
  1128. 'tan': 0xD2B48C,
  1129. 'teal': 0x008080,
  1130. 'thistle': 0xD8BFD8,
  1131. 'tomato': 0xFF6347,
  1132. 'turquoise': 0x40E0D0,
  1133. 'violet': 0xEE82EE,
  1134. 'wheat': 0xF5DEB3,
  1135. 'white': 0xFFFFFF,
  1136. 'whitesmoke': 0xF5F5F5,
  1137. 'yellow': 0xFFFF00,
  1138. 'yellowgreen': 0x9ACD32
  1139. };
  1140. const _rgb = {
  1141. r: 0,
  1142. g: 0,
  1143. b: 0
  1144. };
  1145. const _hslA = {
  1146. h: 0,
  1147. s: 0,
  1148. l: 0
  1149. };
  1150. const _hslB = {
  1151. h: 0,
  1152. s: 0,
  1153. l: 0
  1154. };
  1155. function hue2rgb(p, q, t) {
  1156. if (t < 0) t += 1;
  1157. if (t > 1) t -= 1;
  1158. if (t < 1 / 6) return p + (q - p) * 6 * t;
  1159. if (t < 1 / 2) return q;
  1160. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  1161. return p;
  1162. }
  1163. function toComponents(source, target) {
  1164. target.r = source.r;
  1165. target.g = source.g;
  1166. target.b = source.b;
  1167. return target;
  1168. }
  1169. class Color {
  1170. constructor(r, g, b) {
  1171. this.isColor = true;
  1172. this.r = 1;
  1173. this.g = 1;
  1174. this.b = 1;
  1175. if (g === undefined && b === undefined) {
  1176. // r is THREE.Color, hex or string
  1177. return this.set(r);
  1178. }
  1179. return this.setRGB(r, g, b);
  1180. }
  1181. set(value) {
  1182. if (value && value.isColor) {
  1183. this.copy(value);
  1184. } else if (typeof value === 'number') {
  1185. this.setHex(value);
  1186. } else if (typeof value === 'string') {
  1187. this.setStyle(value);
  1188. }
  1189. return this;
  1190. }
  1191. setScalar(scalar) {
  1192. this.r = scalar;
  1193. this.g = scalar;
  1194. this.b = scalar;
  1195. return this;
  1196. }
  1197. setHex(hex, colorSpace = SRGBColorSpace) {
  1198. hex = Math.floor(hex);
  1199. this.r = (hex >> 16 & 255) / 255;
  1200. this.g = (hex >> 8 & 255) / 255;
  1201. this.b = (hex & 255) / 255;
  1202. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1203. return this;
  1204. }
  1205. setRGB(r, g, b, colorSpace = LinearSRGBColorSpace) {
  1206. this.r = r;
  1207. this.g = g;
  1208. this.b = b;
  1209. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1210. return this;
  1211. }
  1212. setHSL(h, s, l, colorSpace = LinearSRGBColorSpace) {
  1213. // h,s,l ranges are in 0.0 - 1.0
  1214. h = euclideanModulo(h, 1);
  1215. s = clamp(s, 0, 1);
  1216. l = clamp(l, 0, 1);
  1217. if (s === 0) {
  1218. this.r = this.g = this.b = l;
  1219. } else {
  1220. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  1221. const q = 2 * l - p;
  1222. this.r = hue2rgb(q, p, h + 1 / 3);
  1223. this.g = hue2rgb(q, p, h);
  1224. this.b = hue2rgb(q, p, h - 1 / 3);
  1225. }
  1226. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1227. return this;
  1228. }
  1229. setStyle(style, colorSpace = SRGBColorSpace) {
  1230. function handleAlpha(string) {
  1231. if (string === undefined) return;
  1232. if (parseFloat(string) < 1) {
  1233. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  1234. }
  1235. }
  1236. let m;
  1237. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  1238. // rgb / hsl
  1239. let color;
  1240. const name = m[1];
  1241. const components = m[2];
  1242. switch (name) {
  1243. case 'rgb':
  1244. case 'rgba':
  1245. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1246. // rgb(255,0,0) rgba(255,0,0,0.5)
  1247. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  1248. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  1249. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  1250. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1251. handleAlpha(color[4]);
  1252. return this;
  1253. }
  1254. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1255. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1256. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  1257. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  1258. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  1259. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1260. handleAlpha(color[4]);
  1261. return this;
  1262. }
  1263. break;
  1264. case 'hsl':
  1265. case 'hsla':
  1266. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1267. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1268. const h = parseFloat(color[1]) / 360;
  1269. const s = parseInt(color[2], 10) / 100;
  1270. const l = parseInt(color[3], 10) / 100;
  1271. handleAlpha(color[4]);
  1272. return this.setHSL(h, s, l, colorSpace);
  1273. }
  1274. break;
  1275. }
  1276. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  1277. // hex color
  1278. const hex = m[1];
  1279. const size = hex.length;
  1280. if (size === 3) {
  1281. // #ff0
  1282. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  1283. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  1284. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  1285. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1286. return this;
  1287. } else if (size === 6) {
  1288. // #ff0000
  1289. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  1290. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  1291. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  1292. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1293. return this;
  1294. }
  1295. }
  1296. if (style && style.length > 0) {
  1297. return this.setColorName(style, colorSpace);
  1298. }
  1299. return this;
  1300. }
  1301. setColorName(style, colorSpace = SRGBColorSpace) {
  1302. // color keywords
  1303. const hex = _colorKeywords[style.toLowerCase()];
  1304. if (hex !== undefined) {
  1305. // red
  1306. this.setHex(hex, colorSpace);
  1307. } else {
  1308. // unknown color
  1309. console.warn('THREE.Color: Unknown color ' + style);
  1310. }
  1311. return this;
  1312. }
  1313. clone() {
  1314. return new this.constructor(this.r, this.g, this.b);
  1315. }
  1316. copy(color) {
  1317. this.r = color.r;
  1318. this.g = color.g;
  1319. this.b = color.b;
  1320. return this;
  1321. }
  1322. copySRGBToLinear(color) {
  1323. this.r = SRGBToLinear(color.r);
  1324. this.g = SRGBToLinear(color.g);
  1325. this.b = SRGBToLinear(color.b);
  1326. return this;
  1327. }
  1328. copyLinearToSRGB(color) {
  1329. this.r = LinearToSRGB(color.r);
  1330. this.g = LinearToSRGB(color.g);
  1331. this.b = LinearToSRGB(color.b);
  1332. return this;
  1333. }
  1334. convertSRGBToLinear() {
  1335. this.copySRGBToLinear(this);
  1336. return this;
  1337. }
  1338. convertLinearToSRGB() {
  1339. this.copyLinearToSRGB(this);
  1340. return this;
  1341. }
  1342. getHex(colorSpace = SRGBColorSpace) {
  1343. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1344. return clamp(_rgb.r * 255, 0, 255) << 16 ^ clamp(_rgb.g * 255, 0, 255) << 8 ^ clamp(_rgb.b * 255, 0, 255) << 0;
  1345. }
  1346. getHexString(colorSpace = SRGBColorSpace) {
  1347. return ('000000' + this.getHex(colorSpace).toString(16)).slice(-6);
  1348. }
  1349. getHSL(target, colorSpace = LinearSRGBColorSpace) {
  1350. // h,s,l ranges are in 0.0 - 1.0
  1351. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1352. const r = _rgb.r,
  1353. g = _rgb.g,
  1354. b = _rgb.b;
  1355. const max = Math.max(r, g, b);
  1356. const min = Math.min(r, g, b);
  1357. let hue, saturation;
  1358. const lightness = (min + max) / 2.0;
  1359. if (min === max) {
  1360. hue = 0;
  1361. saturation = 0;
  1362. } else {
  1363. const delta = max - min;
  1364. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  1365. switch (max) {
  1366. case r:
  1367. hue = (g - b) / delta + (g < b ? 6 : 0);
  1368. break;
  1369. case g:
  1370. hue = (b - r) / delta + 2;
  1371. break;
  1372. case b:
  1373. hue = (r - g) / delta + 4;
  1374. break;
  1375. }
  1376. hue /= 6;
  1377. }
  1378. target.h = hue;
  1379. target.s = saturation;
  1380. target.l = lightness;
  1381. return target;
  1382. }
  1383. getRGB(target, colorSpace = LinearSRGBColorSpace) {
  1384. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1385. target.r = _rgb.r;
  1386. target.g = _rgb.g;
  1387. target.b = _rgb.b;
  1388. return target;
  1389. }
  1390. getStyle(colorSpace = SRGBColorSpace) {
  1391. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1392. if (colorSpace !== SRGBColorSpace) {
  1393. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1394. return `color(${colorSpace} ${_rgb.r} ${_rgb.g} ${_rgb.b})`;
  1395. }
  1396. return `rgb(${_rgb.r * 255 | 0},${_rgb.g * 255 | 0},${_rgb.b * 255 | 0})`;
  1397. }
  1398. offsetHSL(h, s, l) {
  1399. this.getHSL(_hslA);
  1400. _hslA.h += h;
  1401. _hslA.s += s;
  1402. _hslA.l += l;
  1403. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  1404. return this;
  1405. }
  1406. add(color) {
  1407. this.r += color.r;
  1408. this.g += color.g;
  1409. this.b += color.b;
  1410. return this;
  1411. }
  1412. addColors(color1, color2) {
  1413. this.r = color1.r + color2.r;
  1414. this.g = color1.g + color2.g;
  1415. this.b = color1.b + color2.b;
  1416. return this;
  1417. }
  1418. addScalar(s) {
  1419. this.r += s;
  1420. this.g += s;
  1421. this.b += s;
  1422. return this;
  1423. }
  1424. sub(color) {
  1425. this.r = Math.max(0, this.r - color.r);
  1426. this.g = Math.max(0, this.g - color.g);
  1427. this.b = Math.max(0, this.b - color.b);
  1428. return this;
  1429. }
  1430. multiply(color) {
  1431. this.r *= color.r;
  1432. this.g *= color.g;
  1433. this.b *= color.b;
  1434. return this;
  1435. }
  1436. multiplyScalar(s) {
  1437. this.r *= s;
  1438. this.g *= s;
  1439. this.b *= s;
  1440. return this;
  1441. }
  1442. lerp(color, alpha) {
  1443. this.r += (color.r - this.r) * alpha;
  1444. this.g += (color.g - this.g) * alpha;
  1445. this.b += (color.b - this.b) * alpha;
  1446. return this;
  1447. }
  1448. lerpColors(color1, color2, alpha) {
  1449. this.r = color1.r + (color2.r - color1.r) * alpha;
  1450. this.g = color1.g + (color2.g - color1.g) * alpha;
  1451. this.b = color1.b + (color2.b - color1.b) * alpha;
  1452. return this;
  1453. }
  1454. lerpHSL(color, alpha) {
  1455. this.getHSL(_hslA);
  1456. color.getHSL(_hslB);
  1457. const h = lerp(_hslA.h, _hslB.h, alpha);
  1458. const s = lerp(_hslA.s, _hslB.s, alpha);
  1459. const l = lerp(_hslA.l, _hslB.l, alpha);
  1460. this.setHSL(h, s, l);
  1461. return this;
  1462. }
  1463. equals(c) {
  1464. return c.r === this.r && c.g === this.g && c.b === this.b;
  1465. }
  1466. fromArray(array, offset = 0) {
  1467. this.r = array[offset];
  1468. this.g = array[offset + 1];
  1469. this.b = array[offset + 2];
  1470. return this;
  1471. }
  1472. toArray(array = [], offset = 0) {
  1473. array[offset] = this.r;
  1474. array[offset + 1] = this.g;
  1475. array[offset + 2] = this.b;
  1476. return array;
  1477. }
  1478. fromBufferAttribute(attribute, index) {
  1479. this.r = attribute.getX(index);
  1480. this.g = attribute.getY(index);
  1481. this.b = attribute.getZ(index);
  1482. if (attribute.normalized === true) {
  1483. // assuming Uint8Array
  1484. this.r /= 255;
  1485. this.g /= 255;
  1486. this.b /= 255;
  1487. }
  1488. return this;
  1489. }
  1490. toJSON() {
  1491. return this.getHex();
  1492. }
  1493. *[Symbol.iterator]() {
  1494. yield this.r;
  1495. yield this.g;
  1496. yield this.b;
  1497. }
  1498. }
  1499. Color.NAMES = _colorKeywords;
  1500. let _canvas;
  1501. class ImageUtils {
  1502. static getDataURL(image) {
  1503. if (/^data:/i.test(image.src)) {
  1504. return image.src;
  1505. }
  1506. if (typeof HTMLCanvasElement == 'undefined') {
  1507. return image.src;
  1508. }
  1509. let canvas;
  1510. if (image instanceof HTMLCanvasElement) {
  1511. canvas = image;
  1512. } else {
  1513. if (_canvas === undefined) _canvas = createElementNS('canvas');
  1514. _canvas.width = image.width;
  1515. _canvas.height = image.height;
  1516. const context = _canvas.getContext('2d');
  1517. if (image instanceof ImageData) {
  1518. context.putImageData(image, 0, 0);
  1519. } else {
  1520. context.drawImage(image, 0, 0, image.width, image.height);
  1521. }
  1522. canvas = _canvas;
  1523. }
  1524. if (canvas.width > 2048 || canvas.height > 2048) {
  1525. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  1526. return canvas.toDataURL('image/jpeg', 0.6);
  1527. } else {
  1528. return canvas.toDataURL('image/png');
  1529. }
  1530. }
  1531. static sRGBToLinear(image) {
  1532. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1533. const canvas = createElementNS('canvas');
  1534. canvas.width = image.width;
  1535. canvas.height = image.height;
  1536. const context = canvas.getContext('2d');
  1537. context.drawImage(image, 0, 0, image.width, image.height);
  1538. const imageData = context.getImageData(0, 0, image.width, image.height);
  1539. const data = imageData.data;
  1540. for (let i = 0; i < data.length; i++) {
  1541. data[i] = SRGBToLinear(data[i] / 255) * 255;
  1542. }
  1543. context.putImageData(imageData, 0, 0);
  1544. return canvas;
  1545. } else if (image.data) {
  1546. const data = image.data.slice(0);
  1547. for (let i = 0; i < data.length; i++) {
  1548. if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
  1549. data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255);
  1550. } else {
  1551. // assuming float
  1552. data[i] = SRGBToLinear(data[i]);
  1553. }
  1554. }
  1555. return {
  1556. data: data,
  1557. width: image.width,
  1558. height: image.height
  1559. };
  1560. } else {
  1561. console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.');
  1562. return image;
  1563. }
  1564. }
  1565. }
  1566. class Source {
  1567. constructor(data = null) {
  1568. this.isSource = true;
  1569. this.uuid = generateUUID();
  1570. this.data = data;
  1571. this.version = 0;
  1572. }
  1573. set needsUpdate(value) {
  1574. if (value === true) this.version++;
  1575. }
  1576. toJSON(meta) {
  1577. const isRootObject = meta === undefined || typeof meta === 'string';
  1578. if (!isRootObject && meta.images[this.uuid] !== undefined) {
  1579. return meta.images[this.uuid];
  1580. }
  1581. const output = {
  1582. uuid: this.uuid,
  1583. url: ''
  1584. };
  1585. const data = this.data;
  1586. if (data !== null) {
  1587. let url;
  1588. if (Array.isArray(data)) {
  1589. // cube texture
  1590. url = [];
  1591. for (let i = 0, l = data.length; i < l; i++) {
  1592. if (data[i].isDataTexture) {
  1593. url.push(serializeImage(data[i].image));
  1594. } else {
  1595. url.push(serializeImage(data[i]));
  1596. }
  1597. }
  1598. } else {
  1599. // texture
  1600. url = serializeImage(data);
  1601. }
  1602. output.url = url;
  1603. }
  1604. if (!isRootObject) {
  1605. meta.images[this.uuid] = output;
  1606. }
  1607. return output;
  1608. }
  1609. }
  1610. function serializeImage(image) {
  1611. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1612. // default images
  1613. return ImageUtils.getDataURL(image);
  1614. } else {
  1615. if (image.data) {
  1616. // images of DataTexture
  1617. return {
  1618. data: Array.from(image.data),
  1619. width: image.width,
  1620. height: image.height,
  1621. type: image.data.constructor.name
  1622. };
  1623. } else {
  1624. console.warn('THREE.Texture: Unable to serialize Texture.');
  1625. return {};
  1626. }
  1627. }
  1628. }
  1629. let textureId = 0;
  1630. class Texture extends EventDispatcher {
  1631. 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) {
  1632. super();
  1633. this.isTexture = true;
  1634. Object.defineProperty(this, 'id', {
  1635. value: textureId++
  1636. });
  1637. this.uuid = generateUUID();
  1638. this.name = '';
  1639. this.source = new Source(image);
  1640. this.mipmaps = [];
  1641. this.mapping = mapping;
  1642. this.wrapS = wrapS;
  1643. this.wrapT = wrapT;
  1644. this.magFilter = magFilter;
  1645. this.minFilter = minFilter;
  1646. this.anisotropy = anisotropy;
  1647. this.format = format;
  1648. this.internalFormat = null;
  1649. this.type = type;
  1650. this.offset = new Vector2(0, 0);
  1651. this.repeat = new Vector2(1, 1);
  1652. this.center = new Vector2(0, 0);
  1653. this.rotation = 0;
  1654. this.matrixAutoUpdate = true;
  1655. this.matrix = new Matrix3();
  1656. this.generateMipmaps = true;
  1657. this.premultiplyAlpha = false;
  1658. this.flipY = true;
  1659. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1660. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1661. //
  1662. // Also changing the encoding after already used by a Material will not automatically make the Material
  1663. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1664. this.encoding = encoding;
  1665. this.userData = {};
  1666. this.version = 0;
  1667. this.onUpdate = null;
  1668. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1669. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1670. }
  1671. get image() {
  1672. return this.source.data;
  1673. }
  1674. set image(value) {
  1675. this.source.data = value;
  1676. }
  1677. updateMatrix() {
  1678. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1679. }
  1680. clone() {
  1681. return new this.constructor().copy(this);
  1682. }
  1683. copy(source) {
  1684. this.name = source.name;
  1685. this.source = source.source;
  1686. this.mipmaps = source.mipmaps.slice(0);
  1687. this.mapping = source.mapping;
  1688. this.wrapS = source.wrapS;
  1689. this.wrapT = source.wrapT;
  1690. this.magFilter = source.magFilter;
  1691. this.minFilter = source.minFilter;
  1692. this.anisotropy = source.anisotropy;
  1693. this.format = source.format;
  1694. this.internalFormat = source.internalFormat;
  1695. this.type = source.type;
  1696. this.offset.copy(source.offset);
  1697. this.repeat.copy(source.repeat);
  1698. this.center.copy(source.center);
  1699. this.rotation = source.rotation;
  1700. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1701. this.matrix.copy(source.matrix);
  1702. this.generateMipmaps = source.generateMipmaps;
  1703. this.premultiplyAlpha = source.premultiplyAlpha;
  1704. this.flipY = source.flipY;
  1705. this.unpackAlignment = source.unpackAlignment;
  1706. this.encoding = source.encoding;
  1707. this.userData = JSON.parse(JSON.stringify(source.userData));
  1708. this.needsUpdate = true;
  1709. return this;
  1710. }
  1711. toJSON(meta) {
  1712. const isRootObject = meta === undefined || typeof meta === 'string';
  1713. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1714. return meta.textures[this.uuid];
  1715. }
  1716. const output = {
  1717. metadata: {
  1718. version: 4.5,
  1719. type: 'Texture',
  1720. generator: 'Texture.toJSON'
  1721. },
  1722. uuid: this.uuid,
  1723. name: this.name,
  1724. image: this.source.toJSON(meta).uuid,
  1725. mapping: this.mapping,
  1726. repeat: [this.repeat.x, this.repeat.y],
  1727. offset: [this.offset.x, this.offset.y],
  1728. center: [this.center.x, this.center.y],
  1729. rotation: this.rotation,
  1730. wrap: [this.wrapS, this.wrapT],
  1731. format: this.format,
  1732. type: this.type,
  1733. encoding: this.encoding,
  1734. minFilter: this.minFilter,
  1735. magFilter: this.magFilter,
  1736. anisotropy: this.anisotropy,
  1737. flipY: this.flipY,
  1738. premultiplyAlpha: this.premultiplyAlpha,
  1739. unpackAlignment: this.unpackAlignment
  1740. };
  1741. if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
  1742. if (!isRootObject) {
  1743. meta.textures[this.uuid] = output;
  1744. }
  1745. return output;
  1746. }
  1747. dispose() {
  1748. this.dispatchEvent({
  1749. type: 'dispose'
  1750. });
  1751. }
  1752. transformUv(uv) {
  1753. if (this.mapping !== UVMapping) return uv;
  1754. uv.applyMatrix3(this.matrix);
  1755. if (uv.x < 0 || uv.x > 1) {
  1756. switch (this.wrapS) {
  1757. case RepeatWrapping:
  1758. uv.x = uv.x - Math.floor(uv.x);
  1759. break;
  1760. case ClampToEdgeWrapping:
  1761. uv.x = uv.x < 0 ? 0 : 1;
  1762. break;
  1763. case MirroredRepeatWrapping:
  1764. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1765. uv.x = Math.ceil(uv.x) - uv.x;
  1766. } else {
  1767. uv.x = uv.x - Math.floor(uv.x);
  1768. }
  1769. break;
  1770. }
  1771. }
  1772. if (uv.y < 0 || uv.y > 1) {
  1773. switch (this.wrapT) {
  1774. case RepeatWrapping:
  1775. uv.y = uv.y - Math.floor(uv.y);
  1776. break;
  1777. case ClampToEdgeWrapping:
  1778. uv.y = uv.y < 0 ? 0 : 1;
  1779. break;
  1780. case MirroredRepeatWrapping:
  1781. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1782. uv.y = Math.ceil(uv.y) - uv.y;
  1783. } else {
  1784. uv.y = uv.y - Math.floor(uv.y);
  1785. }
  1786. break;
  1787. }
  1788. }
  1789. if (this.flipY) {
  1790. uv.y = 1 - uv.y;
  1791. }
  1792. return uv;
  1793. }
  1794. set needsUpdate(value) {
  1795. if (value === true) {
  1796. this.version++;
  1797. this.source.needsUpdate = true;
  1798. }
  1799. }
  1800. }
  1801. Texture.DEFAULT_IMAGE = null;
  1802. Texture.DEFAULT_MAPPING = UVMapping;
  1803. class Vector4 {
  1804. constructor(x = 0, y = 0, z = 0, w = 1) {
  1805. Vector4.prototype.isVector4 = true;
  1806. this.x = x;
  1807. this.y = y;
  1808. this.z = z;
  1809. this.w = w;
  1810. }
  1811. get width() {
  1812. return this.z;
  1813. }
  1814. set width(value) {
  1815. this.z = value;
  1816. }
  1817. get height() {
  1818. return this.w;
  1819. }
  1820. set height(value) {
  1821. this.w = value;
  1822. }
  1823. set(x, y, z, w) {
  1824. this.x = x;
  1825. this.y = y;
  1826. this.z = z;
  1827. this.w = w;
  1828. return this;
  1829. }
  1830. setScalar(scalar) {
  1831. this.x = scalar;
  1832. this.y = scalar;
  1833. this.z = scalar;
  1834. this.w = scalar;
  1835. return this;
  1836. }
  1837. setX(x) {
  1838. this.x = x;
  1839. return this;
  1840. }
  1841. setY(y) {
  1842. this.y = y;
  1843. return this;
  1844. }
  1845. setZ(z) {
  1846. this.z = z;
  1847. return this;
  1848. }
  1849. setW(w) {
  1850. this.w = w;
  1851. return this;
  1852. }
  1853. setComponent(index, value) {
  1854. switch (index) {
  1855. case 0:
  1856. this.x = value;
  1857. break;
  1858. case 1:
  1859. this.y = value;
  1860. break;
  1861. case 2:
  1862. this.z = value;
  1863. break;
  1864. case 3:
  1865. this.w = value;
  1866. break;
  1867. default:
  1868. throw new Error('index is out of range: ' + index);
  1869. }
  1870. return this;
  1871. }
  1872. getComponent(index) {
  1873. switch (index) {
  1874. case 0:
  1875. return this.x;
  1876. case 1:
  1877. return this.y;
  1878. case 2:
  1879. return this.z;
  1880. case 3:
  1881. return this.w;
  1882. default:
  1883. throw new Error('index is out of range: ' + index);
  1884. }
  1885. }
  1886. clone() {
  1887. return new this.constructor(this.x, this.y, this.z, this.w);
  1888. }
  1889. copy(v) {
  1890. this.x = v.x;
  1891. this.y = v.y;
  1892. this.z = v.z;
  1893. this.w = v.w !== undefined ? v.w : 1;
  1894. return this;
  1895. }
  1896. add(v) {
  1897. this.x += v.x;
  1898. this.y += v.y;
  1899. this.z += v.z;
  1900. this.w += v.w;
  1901. return this;
  1902. }
  1903. addScalar(s) {
  1904. this.x += s;
  1905. this.y += s;
  1906. this.z += s;
  1907. this.w += s;
  1908. return this;
  1909. }
  1910. addVectors(a, b) {
  1911. this.x = a.x + b.x;
  1912. this.y = a.y + b.y;
  1913. this.z = a.z + b.z;
  1914. this.w = a.w + b.w;
  1915. return this;
  1916. }
  1917. addScaledVector(v, s) {
  1918. this.x += v.x * s;
  1919. this.y += v.y * s;
  1920. this.z += v.z * s;
  1921. this.w += v.w * s;
  1922. return this;
  1923. }
  1924. sub(v) {
  1925. this.x -= v.x;
  1926. this.y -= v.y;
  1927. this.z -= v.z;
  1928. this.w -= v.w;
  1929. return this;
  1930. }
  1931. subScalar(s) {
  1932. this.x -= s;
  1933. this.y -= s;
  1934. this.z -= s;
  1935. this.w -= s;
  1936. return this;
  1937. }
  1938. subVectors(a, b) {
  1939. this.x = a.x - b.x;
  1940. this.y = a.y - b.y;
  1941. this.z = a.z - b.z;
  1942. this.w = a.w - b.w;
  1943. return this;
  1944. }
  1945. multiply(v) {
  1946. this.x *= v.x;
  1947. this.y *= v.y;
  1948. this.z *= v.z;
  1949. this.w *= v.w;
  1950. return this;
  1951. }
  1952. multiplyScalar(scalar) {
  1953. this.x *= scalar;
  1954. this.y *= scalar;
  1955. this.z *= scalar;
  1956. this.w *= scalar;
  1957. return this;
  1958. }
  1959. applyMatrix4(m) {
  1960. const x = this.x,
  1961. y = this.y,
  1962. z = this.z,
  1963. w = this.w;
  1964. const e = m.elements;
  1965. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1966. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1967. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1968. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1969. return this;
  1970. }
  1971. divideScalar(scalar) {
  1972. return this.multiplyScalar(1 / scalar);
  1973. }
  1974. setAxisAngleFromQuaternion(q) {
  1975. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1976. // q is assumed to be normalized
  1977. this.w = 2 * Math.acos(q.w);
  1978. const s = Math.sqrt(1 - q.w * q.w);
  1979. if (s < 0.0001) {
  1980. this.x = 1;
  1981. this.y = 0;
  1982. this.z = 0;
  1983. } else {
  1984. this.x = q.x / s;
  1985. this.y = q.y / s;
  1986. this.z = q.z / s;
  1987. }
  1988. return this;
  1989. }
  1990. setAxisAngleFromRotationMatrix(m) {
  1991. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1992. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1993. let angle, x, y, z; // variables for result
  1994. const epsilon = 0.01,
  1995. // margin to allow for rounding errors
  1996. epsilon2 = 0.1,
  1997. // margin to distinguish between 0 and 180 degrees
  1998. te = m.elements,
  1999. m11 = te[0],
  2000. m12 = te[4],
  2001. m13 = te[8],
  2002. m21 = te[1],
  2003. m22 = te[5],
  2004. m23 = te[9],
  2005. m31 = te[2],
  2006. m32 = te[6],
  2007. m33 = te[10];
  2008. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  2009. // singularity found
  2010. // first check for identity matrix which must have +1 for all terms
  2011. // in leading diagonal and zero in other terms
  2012. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  2013. // this singularity is identity matrix so angle = 0
  2014. this.set(1, 0, 0, 0);
  2015. return this; // zero angle, arbitrary axis
  2016. } // otherwise this singularity is angle = 180
  2017. angle = Math.PI;
  2018. const xx = (m11 + 1) / 2;
  2019. const yy = (m22 + 1) / 2;
  2020. const zz = (m33 + 1) / 2;
  2021. const xy = (m12 + m21) / 4;
  2022. const xz = (m13 + m31) / 4;
  2023. const yz = (m23 + m32) / 4;
  2024. if (xx > yy && xx > zz) {
  2025. // m11 is the largest diagonal term
  2026. if (xx < epsilon) {
  2027. x = 0;
  2028. y = 0.707106781;
  2029. z = 0.707106781;
  2030. } else {
  2031. x = Math.sqrt(xx);
  2032. y = xy / x;
  2033. z = xz / x;
  2034. }
  2035. } else if (yy > zz) {
  2036. // m22 is the largest diagonal term
  2037. if (yy < epsilon) {
  2038. x = 0.707106781;
  2039. y = 0;
  2040. z = 0.707106781;
  2041. } else {
  2042. y = Math.sqrt(yy);
  2043. x = xy / y;
  2044. z = yz / y;
  2045. }
  2046. } else {
  2047. // m33 is the largest diagonal term so base result on this
  2048. if (zz < epsilon) {
  2049. x = 0.707106781;
  2050. y = 0.707106781;
  2051. z = 0;
  2052. } else {
  2053. z = Math.sqrt(zz);
  2054. x = xz / z;
  2055. y = yz / z;
  2056. }
  2057. }
  2058. this.set(x, y, z, angle);
  2059. return this; // return 180 deg rotation
  2060. } // as we have reached here there are no singularities so we can handle normally
  2061. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  2062. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2063. // caught by singularity test above, but I've left it in just in case
  2064. this.x = (m32 - m23) / s;
  2065. this.y = (m13 - m31) / s;
  2066. this.z = (m21 - m12) / s;
  2067. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2068. return this;
  2069. }
  2070. min(v) {
  2071. this.x = Math.min(this.x, v.x);
  2072. this.y = Math.min(this.y, v.y);
  2073. this.z = Math.min(this.z, v.z);
  2074. this.w = Math.min(this.w, v.w);
  2075. return this;
  2076. }
  2077. max(v) {
  2078. this.x = Math.max(this.x, v.x);
  2079. this.y = Math.max(this.y, v.y);
  2080. this.z = Math.max(this.z, v.z);
  2081. this.w = Math.max(this.w, v.w);
  2082. return this;
  2083. }
  2084. clamp(min, max) {
  2085. // assumes min < max, componentwise
  2086. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2087. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2088. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2089. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2090. return this;
  2091. }
  2092. clampScalar(minVal, maxVal) {
  2093. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2094. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2095. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2096. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2097. return this;
  2098. }
  2099. clampLength(min, max) {
  2100. const length = this.length();
  2101. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2102. }
  2103. floor() {
  2104. this.x = Math.floor(this.x);
  2105. this.y = Math.floor(this.y);
  2106. this.z = Math.floor(this.z);
  2107. this.w = Math.floor(this.w);
  2108. return this;
  2109. }
  2110. ceil() {
  2111. this.x = Math.ceil(this.x);
  2112. this.y = Math.ceil(this.y);
  2113. this.z = Math.ceil(this.z);
  2114. this.w = Math.ceil(this.w);
  2115. return this;
  2116. }
  2117. round() {
  2118. this.x = Math.round(this.x);
  2119. this.y = Math.round(this.y);
  2120. this.z = Math.round(this.z);
  2121. this.w = Math.round(this.w);
  2122. return this;
  2123. }
  2124. roundToZero() {
  2125. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2126. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2127. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2128. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2129. return this;
  2130. }
  2131. negate() {
  2132. this.x = -this.x;
  2133. this.y = -this.y;
  2134. this.z = -this.z;
  2135. this.w = -this.w;
  2136. return this;
  2137. }
  2138. dot(v) {
  2139. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2140. }
  2141. lengthSq() {
  2142. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2143. }
  2144. length() {
  2145. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2146. }
  2147. manhattanLength() {
  2148. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2149. }
  2150. normalize() {
  2151. return this.divideScalar(this.length() || 1);
  2152. }
  2153. setLength(length) {
  2154. return this.normalize().multiplyScalar(length);
  2155. }
  2156. lerp(v, alpha) {
  2157. this.x += (v.x - this.x) * alpha;
  2158. this.y += (v.y - this.y) * alpha;
  2159. this.z += (v.z - this.z) * alpha;
  2160. this.w += (v.w - this.w) * alpha;
  2161. return this;
  2162. }
  2163. lerpVectors(v1, v2, alpha) {
  2164. this.x = v1.x + (v2.x - v1.x) * alpha;
  2165. this.y = v1.y + (v2.y - v1.y) * alpha;
  2166. this.z = v1.z + (v2.z - v1.z) * alpha;
  2167. this.w = v1.w + (v2.w - v1.w) * alpha;
  2168. return this;
  2169. }
  2170. equals(v) {
  2171. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2172. }
  2173. fromArray(array, offset = 0) {
  2174. this.x = array[offset];
  2175. this.y = array[offset + 1];
  2176. this.z = array[offset + 2];
  2177. this.w = array[offset + 3];
  2178. return this;
  2179. }
  2180. toArray(array = [], offset = 0) {
  2181. array[offset] = this.x;
  2182. array[offset + 1] = this.y;
  2183. array[offset + 2] = this.z;
  2184. array[offset + 3] = this.w;
  2185. return array;
  2186. }
  2187. fromBufferAttribute(attribute, index) {
  2188. this.x = attribute.getX(index);
  2189. this.y = attribute.getY(index);
  2190. this.z = attribute.getZ(index);
  2191. this.w = attribute.getW(index);
  2192. return this;
  2193. }
  2194. random() {
  2195. this.x = Math.random();
  2196. this.y = Math.random();
  2197. this.z = Math.random();
  2198. this.w = Math.random();
  2199. return this;
  2200. }
  2201. *[Symbol.iterator]() {
  2202. yield this.x;
  2203. yield this.y;
  2204. yield this.z;
  2205. yield this.w;
  2206. }
  2207. }
  2208. /*
  2209. In options, we can specify:
  2210. * Texture parameters for an auto-generated target texture
  2211. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2212. */
  2213. class WebGLRenderTarget extends EventDispatcher {
  2214. constructor(width, height, options = {}) {
  2215. super();
  2216. this.isWebGLRenderTarget = true;
  2217. this.width = width;
  2218. this.height = height;
  2219. this.depth = 1;
  2220. this.scissor = new Vector4(0, 0, width, height);
  2221. this.scissorTest = false;
  2222. this.viewport = new Vector4(0, 0, width, height);
  2223. const image = {
  2224. width: width,
  2225. height: height,
  2226. depth: 1
  2227. };
  2228. this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2229. this.texture.isRenderTargetTexture = true;
  2230. this.texture.flipY = false;
  2231. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2232. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2233. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2234. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2235. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2236. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2237. this.samples = options.samples !== undefined ? options.samples : 0;
  2238. }
  2239. setSize(width, height, depth = 1) {
  2240. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2241. this.width = width;
  2242. this.height = height;
  2243. this.depth = depth;
  2244. this.texture.image.width = width;
  2245. this.texture.image.height = height;
  2246. this.texture.image.depth = depth;
  2247. this.dispose();
  2248. }
  2249. this.viewport.set(0, 0, width, height);
  2250. this.scissor.set(0, 0, width, height);
  2251. }
  2252. clone() {
  2253. return new this.constructor().copy(this);
  2254. }
  2255. copy(source) {
  2256. this.width = source.width;
  2257. this.height = source.height;
  2258. this.depth = source.depth;
  2259. this.viewport.copy(source.viewport);
  2260. this.texture = source.texture.clone();
  2261. this.texture.isRenderTargetTexture = true; // ensure image object is not shared, see #20328
  2262. const image = Object.assign({}, source.texture.image);
  2263. this.texture.source = new Source(image);
  2264. this.depthBuffer = source.depthBuffer;
  2265. this.stencilBuffer = source.stencilBuffer;
  2266. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2267. this.samples = source.samples;
  2268. return this;
  2269. }
  2270. dispose() {
  2271. this.dispatchEvent({
  2272. type: 'dispose'
  2273. });
  2274. }
  2275. }
  2276. class DataArrayTexture extends Texture {
  2277. constructor(data = null, width = 1, height = 1, depth = 1) {
  2278. super(null);
  2279. this.isDataArrayTexture = true;
  2280. this.image = {
  2281. data,
  2282. width,
  2283. height,
  2284. depth
  2285. };
  2286. this.magFilter = NearestFilter;
  2287. this.minFilter = NearestFilter;
  2288. this.wrapR = ClampToEdgeWrapping;
  2289. this.generateMipmaps = false;
  2290. this.flipY = false;
  2291. this.unpackAlignment = 1;
  2292. }
  2293. }
  2294. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2295. constructor(width, height, depth) {
  2296. super(width, height);
  2297. this.isWebGLArrayRenderTarget = true;
  2298. this.depth = depth;
  2299. this.texture = new DataArrayTexture(null, width, height, depth);
  2300. this.texture.isRenderTargetTexture = true;
  2301. }
  2302. }
  2303. class Data3DTexture extends Texture {
  2304. constructor(data = null, width = 1, height = 1, depth = 1) {
  2305. // We're going to add .setXXX() methods for setting properties later.
  2306. // Users can still set in DataTexture3D directly.
  2307. //
  2308. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2309. // texture.anisotropy = 16;
  2310. //
  2311. // See #14839
  2312. super(null);
  2313. this.isData3DTexture = true;
  2314. this.image = {
  2315. data,
  2316. width,
  2317. height,
  2318. depth
  2319. };
  2320. this.magFilter = NearestFilter;
  2321. this.minFilter = NearestFilter;
  2322. this.wrapR = ClampToEdgeWrapping;
  2323. this.generateMipmaps = false;
  2324. this.flipY = false;
  2325. this.unpackAlignment = 1;
  2326. }
  2327. }
  2328. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2329. constructor(width, height, depth) {
  2330. super(width, height);
  2331. this.isWebGL3DRenderTarget = true;
  2332. this.depth = depth;
  2333. this.texture = new Data3DTexture(null, width, height, depth);
  2334. this.texture.isRenderTargetTexture = true;
  2335. }
  2336. }
  2337. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2338. constructor(width, height, count, options = {}) {
  2339. super(width, height, options);
  2340. this.isWebGLMultipleRenderTargets = true;
  2341. const texture = this.texture;
  2342. this.texture = [];
  2343. for (let i = 0; i < count; i++) {
  2344. this.texture[i] = texture.clone();
  2345. this.texture[i].isRenderTargetTexture = true;
  2346. }
  2347. }
  2348. setSize(width, height, depth = 1) {
  2349. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2350. this.width = width;
  2351. this.height = height;
  2352. this.depth = depth;
  2353. for (let i = 0, il = this.texture.length; i < il; i++) {
  2354. this.texture[i].image.width = width;
  2355. this.texture[i].image.height = height;
  2356. this.texture[i].image.depth = depth;
  2357. }
  2358. this.dispose();
  2359. }
  2360. this.viewport.set(0, 0, width, height);
  2361. this.scissor.set(0, 0, width, height);
  2362. return this;
  2363. }
  2364. copy(source) {
  2365. this.dispose();
  2366. this.width = source.width;
  2367. this.height = source.height;
  2368. this.depth = source.depth;
  2369. this.viewport.set(0, 0, this.width, this.height);
  2370. this.scissor.set(0, 0, this.width, this.height);
  2371. this.depthBuffer = source.depthBuffer;
  2372. this.stencilBuffer = source.stencilBuffer;
  2373. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2374. this.texture.length = 0;
  2375. for (let i = 0, il = source.texture.length; i < il; i++) {
  2376. this.texture[i] = source.texture[i].clone();
  2377. this.texture[i].isRenderTargetTexture = true;
  2378. }
  2379. return this;
  2380. }
  2381. }
  2382. class Quaternion {
  2383. constructor(x = 0, y = 0, z = 0, w = 1) {
  2384. this.isQuaternion = true;
  2385. this._x = x;
  2386. this._y = y;
  2387. this._z = z;
  2388. this._w = w;
  2389. }
  2390. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2391. // fuzz-free, array-based Quaternion SLERP operation
  2392. let x0 = src0[srcOffset0 + 0],
  2393. y0 = src0[srcOffset0 + 1],
  2394. z0 = src0[srcOffset0 + 2],
  2395. w0 = src0[srcOffset0 + 3];
  2396. const x1 = src1[srcOffset1 + 0],
  2397. y1 = src1[srcOffset1 + 1],
  2398. z1 = src1[srcOffset1 + 2],
  2399. w1 = src1[srcOffset1 + 3];
  2400. if (t === 0) {
  2401. dst[dstOffset + 0] = x0;
  2402. dst[dstOffset + 1] = y0;
  2403. dst[dstOffset + 2] = z0;
  2404. dst[dstOffset + 3] = w0;
  2405. return;
  2406. }
  2407. if (t === 1) {
  2408. dst[dstOffset + 0] = x1;
  2409. dst[dstOffset + 1] = y1;
  2410. dst[dstOffset + 2] = z1;
  2411. dst[dstOffset + 3] = w1;
  2412. return;
  2413. }
  2414. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2415. let s = 1 - t;
  2416. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2417. dir = cos >= 0 ? 1 : -1,
  2418. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2419. if (sqrSin > Number.EPSILON) {
  2420. const sin = Math.sqrt(sqrSin),
  2421. len = Math.atan2(sin, cos * dir);
  2422. s = Math.sin(s * len) / sin;
  2423. t = Math.sin(t * len) / sin;
  2424. }
  2425. const tDir = t * dir;
  2426. x0 = x0 * s + x1 * tDir;
  2427. y0 = y0 * s + y1 * tDir;
  2428. z0 = z0 * s + z1 * tDir;
  2429. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2430. if (s === 1 - t) {
  2431. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2432. x0 *= f;
  2433. y0 *= f;
  2434. z0 *= f;
  2435. w0 *= f;
  2436. }
  2437. }
  2438. dst[dstOffset] = x0;
  2439. dst[dstOffset + 1] = y0;
  2440. dst[dstOffset + 2] = z0;
  2441. dst[dstOffset + 3] = w0;
  2442. }
  2443. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2444. const x0 = src0[srcOffset0];
  2445. const y0 = src0[srcOffset0 + 1];
  2446. const z0 = src0[srcOffset0 + 2];
  2447. const w0 = src0[srcOffset0 + 3];
  2448. const x1 = src1[srcOffset1];
  2449. const y1 = src1[srcOffset1 + 1];
  2450. const z1 = src1[srcOffset1 + 2];
  2451. const w1 = src1[srcOffset1 + 3];
  2452. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2453. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2454. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2455. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2456. return dst;
  2457. }
  2458. get x() {
  2459. return this._x;
  2460. }
  2461. set x(value) {
  2462. this._x = value;
  2463. this._onChangeCallback();
  2464. }
  2465. get y() {
  2466. return this._y;
  2467. }
  2468. set y(value) {
  2469. this._y = value;
  2470. this._onChangeCallback();
  2471. }
  2472. get z() {
  2473. return this._z;
  2474. }
  2475. set z(value) {
  2476. this._z = value;
  2477. this._onChangeCallback();
  2478. }
  2479. get w() {
  2480. return this._w;
  2481. }
  2482. set w(value) {
  2483. this._w = value;
  2484. this._onChangeCallback();
  2485. }
  2486. set(x, y, z, w) {
  2487. this._x = x;
  2488. this._y = y;
  2489. this._z = z;
  2490. this._w = w;
  2491. this._onChangeCallback();
  2492. return this;
  2493. }
  2494. clone() {
  2495. return new this.constructor(this._x, this._y, this._z, this._w);
  2496. }
  2497. copy(quaternion) {
  2498. this._x = quaternion.x;
  2499. this._y = quaternion.y;
  2500. this._z = quaternion.z;
  2501. this._w = quaternion.w;
  2502. this._onChangeCallback();
  2503. return this;
  2504. }
  2505. setFromEuler(euler, update) {
  2506. if (!(euler && euler.isEuler)) {
  2507. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2508. }
  2509. const x = euler._x,
  2510. y = euler._y,
  2511. z = euler._z,
  2512. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2513. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2514. // content/SpinCalc.m
  2515. const cos = Math.cos;
  2516. const sin = Math.sin;
  2517. const c1 = cos(x / 2);
  2518. const c2 = cos(y / 2);
  2519. const c3 = cos(z / 2);
  2520. const s1 = sin(x / 2);
  2521. const s2 = sin(y / 2);
  2522. const s3 = sin(z / 2);
  2523. switch (order) {
  2524. case 'XYZ':
  2525. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2526. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2527. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2528. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2529. break;
  2530. case 'YXZ':
  2531. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2532. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2533. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2534. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2535. break;
  2536. case 'ZXY':
  2537. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2538. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2539. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2540. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2541. break;
  2542. case 'ZYX':
  2543. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2544. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2545. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2546. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2547. break;
  2548. case 'YZX':
  2549. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2550. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2551. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2552. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2553. break;
  2554. case 'XZY':
  2555. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2556. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2557. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2558. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2559. break;
  2560. default:
  2561. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2562. }
  2563. if (update !== false) this._onChangeCallback();
  2564. return this;
  2565. }
  2566. setFromAxisAngle(axis, angle) {
  2567. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2568. // assumes axis is normalized
  2569. const halfAngle = angle / 2,
  2570. s = Math.sin(halfAngle);
  2571. this._x = axis.x * s;
  2572. this._y = axis.y * s;
  2573. this._z = axis.z * s;
  2574. this._w = Math.cos(halfAngle);
  2575. this._onChangeCallback();
  2576. return this;
  2577. }
  2578. setFromRotationMatrix(m) {
  2579. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2580. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2581. const te = m.elements,
  2582. m11 = te[0],
  2583. m12 = te[4],
  2584. m13 = te[8],
  2585. m21 = te[1],
  2586. m22 = te[5],
  2587. m23 = te[9],
  2588. m31 = te[2],
  2589. m32 = te[6],
  2590. m33 = te[10],
  2591. trace = m11 + m22 + m33;
  2592. if (trace > 0) {
  2593. const s = 0.5 / Math.sqrt(trace + 1.0);
  2594. this._w = 0.25 / s;
  2595. this._x = (m32 - m23) * s;
  2596. this._y = (m13 - m31) * s;
  2597. this._z = (m21 - m12) * s;
  2598. } else if (m11 > m22 && m11 > m33) {
  2599. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2600. this._w = (m32 - m23) / s;
  2601. this._x = 0.25 * s;
  2602. this._y = (m12 + m21) / s;
  2603. this._z = (m13 + m31) / s;
  2604. } else if (m22 > m33) {
  2605. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2606. this._w = (m13 - m31) / s;
  2607. this._x = (m12 + m21) / s;
  2608. this._y = 0.25 * s;
  2609. this._z = (m23 + m32) / s;
  2610. } else {
  2611. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2612. this._w = (m21 - m12) / s;
  2613. this._x = (m13 + m31) / s;
  2614. this._y = (m23 + m32) / s;
  2615. this._z = 0.25 * s;
  2616. }
  2617. this._onChangeCallback();
  2618. return this;
  2619. }
  2620. setFromUnitVectors(vFrom, vTo) {
  2621. // assumes direction vectors vFrom and vTo are normalized
  2622. let r = vFrom.dot(vTo) + 1;
  2623. if (r < Number.EPSILON) {
  2624. // vFrom and vTo point in opposite directions
  2625. r = 0;
  2626. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2627. this._x = -vFrom.y;
  2628. this._y = vFrom.x;
  2629. this._z = 0;
  2630. this._w = r;
  2631. } else {
  2632. this._x = 0;
  2633. this._y = -vFrom.z;
  2634. this._z = vFrom.y;
  2635. this._w = r;
  2636. }
  2637. } else {
  2638. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2639. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2640. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2641. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2642. this._w = r;
  2643. }
  2644. return this.normalize();
  2645. }
  2646. angleTo(q) {
  2647. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2648. }
  2649. rotateTowards(q, step) {
  2650. const angle = this.angleTo(q);
  2651. if (angle === 0) return this;
  2652. const t = Math.min(1, step / angle);
  2653. this.slerp(q, t);
  2654. return this;
  2655. }
  2656. identity() {
  2657. return this.set(0, 0, 0, 1);
  2658. }
  2659. invert() {
  2660. // quaternion is assumed to have unit length
  2661. return this.conjugate();
  2662. }
  2663. conjugate() {
  2664. this._x *= -1;
  2665. this._y *= -1;
  2666. this._z *= -1;
  2667. this._onChangeCallback();
  2668. return this;
  2669. }
  2670. dot(v) {
  2671. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2672. }
  2673. lengthSq() {
  2674. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2675. }
  2676. length() {
  2677. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2678. }
  2679. normalize() {
  2680. let l = this.length();
  2681. if (l === 0) {
  2682. this._x = 0;
  2683. this._y = 0;
  2684. this._z = 0;
  2685. this._w = 1;
  2686. } else {
  2687. l = 1 / l;
  2688. this._x = this._x * l;
  2689. this._y = this._y * l;
  2690. this._z = this._z * l;
  2691. this._w = this._w * l;
  2692. }
  2693. this._onChangeCallback();
  2694. return this;
  2695. }
  2696. multiply(q) {
  2697. return this.multiplyQuaternions(this, q);
  2698. }
  2699. premultiply(q) {
  2700. return this.multiplyQuaternions(q, this);
  2701. }
  2702. multiplyQuaternions(a, b) {
  2703. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2704. const qax = a._x,
  2705. qay = a._y,
  2706. qaz = a._z,
  2707. qaw = a._w;
  2708. const qbx = b._x,
  2709. qby = b._y,
  2710. qbz = b._z,
  2711. qbw = b._w;
  2712. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2713. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2714. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2715. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2716. this._onChangeCallback();
  2717. return this;
  2718. }
  2719. slerp(qb, t) {
  2720. if (t === 0) return this;
  2721. if (t === 1) return this.copy(qb);
  2722. const x = this._x,
  2723. y = this._y,
  2724. z = this._z,
  2725. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2726. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2727. if (cosHalfTheta < 0) {
  2728. this._w = -qb._w;
  2729. this._x = -qb._x;
  2730. this._y = -qb._y;
  2731. this._z = -qb._z;
  2732. cosHalfTheta = -cosHalfTheta;
  2733. } else {
  2734. this.copy(qb);
  2735. }
  2736. if (cosHalfTheta >= 1.0) {
  2737. this._w = w;
  2738. this._x = x;
  2739. this._y = y;
  2740. this._z = z;
  2741. return this;
  2742. }
  2743. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2744. if (sqrSinHalfTheta <= Number.EPSILON) {
  2745. const s = 1 - t;
  2746. this._w = s * w + t * this._w;
  2747. this._x = s * x + t * this._x;
  2748. this._y = s * y + t * this._y;
  2749. this._z = s * z + t * this._z;
  2750. this.normalize();
  2751. this._onChangeCallback();
  2752. return this;
  2753. }
  2754. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2755. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2756. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2757. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2758. this._w = w * ratioA + this._w * ratioB;
  2759. this._x = x * ratioA + this._x * ratioB;
  2760. this._y = y * ratioA + this._y * ratioB;
  2761. this._z = z * ratioA + this._z * ratioB;
  2762. this._onChangeCallback();
  2763. return this;
  2764. }
  2765. slerpQuaternions(qa, qb, t) {
  2766. return this.copy(qa).slerp(qb, t);
  2767. }
  2768. random() {
  2769. // Derived from http://planning.cs.uiuc.edu/node198.html
  2770. // Note, this source uses w, x, y, z ordering,
  2771. // so we swap the order below.
  2772. const u1 = Math.random();
  2773. const sqrt1u1 = Math.sqrt(1 - u1);
  2774. const sqrtu1 = Math.sqrt(u1);
  2775. const u2 = 2 * Math.PI * Math.random();
  2776. const u3 = 2 * Math.PI * Math.random();
  2777. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2778. }
  2779. equals(quaternion) {
  2780. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2781. }
  2782. fromArray(array, offset = 0) {
  2783. this._x = array[offset];
  2784. this._y = array[offset + 1];
  2785. this._z = array[offset + 2];
  2786. this._w = array[offset + 3];
  2787. this._onChangeCallback();
  2788. return this;
  2789. }
  2790. toArray(array = [], offset = 0) {
  2791. array[offset] = this._x;
  2792. array[offset + 1] = this._y;
  2793. array[offset + 2] = this._z;
  2794. array[offset + 3] = this._w;
  2795. return array;
  2796. }
  2797. fromBufferAttribute(attribute, index) {
  2798. this._x = attribute.getX(index);
  2799. this._y = attribute.getY(index);
  2800. this._z = attribute.getZ(index);
  2801. this._w = attribute.getW(index);
  2802. return this;
  2803. }
  2804. _onChange(callback) {
  2805. this._onChangeCallback = callback;
  2806. return this;
  2807. }
  2808. _onChangeCallback() {}
  2809. *[Symbol.iterator]() {
  2810. yield this._x;
  2811. yield this._y;
  2812. yield this._z;
  2813. yield this._w;
  2814. }
  2815. }
  2816. class Vector3 {
  2817. constructor(x = 0, y = 0, z = 0) {
  2818. Vector3.prototype.isVector3 = true;
  2819. this.x = x;
  2820. this.y = y;
  2821. this.z = z;
  2822. }
  2823. set(x, y, z) {
  2824. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2825. this.x = x;
  2826. this.y = y;
  2827. this.z = z;
  2828. return this;
  2829. }
  2830. setScalar(scalar) {
  2831. this.x = scalar;
  2832. this.y = scalar;
  2833. this.z = scalar;
  2834. return this;
  2835. }
  2836. setX(x) {
  2837. this.x = x;
  2838. return this;
  2839. }
  2840. setY(y) {
  2841. this.y = y;
  2842. return this;
  2843. }
  2844. setZ(z) {
  2845. this.z = z;
  2846. return this;
  2847. }
  2848. setComponent(index, value) {
  2849. switch (index) {
  2850. case 0:
  2851. this.x = value;
  2852. break;
  2853. case 1:
  2854. this.y = value;
  2855. break;
  2856. case 2:
  2857. this.z = value;
  2858. break;
  2859. default:
  2860. throw new Error('index is out of range: ' + index);
  2861. }
  2862. return this;
  2863. }
  2864. getComponent(index) {
  2865. switch (index) {
  2866. case 0:
  2867. return this.x;
  2868. case 1:
  2869. return this.y;
  2870. case 2:
  2871. return this.z;
  2872. default:
  2873. throw new Error('index is out of range: ' + index);
  2874. }
  2875. }
  2876. clone() {
  2877. return new this.constructor(this.x, this.y, this.z);
  2878. }
  2879. copy(v) {
  2880. this.x = v.x;
  2881. this.y = v.y;
  2882. this.z = v.z;
  2883. return this;
  2884. }
  2885. add(v) {
  2886. this.x += v.x;
  2887. this.y += v.y;
  2888. this.z += v.z;
  2889. return this;
  2890. }
  2891. addScalar(s) {
  2892. this.x += s;
  2893. this.y += s;
  2894. this.z += s;
  2895. return this;
  2896. }
  2897. addVectors(a, b) {
  2898. this.x = a.x + b.x;
  2899. this.y = a.y + b.y;
  2900. this.z = a.z + b.z;
  2901. return this;
  2902. }
  2903. addScaledVector(v, s) {
  2904. this.x += v.x * s;
  2905. this.y += v.y * s;
  2906. this.z += v.z * s;
  2907. return this;
  2908. }
  2909. sub(v) {
  2910. this.x -= v.x;
  2911. this.y -= v.y;
  2912. this.z -= v.z;
  2913. return this;
  2914. }
  2915. subScalar(s) {
  2916. this.x -= s;
  2917. this.y -= s;
  2918. this.z -= s;
  2919. return this;
  2920. }
  2921. subVectors(a, b) {
  2922. this.x = a.x - b.x;
  2923. this.y = a.y - b.y;
  2924. this.z = a.z - b.z;
  2925. return this;
  2926. }
  2927. multiply(v) {
  2928. this.x *= v.x;
  2929. this.y *= v.y;
  2930. this.z *= v.z;
  2931. return this;
  2932. }
  2933. multiplyScalar(scalar) {
  2934. this.x *= scalar;
  2935. this.y *= scalar;
  2936. this.z *= scalar;
  2937. return this;
  2938. }
  2939. multiplyVectors(a, b) {
  2940. this.x = a.x * b.x;
  2941. this.y = a.y * b.y;
  2942. this.z = a.z * b.z;
  2943. return this;
  2944. }
  2945. applyEuler(euler) {
  2946. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2947. }
  2948. applyAxisAngle(axis, angle) {
  2949. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2950. }
  2951. applyMatrix3(m) {
  2952. const x = this.x,
  2953. y = this.y,
  2954. z = this.z;
  2955. const e = m.elements;
  2956. this.x = e[0] * x + e[3] * y + e[6] * z;
  2957. this.y = e[1] * x + e[4] * y + e[7] * z;
  2958. this.z = e[2] * x + e[5] * y + e[8] * z;
  2959. return this;
  2960. }
  2961. applyNormalMatrix(m) {
  2962. return this.applyMatrix3(m).normalize();
  2963. }
  2964. applyMatrix4(m) {
  2965. const x = this.x,
  2966. y = this.y,
  2967. z = this.z;
  2968. const e = m.elements;
  2969. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2970. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2971. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2972. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2973. return this;
  2974. }
  2975. applyQuaternion(q) {
  2976. const x = this.x,
  2977. y = this.y,
  2978. z = this.z;
  2979. const qx = q.x,
  2980. qy = q.y,
  2981. qz = q.z,
  2982. qw = q.w; // calculate quat * vector
  2983. const ix = qw * x + qy * z - qz * y;
  2984. const iy = qw * y + qz * x - qx * z;
  2985. const iz = qw * z + qx * y - qy * x;
  2986. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2987. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2988. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2989. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2990. return this;
  2991. }
  2992. project(camera) {
  2993. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2994. }
  2995. unproject(camera) {
  2996. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2997. }
  2998. transformDirection(m) {
  2999. // input: THREE.Matrix4 affine matrix
  3000. // vector interpreted as a direction
  3001. const x = this.x,
  3002. y = this.y,
  3003. z = this.z;
  3004. const e = m.elements;
  3005. this.x = e[0] * x + e[4] * y + e[8] * z;
  3006. this.y = e[1] * x + e[5] * y + e[9] * z;
  3007. this.z = e[2] * x + e[6] * y + e[10] * z;
  3008. return this.normalize();
  3009. }
  3010. divide(v) {
  3011. this.x /= v.x;
  3012. this.y /= v.y;
  3013. this.z /= v.z;
  3014. return this;
  3015. }
  3016. divideScalar(scalar) {
  3017. return this.multiplyScalar(1 / scalar);
  3018. }
  3019. min(v) {
  3020. this.x = Math.min(this.x, v.x);
  3021. this.y = Math.min(this.y, v.y);
  3022. this.z = Math.min(this.z, v.z);
  3023. return this;
  3024. }
  3025. max(v) {
  3026. this.x = Math.max(this.x, v.x);
  3027. this.y = Math.max(this.y, v.y);
  3028. this.z = Math.max(this.z, v.z);
  3029. return this;
  3030. }
  3031. clamp(min, max) {
  3032. // assumes min < max, componentwise
  3033. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3034. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3035. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3036. return this;
  3037. }
  3038. clampScalar(minVal, maxVal) {
  3039. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3040. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3041. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3042. return this;
  3043. }
  3044. clampLength(min, max) {
  3045. const length = this.length();
  3046. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3047. }
  3048. floor() {
  3049. this.x = Math.floor(this.x);
  3050. this.y = Math.floor(this.y);
  3051. this.z = Math.floor(this.z);
  3052. return this;
  3053. }
  3054. ceil() {
  3055. this.x = Math.ceil(this.x);
  3056. this.y = Math.ceil(this.y);
  3057. this.z = Math.ceil(this.z);
  3058. return this;
  3059. }
  3060. round() {
  3061. this.x = Math.round(this.x);
  3062. this.y = Math.round(this.y);
  3063. this.z = Math.round(this.z);
  3064. return this;
  3065. }
  3066. roundToZero() {
  3067. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3068. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3069. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3070. return this;
  3071. }
  3072. negate() {
  3073. this.x = -this.x;
  3074. this.y = -this.y;
  3075. this.z = -this.z;
  3076. return this;
  3077. }
  3078. dot(v) {
  3079. return this.x * v.x + this.y * v.y + this.z * v.z;
  3080. } // TODO lengthSquared?
  3081. lengthSq() {
  3082. return this.x * this.x + this.y * this.y + this.z * this.z;
  3083. }
  3084. length() {
  3085. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3086. }
  3087. manhattanLength() {
  3088. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  3089. }
  3090. normalize() {
  3091. return this.divideScalar(this.length() || 1);
  3092. }
  3093. setLength(length) {
  3094. return this.normalize().multiplyScalar(length);
  3095. }
  3096. lerp(v, alpha) {
  3097. this.x += (v.x - this.x) * alpha;
  3098. this.y += (v.y - this.y) * alpha;
  3099. this.z += (v.z - this.z) * alpha;
  3100. return this;
  3101. }
  3102. lerpVectors(v1, v2, alpha) {
  3103. this.x = v1.x + (v2.x - v1.x) * alpha;
  3104. this.y = v1.y + (v2.y - v1.y) * alpha;
  3105. this.z = v1.z + (v2.z - v1.z) * alpha;
  3106. return this;
  3107. }
  3108. cross(v) {
  3109. return this.crossVectors(this, v);
  3110. }
  3111. crossVectors(a, b) {
  3112. const ax = a.x,
  3113. ay = a.y,
  3114. az = a.z;
  3115. const bx = b.x,
  3116. by = b.y,
  3117. bz = b.z;
  3118. this.x = ay * bz - az * by;
  3119. this.y = az * bx - ax * bz;
  3120. this.z = ax * by - ay * bx;
  3121. return this;
  3122. }
  3123. projectOnVector(v) {
  3124. const denominator = v.lengthSq();
  3125. if (denominator === 0) return this.set(0, 0, 0);
  3126. const scalar = v.dot(this) / denominator;
  3127. return this.copy(v).multiplyScalar(scalar);
  3128. }
  3129. projectOnPlane(planeNormal) {
  3130. _vector$c.copy(this).projectOnVector(planeNormal);
  3131. return this.sub(_vector$c);
  3132. }
  3133. reflect(normal) {
  3134. // reflect incident vector off plane orthogonal to normal
  3135. // normal is assumed to have unit length
  3136. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  3137. }
  3138. angleTo(v) {
  3139. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  3140. if (denominator === 0) return Math.PI / 2;
  3141. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  3142. return Math.acos(clamp(theta, -1, 1));
  3143. }
  3144. distanceTo(v) {
  3145. return Math.sqrt(this.distanceToSquared(v));
  3146. }
  3147. distanceToSquared(v) {
  3148. const dx = this.x - v.x,
  3149. dy = this.y - v.y,
  3150. dz = this.z - v.z;
  3151. return dx * dx + dy * dy + dz * dz;
  3152. }
  3153. manhattanDistanceTo(v) {
  3154. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  3155. }
  3156. setFromSpherical(s) {
  3157. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3158. }
  3159. setFromSphericalCoords(radius, phi, theta) {
  3160. const sinPhiRadius = Math.sin(phi) * radius;
  3161. this.x = sinPhiRadius * Math.sin(theta);
  3162. this.y = Math.cos(phi) * radius;
  3163. this.z = sinPhiRadius * Math.cos(theta);
  3164. return this;
  3165. }
  3166. setFromCylindrical(c) {
  3167. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3168. }
  3169. setFromCylindricalCoords(radius, theta, y) {
  3170. this.x = radius * Math.sin(theta);
  3171. this.y = y;
  3172. this.z = radius * Math.cos(theta);
  3173. return this;
  3174. }
  3175. setFromMatrixPosition(m) {
  3176. const e = m.elements;
  3177. this.x = e[12];
  3178. this.y = e[13];
  3179. this.z = e[14];
  3180. return this;
  3181. }
  3182. setFromMatrixScale(m) {
  3183. const sx = this.setFromMatrixColumn(m, 0).length();
  3184. const sy = this.setFromMatrixColumn(m, 1).length();
  3185. const sz = this.setFromMatrixColumn(m, 2).length();
  3186. this.x = sx;
  3187. this.y = sy;
  3188. this.z = sz;
  3189. return this;
  3190. }
  3191. setFromMatrixColumn(m, index) {
  3192. return this.fromArray(m.elements, index * 4);
  3193. }
  3194. setFromMatrix3Column(m, index) {
  3195. return this.fromArray(m.elements, index * 3);
  3196. }
  3197. setFromEuler(e) {
  3198. this.x = e._x;
  3199. this.y = e._y;
  3200. this.z = e._z;
  3201. return this;
  3202. }
  3203. equals(v) {
  3204. return v.x === this.x && v.y === this.y && v.z === this.z;
  3205. }
  3206. fromArray(array, offset = 0) {
  3207. this.x = array[offset];
  3208. this.y = array[offset + 1];
  3209. this.z = array[offset + 2];
  3210. return this;
  3211. }
  3212. toArray(array = [], offset = 0) {
  3213. array[offset] = this.x;
  3214. array[offset + 1] = this.y;
  3215. array[offset + 2] = this.z;
  3216. return array;
  3217. }
  3218. fromBufferAttribute(attribute, index) {
  3219. this.x = attribute.getX(index);
  3220. this.y = attribute.getY(index);
  3221. this.z = attribute.getZ(index);
  3222. return this;
  3223. }
  3224. random() {
  3225. this.x = Math.random();
  3226. this.y = Math.random();
  3227. this.z = Math.random();
  3228. return this;
  3229. }
  3230. randomDirection() {
  3231. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  3232. const u = (Math.random() - 0.5) * 2;
  3233. const t = Math.random() * Math.PI * 2;
  3234. const f = Math.sqrt(1 - u ** 2);
  3235. this.x = f * Math.cos(t);
  3236. this.y = f * Math.sin(t);
  3237. this.z = u;
  3238. return this;
  3239. }
  3240. *[Symbol.iterator]() {
  3241. yield this.x;
  3242. yield this.y;
  3243. yield this.z;
  3244. }
  3245. }
  3246. const _vector$c = /*@__PURE__*/new Vector3();
  3247. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  3248. class Box3 {
  3249. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  3250. this.isBox3 = true;
  3251. this.min = min;
  3252. this.max = max;
  3253. }
  3254. set(min, max) {
  3255. this.min.copy(min);
  3256. this.max.copy(max);
  3257. return this;
  3258. }
  3259. setFromArray(array) {
  3260. let minX = +Infinity;
  3261. let minY = +Infinity;
  3262. let minZ = +Infinity;
  3263. let maxX = -Infinity;
  3264. let maxY = -Infinity;
  3265. let maxZ = -Infinity;
  3266. for (let i = 0, l = array.length; i < l; i += 3) {
  3267. const x = array[i];
  3268. const y = array[i + 1];
  3269. const z = array[i + 2];
  3270. if (x < minX) minX = x;
  3271. if (y < minY) minY = y;
  3272. if (z < minZ) minZ = z;
  3273. if (x > maxX) maxX = x;
  3274. if (y > maxY) maxY = y;
  3275. if (z > maxZ) maxZ = z;
  3276. }
  3277. this.min.set(minX, minY, minZ);
  3278. this.max.set(maxX, maxY, maxZ);
  3279. return this;
  3280. }
  3281. setFromBufferAttribute(attribute) {
  3282. let minX = +Infinity;
  3283. let minY = +Infinity;
  3284. let minZ = +Infinity;
  3285. let maxX = -Infinity;
  3286. let maxY = -Infinity;
  3287. let maxZ = -Infinity;
  3288. for (let i = 0, l = attribute.count; i < l; i++) {
  3289. const x = attribute.getX(i);
  3290. const y = attribute.getY(i);
  3291. const z = attribute.getZ(i);
  3292. if (x < minX) minX = x;
  3293. if (y < minY) minY = y;
  3294. if (z < minZ) minZ = z;
  3295. if (x > maxX) maxX = x;
  3296. if (y > maxY) maxY = y;
  3297. if (z > maxZ) maxZ = z;
  3298. }
  3299. this.min.set(minX, minY, minZ);
  3300. this.max.set(maxX, maxY, maxZ);
  3301. return this;
  3302. }
  3303. setFromPoints(points) {
  3304. this.makeEmpty();
  3305. for (let i = 0, il = points.length; i < il; i++) {
  3306. this.expandByPoint(points[i]);
  3307. }
  3308. return this;
  3309. }
  3310. setFromCenterAndSize(center, size) {
  3311. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  3312. this.min.copy(center).sub(halfSize);
  3313. this.max.copy(center).add(halfSize);
  3314. return this;
  3315. }
  3316. setFromObject(object, precise = false) {
  3317. this.makeEmpty();
  3318. return this.expandByObject(object, precise);
  3319. }
  3320. clone() {
  3321. return new this.constructor().copy(this);
  3322. }
  3323. copy(box) {
  3324. this.min.copy(box.min);
  3325. this.max.copy(box.max);
  3326. return this;
  3327. }
  3328. makeEmpty() {
  3329. this.min.x = this.min.y = this.min.z = +Infinity;
  3330. this.max.x = this.max.y = this.max.z = -Infinity;
  3331. return this;
  3332. }
  3333. isEmpty() {
  3334. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3335. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3336. }
  3337. getCenter(target) {
  3338. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3339. }
  3340. getSize(target) {
  3341. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3342. }
  3343. expandByPoint(point) {
  3344. this.min.min(point);
  3345. this.max.max(point);
  3346. return this;
  3347. }
  3348. expandByVector(vector) {
  3349. this.min.sub(vector);
  3350. this.max.add(vector);
  3351. return this;
  3352. }
  3353. expandByScalar(scalar) {
  3354. this.min.addScalar(-scalar);
  3355. this.max.addScalar(scalar);
  3356. return this;
  3357. }
  3358. expandByObject(object, precise = false) {
  3359. // Computes the world-axis-aligned bounding box of an object (including its children),
  3360. // accounting for both the object's, and children's, world transforms
  3361. object.updateWorldMatrix(false, false);
  3362. const geometry = object.geometry;
  3363. if (geometry !== undefined) {
  3364. if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) {
  3365. const position = geometry.attributes.position;
  3366. for (let i = 0, l = position.count; i < l; i++) {
  3367. _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
  3368. this.expandByPoint(_vector$b);
  3369. }
  3370. } else {
  3371. if (geometry.boundingBox === null) {
  3372. geometry.computeBoundingBox();
  3373. }
  3374. _box$3.copy(geometry.boundingBox);
  3375. _box$3.applyMatrix4(object.matrixWorld);
  3376. this.union(_box$3);
  3377. }
  3378. }
  3379. const children = object.children;
  3380. for (let i = 0, l = children.length; i < l; i++) {
  3381. this.expandByObject(children[i], precise);
  3382. }
  3383. return this;
  3384. }
  3385. containsPoint(point) {
  3386. 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;
  3387. }
  3388. containsBox(box) {
  3389. 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;
  3390. }
  3391. getParameter(point, target) {
  3392. // This can potentially have a divide by zero if the box
  3393. // has a size dimension of 0.
  3394. 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));
  3395. }
  3396. intersectsBox(box) {
  3397. // using 6 splitting planes to rule out intersections.
  3398. 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;
  3399. }
  3400. intersectsSphere(sphere) {
  3401. // Find the point on the AABB closest to the sphere center.
  3402. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  3403. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3404. }
  3405. intersectsPlane(plane) {
  3406. // We compute the minimum and maximum dot product values. If those values
  3407. // are on the same side (back or front) of the plane, then there is no intersection.
  3408. let min, max;
  3409. if (plane.normal.x > 0) {
  3410. min = plane.normal.x * this.min.x;
  3411. max = plane.normal.x * this.max.x;
  3412. } else {
  3413. min = plane.normal.x * this.max.x;
  3414. max = plane.normal.x * this.min.x;
  3415. }
  3416. if (plane.normal.y > 0) {
  3417. min += plane.normal.y * this.min.y;
  3418. max += plane.normal.y * this.max.y;
  3419. } else {
  3420. min += plane.normal.y * this.max.y;
  3421. max += plane.normal.y * this.min.y;
  3422. }
  3423. if (plane.normal.z > 0) {
  3424. min += plane.normal.z * this.min.z;
  3425. max += plane.normal.z * this.max.z;
  3426. } else {
  3427. min += plane.normal.z * this.max.z;
  3428. max += plane.normal.z * this.min.z;
  3429. }
  3430. return min <= -plane.constant && max >= -plane.constant;
  3431. }
  3432. intersectsTriangle(triangle) {
  3433. if (this.isEmpty()) {
  3434. return false;
  3435. } // compute box center and extents
  3436. this.getCenter(_center);
  3437. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  3438. _v0$2.subVectors(triangle.a, _center);
  3439. _v1$7.subVectors(triangle.b, _center);
  3440. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  3441. _f0.subVectors(_v1$7, _v0$2);
  3442. _f1.subVectors(_v2$3, _v1$7);
  3443. _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
  3444. // 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
  3445. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3446. 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];
  3447. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  3448. return false;
  3449. } // test 3 face normals from the aabb
  3450. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3451. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  3452. return false;
  3453. } // finally testing the face normal of the triangle
  3454. // use already existing triangle edge vectors here
  3455. _triangleNormal.crossVectors(_f0, _f1);
  3456. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3457. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  3458. }
  3459. clampPoint(point, target) {
  3460. return target.copy(point).clamp(this.min, this.max);
  3461. }
  3462. distanceToPoint(point) {
  3463. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  3464. return clampedPoint.sub(point).length();
  3465. }
  3466. getBoundingSphere(target) {
  3467. this.getCenter(target.center);
  3468. target.radius = this.getSize(_vector$b).length() * 0.5;
  3469. return target;
  3470. }
  3471. intersect(box) {
  3472. this.min.max(box.min);
  3473. 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.
  3474. if (this.isEmpty()) this.makeEmpty();
  3475. return this;
  3476. }
  3477. union(box) {
  3478. this.min.min(box.min);
  3479. this.max.max(box.max);
  3480. return this;
  3481. }
  3482. applyMatrix4(matrix) {
  3483. // transform of empty box is an empty box.
  3484. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3485. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3486. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3487. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3488. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3489. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3490. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3491. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3492. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3493. this.setFromPoints(_points);
  3494. return this;
  3495. }
  3496. translate(offset) {
  3497. this.min.add(offset);
  3498. this.max.add(offset);
  3499. return this;
  3500. }
  3501. equals(box) {
  3502. return box.min.equals(this.min) && box.max.equals(this.max);
  3503. }
  3504. }
  3505. 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()];
  3506. const _vector$b = /*@__PURE__*/new Vector3();
  3507. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  3508. const _v0$2 = /*@__PURE__*/new Vector3();
  3509. const _v1$7 = /*@__PURE__*/new Vector3();
  3510. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  3511. const _f0 = /*@__PURE__*/new Vector3();
  3512. const _f1 = /*@__PURE__*/new Vector3();
  3513. const _f2 = /*@__PURE__*/new Vector3();
  3514. const _center = /*@__PURE__*/new Vector3();
  3515. const _extents = /*@__PURE__*/new Vector3();
  3516. const _triangleNormal = /*@__PURE__*/new Vector3();
  3517. const _testAxis = /*@__PURE__*/new Vector3();
  3518. function satForAxes(axes, v0, v1, v2, extents) {
  3519. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3520. _testAxis.fromArray(axes, i); // project the aabb onto the separating axis
  3521. 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
  3522. const p0 = v0.dot(_testAxis);
  3523. const p1 = v1.dot(_testAxis);
  3524. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  3525. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3526. // points of the projected triangle are outside the projected half-length of the aabb
  3527. // the axis is separating and we can exit
  3528. return false;
  3529. }
  3530. }
  3531. return true;
  3532. }
  3533. const _box$2 = /*@__PURE__*/new Box3();
  3534. const _v1$6 = /*@__PURE__*/new Vector3();
  3535. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  3536. const _toPoint = /*@__PURE__*/new Vector3();
  3537. class Sphere {
  3538. constructor(center = new Vector3(), radius = -1) {
  3539. this.center = center;
  3540. this.radius = radius;
  3541. }
  3542. set(center, radius) {
  3543. this.center.copy(center);
  3544. this.radius = radius;
  3545. return this;
  3546. }
  3547. setFromPoints(points, optionalCenter) {
  3548. const center = this.center;
  3549. if (optionalCenter !== undefined) {
  3550. center.copy(optionalCenter);
  3551. } else {
  3552. _box$2.setFromPoints(points).getCenter(center);
  3553. }
  3554. let maxRadiusSq = 0;
  3555. for (let i = 0, il = points.length; i < il; i++) {
  3556. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3557. }
  3558. this.radius = Math.sqrt(maxRadiusSq);
  3559. return this;
  3560. }
  3561. copy(sphere) {
  3562. this.center.copy(sphere.center);
  3563. this.radius = sphere.radius;
  3564. return this;
  3565. }
  3566. isEmpty() {
  3567. return this.radius < 0;
  3568. }
  3569. makeEmpty() {
  3570. this.center.set(0, 0, 0);
  3571. this.radius = -1;
  3572. return this;
  3573. }
  3574. containsPoint(point) {
  3575. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3576. }
  3577. distanceToPoint(point) {
  3578. return point.distanceTo(this.center) - this.radius;
  3579. }
  3580. intersectsSphere(sphere) {
  3581. const radiusSum = this.radius + sphere.radius;
  3582. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3583. }
  3584. intersectsBox(box) {
  3585. return box.intersectsSphere(this);
  3586. }
  3587. intersectsPlane(plane) {
  3588. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3589. }
  3590. clampPoint(point, target) {
  3591. const deltaLengthSq = this.center.distanceToSquared(point);
  3592. target.copy(point);
  3593. if (deltaLengthSq > this.radius * this.radius) {
  3594. target.sub(this.center).normalize();
  3595. target.multiplyScalar(this.radius).add(this.center);
  3596. }
  3597. return target;
  3598. }
  3599. getBoundingBox(target) {
  3600. if (this.isEmpty()) {
  3601. // Empty sphere produces empty bounding box
  3602. target.makeEmpty();
  3603. return target;
  3604. }
  3605. target.set(this.center, this.center);
  3606. target.expandByScalar(this.radius);
  3607. return target;
  3608. }
  3609. applyMatrix4(matrix) {
  3610. this.center.applyMatrix4(matrix);
  3611. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3612. return this;
  3613. }
  3614. translate(offset) {
  3615. this.center.add(offset);
  3616. return this;
  3617. }
  3618. expandByPoint(point) {
  3619. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3620. _toPoint.subVectors(point, this.center);
  3621. const lengthSq = _toPoint.lengthSq();
  3622. if (lengthSq > this.radius * this.radius) {
  3623. const length = Math.sqrt(lengthSq);
  3624. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3625. // and the other half to position. This gives a tighter enclosure, instead of if
  3626. // the whole missing distance were just added to radius.
  3627. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  3628. this.radius += missingRadiusHalf;
  3629. }
  3630. return this;
  3631. }
  3632. union(sphere) {
  3633. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3634. // To enclose another sphere into this sphere, we only need to enclose two points:
  3635. // 1) Enclose the farthest point on the other sphere into this sphere.
  3636. // 2) Enclose the opposite point of the farthest point into this sphere.
  3637. if (this.center.equals(sphere.center) === true) {
  3638. _toFarthestPoint.set(0, 0, 1).multiplyScalar(sphere.radius);
  3639. } else {
  3640. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  3641. }
  3642. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  3643. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  3644. return this;
  3645. }
  3646. equals(sphere) {
  3647. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3648. }
  3649. clone() {
  3650. return new this.constructor().copy(this);
  3651. }
  3652. }
  3653. const _vector$a = /*@__PURE__*/new Vector3();
  3654. const _segCenter = /*@__PURE__*/new Vector3();
  3655. const _segDir = /*@__PURE__*/new Vector3();
  3656. const _diff = /*@__PURE__*/new Vector3();
  3657. const _edge1 = /*@__PURE__*/new Vector3();
  3658. const _edge2 = /*@__PURE__*/new Vector3();
  3659. const _normal$1 = /*@__PURE__*/new Vector3();
  3660. class Ray {
  3661. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3662. this.origin = origin;
  3663. this.direction = direction;
  3664. }
  3665. set(origin, direction) {
  3666. this.origin.copy(origin);
  3667. this.direction.copy(direction);
  3668. return this;
  3669. }
  3670. copy(ray) {
  3671. this.origin.copy(ray.origin);
  3672. this.direction.copy(ray.direction);
  3673. return this;
  3674. }
  3675. at(t, target) {
  3676. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3677. }
  3678. lookAt(v) {
  3679. this.direction.copy(v).sub(this.origin).normalize();
  3680. return this;
  3681. }
  3682. recast(t) {
  3683. this.origin.copy(this.at(t, _vector$a));
  3684. return this;
  3685. }
  3686. closestPointToPoint(point, target) {
  3687. target.subVectors(point, this.origin);
  3688. const directionDistance = target.dot(this.direction);
  3689. if (directionDistance < 0) {
  3690. return target.copy(this.origin);
  3691. }
  3692. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3693. }
  3694. distanceToPoint(point) {
  3695. return Math.sqrt(this.distanceSqToPoint(point));
  3696. }
  3697. distanceSqToPoint(point) {
  3698. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3699. if (directionDistance < 0) {
  3700. return this.origin.distanceToSquared(point);
  3701. }
  3702. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3703. return _vector$a.distanceToSquared(point);
  3704. }
  3705. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3706. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3707. // It returns the min distance between the ray and the segment
  3708. // defined by v0 and v1
  3709. // It can also set two optional targets :
  3710. // - The closest point on the ray
  3711. // - The closest point on the segment
  3712. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3713. _segDir.copy(v1).sub(v0).normalize();
  3714. _diff.copy(this.origin).sub(_segCenter);
  3715. const segExtent = v0.distanceTo(v1) * 0.5;
  3716. const a01 = -this.direction.dot(_segDir);
  3717. const b0 = _diff.dot(this.direction);
  3718. const b1 = -_diff.dot(_segDir);
  3719. const c = _diff.lengthSq();
  3720. const det = Math.abs(1 - a01 * a01);
  3721. let s0, s1, sqrDist, extDet;
  3722. if (det > 0) {
  3723. // The ray and segment are not parallel.
  3724. s0 = a01 * b1 - b0;
  3725. s1 = a01 * b0 - b1;
  3726. extDet = segExtent * det;
  3727. if (s0 >= 0) {
  3728. if (s1 >= -extDet) {
  3729. if (s1 <= extDet) {
  3730. // region 0
  3731. // Minimum at interior points of ray and segment.
  3732. const invDet = 1 / det;
  3733. s0 *= invDet;
  3734. s1 *= invDet;
  3735. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3736. } else {
  3737. // region 1
  3738. s1 = segExtent;
  3739. s0 = Math.max(0, -(a01 * s1 + b0));
  3740. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3741. }
  3742. } else {
  3743. // region 5
  3744. s1 = -segExtent;
  3745. s0 = Math.max(0, -(a01 * s1 + b0));
  3746. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3747. }
  3748. } else {
  3749. if (s1 <= -extDet) {
  3750. // region 4
  3751. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3752. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3753. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3754. } else if (s1 <= extDet) {
  3755. // region 3
  3756. s0 = 0;
  3757. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3758. sqrDist = s1 * (s1 + 2 * b1) + c;
  3759. } else {
  3760. // region 2
  3761. s0 = Math.max(0, -(a01 * segExtent + b0));
  3762. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3763. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3764. }
  3765. }
  3766. } else {
  3767. // Ray and segment are parallel.
  3768. s1 = a01 > 0 ? -segExtent : segExtent;
  3769. s0 = Math.max(0, -(a01 * s1 + b0));
  3770. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3771. }
  3772. if (optionalPointOnRay) {
  3773. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3774. }
  3775. if (optionalPointOnSegment) {
  3776. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3777. }
  3778. return sqrDist;
  3779. }
  3780. intersectSphere(sphere, target) {
  3781. _vector$a.subVectors(sphere.center, this.origin);
  3782. const tca = _vector$a.dot(this.direction);
  3783. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3784. const radius2 = sphere.radius * sphere.radius;
  3785. if (d2 > radius2) return null;
  3786. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3787. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3788. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3789. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3790. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3791. // in order to always return an intersect point that is in front of the ray.
  3792. 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
  3793. return this.at(t0, target);
  3794. }
  3795. intersectsSphere(sphere) {
  3796. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3797. }
  3798. distanceToPlane(plane) {
  3799. const denominator = plane.normal.dot(this.direction);
  3800. if (denominator === 0) {
  3801. // line is coplanar, return origin
  3802. if (plane.distanceToPoint(this.origin) === 0) {
  3803. return 0;
  3804. } // Null is preferable to undefined since undefined means.... it is undefined
  3805. return null;
  3806. }
  3807. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3808. return t >= 0 ? t : null;
  3809. }
  3810. intersectPlane(plane, target) {
  3811. const t = this.distanceToPlane(plane);
  3812. if (t === null) {
  3813. return null;
  3814. }
  3815. return this.at(t, target);
  3816. }
  3817. intersectsPlane(plane) {
  3818. // check if the ray lies on the plane first
  3819. const distToPoint = plane.distanceToPoint(this.origin);
  3820. if (distToPoint === 0) {
  3821. return true;
  3822. }
  3823. const denominator = plane.normal.dot(this.direction);
  3824. if (denominator * distToPoint < 0) {
  3825. return true;
  3826. } // ray origin is behind the plane (and is pointing behind it)
  3827. return false;
  3828. }
  3829. intersectBox(box, target) {
  3830. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3831. const invdirx = 1 / this.direction.x,
  3832. invdiry = 1 / this.direction.y,
  3833. invdirz = 1 / this.direction.z;
  3834. const origin = this.origin;
  3835. if (invdirx >= 0) {
  3836. tmin = (box.min.x - origin.x) * invdirx;
  3837. tmax = (box.max.x - origin.x) * invdirx;
  3838. } else {
  3839. tmin = (box.max.x - origin.x) * invdirx;
  3840. tmax = (box.min.x - origin.x) * invdirx;
  3841. }
  3842. if (invdiry >= 0) {
  3843. tymin = (box.min.y - origin.y) * invdiry;
  3844. tymax = (box.max.y - origin.y) * invdiry;
  3845. } else {
  3846. tymin = (box.max.y - origin.y) * invdiry;
  3847. tymax = (box.min.y - origin.y) * invdiry;
  3848. }
  3849. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3850. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3851. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3852. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3853. if (invdirz >= 0) {
  3854. tzmin = (box.min.z - origin.z) * invdirz;
  3855. tzmax = (box.max.z - origin.z) * invdirz;
  3856. } else {
  3857. tzmin = (box.max.z - origin.z) * invdirz;
  3858. tzmax = (box.min.z - origin.z) * invdirz;
  3859. }
  3860. if (tmin > tzmax || tzmin > tmax) return null;
  3861. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3862. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3863. if (tmax < 0) return null;
  3864. return this.at(tmin >= 0 ? tmin : tmax, target);
  3865. }
  3866. intersectsBox(box) {
  3867. return this.intersectBox(box, _vector$a) !== null;
  3868. }
  3869. intersectTriangle(a, b, c, backfaceCulling, target) {
  3870. // Compute the offset origin, edges, and normal.
  3871. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3872. _edge1.subVectors(b, a);
  3873. _edge2.subVectors(c, a);
  3874. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3875. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3876. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3877. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3878. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3879. let DdN = this.direction.dot(_normal$1);
  3880. let sign;
  3881. if (DdN > 0) {
  3882. if (backfaceCulling) return null;
  3883. sign = 1;
  3884. } else if (DdN < 0) {
  3885. sign = -1;
  3886. DdN = -DdN;
  3887. } else {
  3888. return null;
  3889. }
  3890. _diff.subVectors(this.origin, a);
  3891. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3892. if (DdQxE2 < 0) {
  3893. return null;
  3894. }
  3895. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3896. if (DdE1xQ < 0) {
  3897. return null;
  3898. } // b1+b2 > 1, no intersection
  3899. if (DdQxE2 + DdE1xQ > DdN) {
  3900. return null;
  3901. } // Line intersects triangle, check if ray does.
  3902. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3903. if (QdN < 0) {
  3904. return null;
  3905. } // Ray intersects triangle.
  3906. return this.at(QdN / DdN, target);
  3907. }
  3908. applyMatrix4(matrix4) {
  3909. this.origin.applyMatrix4(matrix4);
  3910. this.direction.transformDirection(matrix4);
  3911. return this;
  3912. }
  3913. equals(ray) {
  3914. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3915. }
  3916. clone() {
  3917. return new this.constructor().copy(this);
  3918. }
  3919. }
  3920. class Matrix4 {
  3921. constructor() {
  3922. Matrix4.prototype.isMatrix4 = true;
  3923. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3924. }
  3925. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3926. const te = this.elements;
  3927. te[0] = n11;
  3928. te[4] = n12;
  3929. te[8] = n13;
  3930. te[12] = n14;
  3931. te[1] = n21;
  3932. te[5] = n22;
  3933. te[9] = n23;
  3934. te[13] = n24;
  3935. te[2] = n31;
  3936. te[6] = n32;
  3937. te[10] = n33;
  3938. te[14] = n34;
  3939. te[3] = n41;
  3940. te[7] = n42;
  3941. te[11] = n43;
  3942. te[15] = n44;
  3943. return this;
  3944. }
  3945. identity() {
  3946. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3947. return this;
  3948. }
  3949. clone() {
  3950. return new Matrix4().fromArray(this.elements);
  3951. }
  3952. copy(m) {
  3953. const te = this.elements;
  3954. const me = m.elements;
  3955. te[0] = me[0];
  3956. te[1] = me[1];
  3957. te[2] = me[2];
  3958. te[3] = me[3];
  3959. te[4] = me[4];
  3960. te[5] = me[5];
  3961. te[6] = me[6];
  3962. te[7] = me[7];
  3963. te[8] = me[8];
  3964. te[9] = me[9];
  3965. te[10] = me[10];
  3966. te[11] = me[11];
  3967. te[12] = me[12];
  3968. te[13] = me[13];
  3969. te[14] = me[14];
  3970. te[15] = me[15];
  3971. return this;
  3972. }
  3973. copyPosition(m) {
  3974. const te = this.elements,
  3975. me = m.elements;
  3976. te[12] = me[12];
  3977. te[13] = me[13];
  3978. te[14] = me[14];
  3979. return this;
  3980. }
  3981. setFromMatrix3(m) {
  3982. const me = m.elements;
  3983. 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);
  3984. return this;
  3985. }
  3986. extractBasis(xAxis, yAxis, zAxis) {
  3987. xAxis.setFromMatrixColumn(this, 0);
  3988. yAxis.setFromMatrixColumn(this, 1);
  3989. zAxis.setFromMatrixColumn(this, 2);
  3990. return this;
  3991. }
  3992. makeBasis(xAxis, yAxis, zAxis) {
  3993. 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);
  3994. return this;
  3995. }
  3996. extractRotation(m) {
  3997. // this method does not support reflection matrices
  3998. const te = this.elements;
  3999. const me = m.elements;
  4000. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  4001. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  4002. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  4003. te[0] = me[0] * scaleX;
  4004. te[1] = me[1] * scaleX;
  4005. te[2] = me[2] * scaleX;
  4006. te[3] = 0;
  4007. te[4] = me[4] * scaleY;
  4008. te[5] = me[5] * scaleY;
  4009. te[6] = me[6] * scaleY;
  4010. te[7] = 0;
  4011. te[8] = me[8] * scaleZ;
  4012. te[9] = me[9] * scaleZ;
  4013. te[10] = me[10] * scaleZ;
  4014. te[11] = 0;
  4015. te[12] = 0;
  4016. te[13] = 0;
  4017. te[14] = 0;
  4018. te[15] = 1;
  4019. return this;
  4020. }
  4021. makeRotationFromEuler(euler) {
  4022. const te = this.elements;
  4023. const x = euler.x,
  4024. y = euler.y,
  4025. z = euler.z;
  4026. const a = Math.cos(x),
  4027. b = Math.sin(x);
  4028. const c = Math.cos(y),
  4029. d = Math.sin(y);
  4030. const e = Math.cos(z),
  4031. f = Math.sin(z);
  4032. if (euler.order === 'XYZ') {
  4033. const ae = a * e,
  4034. af = a * f,
  4035. be = b * e,
  4036. bf = b * f;
  4037. te[0] = c * e;
  4038. te[4] = -c * f;
  4039. te[8] = d;
  4040. te[1] = af + be * d;
  4041. te[5] = ae - bf * d;
  4042. te[9] = -b * c;
  4043. te[2] = bf - ae * d;
  4044. te[6] = be + af * d;
  4045. te[10] = a * c;
  4046. } else if (euler.order === 'YXZ') {
  4047. const ce = c * e,
  4048. cf = c * f,
  4049. de = d * e,
  4050. df = d * f;
  4051. te[0] = ce + df * b;
  4052. te[4] = de * b - cf;
  4053. te[8] = a * d;
  4054. te[1] = a * f;
  4055. te[5] = a * e;
  4056. te[9] = -b;
  4057. te[2] = cf * b - de;
  4058. te[6] = df + ce * b;
  4059. te[10] = a * c;
  4060. } else if (euler.order === 'ZXY') {
  4061. const ce = c * e,
  4062. cf = c * f,
  4063. de = d * e,
  4064. df = d * f;
  4065. te[0] = ce - df * b;
  4066. te[4] = -a * f;
  4067. te[8] = de + cf * b;
  4068. te[1] = cf + de * b;
  4069. te[5] = a * e;
  4070. te[9] = df - ce * b;
  4071. te[2] = -a * d;
  4072. te[6] = b;
  4073. te[10] = a * c;
  4074. } else if (euler.order === 'ZYX') {
  4075. const ae = a * e,
  4076. af = a * f,
  4077. be = b * e,
  4078. bf = b * f;
  4079. te[0] = c * e;
  4080. te[4] = be * d - af;
  4081. te[8] = ae * d + bf;
  4082. te[1] = c * f;
  4083. te[5] = bf * d + ae;
  4084. te[9] = af * d - be;
  4085. te[2] = -d;
  4086. te[6] = b * c;
  4087. te[10] = a * c;
  4088. } else if (euler.order === 'YZX') {
  4089. const ac = a * c,
  4090. ad = a * d,
  4091. bc = b * c,
  4092. bd = b * d;
  4093. te[0] = c * e;
  4094. te[4] = bd - ac * f;
  4095. te[8] = bc * f + ad;
  4096. te[1] = f;
  4097. te[5] = a * e;
  4098. te[9] = -b * e;
  4099. te[2] = -d * e;
  4100. te[6] = ad * f + bc;
  4101. te[10] = ac - bd * f;
  4102. } else if (euler.order === 'XZY') {
  4103. const ac = a * c,
  4104. ad = a * d,
  4105. bc = b * c,
  4106. bd = b * d;
  4107. te[0] = c * e;
  4108. te[4] = -f;
  4109. te[8] = d * e;
  4110. te[1] = ac * f + bd;
  4111. te[5] = a * e;
  4112. te[9] = ad * f - bc;
  4113. te[2] = bc * f - ad;
  4114. te[6] = b * e;
  4115. te[10] = bd * f + ac;
  4116. } // bottom row
  4117. te[3] = 0;
  4118. te[7] = 0;
  4119. te[11] = 0; // last column
  4120. te[12] = 0;
  4121. te[13] = 0;
  4122. te[14] = 0;
  4123. te[15] = 1;
  4124. return this;
  4125. }
  4126. makeRotationFromQuaternion(q) {
  4127. return this.compose(_zero, q, _one);
  4128. }
  4129. lookAt(eye, target, up) {
  4130. const te = this.elements;
  4131. _z.subVectors(eye, target);
  4132. if (_z.lengthSq() === 0) {
  4133. // eye and target are in the same position
  4134. _z.z = 1;
  4135. }
  4136. _z.normalize();
  4137. _x.crossVectors(up, _z);
  4138. if (_x.lengthSq() === 0) {
  4139. // up and z are parallel
  4140. if (Math.abs(up.z) === 1) {
  4141. _z.x += 0.0001;
  4142. } else {
  4143. _z.z += 0.0001;
  4144. }
  4145. _z.normalize();
  4146. _x.crossVectors(up, _z);
  4147. }
  4148. _x.normalize();
  4149. _y.crossVectors(_z, _x);
  4150. te[0] = _x.x;
  4151. te[4] = _y.x;
  4152. te[8] = _z.x;
  4153. te[1] = _x.y;
  4154. te[5] = _y.y;
  4155. te[9] = _z.y;
  4156. te[2] = _x.z;
  4157. te[6] = _y.z;
  4158. te[10] = _z.z;
  4159. return this;
  4160. }
  4161. multiply(m) {
  4162. return this.multiplyMatrices(this, m);
  4163. }
  4164. premultiply(m) {
  4165. return this.multiplyMatrices(m, this);
  4166. }
  4167. multiplyMatrices(a, b) {
  4168. const ae = a.elements;
  4169. const be = b.elements;
  4170. const te = this.elements;
  4171. const a11 = ae[0],
  4172. a12 = ae[4],
  4173. a13 = ae[8],
  4174. a14 = ae[12];
  4175. const a21 = ae[1],
  4176. a22 = ae[5],
  4177. a23 = ae[9],
  4178. a24 = ae[13];
  4179. const a31 = ae[2],
  4180. a32 = ae[6],
  4181. a33 = ae[10],
  4182. a34 = ae[14];
  4183. const a41 = ae[3],
  4184. a42 = ae[7],
  4185. a43 = ae[11],
  4186. a44 = ae[15];
  4187. const b11 = be[0],
  4188. b12 = be[4],
  4189. b13 = be[8],
  4190. b14 = be[12];
  4191. const b21 = be[1],
  4192. b22 = be[5],
  4193. b23 = be[9],
  4194. b24 = be[13];
  4195. const b31 = be[2],
  4196. b32 = be[6],
  4197. b33 = be[10],
  4198. b34 = be[14];
  4199. const b41 = be[3],
  4200. b42 = be[7],
  4201. b43 = be[11],
  4202. b44 = be[15];
  4203. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4204. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4205. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4206. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4207. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4208. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4209. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4210. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4211. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4212. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4213. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4214. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4215. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4216. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4217. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4218. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4219. return this;
  4220. }
  4221. multiplyScalar(s) {
  4222. const te = this.elements;
  4223. te[0] *= s;
  4224. te[4] *= s;
  4225. te[8] *= s;
  4226. te[12] *= s;
  4227. te[1] *= s;
  4228. te[5] *= s;
  4229. te[9] *= s;
  4230. te[13] *= s;
  4231. te[2] *= s;
  4232. te[6] *= s;
  4233. te[10] *= s;
  4234. te[14] *= s;
  4235. te[3] *= s;
  4236. te[7] *= s;
  4237. te[11] *= s;
  4238. te[15] *= s;
  4239. return this;
  4240. }
  4241. determinant() {
  4242. const te = this.elements;
  4243. const n11 = te[0],
  4244. n12 = te[4],
  4245. n13 = te[8],
  4246. n14 = te[12];
  4247. const n21 = te[1],
  4248. n22 = te[5],
  4249. n23 = te[9],
  4250. n24 = te[13];
  4251. const n31 = te[2],
  4252. n32 = te[6],
  4253. n33 = te[10],
  4254. n34 = te[14];
  4255. const n41 = te[3],
  4256. n42 = te[7],
  4257. n43 = te[11],
  4258. n44 = te[15]; //TODO: make this more efficient
  4259. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4260. 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);
  4261. }
  4262. transpose() {
  4263. const te = this.elements;
  4264. let tmp;
  4265. tmp = te[1];
  4266. te[1] = te[4];
  4267. te[4] = tmp;
  4268. tmp = te[2];
  4269. te[2] = te[8];
  4270. te[8] = tmp;
  4271. tmp = te[6];
  4272. te[6] = te[9];
  4273. te[9] = tmp;
  4274. tmp = te[3];
  4275. te[3] = te[12];
  4276. te[12] = tmp;
  4277. tmp = te[7];
  4278. te[7] = te[13];
  4279. te[13] = tmp;
  4280. tmp = te[11];
  4281. te[11] = te[14];
  4282. te[14] = tmp;
  4283. return this;
  4284. }
  4285. setPosition(x, y, z) {
  4286. const te = this.elements;
  4287. if (x.isVector3) {
  4288. te[12] = x.x;
  4289. te[13] = x.y;
  4290. te[14] = x.z;
  4291. } else {
  4292. te[12] = x;
  4293. te[13] = y;
  4294. te[14] = z;
  4295. }
  4296. return this;
  4297. }
  4298. invert() {
  4299. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4300. const te = this.elements,
  4301. n11 = te[0],
  4302. n21 = te[1],
  4303. n31 = te[2],
  4304. n41 = te[3],
  4305. n12 = te[4],
  4306. n22 = te[5],
  4307. n32 = te[6],
  4308. n42 = te[7],
  4309. n13 = te[8],
  4310. n23 = te[9],
  4311. n33 = te[10],
  4312. n43 = te[11],
  4313. n14 = te[12],
  4314. n24 = te[13],
  4315. n34 = te[14],
  4316. n44 = te[15],
  4317. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4318. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4319. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4320. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4321. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4322. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4323. const detInv = 1 / det;
  4324. te[0] = t11 * detInv;
  4325. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4326. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4327. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4328. te[4] = t12 * detInv;
  4329. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4330. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4331. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4332. te[8] = t13 * detInv;
  4333. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4334. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4335. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4336. te[12] = t14 * detInv;
  4337. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4338. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4339. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4340. return this;
  4341. }
  4342. scale(v) {
  4343. const te = this.elements;
  4344. const x = v.x,
  4345. y = v.y,
  4346. z = v.z;
  4347. te[0] *= x;
  4348. te[4] *= y;
  4349. te[8] *= z;
  4350. te[1] *= x;
  4351. te[5] *= y;
  4352. te[9] *= z;
  4353. te[2] *= x;
  4354. te[6] *= y;
  4355. te[10] *= z;
  4356. te[3] *= x;
  4357. te[7] *= y;
  4358. te[11] *= z;
  4359. return this;
  4360. }
  4361. getMaxScaleOnAxis() {
  4362. const te = this.elements;
  4363. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4364. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4365. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4366. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4367. }
  4368. makeTranslation(x, y, z) {
  4369. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4370. return this;
  4371. }
  4372. makeRotationX(theta) {
  4373. const c = Math.cos(theta),
  4374. s = Math.sin(theta);
  4375. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4376. return this;
  4377. }
  4378. makeRotationY(theta) {
  4379. const c = Math.cos(theta),
  4380. s = Math.sin(theta);
  4381. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4382. return this;
  4383. }
  4384. makeRotationZ(theta) {
  4385. const c = Math.cos(theta),
  4386. s = Math.sin(theta);
  4387. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4388. return this;
  4389. }
  4390. makeRotationAxis(axis, angle) {
  4391. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4392. const c = Math.cos(angle);
  4393. const s = Math.sin(angle);
  4394. const t = 1 - c;
  4395. const x = axis.x,
  4396. y = axis.y,
  4397. z = axis.z;
  4398. const tx = t * x,
  4399. ty = t * y;
  4400. 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);
  4401. return this;
  4402. }
  4403. makeScale(x, y, z) {
  4404. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4405. return this;
  4406. }
  4407. makeShear(xy, xz, yx, yz, zx, zy) {
  4408. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  4409. return this;
  4410. }
  4411. compose(position, quaternion, scale) {
  4412. const te = this.elements;
  4413. const x = quaternion._x,
  4414. y = quaternion._y,
  4415. z = quaternion._z,
  4416. w = quaternion._w;
  4417. const x2 = x + x,
  4418. y2 = y + y,
  4419. z2 = z + z;
  4420. const xx = x * x2,
  4421. xy = x * y2,
  4422. xz = x * z2;
  4423. const yy = y * y2,
  4424. yz = y * z2,
  4425. zz = z * z2;
  4426. const wx = w * x2,
  4427. wy = w * y2,
  4428. wz = w * z2;
  4429. const sx = scale.x,
  4430. sy = scale.y,
  4431. sz = scale.z;
  4432. te[0] = (1 - (yy + zz)) * sx;
  4433. te[1] = (xy + wz) * sx;
  4434. te[2] = (xz - wy) * sx;
  4435. te[3] = 0;
  4436. te[4] = (xy - wz) * sy;
  4437. te[5] = (1 - (xx + zz)) * sy;
  4438. te[6] = (yz + wx) * sy;
  4439. te[7] = 0;
  4440. te[8] = (xz + wy) * sz;
  4441. te[9] = (yz - wx) * sz;
  4442. te[10] = (1 - (xx + yy)) * sz;
  4443. te[11] = 0;
  4444. te[12] = position.x;
  4445. te[13] = position.y;
  4446. te[14] = position.z;
  4447. te[15] = 1;
  4448. return this;
  4449. }
  4450. decompose(position, quaternion, scale) {
  4451. const te = this.elements;
  4452. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  4453. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  4454. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4455. const det = this.determinant();
  4456. if (det < 0) sx = -sx;
  4457. position.x = te[12];
  4458. position.y = te[13];
  4459. position.z = te[14]; // scale the rotation part
  4460. _m1$2.copy(this);
  4461. const invSX = 1 / sx;
  4462. const invSY = 1 / sy;
  4463. const invSZ = 1 / sz;
  4464. _m1$2.elements[0] *= invSX;
  4465. _m1$2.elements[1] *= invSX;
  4466. _m1$2.elements[2] *= invSX;
  4467. _m1$2.elements[4] *= invSY;
  4468. _m1$2.elements[5] *= invSY;
  4469. _m1$2.elements[6] *= invSY;
  4470. _m1$2.elements[8] *= invSZ;
  4471. _m1$2.elements[9] *= invSZ;
  4472. _m1$2.elements[10] *= invSZ;
  4473. quaternion.setFromRotationMatrix(_m1$2);
  4474. scale.x = sx;
  4475. scale.y = sy;
  4476. scale.z = sz;
  4477. return this;
  4478. }
  4479. makePerspective(left, right, top, bottom, near, far) {
  4480. const te = this.elements;
  4481. const x = 2 * near / (right - left);
  4482. const y = 2 * near / (top - bottom);
  4483. const a = (right + left) / (right - left);
  4484. const b = (top + bottom) / (top - bottom);
  4485. const c = -(far + near) / (far - near);
  4486. const d = -2 * far * near / (far - near);
  4487. te[0] = x;
  4488. te[4] = 0;
  4489. te[8] = a;
  4490. te[12] = 0;
  4491. te[1] = 0;
  4492. te[5] = y;
  4493. te[9] = b;
  4494. te[13] = 0;
  4495. te[2] = 0;
  4496. te[6] = 0;
  4497. te[10] = c;
  4498. te[14] = d;
  4499. te[3] = 0;
  4500. te[7] = 0;
  4501. te[11] = -1;
  4502. te[15] = 0;
  4503. return this;
  4504. }
  4505. makeOrthographic(left, right, top, bottom, near, far) {
  4506. const te = this.elements;
  4507. const w = 1.0 / (right - left);
  4508. const h = 1.0 / (top - bottom);
  4509. const p = 1.0 / (far - near);
  4510. const x = (right + left) * w;
  4511. const y = (top + bottom) * h;
  4512. const z = (far + near) * p;
  4513. te[0] = 2 * w;
  4514. te[4] = 0;
  4515. te[8] = 0;
  4516. te[12] = -x;
  4517. te[1] = 0;
  4518. te[5] = 2 * h;
  4519. te[9] = 0;
  4520. te[13] = -y;
  4521. te[2] = 0;
  4522. te[6] = 0;
  4523. te[10] = -2 * p;
  4524. te[14] = -z;
  4525. te[3] = 0;
  4526. te[7] = 0;
  4527. te[11] = 0;
  4528. te[15] = 1;
  4529. return this;
  4530. }
  4531. equals(matrix) {
  4532. const te = this.elements;
  4533. const me = matrix.elements;
  4534. for (let i = 0; i < 16; i++) {
  4535. if (te[i] !== me[i]) return false;
  4536. }
  4537. return true;
  4538. }
  4539. fromArray(array, offset = 0) {
  4540. for (let i = 0; i < 16; i++) {
  4541. this.elements[i] = array[i + offset];
  4542. }
  4543. return this;
  4544. }
  4545. toArray(array = [], offset = 0) {
  4546. const te = this.elements;
  4547. array[offset] = te[0];
  4548. array[offset + 1] = te[1];
  4549. array[offset + 2] = te[2];
  4550. array[offset + 3] = te[3];
  4551. array[offset + 4] = te[4];
  4552. array[offset + 5] = te[5];
  4553. array[offset + 6] = te[6];
  4554. array[offset + 7] = te[7];
  4555. array[offset + 8] = te[8];
  4556. array[offset + 9] = te[9];
  4557. array[offset + 10] = te[10];
  4558. array[offset + 11] = te[11];
  4559. array[offset + 12] = te[12];
  4560. array[offset + 13] = te[13];
  4561. array[offset + 14] = te[14];
  4562. array[offset + 15] = te[15];
  4563. return array;
  4564. }
  4565. }
  4566. const _v1$5 = /*@__PURE__*/new Vector3();
  4567. const _m1$2 = /*@__PURE__*/new Matrix4();
  4568. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  4569. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  4570. const _x = /*@__PURE__*/new Vector3();
  4571. const _y = /*@__PURE__*/new Vector3();
  4572. const _z = /*@__PURE__*/new Vector3();
  4573. const _matrix$1 = /*@__PURE__*/new Matrix4();
  4574. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  4575. class Euler {
  4576. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4577. this.isEuler = true;
  4578. this._x = x;
  4579. this._y = y;
  4580. this._z = z;
  4581. this._order = order;
  4582. }
  4583. get x() {
  4584. return this._x;
  4585. }
  4586. set x(value) {
  4587. this._x = value;
  4588. this._onChangeCallback();
  4589. }
  4590. get y() {
  4591. return this._y;
  4592. }
  4593. set y(value) {
  4594. this._y = value;
  4595. this._onChangeCallback();
  4596. }
  4597. get z() {
  4598. return this._z;
  4599. }
  4600. set z(value) {
  4601. this._z = value;
  4602. this._onChangeCallback();
  4603. }
  4604. get order() {
  4605. return this._order;
  4606. }
  4607. set order(value) {
  4608. this._order = value;
  4609. this._onChangeCallback();
  4610. }
  4611. set(x, y, z, order = this._order) {
  4612. this._x = x;
  4613. this._y = y;
  4614. this._z = z;
  4615. this._order = order;
  4616. this._onChangeCallback();
  4617. return this;
  4618. }
  4619. clone() {
  4620. return new this.constructor(this._x, this._y, this._z, this._order);
  4621. }
  4622. copy(euler) {
  4623. this._x = euler._x;
  4624. this._y = euler._y;
  4625. this._z = euler._z;
  4626. this._order = euler._order;
  4627. this._onChangeCallback();
  4628. return this;
  4629. }
  4630. setFromRotationMatrix(m, order = this._order, update = true) {
  4631. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4632. const te = m.elements;
  4633. const m11 = te[0],
  4634. m12 = te[4],
  4635. m13 = te[8];
  4636. const m21 = te[1],
  4637. m22 = te[5],
  4638. m23 = te[9];
  4639. const m31 = te[2],
  4640. m32 = te[6],
  4641. m33 = te[10];
  4642. switch (order) {
  4643. case 'XYZ':
  4644. this._y = Math.asin(clamp(m13, -1, 1));
  4645. if (Math.abs(m13) < 0.9999999) {
  4646. this._x = Math.atan2(-m23, m33);
  4647. this._z = Math.atan2(-m12, m11);
  4648. } else {
  4649. this._x = Math.atan2(m32, m22);
  4650. this._z = 0;
  4651. }
  4652. break;
  4653. case 'YXZ':
  4654. this._x = Math.asin(-clamp(m23, -1, 1));
  4655. if (Math.abs(m23) < 0.9999999) {
  4656. this._y = Math.atan2(m13, m33);
  4657. this._z = Math.atan2(m21, m22);
  4658. } else {
  4659. this._y = Math.atan2(-m31, m11);
  4660. this._z = 0;
  4661. }
  4662. break;
  4663. case 'ZXY':
  4664. this._x = Math.asin(clamp(m32, -1, 1));
  4665. if (Math.abs(m32) < 0.9999999) {
  4666. this._y = Math.atan2(-m31, m33);
  4667. this._z = Math.atan2(-m12, m22);
  4668. } else {
  4669. this._y = 0;
  4670. this._z = Math.atan2(m21, m11);
  4671. }
  4672. break;
  4673. case 'ZYX':
  4674. this._y = Math.asin(-clamp(m31, -1, 1));
  4675. if (Math.abs(m31) < 0.9999999) {
  4676. this._x = Math.atan2(m32, m33);
  4677. this._z = Math.atan2(m21, m11);
  4678. } else {
  4679. this._x = 0;
  4680. this._z = Math.atan2(-m12, m22);
  4681. }
  4682. break;
  4683. case 'YZX':
  4684. this._z = Math.asin(clamp(m21, -1, 1));
  4685. if (Math.abs(m21) < 0.9999999) {
  4686. this._x = Math.atan2(-m23, m22);
  4687. this._y = Math.atan2(-m31, m11);
  4688. } else {
  4689. this._x = 0;
  4690. this._y = Math.atan2(m13, m33);
  4691. }
  4692. break;
  4693. case 'XZY':
  4694. this._z = Math.asin(-clamp(m12, -1, 1));
  4695. if (Math.abs(m12) < 0.9999999) {
  4696. this._x = Math.atan2(m32, m22);
  4697. this._y = Math.atan2(m13, m11);
  4698. } else {
  4699. this._x = Math.atan2(-m23, m33);
  4700. this._y = 0;
  4701. }
  4702. break;
  4703. default:
  4704. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4705. }
  4706. this._order = order;
  4707. if (update === true) this._onChangeCallback();
  4708. return this;
  4709. }
  4710. setFromQuaternion(q, order, update) {
  4711. _matrix$1.makeRotationFromQuaternion(q);
  4712. return this.setFromRotationMatrix(_matrix$1, order, update);
  4713. }
  4714. setFromVector3(v, order = this._order) {
  4715. return this.set(v.x, v.y, v.z, order);
  4716. }
  4717. reorder(newOrder) {
  4718. // WARNING: this discards revolution information -bhouston
  4719. _quaternion$3.setFromEuler(this);
  4720. return this.setFromQuaternion(_quaternion$3, newOrder);
  4721. }
  4722. equals(euler) {
  4723. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4724. }
  4725. fromArray(array) {
  4726. this._x = array[0];
  4727. this._y = array[1];
  4728. this._z = array[2];
  4729. if (array[3] !== undefined) this._order = array[3];
  4730. this._onChangeCallback();
  4731. return this;
  4732. }
  4733. toArray(array = [], offset = 0) {
  4734. array[offset] = this._x;
  4735. array[offset + 1] = this._y;
  4736. array[offset + 2] = this._z;
  4737. array[offset + 3] = this._order;
  4738. return array;
  4739. }
  4740. _onChange(callback) {
  4741. this._onChangeCallback = callback;
  4742. return this;
  4743. }
  4744. _onChangeCallback() {}
  4745. *[Symbol.iterator]() {
  4746. yield this._x;
  4747. yield this._y;
  4748. yield this._z;
  4749. yield this._order;
  4750. } // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4751. toVector3() {
  4752. console.error('THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead');
  4753. }
  4754. }
  4755. Euler.DefaultOrder = 'XYZ';
  4756. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4757. class Layers {
  4758. constructor() {
  4759. this.mask = 1 | 0;
  4760. }
  4761. set(channel) {
  4762. this.mask = (1 << channel | 0) >>> 0;
  4763. }
  4764. enable(channel) {
  4765. this.mask |= 1 << channel | 0;
  4766. }
  4767. enableAll() {
  4768. this.mask = 0xffffffff | 0;
  4769. }
  4770. toggle(channel) {
  4771. this.mask ^= 1 << channel | 0;
  4772. }
  4773. disable(channel) {
  4774. this.mask &= ~(1 << channel | 0);
  4775. }
  4776. disableAll() {
  4777. this.mask = 0;
  4778. }
  4779. test(layers) {
  4780. return (this.mask & layers.mask) !== 0;
  4781. }
  4782. isEnabled(channel) {
  4783. return (this.mask & (1 << channel | 0)) !== 0;
  4784. }
  4785. }
  4786. let _object3DId = 0;
  4787. const _v1$4 = /*@__PURE__*/new Vector3();
  4788. const _q1 = /*@__PURE__*/new Quaternion();
  4789. const _m1$1 = /*@__PURE__*/new Matrix4();
  4790. const _target = /*@__PURE__*/new Vector3();
  4791. const _position$3 = /*@__PURE__*/new Vector3();
  4792. const _scale$2 = /*@__PURE__*/new Vector3();
  4793. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4794. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4795. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4796. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4797. const _addedEvent = {
  4798. type: 'added'
  4799. };
  4800. const _removedEvent = {
  4801. type: 'removed'
  4802. };
  4803. class Object3D extends EventDispatcher {
  4804. constructor() {
  4805. super();
  4806. this.isObject3D = true;
  4807. Object.defineProperty(this, 'id', {
  4808. value: _object3DId++
  4809. });
  4810. this.uuid = generateUUID();
  4811. this.name = '';
  4812. this.type = 'Object3D';
  4813. this.parent = null;
  4814. this.children = [];
  4815. this.up = Object3D.DefaultUp.clone();
  4816. const position = new Vector3();
  4817. const rotation = new Euler();
  4818. const quaternion = new Quaternion();
  4819. const scale = new Vector3(1, 1, 1);
  4820. function onRotationChange() {
  4821. quaternion.setFromEuler(rotation, false);
  4822. }
  4823. function onQuaternionChange() {
  4824. rotation.setFromQuaternion(quaternion, undefined, false);
  4825. }
  4826. rotation._onChange(onRotationChange);
  4827. quaternion._onChange(onQuaternionChange);
  4828. Object.defineProperties(this, {
  4829. position: {
  4830. configurable: true,
  4831. enumerable: true,
  4832. value: position
  4833. },
  4834. rotation: {
  4835. configurable: true,
  4836. enumerable: true,
  4837. value: rotation
  4838. },
  4839. quaternion: {
  4840. configurable: true,
  4841. enumerable: true,
  4842. value: quaternion
  4843. },
  4844. scale: {
  4845. configurable: true,
  4846. enumerable: true,
  4847. value: scale
  4848. },
  4849. modelViewMatrix: {
  4850. value: new Matrix4()
  4851. },
  4852. normalMatrix: {
  4853. value: new Matrix3()
  4854. }
  4855. });
  4856. this.matrix = new Matrix4();
  4857. this.matrixWorld = new Matrix4();
  4858. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4859. this.matrixWorldNeedsUpdate = false;
  4860. this.layers = new Layers();
  4861. this.visible = true;
  4862. this.castShadow = false;
  4863. this.receiveShadow = false;
  4864. this.frustumCulled = true;
  4865. this.renderOrder = 0;
  4866. this.animations = [];
  4867. this.userData = {};
  4868. }
  4869. onBeforeRender() {}
  4870. onAfterRender() {}
  4871. applyMatrix4(matrix) {
  4872. if (this.matrixAutoUpdate) this.updateMatrix();
  4873. this.matrix.premultiply(matrix);
  4874. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4875. }
  4876. applyQuaternion(q) {
  4877. this.quaternion.premultiply(q);
  4878. return this;
  4879. }
  4880. setRotationFromAxisAngle(axis, angle) {
  4881. // assumes axis is normalized
  4882. this.quaternion.setFromAxisAngle(axis, angle);
  4883. }
  4884. setRotationFromEuler(euler) {
  4885. this.quaternion.setFromEuler(euler, true);
  4886. }
  4887. setRotationFromMatrix(m) {
  4888. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4889. this.quaternion.setFromRotationMatrix(m);
  4890. }
  4891. setRotationFromQuaternion(q) {
  4892. // assumes q is normalized
  4893. this.quaternion.copy(q);
  4894. }
  4895. rotateOnAxis(axis, angle) {
  4896. // rotate object on axis in object space
  4897. // axis is assumed to be normalized
  4898. _q1.setFromAxisAngle(axis, angle);
  4899. this.quaternion.multiply(_q1);
  4900. return this;
  4901. }
  4902. rotateOnWorldAxis(axis, angle) {
  4903. // rotate object on axis in world space
  4904. // axis is assumed to be normalized
  4905. // method assumes no rotated parent
  4906. _q1.setFromAxisAngle(axis, angle);
  4907. this.quaternion.premultiply(_q1);
  4908. return this;
  4909. }
  4910. rotateX(angle) {
  4911. return this.rotateOnAxis(_xAxis, angle);
  4912. }
  4913. rotateY(angle) {
  4914. return this.rotateOnAxis(_yAxis, angle);
  4915. }
  4916. rotateZ(angle) {
  4917. return this.rotateOnAxis(_zAxis, angle);
  4918. }
  4919. translateOnAxis(axis, distance) {
  4920. // translate object by distance along axis in object space
  4921. // axis is assumed to be normalized
  4922. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4923. this.position.add(_v1$4.multiplyScalar(distance));
  4924. return this;
  4925. }
  4926. translateX(distance) {
  4927. return this.translateOnAxis(_xAxis, distance);
  4928. }
  4929. translateY(distance) {
  4930. return this.translateOnAxis(_yAxis, distance);
  4931. }
  4932. translateZ(distance) {
  4933. return this.translateOnAxis(_zAxis, distance);
  4934. }
  4935. localToWorld(vector) {
  4936. return vector.applyMatrix4(this.matrixWorld);
  4937. }
  4938. worldToLocal(vector) {
  4939. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4940. }
  4941. lookAt(x, y, z) {
  4942. // This method does not support objects having non-uniformly-scaled parent(s)
  4943. if (x.isVector3) {
  4944. _target.copy(x);
  4945. } else {
  4946. _target.set(x, y, z);
  4947. }
  4948. const parent = this.parent;
  4949. this.updateWorldMatrix(true, false);
  4950. _position$3.setFromMatrixPosition(this.matrixWorld);
  4951. if (this.isCamera || this.isLight) {
  4952. _m1$1.lookAt(_position$3, _target, this.up);
  4953. } else {
  4954. _m1$1.lookAt(_target, _position$3, this.up);
  4955. }
  4956. this.quaternion.setFromRotationMatrix(_m1$1);
  4957. if (parent) {
  4958. _m1$1.extractRotation(parent.matrixWorld);
  4959. _q1.setFromRotationMatrix(_m1$1);
  4960. this.quaternion.premultiply(_q1.invert());
  4961. }
  4962. }
  4963. add(object) {
  4964. if (arguments.length > 1) {
  4965. for (let i = 0; i < arguments.length; i++) {
  4966. this.add(arguments[i]);
  4967. }
  4968. return this;
  4969. }
  4970. if (object === this) {
  4971. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4972. return this;
  4973. }
  4974. if (object && object.isObject3D) {
  4975. if (object.parent !== null) {
  4976. object.parent.remove(object);
  4977. }
  4978. object.parent = this;
  4979. this.children.push(object);
  4980. object.dispatchEvent(_addedEvent);
  4981. } else {
  4982. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4983. }
  4984. return this;
  4985. }
  4986. remove(object) {
  4987. if (arguments.length > 1) {
  4988. for (let i = 0; i < arguments.length; i++) {
  4989. this.remove(arguments[i]);
  4990. }
  4991. return this;
  4992. }
  4993. const index = this.children.indexOf(object);
  4994. if (index !== -1) {
  4995. object.parent = null;
  4996. this.children.splice(index, 1);
  4997. object.dispatchEvent(_removedEvent);
  4998. }
  4999. return this;
  5000. }
  5001. removeFromParent() {
  5002. const parent = this.parent;
  5003. if (parent !== null) {
  5004. parent.remove(this);
  5005. }
  5006. return this;
  5007. }
  5008. clear() {
  5009. for (let i = 0; i < this.children.length; i++) {
  5010. const object = this.children[i];
  5011. object.parent = null;
  5012. object.dispatchEvent(_removedEvent);
  5013. }
  5014. this.children.length = 0;
  5015. return this;
  5016. }
  5017. attach(object) {
  5018. // adds object as a child of this, while maintaining the object's world transform
  5019. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  5020. this.updateWorldMatrix(true, false);
  5021. _m1$1.copy(this.matrixWorld).invert();
  5022. if (object.parent !== null) {
  5023. object.parent.updateWorldMatrix(true, false);
  5024. _m1$1.multiply(object.parent.matrixWorld);
  5025. }
  5026. object.applyMatrix4(_m1$1);
  5027. this.add(object);
  5028. object.updateWorldMatrix(false, true);
  5029. return this;
  5030. }
  5031. getObjectById(id) {
  5032. return this.getObjectByProperty('id', id);
  5033. }
  5034. getObjectByName(name) {
  5035. return this.getObjectByProperty('name', name);
  5036. }
  5037. getObjectByProperty(name, value) {
  5038. if (this[name] === value) return this;
  5039. for (let i = 0, l = this.children.length; i < l; i++) {
  5040. const child = this.children[i];
  5041. const object = child.getObjectByProperty(name, value);
  5042. if (object !== undefined) {
  5043. return object;
  5044. }
  5045. }
  5046. return undefined;
  5047. }
  5048. getWorldPosition(target) {
  5049. this.updateWorldMatrix(true, false);
  5050. return target.setFromMatrixPosition(this.matrixWorld);
  5051. }
  5052. getWorldQuaternion(target) {
  5053. this.updateWorldMatrix(true, false);
  5054. this.matrixWorld.decompose(_position$3, target, _scale$2);
  5055. return target;
  5056. }
  5057. getWorldScale(target) {
  5058. this.updateWorldMatrix(true, false);
  5059. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  5060. return target;
  5061. }
  5062. getWorldDirection(target) {
  5063. this.updateWorldMatrix(true, false);
  5064. const e = this.matrixWorld.elements;
  5065. return target.set(e[8], e[9], e[10]).normalize();
  5066. }
  5067. raycast() {}
  5068. traverse(callback) {
  5069. callback(this);
  5070. const children = this.children;
  5071. for (let i = 0, l = children.length; i < l; i++) {
  5072. children[i].traverse(callback);
  5073. }
  5074. }
  5075. traverseVisible(callback) {
  5076. if (this.visible === false) return;
  5077. callback(this);
  5078. const children = this.children;
  5079. for (let i = 0, l = children.length; i < l; i++) {
  5080. children[i].traverseVisible(callback);
  5081. }
  5082. }
  5083. traverseAncestors(callback) {
  5084. const parent = this.parent;
  5085. if (parent !== null) {
  5086. callback(parent);
  5087. parent.traverseAncestors(callback);
  5088. }
  5089. }
  5090. updateMatrix() {
  5091. this.matrix.compose(this.position, this.quaternion, this.scale);
  5092. this.matrixWorldNeedsUpdate = true;
  5093. }
  5094. updateMatrixWorld(force) {
  5095. if (this.matrixAutoUpdate) this.updateMatrix();
  5096. if (this.matrixWorldNeedsUpdate || force) {
  5097. if (this.parent === null) {
  5098. this.matrixWorld.copy(this.matrix);
  5099. } else {
  5100. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5101. }
  5102. this.matrixWorldNeedsUpdate = false;
  5103. force = true;
  5104. } // update children
  5105. const children = this.children;
  5106. for (let i = 0, l = children.length; i < l; i++) {
  5107. children[i].updateMatrixWorld(force);
  5108. }
  5109. }
  5110. updateWorldMatrix(updateParents, updateChildren) {
  5111. const parent = this.parent;
  5112. if (updateParents === true && parent !== null) {
  5113. parent.updateWorldMatrix(true, false);
  5114. }
  5115. if (this.matrixAutoUpdate) this.updateMatrix();
  5116. if (this.parent === null) {
  5117. this.matrixWorld.copy(this.matrix);
  5118. } else {
  5119. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5120. } // update children
  5121. if (updateChildren === true) {
  5122. const children = this.children;
  5123. for (let i = 0, l = children.length; i < l; i++) {
  5124. children[i].updateWorldMatrix(false, true);
  5125. }
  5126. }
  5127. }
  5128. toJSON(meta) {
  5129. // meta is a string when called from JSON.stringify
  5130. const isRootObject = meta === undefined || typeof meta === 'string';
  5131. const output = {}; // meta is a hash used to collect geometries, materials.
  5132. // not providing it implies that this is the root object
  5133. // being serialized.
  5134. if (isRootObject) {
  5135. // initialize meta obj
  5136. meta = {
  5137. geometries: {},
  5138. materials: {},
  5139. textures: {},
  5140. images: {},
  5141. shapes: {},
  5142. skeletons: {},
  5143. animations: {},
  5144. nodes: {}
  5145. };
  5146. output.metadata = {
  5147. version: 4.5,
  5148. type: 'Object',
  5149. generator: 'Object3D.toJSON'
  5150. };
  5151. } // standard Object3D serialization
  5152. const object = {};
  5153. object.uuid = this.uuid;
  5154. object.type = this.type;
  5155. if (this.name !== '') object.name = this.name;
  5156. if (this.castShadow === true) object.castShadow = true;
  5157. if (this.receiveShadow === true) object.receiveShadow = true;
  5158. if (this.visible === false) object.visible = false;
  5159. if (this.frustumCulled === false) object.frustumCulled = false;
  5160. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5161. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5162. object.layers = this.layers.mask;
  5163. object.matrix = this.matrix.toArray();
  5164. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5165. if (this.isInstancedMesh) {
  5166. object.type = 'InstancedMesh';
  5167. object.count = this.count;
  5168. object.instanceMatrix = this.instanceMatrix.toJSON();
  5169. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  5170. } //
  5171. function serialize(library, element) {
  5172. if (library[element.uuid] === undefined) {
  5173. library[element.uuid] = element.toJSON(meta);
  5174. }
  5175. return element.uuid;
  5176. }
  5177. if (this.isScene) {
  5178. if (this.background) {
  5179. if (this.background.isColor) {
  5180. object.background = this.background.toJSON();
  5181. } else if (this.background.isTexture) {
  5182. object.background = this.background.toJSON(meta).uuid;
  5183. }
  5184. }
  5185. if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) {
  5186. object.environment = this.environment.toJSON(meta).uuid;
  5187. }
  5188. } else if (this.isMesh || this.isLine || this.isPoints) {
  5189. object.geometry = serialize(meta.geometries, this.geometry);
  5190. const parameters = this.geometry.parameters;
  5191. if (parameters !== undefined && parameters.shapes !== undefined) {
  5192. const shapes = parameters.shapes;
  5193. if (Array.isArray(shapes)) {
  5194. for (let i = 0, l = shapes.length; i < l; i++) {
  5195. const shape = shapes[i];
  5196. serialize(meta.shapes, shape);
  5197. }
  5198. } else {
  5199. serialize(meta.shapes, shapes);
  5200. }
  5201. }
  5202. }
  5203. if (this.isSkinnedMesh) {
  5204. object.bindMode = this.bindMode;
  5205. object.bindMatrix = this.bindMatrix.toArray();
  5206. if (this.skeleton !== undefined) {
  5207. serialize(meta.skeletons, this.skeleton);
  5208. object.skeleton = this.skeleton.uuid;
  5209. }
  5210. }
  5211. if (this.material !== undefined) {
  5212. if (Array.isArray(this.material)) {
  5213. const uuids = [];
  5214. for (let i = 0, l = this.material.length; i < l; i++) {
  5215. uuids.push(serialize(meta.materials, this.material[i]));
  5216. }
  5217. object.material = uuids;
  5218. } else {
  5219. object.material = serialize(meta.materials, this.material);
  5220. }
  5221. } //
  5222. if (this.children.length > 0) {
  5223. object.children = [];
  5224. for (let i = 0; i < this.children.length; i++) {
  5225. object.children.push(this.children[i].toJSON(meta).object);
  5226. }
  5227. } //
  5228. if (this.animations.length > 0) {
  5229. object.animations = [];
  5230. for (let i = 0; i < this.animations.length; i++) {
  5231. const animation = this.animations[i];
  5232. object.animations.push(serialize(meta.animations, animation));
  5233. }
  5234. }
  5235. if (isRootObject) {
  5236. const geometries = extractFromCache(meta.geometries);
  5237. const materials = extractFromCache(meta.materials);
  5238. const textures = extractFromCache(meta.textures);
  5239. const images = extractFromCache(meta.images);
  5240. const shapes = extractFromCache(meta.shapes);
  5241. const skeletons = extractFromCache(meta.skeletons);
  5242. const animations = extractFromCache(meta.animations);
  5243. const nodes = extractFromCache(meta.nodes);
  5244. if (geometries.length > 0) output.geometries = geometries;
  5245. if (materials.length > 0) output.materials = materials;
  5246. if (textures.length > 0) output.textures = textures;
  5247. if (images.length > 0) output.images = images;
  5248. if (shapes.length > 0) output.shapes = shapes;
  5249. if (skeletons.length > 0) output.skeletons = skeletons;
  5250. if (animations.length > 0) output.animations = animations;
  5251. if (nodes.length > 0) output.nodes = nodes;
  5252. }
  5253. output.object = object;
  5254. return output; // extract data from the cache hash
  5255. // remove metadata on each item
  5256. // and return as array
  5257. function extractFromCache(cache) {
  5258. const values = [];
  5259. for (const key in cache) {
  5260. const data = cache[key];
  5261. delete data.metadata;
  5262. values.push(data);
  5263. }
  5264. return values;
  5265. }
  5266. }
  5267. clone(recursive) {
  5268. return new this.constructor().copy(this, recursive);
  5269. }
  5270. copy(source, recursive = true) {
  5271. this.name = source.name;
  5272. this.up.copy(source.up);
  5273. this.position.copy(source.position);
  5274. this.rotation.order = source.rotation.order;
  5275. this.quaternion.copy(source.quaternion);
  5276. this.scale.copy(source.scale);
  5277. this.matrix.copy(source.matrix);
  5278. this.matrixWorld.copy(source.matrixWorld);
  5279. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5280. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5281. this.layers.mask = source.layers.mask;
  5282. this.visible = source.visible;
  5283. this.castShadow = source.castShadow;
  5284. this.receiveShadow = source.receiveShadow;
  5285. this.frustumCulled = source.frustumCulled;
  5286. this.renderOrder = source.renderOrder;
  5287. this.userData = JSON.parse(JSON.stringify(source.userData));
  5288. if (recursive === true) {
  5289. for (let i = 0; i < source.children.length; i++) {
  5290. const child = source.children[i];
  5291. this.add(child.clone());
  5292. }
  5293. }
  5294. return this;
  5295. }
  5296. }
  5297. Object3D.DefaultUp = /*@__PURE__*/new Vector3(0, 1, 0);
  5298. Object3D.DefaultMatrixAutoUpdate = true;
  5299. const _v0$1 = /*@__PURE__*/new Vector3();
  5300. const _v1$3 = /*@__PURE__*/new Vector3();
  5301. const _v2$2 = /*@__PURE__*/new Vector3();
  5302. const _v3$1 = /*@__PURE__*/new Vector3();
  5303. const _vab = /*@__PURE__*/new Vector3();
  5304. const _vac = /*@__PURE__*/new Vector3();
  5305. const _vbc = /*@__PURE__*/new Vector3();
  5306. const _vap = /*@__PURE__*/new Vector3();
  5307. const _vbp = /*@__PURE__*/new Vector3();
  5308. const _vcp = /*@__PURE__*/new Vector3();
  5309. class Triangle {
  5310. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  5311. this.a = a;
  5312. this.b = b;
  5313. this.c = c;
  5314. }
  5315. static getNormal(a, b, c, target) {
  5316. target.subVectors(c, b);
  5317. _v0$1.subVectors(a, b);
  5318. target.cross(_v0$1);
  5319. const targetLengthSq = target.lengthSq();
  5320. if (targetLengthSq > 0) {
  5321. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5322. }
  5323. return target.set(0, 0, 0);
  5324. } // static/instance method to calculate barycentric coordinates
  5325. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5326. static getBarycoord(point, a, b, c, target) {
  5327. _v0$1.subVectors(c, a);
  5328. _v1$3.subVectors(b, a);
  5329. _v2$2.subVectors(point, a);
  5330. const dot00 = _v0$1.dot(_v0$1);
  5331. const dot01 = _v0$1.dot(_v1$3);
  5332. const dot02 = _v0$1.dot(_v2$2);
  5333. const dot11 = _v1$3.dot(_v1$3);
  5334. const dot12 = _v1$3.dot(_v2$2);
  5335. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  5336. if (denom === 0) {
  5337. // arbitrary location outside of triangle?
  5338. // not sure if this is the best idea, maybe should be returning undefined
  5339. return target.set(-2, -1, -1);
  5340. }
  5341. const invDenom = 1 / denom;
  5342. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5343. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5344. return target.set(1 - u - v, v, u);
  5345. }
  5346. static containsPoint(point, a, b, c) {
  5347. this.getBarycoord(point, a, b, c, _v3$1);
  5348. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  5349. }
  5350. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5351. this.getBarycoord(point, p1, p2, p3, _v3$1);
  5352. target.set(0, 0);
  5353. target.addScaledVector(uv1, _v3$1.x);
  5354. target.addScaledVector(uv2, _v3$1.y);
  5355. target.addScaledVector(uv3, _v3$1.z);
  5356. return target;
  5357. }
  5358. static isFrontFacing(a, b, c, direction) {
  5359. _v0$1.subVectors(c, b);
  5360. _v1$3.subVectors(a, b); // strictly front facing
  5361. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5362. }
  5363. set(a, b, c) {
  5364. this.a.copy(a);
  5365. this.b.copy(b);
  5366. this.c.copy(c);
  5367. return this;
  5368. }
  5369. setFromPointsAndIndices(points, i0, i1, i2) {
  5370. this.a.copy(points[i0]);
  5371. this.b.copy(points[i1]);
  5372. this.c.copy(points[i2]);
  5373. return this;
  5374. }
  5375. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  5376. this.a.fromBufferAttribute(attribute, i0);
  5377. this.b.fromBufferAttribute(attribute, i1);
  5378. this.c.fromBufferAttribute(attribute, i2);
  5379. return this;
  5380. }
  5381. clone() {
  5382. return new this.constructor().copy(this);
  5383. }
  5384. copy(triangle) {
  5385. this.a.copy(triangle.a);
  5386. this.b.copy(triangle.b);
  5387. this.c.copy(triangle.c);
  5388. return this;
  5389. }
  5390. getArea() {
  5391. _v0$1.subVectors(this.c, this.b);
  5392. _v1$3.subVectors(this.a, this.b);
  5393. return _v0$1.cross(_v1$3).length() * 0.5;
  5394. }
  5395. getMidpoint(target) {
  5396. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5397. }
  5398. getNormal(target) {
  5399. return Triangle.getNormal(this.a, this.b, this.c, target);
  5400. }
  5401. getPlane(target) {
  5402. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5403. }
  5404. getBarycoord(point, target) {
  5405. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5406. }
  5407. getUV(point, uv1, uv2, uv3, target) {
  5408. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5409. }
  5410. containsPoint(point) {
  5411. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5412. }
  5413. isFrontFacing(direction) {
  5414. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5415. }
  5416. intersectsBox(box) {
  5417. return box.intersectsTriangle(this);
  5418. }
  5419. closestPointToPoint(p, target) {
  5420. const a = this.a,
  5421. b = this.b,
  5422. c = this.c;
  5423. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5424. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5425. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5426. // basically, we're distinguishing which of the voronoi regions of the triangle
  5427. // the point lies in with the minimum amount of redundant computation.
  5428. _vab.subVectors(b, a);
  5429. _vac.subVectors(c, a);
  5430. _vap.subVectors(p, a);
  5431. const d1 = _vab.dot(_vap);
  5432. const d2 = _vac.dot(_vap);
  5433. if (d1 <= 0 && d2 <= 0) {
  5434. // vertex region of A; barycentric coords (1, 0, 0)
  5435. return target.copy(a);
  5436. }
  5437. _vbp.subVectors(p, b);
  5438. const d3 = _vab.dot(_vbp);
  5439. const d4 = _vac.dot(_vbp);
  5440. if (d3 >= 0 && d4 <= d3) {
  5441. // vertex region of B; barycentric coords (0, 1, 0)
  5442. return target.copy(b);
  5443. }
  5444. const vc = d1 * d4 - d3 * d2;
  5445. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5446. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5447. return target.copy(a).addScaledVector(_vab, v);
  5448. }
  5449. _vcp.subVectors(p, c);
  5450. const d5 = _vab.dot(_vcp);
  5451. const d6 = _vac.dot(_vcp);
  5452. if (d6 >= 0 && d5 <= d6) {
  5453. // vertex region of C; barycentric coords (0, 0, 1)
  5454. return target.copy(c);
  5455. }
  5456. const vb = d5 * d2 - d1 * d6;
  5457. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5458. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5459. return target.copy(a).addScaledVector(_vac, w);
  5460. }
  5461. const va = d3 * d6 - d5 * d4;
  5462. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5463. _vbc.subVectors(c, b);
  5464. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5465. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5466. } // face region
  5467. const denom = 1 / (va + vb + vc); // u = va * denom
  5468. v = vb * denom;
  5469. w = vc * denom;
  5470. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5471. }
  5472. equals(triangle) {
  5473. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5474. }
  5475. }
  5476. let materialId = 0;
  5477. class Material extends EventDispatcher {
  5478. constructor() {
  5479. super();
  5480. this.isMaterial = true;
  5481. Object.defineProperty(this, 'id', {
  5482. value: materialId++
  5483. });
  5484. this.uuid = generateUUID();
  5485. this.name = '';
  5486. this.type = 'Material';
  5487. this.blending = NormalBlending;
  5488. this.side = FrontSide;
  5489. this.vertexColors = false;
  5490. this.opacity = 1;
  5491. this.transparent = false;
  5492. this.blendSrc = SrcAlphaFactor;
  5493. this.blendDst = OneMinusSrcAlphaFactor;
  5494. this.blendEquation = AddEquation;
  5495. this.blendSrcAlpha = null;
  5496. this.blendDstAlpha = null;
  5497. this.blendEquationAlpha = null;
  5498. this.depthFunc = LessEqualDepth;
  5499. this.depthTest = true;
  5500. this.depthWrite = true;
  5501. this.stencilWriteMask = 0xff;
  5502. this.stencilFunc = AlwaysStencilFunc;
  5503. this.stencilRef = 0;
  5504. this.stencilFuncMask = 0xff;
  5505. this.stencilFail = KeepStencilOp;
  5506. this.stencilZFail = KeepStencilOp;
  5507. this.stencilZPass = KeepStencilOp;
  5508. this.stencilWrite = false;
  5509. this.clippingPlanes = null;
  5510. this.clipIntersection = false;
  5511. this.clipShadows = false;
  5512. this.shadowSide = null;
  5513. this.colorWrite = true;
  5514. this.precision = null; // override the renderer's default precision for this material
  5515. this.polygonOffset = false;
  5516. this.polygonOffsetFactor = 0;
  5517. this.polygonOffsetUnits = 0;
  5518. this.dithering = false;
  5519. this.alphaToCoverage = false;
  5520. this.premultipliedAlpha = false;
  5521. this.visible = true;
  5522. this.toneMapped = true;
  5523. this.userData = {};
  5524. this.version = 0;
  5525. this._alphaTest = 0;
  5526. }
  5527. get alphaTest() {
  5528. return this._alphaTest;
  5529. }
  5530. set alphaTest(value) {
  5531. if (this._alphaTest > 0 !== value > 0) {
  5532. this.version++;
  5533. }
  5534. this._alphaTest = value;
  5535. }
  5536. onBuild() {}
  5537. onBeforeRender() {}
  5538. onBeforeCompile() {}
  5539. customProgramCacheKey() {
  5540. return this.onBeforeCompile.toString();
  5541. }
  5542. setValues(values) {
  5543. if (values === undefined) return;
  5544. for (const key in values) {
  5545. const newValue = values[key];
  5546. if (newValue === undefined) {
  5547. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5548. continue;
  5549. } // for backward compatibility if shading is set in the constructor
  5550. if (key === 'shading') {
  5551. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5552. this.flatShading = newValue === FlatShading ? true : false;
  5553. continue;
  5554. }
  5555. const currentValue = this[key];
  5556. if (currentValue === undefined) {
  5557. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5558. continue;
  5559. }
  5560. if (currentValue && currentValue.isColor) {
  5561. currentValue.set(newValue);
  5562. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5563. currentValue.copy(newValue);
  5564. } else {
  5565. this[key] = newValue;
  5566. }
  5567. }
  5568. }
  5569. toJSON(meta) {
  5570. const isRootObject = meta === undefined || typeof meta === 'string';
  5571. if (isRootObject) {
  5572. meta = {
  5573. textures: {},
  5574. images: {}
  5575. };
  5576. }
  5577. const data = {
  5578. metadata: {
  5579. version: 4.5,
  5580. type: 'Material',
  5581. generator: 'Material.toJSON'
  5582. }
  5583. }; // standard Material serialization
  5584. data.uuid = this.uuid;
  5585. data.type = this.type;
  5586. if (this.name !== '') data.name = this.name;
  5587. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5588. if (this.roughness !== undefined) data.roughness = this.roughness;
  5589. if (this.metalness !== undefined) data.metalness = this.metalness;
  5590. if (this.sheen !== undefined) data.sheen = this.sheen;
  5591. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  5592. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  5593. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5594. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5595. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5596. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  5597. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  5598. if (this.shininess !== undefined) data.shininess = this.shininess;
  5599. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5600. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5601. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5602. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5603. }
  5604. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5605. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5606. }
  5607. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5608. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5609. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5610. }
  5611. if (this.iridescence !== undefined) data.iridescence = this.iridescence;
  5612. if (this.iridescenceIOR !== undefined) data.iridescenceIOR = this.iridescenceIOR;
  5613. if (this.iridescenceThicknessRange !== undefined) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5614. if (this.iridescenceMap && this.iridescenceMap.isTexture) {
  5615. data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid;
  5616. }
  5617. if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) {
  5618. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid;
  5619. }
  5620. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5621. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5622. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5623. if (this.lightMap && this.lightMap.isTexture) {
  5624. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5625. data.lightMapIntensity = this.lightMapIntensity;
  5626. }
  5627. if (this.aoMap && this.aoMap.isTexture) {
  5628. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5629. data.aoMapIntensity = this.aoMapIntensity;
  5630. }
  5631. if (this.bumpMap && this.bumpMap.isTexture) {
  5632. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5633. data.bumpScale = this.bumpScale;
  5634. }
  5635. if (this.normalMap && this.normalMap.isTexture) {
  5636. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5637. data.normalMapType = this.normalMapType;
  5638. data.normalScale = this.normalScale.toArray();
  5639. }
  5640. if (this.displacementMap && this.displacementMap.isTexture) {
  5641. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5642. data.displacementScale = this.displacementScale;
  5643. data.displacementBias = this.displacementBias;
  5644. }
  5645. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5646. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5647. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5648. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5649. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5650. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5651. if (this.envMap && this.envMap.isTexture) {
  5652. data.envMap = this.envMap.toJSON(meta).uuid;
  5653. if (this.combine !== undefined) data.combine = this.combine;
  5654. }
  5655. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5656. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5657. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5658. if (this.gradientMap && this.gradientMap.isTexture) {
  5659. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5660. }
  5661. if (this.transmission !== undefined) data.transmission = this.transmission;
  5662. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5663. if (this.thickness !== undefined) data.thickness = this.thickness;
  5664. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5665. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5666. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5667. if (this.size !== undefined) data.size = this.size;
  5668. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5669. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5670. if (this.blending !== NormalBlending) data.blending = this.blending;
  5671. if (this.side !== FrontSide) data.side = this.side;
  5672. if (this.vertexColors) data.vertexColors = true;
  5673. if (this.opacity < 1) data.opacity = this.opacity;
  5674. if (this.transparent === true) data.transparent = this.transparent;
  5675. data.depthFunc = this.depthFunc;
  5676. data.depthTest = this.depthTest;
  5677. data.depthWrite = this.depthWrite;
  5678. data.colorWrite = this.colorWrite;
  5679. data.stencilWrite = this.stencilWrite;
  5680. data.stencilWriteMask = this.stencilWriteMask;
  5681. data.stencilFunc = this.stencilFunc;
  5682. data.stencilRef = this.stencilRef;
  5683. data.stencilFuncMask = this.stencilFuncMask;
  5684. data.stencilFail = this.stencilFail;
  5685. data.stencilZFail = this.stencilZFail;
  5686. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5687. if (this.rotation !== undefined && this.rotation !== 0) data.rotation = this.rotation;
  5688. if (this.polygonOffset === true) data.polygonOffset = true;
  5689. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5690. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5691. if (this.linewidth !== undefined && this.linewidth !== 1) data.linewidth = this.linewidth;
  5692. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5693. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5694. if (this.scale !== undefined) data.scale = this.scale;
  5695. if (this.dithering === true) data.dithering = true;
  5696. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5697. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5698. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5699. if (this.wireframe === true) data.wireframe = this.wireframe;
  5700. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5701. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5702. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5703. if (this.flatShading === true) data.flatShading = this.flatShading;
  5704. if (this.visible === false) data.visible = false;
  5705. if (this.toneMapped === false) data.toneMapped = false;
  5706. if (this.fog === false) data.fog = false;
  5707. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5708. function extractFromCache(cache) {
  5709. const values = [];
  5710. for (const key in cache) {
  5711. const data = cache[key];
  5712. delete data.metadata;
  5713. values.push(data);
  5714. }
  5715. return values;
  5716. }
  5717. if (isRootObject) {
  5718. const textures = extractFromCache(meta.textures);
  5719. const images = extractFromCache(meta.images);
  5720. if (textures.length > 0) data.textures = textures;
  5721. if (images.length > 0) data.images = images;
  5722. }
  5723. return data;
  5724. }
  5725. clone() {
  5726. return new this.constructor().copy(this);
  5727. }
  5728. copy(source) {
  5729. this.name = source.name;
  5730. this.blending = source.blending;
  5731. this.side = source.side;
  5732. this.vertexColors = source.vertexColors;
  5733. this.opacity = source.opacity;
  5734. this.transparent = source.transparent;
  5735. this.blendSrc = source.blendSrc;
  5736. this.blendDst = source.blendDst;
  5737. this.blendEquation = source.blendEquation;
  5738. this.blendSrcAlpha = source.blendSrcAlpha;
  5739. this.blendDstAlpha = source.blendDstAlpha;
  5740. this.blendEquationAlpha = source.blendEquationAlpha;
  5741. this.depthFunc = source.depthFunc;
  5742. this.depthTest = source.depthTest;
  5743. this.depthWrite = source.depthWrite;
  5744. this.stencilWriteMask = source.stencilWriteMask;
  5745. this.stencilFunc = source.stencilFunc;
  5746. this.stencilRef = source.stencilRef;
  5747. this.stencilFuncMask = source.stencilFuncMask;
  5748. this.stencilFail = source.stencilFail;
  5749. this.stencilZFail = source.stencilZFail;
  5750. this.stencilZPass = source.stencilZPass;
  5751. this.stencilWrite = source.stencilWrite;
  5752. const srcPlanes = source.clippingPlanes;
  5753. let dstPlanes = null;
  5754. if (srcPlanes !== null) {
  5755. const n = srcPlanes.length;
  5756. dstPlanes = new Array(n);
  5757. for (let i = 0; i !== n; ++i) {
  5758. dstPlanes[i] = srcPlanes[i].clone();
  5759. }
  5760. }
  5761. this.clippingPlanes = dstPlanes;
  5762. this.clipIntersection = source.clipIntersection;
  5763. this.clipShadows = source.clipShadows;
  5764. this.shadowSide = source.shadowSide;
  5765. this.colorWrite = source.colorWrite;
  5766. this.precision = source.precision;
  5767. this.polygonOffset = source.polygonOffset;
  5768. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5769. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5770. this.dithering = source.dithering;
  5771. this.alphaTest = source.alphaTest;
  5772. this.alphaToCoverage = source.alphaToCoverage;
  5773. this.premultipliedAlpha = source.premultipliedAlpha;
  5774. this.visible = source.visible;
  5775. this.toneMapped = source.toneMapped;
  5776. this.userData = JSON.parse(JSON.stringify(source.userData));
  5777. return this;
  5778. }
  5779. dispose() {
  5780. this.dispatchEvent({
  5781. type: 'dispose'
  5782. });
  5783. }
  5784. set needsUpdate(value) {
  5785. if (value === true) this.version++;
  5786. }
  5787. }
  5788. class MeshBasicMaterial extends Material {
  5789. constructor(parameters) {
  5790. super();
  5791. this.isMeshBasicMaterial = true;
  5792. this.type = 'MeshBasicMaterial';
  5793. this.color = new Color(0xffffff); // emissive
  5794. this.map = null;
  5795. this.lightMap = null;
  5796. this.lightMapIntensity = 1.0;
  5797. this.aoMap = null;
  5798. this.aoMapIntensity = 1.0;
  5799. this.specularMap = null;
  5800. this.alphaMap = null;
  5801. this.envMap = null;
  5802. this.combine = MultiplyOperation;
  5803. this.reflectivity = 1;
  5804. this.refractionRatio = 0.98;
  5805. this.wireframe = false;
  5806. this.wireframeLinewidth = 1;
  5807. this.wireframeLinecap = 'round';
  5808. this.wireframeLinejoin = 'round';
  5809. this.fog = true;
  5810. this.setValues(parameters);
  5811. }
  5812. copy(source) {
  5813. super.copy(source);
  5814. this.color.copy(source.color);
  5815. this.map = source.map;
  5816. this.lightMap = source.lightMap;
  5817. this.lightMapIntensity = source.lightMapIntensity;
  5818. this.aoMap = source.aoMap;
  5819. this.aoMapIntensity = source.aoMapIntensity;
  5820. this.specularMap = source.specularMap;
  5821. this.alphaMap = source.alphaMap;
  5822. this.envMap = source.envMap;
  5823. this.combine = source.combine;
  5824. this.reflectivity = source.reflectivity;
  5825. this.refractionRatio = source.refractionRatio;
  5826. this.wireframe = source.wireframe;
  5827. this.wireframeLinewidth = source.wireframeLinewidth;
  5828. this.wireframeLinecap = source.wireframeLinecap;
  5829. this.wireframeLinejoin = source.wireframeLinejoin;
  5830. this.fog = source.fog;
  5831. return this;
  5832. }
  5833. }
  5834. const _vector$9 = /*@__PURE__*/new Vector3();
  5835. const _vector2$1 = /*@__PURE__*/new Vector2();
  5836. class BufferAttribute {
  5837. constructor(array, itemSize, normalized) {
  5838. if (Array.isArray(array)) {
  5839. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5840. }
  5841. this.isBufferAttribute = true;
  5842. this.name = '';
  5843. this.array = array;
  5844. this.itemSize = itemSize;
  5845. this.count = array !== undefined ? array.length / itemSize : 0;
  5846. this.normalized = normalized === true;
  5847. this.usage = StaticDrawUsage;
  5848. this.updateRange = {
  5849. offset: 0,
  5850. count: -1
  5851. };
  5852. this.version = 0;
  5853. }
  5854. onUploadCallback() {}
  5855. set needsUpdate(value) {
  5856. if (value === true) this.version++;
  5857. }
  5858. setUsage(value) {
  5859. this.usage = value;
  5860. return this;
  5861. }
  5862. copy(source) {
  5863. this.name = source.name;
  5864. this.array = new source.array.constructor(source.array);
  5865. this.itemSize = source.itemSize;
  5866. this.count = source.count;
  5867. this.normalized = source.normalized;
  5868. this.usage = source.usage;
  5869. return this;
  5870. }
  5871. copyAt(index1, attribute, index2) {
  5872. index1 *= this.itemSize;
  5873. index2 *= attribute.itemSize;
  5874. for (let i = 0, l = this.itemSize; i < l; i++) {
  5875. this.array[index1 + i] = attribute.array[index2 + i];
  5876. }
  5877. return this;
  5878. }
  5879. copyArray(array) {
  5880. this.array.set(array);
  5881. return this;
  5882. }
  5883. copyColorsArray(colors) {
  5884. const array = this.array;
  5885. let offset = 0;
  5886. for (let i = 0, l = colors.length; i < l; i++) {
  5887. let color = colors[i];
  5888. if (color === undefined) {
  5889. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5890. color = new Color();
  5891. }
  5892. array[offset++] = color.r;
  5893. array[offset++] = color.g;
  5894. array[offset++] = color.b;
  5895. }
  5896. return this;
  5897. }
  5898. copyVector2sArray(vectors) {
  5899. const array = this.array;
  5900. let offset = 0;
  5901. for (let i = 0, l = vectors.length; i < l; i++) {
  5902. let vector = vectors[i];
  5903. if (vector === undefined) {
  5904. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5905. vector = new Vector2();
  5906. }
  5907. array[offset++] = vector.x;
  5908. array[offset++] = vector.y;
  5909. }
  5910. return this;
  5911. }
  5912. copyVector3sArray(vectors) {
  5913. const array = this.array;
  5914. let offset = 0;
  5915. for (let i = 0, l = vectors.length; i < l; i++) {
  5916. let vector = vectors[i];
  5917. if (vector === undefined) {
  5918. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5919. vector = new Vector3();
  5920. }
  5921. array[offset++] = vector.x;
  5922. array[offset++] = vector.y;
  5923. array[offset++] = vector.z;
  5924. }
  5925. return this;
  5926. }
  5927. copyVector4sArray(vectors) {
  5928. const array = this.array;
  5929. let offset = 0;
  5930. for (let i = 0, l = vectors.length; i < l; i++) {
  5931. let vector = vectors[i];
  5932. if (vector === undefined) {
  5933. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5934. vector = new Vector4();
  5935. }
  5936. array[offset++] = vector.x;
  5937. array[offset++] = vector.y;
  5938. array[offset++] = vector.z;
  5939. array[offset++] = vector.w;
  5940. }
  5941. return this;
  5942. }
  5943. applyMatrix3(m) {
  5944. if (this.itemSize === 2) {
  5945. for (let i = 0, l = this.count; i < l; i++) {
  5946. _vector2$1.fromBufferAttribute(this, i);
  5947. _vector2$1.applyMatrix3(m);
  5948. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5949. }
  5950. } else if (this.itemSize === 3) {
  5951. for (let i = 0, l = this.count; i < l; i++) {
  5952. _vector$9.fromBufferAttribute(this, i);
  5953. _vector$9.applyMatrix3(m);
  5954. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5955. }
  5956. }
  5957. return this;
  5958. }
  5959. applyMatrix4(m) {
  5960. for (let i = 0, l = this.count; i < l; i++) {
  5961. _vector$9.fromBufferAttribute(this, i);
  5962. _vector$9.applyMatrix4(m);
  5963. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5964. }
  5965. return this;
  5966. }
  5967. applyNormalMatrix(m) {
  5968. for (let i = 0, l = this.count; i < l; i++) {
  5969. _vector$9.fromBufferAttribute(this, i);
  5970. _vector$9.applyNormalMatrix(m);
  5971. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5972. }
  5973. return this;
  5974. }
  5975. transformDirection(m) {
  5976. for (let i = 0, l = this.count; i < l; i++) {
  5977. _vector$9.fromBufferAttribute(this, i);
  5978. _vector$9.transformDirection(m);
  5979. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5980. }
  5981. return this;
  5982. }
  5983. set(value, offset = 0) {
  5984. this.array.set(value, offset);
  5985. return this;
  5986. }
  5987. getX(index) {
  5988. return this.array[index * this.itemSize];
  5989. }
  5990. setX(index, x) {
  5991. this.array[index * this.itemSize] = x;
  5992. return this;
  5993. }
  5994. getY(index) {
  5995. return this.array[index * this.itemSize + 1];
  5996. }
  5997. setY(index, y) {
  5998. this.array[index * this.itemSize + 1] = y;
  5999. return this;
  6000. }
  6001. getZ(index) {
  6002. return this.array[index * this.itemSize + 2];
  6003. }
  6004. setZ(index, z) {
  6005. this.array[index * this.itemSize + 2] = z;
  6006. return this;
  6007. }
  6008. getW(index) {
  6009. return this.array[index * this.itemSize + 3];
  6010. }
  6011. setW(index, w) {
  6012. this.array[index * this.itemSize + 3] = w;
  6013. return this;
  6014. }
  6015. setXY(index, x, y) {
  6016. index *= this.itemSize;
  6017. this.array[index + 0] = x;
  6018. this.array[index + 1] = y;
  6019. return this;
  6020. }
  6021. setXYZ(index, x, y, z) {
  6022. index *= this.itemSize;
  6023. this.array[index + 0] = x;
  6024. this.array[index + 1] = y;
  6025. this.array[index + 2] = z;
  6026. return this;
  6027. }
  6028. setXYZW(index, x, y, z, w) {
  6029. index *= this.itemSize;
  6030. this.array[index + 0] = x;
  6031. this.array[index + 1] = y;
  6032. this.array[index + 2] = z;
  6033. this.array[index + 3] = w;
  6034. return this;
  6035. }
  6036. onUpload(callback) {
  6037. this.onUploadCallback = callback;
  6038. return this;
  6039. }
  6040. clone() {
  6041. return new this.constructor(this.array, this.itemSize).copy(this);
  6042. }
  6043. toJSON() {
  6044. const data = {
  6045. itemSize: this.itemSize,
  6046. type: this.array.constructor.name,
  6047. array: Array.from(this.array),
  6048. normalized: this.normalized
  6049. };
  6050. if (this.name !== '') data.name = this.name;
  6051. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6052. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6053. return data;
  6054. }
  6055. } //
  6056. class Int8BufferAttribute extends BufferAttribute {
  6057. constructor(array, itemSize, normalized) {
  6058. super(new Int8Array(array), itemSize, normalized);
  6059. }
  6060. }
  6061. class Uint8BufferAttribute extends BufferAttribute {
  6062. constructor(array, itemSize, normalized) {
  6063. super(new Uint8Array(array), itemSize, normalized);
  6064. }
  6065. }
  6066. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6067. constructor(array, itemSize, normalized) {
  6068. super(new Uint8ClampedArray(array), itemSize, normalized);
  6069. }
  6070. }
  6071. class Int16BufferAttribute extends BufferAttribute {
  6072. constructor(array, itemSize, normalized) {
  6073. super(new Int16Array(array), itemSize, normalized);
  6074. }
  6075. }
  6076. class Uint16BufferAttribute extends BufferAttribute {
  6077. constructor(array, itemSize, normalized) {
  6078. super(new Uint16Array(array), itemSize, normalized);
  6079. }
  6080. }
  6081. class Int32BufferAttribute extends BufferAttribute {
  6082. constructor(array, itemSize, normalized) {
  6083. super(new Int32Array(array), itemSize, normalized);
  6084. }
  6085. }
  6086. class Uint32BufferAttribute extends BufferAttribute {
  6087. constructor(array, itemSize, normalized) {
  6088. super(new Uint32Array(array), itemSize, normalized);
  6089. }
  6090. }
  6091. class Float16BufferAttribute extends BufferAttribute {
  6092. constructor(array, itemSize, normalized) {
  6093. super(new Uint16Array(array), itemSize, normalized);
  6094. this.isFloat16BufferAttribute = true;
  6095. }
  6096. }
  6097. class Float32BufferAttribute extends BufferAttribute {
  6098. constructor(array, itemSize, normalized) {
  6099. super(new Float32Array(array), itemSize, normalized);
  6100. }
  6101. }
  6102. class Float64BufferAttribute extends BufferAttribute {
  6103. constructor(array, itemSize, normalized) {
  6104. super(new Float64Array(array), itemSize, normalized);
  6105. }
  6106. } //
  6107. let _id$1 = 0;
  6108. const _m1 = /*@__PURE__*/new Matrix4();
  6109. const _obj = /*@__PURE__*/new Object3D();
  6110. const _offset = /*@__PURE__*/new Vector3();
  6111. const _box$1 = /*@__PURE__*/new Box3();
  6112. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6113. const _vector$8 = /*@__PURE__*/new Vector3();
  6114. class BufferGeometry extends EventDispatcher {
  6115. constructor() {
  6116. super();
  6117. this.isBufferGeometry = true;
  6118. Object.defineProperty(this, 'id', {
  6119. value: _id$1++
  6120. });
  6121. this.uuid = generateUUID();
  6122. this.name = '';
  6123. this.type = 'BufferGeometry';
  6124. this.index = null;
  6125. this.attributes = {};
  6126. this.morphAttributes = {};
  6127. this.morphTargetsRelative = false;
  6128. this.groups = [];
  6129. this.boundingBox = null;
  6130. this.boundingSphere = null;
  6131. this.drawRange = {
  6132. start: 0,
  6133. count: Infinity
  6134. };
  6135. this.userData = {};
  6136. }
  6137. getIndex() {
  6138. return this.index;
  6139. }
  6140. setIndex(index) {
  6141. if (Array.isArray(index)) {
  6142. this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6143. } else {
  6144. this.index = index;
  6145. }
  6146. return this;
  6147. }
  6148. getAttribute(name) {
  6149. return this.attributes[name];
  6150. }
  6151. setAttribute(name, attribute) {
  6152. this.attributes[name] = attribute;
  6153. return this;
  6154. }
  6155. deleteAttribute(name) {
  6156. delete this.attributes[name];
  6157. return this;
  6158. }
  6159. hasAttribute(name) {
  6160. return this.attributes[name] !== undefined;
  6161. }
  6162. addGroup(start, count, materialIndex = 0) {
  6163. this.groups.push({
  6164. start: start,
  6165. count: count,
  6166. materialIndex: materialIndex
  6167. });
  6168. }
  6169. clearGroups() {
  6170. this.groups = [];
  6171. }
  6172. setDrawRange(start, count) {
  6173. this.drawRange.start = start;
  6174. this.drawRange.count = count;
  6175. }
  6176. applyMatrix4(matrix) {
  6177. const position = this.attributes.position;
  6178. if (position !== undefined) {
  6179. position.applyMatrix4(matrix);
  6180. position.needsUpdate = true;
  6181. }
  6182. const normal = this.attributes.normal;
  6183. if (normal !== undefined) {
  6184. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6185. normal.applyNormalMatrix(normalMatrix);
  6186. normal.needsUpdate = true;
  6187. }
  6188. const tangent = this.attributes.tangent;
  6189. if (tangent !== undefined) {
  6190. tangent.transformDirection(matrix);
  6191. tangent.needsUpdate = true;
  6192. }
  6193. if (this.boundingBox !== null) {
  6194. this.computeBoundingBox();
  6195. }
  6196. if (this.boundingSphere !== null) {
  6197. this.computeBoundingSphere();
  6198. }
  6199. return this;
  6200. }
  6201. applyQuaternion(q) {
  6202. _m1.makeRotationFromQuaternion(q);
  6203. this.applyMatrix4(_m1);
  6204. return this;
  6205. }
  6206. rotateX(angle) {
  6207. // rotate geometry around world x-axis
  6208. _m1.makeRotationX(angle);
  6209. this.applyMatrix4(_m1);
  6210. return this;
  6211. }
  6212. rotateY(angle) {
  6213. // rotate geometry around world y-axis
  6214. _m1.makeRotationY(angle);
  6215. this.applyMatrix4(_m1);
  6216. return this;
  6217. }
  6218. rotateZ(angle) {
  6219. // rotate geometry around world z-axis
  6220. _m1.makeRotationZ(angle);
  6221. this.applyMatrix4(_m1);
  6222. return this;
  6223. }
  6224. translate(x, y, z) {
  6225. // translate geometry
  6226. _m1.makeTranslation(x, y, z);
  6227. this.applyMatrix4(_m1);
  6228. return this;
  6229. }
  6230. scale(x, y, z) {
  6231. // scale geometry
  6232. _m1.makeScale(x, y, z);
  6233. this.applyMatrix4(_m1);
  6234. return this;
  6235. }
  6236. lookAt(vector) {
  6237. _obj.lookAt(vector);
  6238. _obj.updateMatrix();
  6239. this.applyMatrix4(_obj.matrix);
  6240. return this;
  6241. }
  6242. center() {
  6243. this.computeBoundingBox();
  6244. this.boundingBox.getCenter(_offset).negate();
  6245. this.translate(_offset.x, _offset.y, _offset.z);
  6246. return this;
  6247. }
  6248. setFromPoints(points) {
  6249. const position = [];
  6250. for (let i = 0, l = points.length; i < l; i++) {
  6251. const point = points[i];
  6252. position.push(point.x, point.y, point.z || 0);
  6253. }
  6254. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6255. return this;
  6256. }
  6257. computeBoundingBox() {
  6258. if (this.boundingBox === null) {
  6259. this.boundingBox = new Box3();
  6260. }
  6261. const position = this.attributes.position;
  6262. const morphAttributesPosition = this.morphAttributes.position;
  6263. if (position && position.isGLBufferAttribute) {
  6264. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6265. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6266. return;
  6267. }
  6268. if (position !== undefined) {
  6269. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6270. if (morphAttributesPosition) {
  6271. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6272. const morphAttribute = morphAttributesPosition[i];
  6273. _box$1.setFromBufferAttribute(morphAttribute);
  6274. if (this.morphTargetsRelative) {
  6275. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6276. this.boundingBox.expandByPoint(_vector$8);
  6277. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6278. this.boundingBox.expandByPoint(_vector$8);
  6279. } else {
  6280. this.boundingBox.expandByPoint(_box$1.min);
  6281. this.boundingBox.expandByPoint(_box$1.max);
  6282. }
  6283. }
  6284. }
  6285. } else {
  6286. this.boundingBox.makeEmpty();
  6287. }
  6288. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6289. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6290. }
  6291. }
  6292. computeBoundingSphere() {
  6293. if (this.boundingSphere === null) {
  6294. this.boundingSphere = new Sphere();
  6295. }
  6296. const position = this.attributes.position;
  6297. const morphAttributesPosition = this.morphAttributes.position;
  6298. if (position && position.isGLBufferAttribute) {
  6299. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6300. this.boundingSphere.set(new Vector3(), Infinity);
  6301. return;
  6302. }
  6303. if (position) {
  6304. // first, find the center of the bounding sphere
  6305. const center = this.boundingSphere.center;
  6306. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6307. if (morphAttributesPosition) {
  6308. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6309. const morphAttribute = morphAttributesPosition[i];
  6310. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6311. if (this.morphTargetsRelative) {
  6312. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6313. _box$1.expandByPoint(_vector$8);
  6314. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6315. _box$1.expandByPoint(_vector$8);
  6316. } else {
  6317. _box$1.expandByPoint(_boxMorphTargets.min);
  6318. _box$1.expandByPoint(_boxMorphTargets.max);
  6319. }
  6320. }
  6321. }
  6322. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6323. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6324. let maxRadiusSq = 0;
  6325. for (let i = 0, il = position.count; i < il; i++) {
  6326. _vector$8.fromBufferAttribute(position, i);
  6327. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6328. } // process morph attributes if present
  6329. if (morphAttributesPosition) {
  6330. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6331. const morphAttribute = morphAttributesPosition[i];
  6332. const morphTargetsRelative = this.morphTargetsRelative;
  6333. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6334. _vector$8.fromBufferAttribute(morphAttribute, j);
  6335. if (morphTargetsRelative) {
  6336. _offset.fromBufferAttribute(position, j);
  6337. _vector$8.add(_offset);
  6338. }
  6339. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6340. }
  6341. }
  6342. }
  6343. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6344. if (isNaN(this.boundingSphere.radius)) {
  6345. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6346. }
  6347. }
  6348. }
  6349. computeTangents() {
  6350. const index = this.index;
  6351. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6352. // (per vertex tangents)
  6353. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6354. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6355. return;
  6356. }
  6357. const indices = index.array;
  6358. const positions = attributes.position.array;
  6359. const normals = attributes.normal.array;
  6360. const uvs = attributes.uv.array;
  6361. const nVertices = positions.length / 3;
  6362. if (this.hasAttribute('tangent') === false) {
  6363. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6364. }
  6365. const tangents = this.getAttribute('tangent').array;
  6366. const tan1 = [],
  6367. tan2 = [];
  6368. for (let i = 0; i < nVertices; i++) {
  6369. tan1[i] = new Vector3();
  6370. tan2[i] = new Vector3();
  6371. }
  6372. const vA = new Vector3(),
  6373. vB = new Vector3(),
  6374. vC = new Vector3(),
  6375. uvA = new Vector2(),
  6376. uvB = new Vector2(),
  6377. uvC = new Vector2(),
  6378. sdir = new Vector3(),
  6379. tdir = new Vector3();
  6380. function handleTriangle(a, b, c) {
  6381. vA.fromArray(positions, a * 3);
  6382. vB.fromArray(positions, b * 3);
  6383. vC.fromArray(positions, c * 3);
  6384. uvA.fromArray(uvs, a * 2);
  6385. uvB.fromArray(uvs, b * 2);
  6386. uvC.fromArray(uvs, c * 2);
  6387. vB.sub(vA);
  6388. vC.sub(vA);
  6389. uvB.sub(uvA);
  6390. uvC.sub(uvA);
  6391. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6392. if (!isFinite(r)) return;
  6393. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6394. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6395. tan1[a].add(sdir);
  6396. tan1[b].add(sdir);
  6397. tan1[c].add(sdir);
  6398. tan2[a].add(tdir);
  6399. tan2[b].add(tdir);
  6400. tan2[c].add(tdir);
  6401. }
  6402. let groups = this.groups;
  6403. if (groups.length === 0) {
  6404. groups = [{
  6405. start: 0,
  6406. count: indices.length
  6407. }];
  6408. }
  6409. for (let i = 0, il = groups.length; i < il; ++i) {
  6410. const group = groups[i];
  6411. const start = group.start;
  6412. const count = group.count;
  6413. for (let j = start, jl = start + count; j < jl; j += 3) {
  6414. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6415. }
  6416. }
  6417. const tmp = new Vector3(),
  6418. tmp2 = new Vector3();
  6419. const n = new Vector3(),
  6420. n2 = new Vector3();
  6421. function handleVertex(v) {
  6422. n.fromArray(normals, v * 3);
  6423. n2.copy(n);
  6424. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6425. tmp.copy(t);
  6426. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6427. tmp2.crossVectors(n2, t);
  6428. const test = tmp2.dot(tan2[v]);
  6429. const w = test < 0.0 ? -1.0 : 1.0;
  6430. tangents[v * 4] = tmp.x;
  6431. tangents[v * 4 + 1] = tmp.y;
  6432. tangents[v * 4 + 2] = tmp.z;
  6433. tangents[v * 4 + 3] = w;
  6434. }
  6435. for (let i = 0, il = groups.length; i < il; ++i) {
  6436. const group = groups[i];
  6437. const start = group.start;
  6438. const count = group.count;
  6439. for (let j = start, jl = start + count; j < jl; j += 3) {
  6440. handleVertex(indices[j + 0]);
  6441. handleVertex(indices[j + 1]);
  6442. handleVertex(indices[j + 2]);
  6443. }
  6444. }
  6445. }
  6446. computeVertexNormals() {
  6447. const index = this.index;
  6448. const positionAttribute = this.getAttribute('position');
  6449. if (positionAttribute !== undefined) {
  6450. let normalAttribute = this.getAttribute('normal');
  6451. if (normalAttribute === undefined) {
  6452. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6453. this.setAttribute('normal', normalAttribute);
  6454. } else {
  6455. // reset existing normals to zero
  6456. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6457. normalAttribute.setXYZ(i, 0, 0, 0);
  6458. }
  6459. }
  6460. const pA = new Vector3(),
  6461. pB = new Vector3(),
  6462. pC = new Vector3();
  6463. const nA = new Vector3(),
  6464. nB = new Vector3(),
  6465. nC = new Vector3();
  6466. const cb = new Vector3(),
  6467. ab = new Vector3(); // indexed elements
  6468. if (index) {
  6469. for (let i = 0, il = index.count; i < il; i += 3) {
  6470. const vA = index.getX(i + 0);
  6471. const vB = index.getX(i + 1);
  6472. const vC = index.getX(i + 2);
  6473. pA.fromBufferAttribute(positionAttribute, vA);
  6474. pB.fromBufferAttribute(positionAttribute, vB);
  6475. pC.fromBufferAttribute(positionAttribute, vC);
  6476. cb.subVectors(pC, pB);
  6477. ab.subVectors(pA, pB);
  6478. cb.cross(ab);
  6479. nA.fromBufferAttribute(normalAttribute, vA);
  6480. nB.fromBufferAttribute(normalAttribute, vB);
  6481. nC.fromBufferAttribute(normalAttribute, vC);
  6482. nA.add(cb);
  6483. nB.add(cb);
  6484. nC.add(cb);
  6485. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6486. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6487. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6488. }
  6489. } else {
  6490. // non-indexed elements (unconnected triangle soup)
  6491. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6492. pA.fromBufferAttribute(positionAttribute, i + 0);
  6493. pB.fromBufferAttribute(positionAttribute, i + 1);
  6494. pC.fromBufferAttribute(positionAttribute, i + 2);
  6495. cb.subVectors(pC, pB);
  6496. ab.subVectors(pA, pB);
  6497. cb.cross(ab);
  6498. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6499. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6500. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6501. }
  6502. }
  6503. this.normalizeNormals();
  6504. normalAttribute.needsUpdate = true;
  6505. }
  6506. }
  6507. merge(geometry, offset) {
  6508. if (!(geometry && geometry.isBufferGeometry)) {
  6509. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6510. return;
  6511. }
  6512. if (offset === undefined) {
  6513. offset = 0;
  6514. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6515. }
  6516. const attributes = this.attributes;
  6517. for (const key in attributes) {
  6518. if (geometry.attributes[key] === undefined) continue;
  6519. const attribute1 = attributes[key];
  6520. const attributeArray1 = attribute1.array;
  6521. const attribute2 = geometry.attributes[key];
  6522. const attributeArray2 = attribute2.array;
  6523. const attributeOffset = attribute2.itemSize * offset;
  6524. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6525. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6526. attributeArray1[j] = attributeArray2[i];
  6527. }
  6528. }
  6529. return this;
  6530. }
  6531. normalizeNormals() {
  6532. const normals = this.attributes.normal;
  6533. for (let i = 0, il = normals.count; i < il; i++) {
  6534. _vector$8.fromBufferAttribute(normals, i);
  6535. _vector$8.normalize();
  6536. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6537. }
  6538. }
  6539. toNonIndexed() {
  6540. function convertBufferAttribute(attribute, indices) {
  6541. const array = attribute.array;
  6542. const itemSize = attribute.itemSize;
  6543. const normalized = attribute.normalized;
  6544. const array2 = new array.constructor(indices.length * itemSize);
  6545. let index = 0,
  6546. index2 = 0;
  6547. for (let i = 0, l = indices.length; i < l; i++) {
  6548. if (attribute.isInterleavedBufferAttribute) {
  6549. index = indices[i] * attribute.data.stride + attribute.offset;
  6550. } else {
  6551. index = indices[i] * itemSize;
  6552. }
  6553. for (let j = 0; j < itemSize; j++) {
  6554. array2[index2++] = array[index++];
  6555. }
  6556. }
  6557. return new BufferAttribute(array2, itemSize, normalized);
  6558. } //
  6559. if (this.index === null) {
  6560. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6561. return this;
  6562. }
  6563. const geometry2 = new BufferGeometry();
  6564. const indices = this.index.array;
  6565. const attributes = this.attributes; // attributes
  6566. for (const name in attributes) {
  6567. const attribute = attributes[name];
  6568. const newAttribute = convertBufferAttribute(attribute, indices);
  6569. geometry2.setAttribute(name, newAttribute);
  6570. } // morph attributes
  6571. const morphAttributes = this.morphAttributes;
  6572. for (const name in morphAttributes) {
  6573. const morphArray = [];
  6574. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6575. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6576. const attribute = morphAttribute[i];
  6577. const newAttribute = convertBufferAttribute(attribute, indices);
  6578. morphArray.push(newAttribute);
  6579. }
  6580. geometry2.morphAttributes[name] = morphArray;
  6581. }
  6582. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6583. const groups = this.groups;
  6584. for (let i = 0, l = groups.length; i < l; i++) {
  6585. const group = groups[i];
  6586. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6587. }
  6588. return geometry2;
  6589. }
  6590. toJSON() {
  6591. const data = {
  6592. metadata: {
  6593. version: 4.5,
  6594. type: 'BufferGeometry',
  6595. generator: 'BufferGeometry.toJSON'
  6596. }
  6597. }; // standard BufferGeometry serialization
  6598. data.uuid = this.uuid;
  6599. data.type = this.type;
  6600. if (this.name !== '') data.name = this.name;
  6601. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6602. if (this.parameters !== undefined) {
  6603. const parameters = this.parameters;
  6604. for (const key in parameters) {
  6605. if (parameters[key] !== undefined) data[key] = parameters[key];
  6606. }
  6607. return data;
  6608. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6609. data.data = {
  6610. attributes: {}
  6611. };
  6612. const index = this.index;
  6613. if (index !== null) {
  6614. data.data.index = {
  6615. type: index.array.constructor.name,
  6616. array: Array.prototype.slice.call(index.array)
  6617. };
  6618. }
  6619. const attributes = this.attributes;
  6620. for (const key in attributes) {
  6621. const attribute = attributes[key];
  6622. data.data.attributes[key] = attribute.toJSON(data.data);
  6623. }
  6624. const morphAttributes = {};
  6625. let hasMorphAttributes = false;
  6626. for (const key in this.morphAttributes) {
  6627. const attributeArray = this.morphAttributes[key];
  6628. const array = [];
  6629. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6630. const attribute = attributeArray[i];
  6631. array.push(attribute.toJSON(data.data));
  6632. }
  6633. if (array.length > 0) {
  6634. morphAttributes[key] = array;
  6635. hasMorphAttributes = true;
  6636. }
  6637. }
  6638. if (hasMorphAttributes) {
  6639. data.data.morphAttributes = morphAttributes;
  6640. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6641. }
  6642. const groups = this.groups;
  6643. if (groups.length > 0) {
  6644. data.data.groups = JSON.parse(JSON.stringify(groups));
  6645. }
  6646. const boundingSphere = this.boundingSphere;
  6647. if (boundingSphere !== null) {
  6648. data.data.boundingSphere = {
  6649. center: boundingSphere.center.toArray(),
  6650. radius: boundingSphere.radius
  6651. };
  6652. }
  6653. return data;
  6654. }
  6655. clone() {
  6656. return new this.constructor().copy(this);
  6657. }
  6658. copy(source) {
  6659. // reset
  6660. this.index = null;
  6661. this.attributes = {};
  6662. this.morphAttributes = {};
  6663. this.groups = [];
  6664. this.boundingBox = null;
  6665. this.boundingSphere = null; // used for storing cloned, shared data
  6666. const data = {}; // name
  6667. this.name = source.name; // index
  6668. const index = source.index;
  6669. if (index !== null) {
  6670. this.setIndex(index.clone(data));
  6671. } // attributes
  6672. const attributes = source.attributes;
  6673. for (const name in attributes) {
  6674. const attribute = attributes[name];
  6675. this.setAttribute(name, attribute.clone(data));
  6676. } // morph attributes
  6677. const morphAttributes = source.morphAttributes;
  6678. for (const name in morphAttributes) {
  6679. const array = [];
  6680. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6681. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6682. array.push(morphAttribute[i].clone(data));
  6683. }
  6684. this.morphAttributes[name] = array;
  6685. }
  6686. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6687. const groups = source.groups;
  6688. for (let i = 0, l = groups.length; i < l; i++) {
  6689. const group = groups[i];
  6690. this.addGroup(group.start, group.count, group.materialIndex);
  6691. } // bounding box
  6692. const boundingBox = source.boundingBox;
  6693. if (boundingBox !== null) {
  6694. this.boundingBox = boundingBox.clone();
  6695. } // bounding sphere
  6696. const boundingSphere = source.boundingSphere;
  6697. if (boundingSphere !== null) {
  6698. this.boundingSphere = boundingSphere.clone();
  6699. } // draw range
  6700. this.drawRange.start = source.drawRange.start;
  6701. this.drawRange.count = source.drawRange.count; // user data
  6702. this.userData = source.userData; // geometry generator parameters
  6703. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6704. return this;
  6705. }
  6706. dispose() {
  6707. this.dispatchEvent({
  6708. type: 'dispose'
  6709. });
  6710. }
  6711. }
  6712. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6713. const _ray$2 = /*@__PURE__*/new Ray();
  6714. const _sphere$3 = /*@__PURE__*/new Sphere();
  6715. const _vA$1 = /*@__PURE__*/new Vector3();
  6716. const _vB$1 = /*@__PURE__*/new Vector3();
  6717. const _vC$1 = /*@__PURE__*/new Vector3();
  6718. const _tempA = /*@__PURE__*/new Vector3();
  6719. const _tempB = /*@__PURE__*/new Vector3();
  6720. const _tempC = /*@__PURE__*/new Vector3();
  6721. const _morphA = /*@__PURE__*/new Vector3();
  6722. const _morphB = /*@__PURE__*/new Vector3();
  6723. const _morphC = /*@__PURE__*/new Vector3();
  6724. const _uvA$1 = /*@__PURE__*/new Vector2();
  6725. const _uvB$1 = /*@__PURE__*/new Vector2();
  6726. const _uvC$1 = /*@__PURE__*/new Vector2();
  6727. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6728. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6729. class Mesh extends Object3D {
  6730. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6731. super();
  6732. this.isMesh = true;
  6733. this.type = 'Mesh';
  6734. this.geometry = geometry;
  6735. this.material = material;
  6736. this.updateMorphTargets();
  6737. }
  6738. copy(source, recursive) {
  6739. super.copy(source, recursive);
  6740. if (source.morphTargetInfluences !== undefined) {
  6741. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6742. }
  6743. if (source.morphTargetDictionary !== undefined) {
  6744. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6745. }
  6746. this.material = source.material;
  6747. this.geometry = source.geometry;
  6748. return this;
  6749. }
  6750. updateMorphTargets() {
  6751. const geometry = this.geometry;
  6752. const morphAttributes = geometry.morphAttributes;
  6753. const keys = Object.keys(morphAttributes);
  6754. if (keys.length > 0) {
  6755. const morphAttribute = morphAttributes[keys[0]];
  6756. if (morphAttribute !== undefined) {
  6757. this.morphTargetInfluences = [];
  6758. this.morphTargetDictionary = {};
  6759. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6760. const name = morphAttribute[m].name || String(m);
  6761. this.morphTargetInfluences.push(0);
  6762. this.morphTargetDictionary[name] = m;
  6763. }
  6764. }
  6765. }
  6766. }
  6767. raycast(raycaster, intersects) {
  6768. const geometry = this.geometry;
  6769. const material = this.material;
  6770. const matrixWorld = this.matrixWorld;
  6771. if (material === undefined) return; // Checking boundingSphere distance to ray
  6772. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6773. _sphere$3.copy(geometry.boundingSphere);
  6774. _sphere$3.applyMatrix4(matrixWorld);
  6775. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6776. _inverseMatrix$2.copy(matrixWorld).invert();
  6777. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6778. if (geometry.boundingBox !== null) {
  6779. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6780. }
  6781. let intersection;
  6782. const index = geometry.index;
  6783. const position = geometry.attributes.position;
  6784. const morphPosition = geometry.morphAttributes.position;
  6785. const morphTargetsRelative = geometry.morphTargetsRelative;
  6786. const uv = geometry.attributes.uv;
  6787. const uv2 = geometry.attributes.uv2;
  6788. const groups = geometry.groups;
  6789. const drawRange = geometry.drawRange;
  6790. if (index !== null) {
  6791. // indexed buffer geometry
  6792. if (Array.isArray(material)) {
  6793. for (let i = 0, il = groups.length; i < il; i++) {
  6794. const group = groups[i];
  6795. const groupMaterial = material[group.materialIndex];
  6796. const start = Math.max(group.start, drawRange.start);
  6797. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6798. for (let j = start, jl = end; j < jl; j += 3) {
  6799. const a = index.getX(j);
  6800. const b = index.getX(j + 1);
  6801. const c = index.getX(j + 2);
  6802. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6803. if (intersection) {
  6804. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6805. intersection.face.materialIndex = group.materialIndex;
  6806. intersects.push(intersection);
  6807. }
  6808. }
  6809. }
  6810. } else {
  6811. const start = Math.max(0, drawRange.start);
  6812. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6813. for (let i = start, il = end; i < il; i += 3) {
  6814. const a = index.getX(i);
  6815. const b = index.getX(i + 1);
  6816. const c = index.getX(i + 2);
  6817. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6818. if (intersection) {
  6819. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6820. intersects.push(intersection);
  6821. }
  6822. }
  6823. }
  6824. } else if (position !== undefined) {
  6825. // non-indexed buffer geometry
  6826. if (Array.isArray(material)) {
  6827. for (let i = 0, il = groups.length; i < il; i++) {
  6828. const group = groups[i];
  6829. const groupMaterial = material[group.materialIndex];
  6830. const start = Math.max(group.start, drawRange.start);
  6831. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6832. for (let j = start, jl = end; j < jl; j += 3) {
  6833. const a = j;
  6834. const b = j + 1;
  6835. const c = j + 2;
  6836. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6837. if (intersection) {
  6838. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6839. intersection.face.materialIndex = group.materialIndex;
  6840. intersects.push(intersection);
  6841. }
  6842. }
  6843. }
  6844. } else {
  6845. const start = Math.max(0, drawRange.start);
  6846. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6847. for (let i = start, il = end; i < il; i += 3) {
  6848. const a = i;
  6849. const b = i + 1;
  6850. const c = i + 2;
  6851. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6852. if (intersection) {
  6853. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6854. intersects.push(intersection);
  6855. }
  6856. }
  6857. }
  6858. }
  6859. }
  6860. }
  6861. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6862. let intersect;
  6863. if (material.side === BackSide) {
  6864. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6865. } else {
  6866. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6867. }
  6868. if (intersect === null) return null;
  6869. _intersectionPointWorld.copy(point);
  6870. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6871. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6872. if (distance < raycaster.near || distance > raycaster.far) return null;
  6873. return {
  6874. distance: distance,
  6875. point: _intersectionPointWorld.clone(),
  6876. object: object
  6877. };
  6878. }
  6879. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6880. _vA$1.fromBufferAttribute(position, a);
  6881. _vB$1.fromBufferAttribute(position, b);
  6882. _vC$1.fromBufferAttribute(position, c);
  6883. const morphInfluences = object.morphTargetInfluences;
  6884. if (morphPosition && morphInfluences) {
  6885. _morphA.set(0, 0, 0);
  6886. _morphB.set(0, 0, 0);
  6887. _morphC.set(0, 0, 0);
  6888. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6889. const influence = morphInfluences[i];
  6890. const morphAttribute = morphPosition[i];
  6891. if (influence === 0) continue;
  6892. _tempA.fromBufferAttribute(morphAttribute, a);
  6893. _tempB.fromBufferAttribute(morphAttribute, b);
  6894. _tempC.fromBufferAttribute(morphAttribute, c);
  6895. if (morphTargetsRelative) {
  6896. _morphA.addScaledVector(_tempA, influence);
  6897. _morphB.addScaledVector(_tempB, influence);
  6898. _morphC.addScaledVector(_tempC, influence);
  6899. } else {
  6900. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6901. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6902. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6903. }
  6904. }
  6905. _vA$1.add(_morphA);
  6906. _vB$1.add(_morphB);
  6907. _vC$1.add(_morphC);
  6908. }
  6909. if (object.isSkinnedMesh) {
  6910. object.boneTransform(a, _vA$1);
  6911. object.boneTransform(b, _vB$1);
  6912. object.boneTransform(c, _vC$1);
  6913. }
  6914. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6915. if (intersection) {
  6916. if (uv) {
  6917. _uvA$1.fromBufferAttribute(uv, a);
  6918. _uvB$1.fromBufferAttribute(uv, b);
  6919. _uvC$1.fromBufferAttribute(uv, c);
  6920. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6921. }
  6922. if (uv2) {
  6923. _uvA$1.fromBufferAttribute(uv2, a);
  6924. _uvB$1.fromBufferAttribute(uv2, b);
  6925. _uvC$1.fromBufferAttribute(uv2, c);
  6926. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6927. }
  6928. const face = {
  6929. a: a,
  6930. b: b,
  6931. c: c,
  6932. normal: new Vector3(),
  6933. materialIndex: 0
  6934. };
  6935. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6936. intersection.face = face;
  6937. }
  6938. return intersection;
  6939. }
  6940. class BoxGeometry extends BufferGeometry {
  6941. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6942. super();
  6943. this.type = 'BoxGeometry';
  6944. this.parameters = {
  6945. width: width,
  6946. height: height,
  6947. depth: depth,
  6948. widthSegments: widthSegments,
  6949. heightSegments: heightSegments,
  6950. depthSegments: depthSegments
  6951. };
  6952. const scope = this; // segments
  6953. widthSegments = Math.floor(widthSegments);
  6954. heightSegments = Math.floor(heightSegments);
  6955. depthSegments = Math.floor(depthSegments); // buffers
  6956. const indices = [];
  6957. const vertices = [];
  6958. const normals = [];
  6959. const uvs = []; // helper variables
  6960. let numberOfVertices = 0;
  6961. let groupStart = 0; // build each side of the box geometry
  6962. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6963. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6964. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6965. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6966. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6967. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6968. // build geometry
  6969. this.setIndex(indices);
  6970. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6971. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6972. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6973. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6974. const segmentWidth = width / gridX;
  6975. const segmentHeight = height / gridY;
  6976. const widthHalf = width / 2;
  6977. const heightHalf = height / 2;
  6978. const depthHalf = depth / 2;
  6979. const gridX1 = gridX + 1;
  6980. const gridY1 = gridY + 1;
  6981. let vertexCounter = 0;
  6982. let groupCount = 0;
  6983. const vector = new Vector3(); // generate vertices, normals and uvs
  6984. for (let iy = 0; iy < gridY1; iy++) {
  6985. const y = iy * segmentHeight - heightHalf;
  6986. for (let ix = 0; ix < gridX1; ix++) {
  6987. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6988. vector[u] = x * udir;
  6989. vector[v] = y * vdir;
  6990. vector[w] = depthHalf; // now apply vector to vertex buffer
  6991. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6992. vector[u] = 0;
  6993. vector[v] = 0;
  6994. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6995. normals.push(vector.x, vector.y, vector.z); // uvs
  6996. uvs.push(ix / gridX);
  6997. uvs.push(1 - iy / gridY); // counters
  6998. vertexCounter += 1;
  6999. }
  7000. } // indices
  7001. // 1. you need three indices to draw a single face
  7002. // 2. a single segment consists of two faces
  7003. // 3. so we need to generate six (2*3) indices per segment
  7004. for (let iy = 0; iy < gridY; iy++) {
  7005. for (let ix = 0; ix < gridX; ix++) {
  7006. const a = numberOfVertices + ix + gridX1 * iy;
  7007. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7008. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7009. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7010. indices.push(a, b, d);
  7011. indices.push(b, c, d); // increase counter
  7012. groupCount += 6;
  7013. }
  7014. } // add a group to the geometry. this will ensure multi material support
  7015. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7016. groupStart += groupCount; // update total number of vertices
  7017. numberOfVertices += vertexCounter;
  7018. }
  7019. }
  7020. static fromJSON(data) {
  7021. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  7022. }
  7023. }
  7024. /**
  7025. * Uniform Utilities
  7026. */
  7027. function cloneUniforms(src) {
  7028. const dst = {};
  7029. for (const u in src) {
  7030. dst[u] = {};
  7031. for (const p in src[u]) {
  7032. const property = src[u][p];
  7033. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7034. dst[u][p] = property.clone();
  7035. } else if (Array.isArray(property)) {
  7036. dst[u][p] = property.slice();
  7037. } else {
  7038. dst[u][p] = property;
  7039. }
  7040. }
  7041. }
  7042. return dst;
  7043. }
  7044. function mergeUniforms(uniforms) {
  7045. const merged = {};
  7046. for (let u = 0; u < uniforms.length; u++) {
  7047. const tmp = cloneUniforms(uniforms[u]);
  7048. for (const p in tmp) {
  7049. merged[p] = tmp[p];
  7050. }
  7051. }
  7052. return merged;
  7053. }
  7054. function cloneUniformsGroups(src) {
  7055. const dst = [];
  7056. for (let u = 0; u < src.length; u++) {
  7057. dst.push(src[u].clone());
  7058. }
  7059. return dst;
  7060. } // Legacy
  7061. const UniformsUtils = {
  7062. clone: cloneUniforms,
  7063. merge: mergeUniforms
  7064. };
  7065. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7066. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7067. class ShaderMaterial extends Material {
  7068. constructor(parameters) {
  7069. super();
  7070. this.isShaderMaterial = true;
  7071. this.type = 'ShaderMaterial';
  7072. this.defines = {};
  7073. this.uniforms = {};
  7074. this.uniformsGroups = [];
  7075. this.vertexShader = default_vertex;
  7076. this.fragmentShader = default_fragment;
  7077. this.linewidth = 1;
  7078. this.wireframe = false;
  7079. this.wireframeLinewidth = 1;
  7080. this.fog = false; // set to use scene fog
  7081. this.lights = false; // set to use scene lights
  7082. this.clipping = false; // set to use user-defined clipping planes
  7083. this.extensions = {
  7084. derivatives: false,
  7085. // set to use derivatives
  7086. fragDepth: false,
  7087. // set to use fragment depth values
  7088. drawBuffers: false,
  7089. // set to use draw buffers
  7090. shaderTextureLOD: false // set to use shader texture LOD
  7091. }; // When rendered geometry doesn't include these attributes but the material does,
  7092. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7093. this.defaultAttributeValues = {
  7094. 'color': [1, 1, 1],
  7095. 'uv': [0, 0],
  7096. 'uv2': [0, 0]
  7097. };
  7098. this.index0AttributeName = undefined;
  7099. this.uniformsNeedUpdate = false;
  7100. this.glslVersion = null;
  7101. if (parameters !== undefined) {
  7102. if (parameters.attributes !== undefined) {
  7103. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7104. }
  7105. this.setValues(parameters);
  7106. }
  7107. }
  7108. copy(source) {
  7109. super.copy(source);
  7110. this.fragmentShader = source.fragmentShader;
  7111. this.vertexShader = source.vertexShader;
  7112. this.uniforms = cloneUniforms(source.uniforms);
  7113. this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups);
  7114. this.defines = Object.assign({}, source.defines);
  7115. this.wireframe = source.wireframe;
  7116. this.wireframeLinewidth = source.wireframeLinewidth;
  7117. this.fog = source.fog;
  7118. this.lights = source.lights;
  7119. this.clipping = source.clipping;
  7120. this.extensions = Object.assign({}, source.extensions);
  7121. this.glslVersion = source.glslVersion;
  7122. return this;
  7123. }
  7124. toJSON(meta) {
  7125. const data = super.toJSON(meta);
  7126. data.glslVersion = this.glslVersion;
  7127. data.uniforms = {};
  7128. for (const name in this.uniforms) {
  7129. const uniform = this.uniforms[name];
  7130. const value = uniform.value;
  7131. if (value && value.isTexture) {
  7132. data.uniforms[name] = {
  7133. type: 't',
  7134. value: value.toJSON(meta).uuid
  7135. };
  7136. } else if (value && value.isColor) {
  7137. data.uniforms[name] = {
  7138. type: 'c',
  7139. value: value.getHex()
  7140. };
  7141. } else if (value && value.isVector2) {
  7142. data.uniforms[name] = {
  7143. type: 'v2',
  7144. value: value.toArray()
  7145. };
  7146. } else if (value && value.isVector3) {
  7147. data.uniforms[name] = {
  7148. type: 'v3',
  7149. value: value.toArray()
  7150. };
  7151. } else if (value && value.isVector4) {
  7152. data.uniforms[name] = {
  7153. type: 'v4',
  7154. value: value.toArray()
  7155. };
  7156. } else if (value && value.isMatrix3) {
  7157. data.uniforms[name] = {
  7158. type: 'm3',
  7159. value: value.toArray()
  7160. };
  7161. } else if (value && value.isMatrix4) {
  7162. data.uniforms[name] = {
  7163. type: 'm4',
  7164. value: value.toArray()
  7165. };
  7166. } else {
  7167. data.uniforms[name] = {
  7168. value: value
  7169. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7170. }
  7171. }
  7172. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7173. data.vertexShader = this.vertexShader;
  7174. data.fragmentShader = this.fragmentShader;
  7175. const extensions = {};
  7176. for (const key in this.extensions) {
  7177. if (this.extensions[key] === true) extensions[key] = true;
  7178. }
  7179. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7180. return data;
  7181. }
  7182. }
  7183. class Camera extends Object3D {
  7184. constructor() {
  7185. super();
  7186. this.isCamera = true;
  7187. this.type = 'Camera';
  7188. this.matrixWorldInverse = new Matrix4();
  7189. this.projectionMatrix = new Matrix4();
  7190. this.projectionMatrixInverse = new Matrix4();
  7191. }
  7192. copy(source, recursive) {
  7193. super.copy(source, recursive);
  7194. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7195. this.projectionMatrix.copy(source.projectionMatrix);
  7196. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7197. return this;
  7198. }
  7199. getWorldDirection(target) {
  7200. this.updateWorldMatrix(true, false);
  7201. const e = this.matrixWorld.elements;
  7202. return target.set(-e[8], -e[9], -e[10]).normalize();
  7203. }
  7204. updateMatrixWorld(force) {
  7205. super.updateMatrixWorld(force);
  7206. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7207. }
  7208. updateWorldMatrix(updateParents, updateChildren) {
  7209. super.updateWorldMatrix(updateParents, updateChildren);
  7210. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7211. }
  7212. clone() {
  7213. return new this.constructor().copy(this);
  7214. }
  7215. }
  7216. class PerspectiveCamera extends Camera {
  7217. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7218. super();
  7219. this.isPerspectiveCamera = true;
  7220. this.type = 'PerspectiveCamera';
  7221. this.fov = fov;
  7222. this.zoom = 1;
  7223. this.near = near;
  7224. this.far = far;
  7225. this.focus = 10;
  7226. this.aspect = aspect;
  7227. this.view = null;
  7228. this.filmGauge = 35; // width of the film (default in millimeters)
  7229. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7230. this.updateProjectionMatrix();
  7231. }
  7232. copy(source, recursive) {
  7233. super.copy(source, recursive);
  7234. this.fov = source.fov;
  7235. this.zoom = source.zoom;
  7236. this.near = source.near;
  7237. this.far = source.far;
  7238. this.focus = source.focus;
  7239. this.aspect = source.aspect;
  7240. this.view = source.view === null ? null : Object.assign({}, source.view);
  7241. this.filmGauge = source.filmGauge;
  7242. this.filmOffset = source.filmOffset;
  7243. return this;
  7244. }
  7245. /**
  7246. * Sets the FOV by focal length in respect to the current .filmGauge.
  7247. *
  7248. * The default film gauge is 35, so that the focal length can be specified for
  7249. * a 35mm (full frame) camera.
  7250. *
  7251. * Values for focal length and film gauge must have the same unit.
  7252. */
  7253. setFocalLength(focalLength) {
  7254. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7255. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7256. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7257. this.updateProjectionMatrix();
  7258. }
  7259. /**
  7260. * Calculates the focal length from the current .fov and .filmGauge.
  7261. */
  7262. getFocalLength() {
  7263. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7264. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7265. }
  7266. getEffectiveFOV() {
  7267. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7268. }
  7269. getFilmWidth() {
  7270. // film not completely covered in portrait format (aspect < 1)
  7271. return this.filmGauge * Math.min(this.aspect, 1);
  7272. }
  7273. getFilmHeight() {
  7274. // film not completely covered in landscape format (aspect > 1)
  7275. return this.filmGauge / Math.max(this.aspect, 1);
  7276. }
  7277. /**
  7278. * Sets an offset in a larger frustum. This is useful for multi-window or
  7279. * multi-monitor/multi-machine setups.
  7280. *
  7281. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7282. * the monitors are in grid like this
  7283. *
  7284. * +---+---+---+
  7285. * | A | B | C |
  7286. * +---+---+---+
  7287. * | D | E | F |
  7288. * +---+---+---+
  7289. *
  7290. * then for each monitor you would call it like this
  7291. *
  7292. * const w = 1920;
  7293. * const h = 1080;
  7294. * const fullWidth = w * 3;
  7295. * const fullHeight = h * 2;
  7296. *
  7297. * --A--
  7298. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7299. * --B--
  7300. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7301. * --C--
  7302. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7303. * --D--
  7304. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7305. * --E--
  7306. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7307. * --F--
  7308. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7309. *
  7310. * Note there is no reason monitors have to be the same size or in a grid.
  7311. */
  7312. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7313. this.aspect = fullWidth / fullHeight;
  7314. if (this.view === null) {
  7315. this.view = {
  7316. enabled: true,
  7317. fullWidth: 1,
  7318. fullHeight: 1,
  7319. offsetX: 0,
  7320. offsetY: 0,
  7321. width: 1,
  7322. height: 1
  7323. };
  7324. }
  7325. this.view.enabled = true;
  7326. this.view.fullWidth = fullWidth;
  7327. this.view.fullHeight = fullHeight;
  7328. this.view.offsetX = x;
  7329. this.view.offsetY = y;
  7330. this.view.width = width;
  7331. this.view.height = height;
  7332. this.updateProjectionMatrix();
  7333. }
  7334. clearViewOffset() {
  7335. if (this.view !== null) {
  7336. this.view.enabled = false;
  7337. }
  7338. this.updateProjectionMatrix();
  7339. }
  7340. updateProjectionMatrix() {
  7341. const near = this.near;
  7342. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7343. let height = 2 * top;
  7344. let width = this.aspect * height;
  7345. let left = -0.5 * width;
  7346. const view = this.view;
  7347. if (this.view !== null && this.view.enabled) {
  7348. const fullWidth = view.fullWidth,
  7349. fullHeight = view.fullHeight;
  7350. left += view.offsetX * width / fullWidth;
  7351. top -= view.offsetY * height / fullHeight;
  7352. width *= view.width / fullWidth;
  7353. height *= view.height / fullHeight;
  7354. }
  7355. const skew = this.filmOffset;
  7356. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7357. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7358. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7359. }
  7360. toJSON(meta) {
  7361. const data = super.toJSON(meta);
  7362. data.object.fov = this.fov;
  7363. data.object.zoom = this.zoom;
  7364. data.object.near = this.near;
  7365. data.object.far = this.far;
  7366. data.object.focus = this.focus;
  7367. data.object.aspect = this.aspect;
  7368. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7369. data.object.filmGauge = this.filmGauge;
  7370. data.object.filmOffset = this.filmOffset;
  7371. return data;
  7372. }
  7373. }
  7374. const fov = 90,
  7375. aspect = 1;
  7376. class CubeCamera extends Object3D {
  7377. constructor(near, far, renderTarget) {
  7378. super();
  7379. this.type = 'CubeCamera';
  7380. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7381. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7382. return;
  7383. }
  7384. this.renderTarget = renderTarget;
  7385. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7386. cameraPX.layers = this.layers;
  7387. cameraPX.up.set(0, -1, 0);
  7388. cameraPX.lookAt(new Vector3(1, 0, 0));
  7389. this.add(cameraPX);
  7390. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7391. cameraNX.layers = this.layers;
  7392. cameraNX.up.set(0, -1, 0);
  7393. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7394. this.add(cameraNX);
  7395. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7396. cameraPY.layers = this.layers;
  7397. cameraPY.up.set(0, 0, 1);
  7398. cameraPY.lookAt(new Vector3(0, 1, 0));
  7399. this.add(cameraPY);
  7400. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7401. cameraNY.layers = this.layers;
  7402. cameraNY.up.set(0, 0, -1);
  7403. cameraNY.lookAt(new Vector3(0, -1, 0));
  7404. this.add(cameraNY);
  7405. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7406. cameraPZ.layers = this.layers;
  7407. cameraPZ.up.set(0, -1, 0);
  7408. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7409. this.add(cameraPZ);
  7410. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7411. cameraNZ.layers = this.layers;
  7412. cameraNZ.up.set(0, -1, 0);
  7413. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7414. this.add(cameraNZ);
  7415. }
  7416. update(renderer, scene) {
  7417. if (this.parent === null) this.updateMatrixWorld();
  7418. const renderTarget = this.renderTarget;
  7419. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7420. const currentRenderTarget = renderer.getRenderTarget();
  7421. const currentToneMapping = renderer.toneMapping;
  7422. const currentXrEnabled = renderer.xr.enabled;
  7423. renderer.toneMapping = NoToneMapping;
  7424. renderer.xr.enabled = false;
  7425. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7426. renderTarget.texture.generateMipmaps = false;
  7427. renderer.setRenderTarget(renderTarget, 0);
  7428. renderer.render(scene, cameraPX);
  7429. renderer.setRenderTarget(renderTarget, 1);
  7430. renderer.render(scene, cameraNX);
  7431. renderer.setRenderTarget(renderTarget, 2);
  7432. renderer.render(scene, cameraPY);
  7433. renderer.setRenderTarget(renderTarget, 3);
  7434. renderer.render(scene, cameraNY);
  7435. renderer.setRenderTarget(renderTarget, 4);
  7436. renderer.render(scene, cameraPZ);
  7437. renderTarget.texture.generateMipmaps = generateMipmaps;
  7438. renderer.setRenderTarget(renderTarget, 5);
  7439. renderer.render(scene, cameraNZ);
  7440. renderer.setRenderTarget(currentRenderTarget);
  7441. renderer.toneMapping = currentToneMapping;
  7442. renderer.xr.enabled = currentXrEnabled;
  7443. renderTarget.texture.needsPMREMUpdate = true;
  7444. }
  7445. }
  7446. class CubeTexture extends Texture {
  7447. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7448. images = images !== undefined ? images : [];
  7449. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7450. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7451. this.isCubeTexture = true;
  7452. this.flipY = false;
  7453. }
  7454. get images() {
  7455. return this.image;
  7456. }
  7457. set images(value) {
  7458. this.image = value;
  7459. }
  7460. }
  7461. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7462. constructor(size, options = {}) {
  7463. super(size, size, options);
  7464. this.isWebGLCubeRenderTarget = true;
  7465. const image = {
  7466. width: size,
  7467. height: size,
  7468. depth: 1
  7469. };
  7470. const images = [image, image, image, image, image, image];
  7471. 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)
  7472. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7473. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7474. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7475. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7476. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7477. this.texture.isRenderTargetTexture = true;
  7478. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7479. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7480. }
  7481. fromEquirectangularTexture(renderer, texture) {
  7482. this.texture.type = texture.type;
  7483. this.texture.encoding = texture.encoding;
  7484. this.texture.generateMipmaps = texture.generateMipmaps;
  7485. this.texture.minFilter = texture.minFilter;
  7486. this.texture.magFilter = texture.magFilter;
  7487. const shader = {
  7488. uniforms: {
  7489. tEquirect: {
  7490. value: null
  7491. }
  7492. },
  7493. vertexShader:
  7494. /* glsl */
  7495. `
  7496. varying vec3 vWorldDirection;
  7497. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7498. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7499. }
  7500. void main() {
  7501. vWorldDirection = transformDirection( position, modelMatrix );
  7502. #include <begin_vertex>
  7503. #include <project_vertex>
  7504. }
  7505. `,
  7506. fragmentShader:
  7507. /* glsl */
  7508. `
  7509. uniform sampler2D tEquirect;
  7510. varying vec3 vWorldDirection;
  7511. #include <common>
  7512. void main() {
  7513. vec3 direction = normalize( vWorldDirection );
  7514. vec2 sampleUV = equirectUv( direction );
  7515. gl_FragColor = texture2D( tEquirect, sampleUV );
  7516. }
  7517. `
  7518. };
  7519. const geometry = new BoxGeometry(5, 5, 5);
  7520. const material = new ShaderMaterial({
  7521. name: 'CubemapFromEquirect',
  7522. uniforms: cloneUniforms(shader.uniforms),
  7523. vertexShader: shader.vertexShader,
  7524. fragmentShader: shader.fragmentShader,
  7525. side: BackSide,
  7526. blending: NoBlending
  7527. });
  7528. material.uniforms.tEquirect.value = texture;
  7529. const mesh = new Mesh(geometry, material);
  7530. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7531. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7532. const camera = new CubeCamera(1, 10, this);
  7533. camera.update(renderer, mesh);
  7534. texture.minFilter = currentMinFilter;
  7535. mesh.geometry.dispose();
  7536. mesh.material.dispose();
  7537. return this;
  7538. }
  7539. clear(renderer, color, depth, stencil) {
  7540. const currentRenderTarget = renderer.getRenderTarget();
  7541. for (let i = 0; i < 6; i++) {
  7542. renderer.setRenderTarget(this, i);
  7543. renderer.clear(color, depth, stencil);
  7544. }
  7545. renderer.setRenderTarget(currentRenderTarget);
  7546. }
  7547. }
  7548. const _vector1 = /*@__PURE__*/new Vector3();
  7549. const _vector2 = /*@__PURE__*/new Vector3();
  7550. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7551. class Plane {
  7552. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7553. this.isPlane = true; // normal is assumed to be normalized
  7554. this.normal = normal;
  7555. this.constant = constant;
  7556. }
  7557. set(normal, constant) {
  7558. this.normal.copy(normal);
  7559. this.constant = constant;
  7560. return this;
  7561. }
  7562. setComponents(x, y, z, w) {
  7563. this.normal.set(x, y, z);
  7564. this.constant = w;
  7565. return this;
  7566. }
  7567. setFromNormalAndCoplanarPoint(normal, point) {
  7568. this.normal.copy(normal);
  7569. this.constant = -point.dot(this.normal);
  7570. return this;
  7571. }
  7572. setFromCoplanarPoints(a, b, c) {
  7573. 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)?
  7574. this.setFromNormalAndCoplanarPoint(normal, a);
  7575. return this;
  7576. }
  7577. copy(plane) {
  7578. this.normal.copy(plane.normal);
  7579. this.constant = plane.constant;
  7580. return this;
  7581. }
  7582. normalize() {
  7583. // Note: will lead to a divide by zero if the plane is invalid.
  7584. const inverseNormalLength = 1.0 / this.normal.length();
  7585. this.normal.multiplyScalar(inverseNormalLength);
  7586. this.constant *= inverseNormalLength;
  7587. return this;
  7588. }
  7589. negate() {
  7590. this.constant *= -1;
  7591. this.normal.negate();
  7592. return this;
  7593. }
  7594. distanceToPoint(point) {
  7595. return this.normal.dot(point) + this.constant;
  7596. }
  7597. distanceToSphere(sphere) {
  7598. return this.distanceToPoint(sphere.center) - sphere.radius;
  7599. }
  7600. projectPoint(point, target) {
  7601. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7602. }
  7603. intersectLine(line, target) {
  7604. const direction = line.delta(_vector1);
  7605. const denominator = this.normal.dot(direction);
  7606. if (denominator === 0) {
  7607. // line is coplanar, return origin
  7608. if (this.distanceToPoint(line.start) === 0) {
  7609. return target.copy(line.start);
  7610. } // Unsure if this is the correct method to handle this case.
  7611. return null;
  7612. }
  7613. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7614. if (t < 0 || t > 1) {
  7615. return null;
  7616. }
  7617. return target.copy(direction).multiplyScalar(t).add(line.start);
  7618. }
  7619. intersectsLine(line) {
  7620. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7621. const startSign = this.distanceToPoint(line.start);
  7622. const endSign = this.distanceToPoint(line.end);
  7623. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7624. }
  7625. intersectsBox(box) {
  7626. return box.intersectsPlane(this);
  7627. }
  7628. intersectsSphere(sphere) {
  7629. return sphere.intersectsPlane(this);
  7630. }
  7631. coplanarPoint(target) {
  7632. return target.copy(this.normal).multiplyScalar(-this.constant);
  7633. }
  7634. applyMatrix4(matrix, optionalNormalMatrix) {
  7635. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7636. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7637. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7638. this.constant = -referencePoint.dot(normal);
  7639. return this;
  7640. }
  7641. translate(offset) {
  7642. this.constant -= offset.dot(this.normal);
  7643. return this;
  7644. }
  7645. equals(plane) {
  7646. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7647. }
  7648. clone() {
  7649. return new this.constructor().copy(this);
  7650. }
  7651. }
  7652. const _sphere$2 = /*@__PURE__*/new Sphere();
  7653. const _vector$7 = /*@__PURE__*/new Vector3();
  7654. class Frustum {
  7655. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7656. this.planes = [p0, p1, p2, p3, p4, p5];
  7657. }
  7658. set(p0, p1, p2, p3, p4, p5) {
  7659. const planes = this.planes;
  7660. planes[0].copy(p0);
  7661. planes[1].copy(p1);
  7662. planes[2].copy(p2);
  7663. planes[3].copy(p3);
  7664. planes[4].copy(p4);
  7665. planes[5].copy(p5);
  7666. return this;
  7667. }
  7668. copy(frustum) {
  7669. const planes = this.planes;
  7670. for (let i = 0; i < 6; i++) {
  7671. planes[i].copy(frustum.planes[i]);
  7672. }
  7673. return this;
  7674. }
  7675. setFromProjectionMatrix(m) {
  7676. const planes = this.planes;
  7677. const me = m.elements;
  7678. const me0 = me[0],
  7679. me1 = me[1],
  7680. me2 = me[2],
  7681. me3 = me[3];
  7682. const me4 = me[4],
  7683. me5 = me[5],
  7684. me6 = me[6],
  7685. me7 = me[7];
  7686. const me8 = me[8],
  7687. me9 = me[9],
  7688. me10 = me[10],
  7689. me11 = me[11];
  7690. const me12 = me[12],
  7691. me13 = me[13],
  7692. me14 = me[14],
  7693. me15 = me[15];
  7694. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7695. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7696. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7697. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7698. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7699. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7700. return this;
  7701. }
  7702. intersectsObject(object) {
  7703. const geometry = object.geometry;
  7704. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7705. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7706. return this.intersectsSphere(_sphere$2);
  7707. }
  7708. intersectsSprite(sprite) {
  7709. _sphere$2.center.set(0, 0, 0);
  7710. _sphere$2.radius = 0.7071067811865476;
  7711. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7712. return this.intersectsSphere(_sphere$2);
  7713. }
  7714. intersectsSphere(sphere) {
  7715. const planes = this.planes;
  7716. const center = sphere.center;
  7717. const negRadius = -sphere.radius;
  7718. for (let i = 0; i < 6; i++) {
  7719. const distance = planes[i].distanceToPoint(center);
  7720. if (distance < negRadius) {
  7721. return false;
  7722. }
  7723. }
  7724. return true;
  7725. }
  7726. intersectsBox(box) {
  7727. const planes = this.planes;
  7728. for (let i = 0; i < 6; i++) {
  7729. const plane = planes[i]; // corner at max distance
  7730. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7731. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7732. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7733. if (plane.distanceToPoint(_vector$7) < 0) {
  7734. return false;
  7735. }
  7736. }
  7737. return true;
  7738. }
  7739. containsPoint(point) {
  7740. const planes = this.planes;
  7741. for (let i = 0; i < 6; i++) {
  7742. if (planes[i].distanceToPoint(point) < 0) {
  7743. return false;
  7744. }
  7745. }
  7746. return true;
  7747. }
  7748. clone() {
  7749. return new this.constructor().copy(this);
  7750. }
  7751. }
  7752. function WebGLAnimation() {
  7753. let context = null;
  7754. let isAnimating = false;
  7755. let animationLoop = null;
  7756. let requestId = null;
  7757. function onAnimationFrame(time, frame) {
  7758. animationLoop(time, frame);
  7759. requestId = context.requestAnimationFrame(onAnimationFrame);
  7760. }
  7761. return {
  7762. start: function () {
  7763. if (isAnimating === true) return;
  7764. if (animationLoop === null) return;
  7765. requestId = context.requestAnimationFrame(onAnimationFrame);
  7766. isAnimating = true;
  7767. },
  7768. stop: function () {
  7769. context.cancelAnimationFrame(requestId);
  7770. isAnimating = false;
  7771. },
  7772. setAnimationLoop: function (callback) {
  7773. animationLoop = callback;
  7774. },
  7775. setContext: function (value) {
  7776. context = value;
  7777. }
  7778. };
  7779. }
  7780. function WebGLAttributes(gl, capabilities) {
  7781. const isWebGL2 = capabilities.isWebGL2;
  7782. const buffers = new WeakMap();
  7783. function createBuffer(attribute, bufferType) {
  7784. const array = attribute.array;
  7785. const usage = attribute.usage;
  7786. const buffer = gl.createBuffer();
  7787. gl.bindBuffer(bufferType, buffer);
  7788. gl.bufferData(bufferType, array, usage);
  7789. attribute.onUploadCallback();
  7790. let type;
  7791. if (array instanceof Float32Array) {
  7792. type = gl.FLOAT;
  7793. } else if (array instanceof Uint16Array) {
  7794. if (attribute.isFloat16BufferAttribute) {
  7795. if (isWebGL2) {
  7796. type = gl.HALF_FLOAT;
  7797. } else {
  7798. throw new Error('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7799. }
  7800. } else {
  7801. type = gl.UNSIGNED_SHORT;
  7802. }
  7803. } else if (array instanceof Int16Array) {
  7804. type = gl.SHORT;
  7805. } else if (array instanceof Uint32Array) {
  7806. type = gl.UNSIGNED_INT;
  7807. } else if (array instanceof Int32Array) {
  7808. type = gl.INT;
  7809. } else if (array instanceof Int8Array) {
  7810. type = gl.BYTE;
  7811. } else if (array instanceof Uint8Array) {
  7812. type = gl.UNSIGNED_BYTE;
  7813. } else if (array instanceof Uint8ClampedArray) {
  7814. type = gl.UNSIGNED_BYTE;
  7815. } else {
  7816. throw new Error('THREE.WebGLAttributes: Unsupported buffer data format: ' + array);
  7817. }
  7818. return {
  7819. buffer: buffer,
  7820. type: type,
  7821. bytesPerElement: array.BYTES_PER_ELEMENT,
  7822. version: attribute.version
  7823. };
  7824. }
  7825. function updateBuffer(buffer, attribute, bufferType) {
  7826. const array = attribute.array;
  7827. const updateRange = attribute.updateRange;
  7828. gl.bindBuffer(bufferType, buffer);
  7829. if (updateRange.count === -1) {
  7830. // Not using update ranges
  7831. gl.bufferSubData(bufferType, 0, array);
  7832. } else {
  7833. if (isWebGL2) {
  7834. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7835. } else {
  7836. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7837. }
  7838. updateRange.count = -1; // reset range
  7839. }
  7840. } //
  7841. function get(attribute) {
  7842. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7843. return buffers.get(attribute);
  7844. }
  7845. function remove(attribute) {
  7846. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7847. const data = buffers.get(attribute);
  7848. if (data) {
  7849. gl.deleteBuffer(data.buffer);
  7850. buffers.delete(attribute);
  7851. }
  7852. }
  7853. function update(attribute, bufferType) {
  7854. if (attribute.isGLBufferAttribute) {
  7855. const cached = buffers.get(attribute);
  7856. if (!cached || cached.version < attribute.version) {
  7857. buffers.set(attribute, {
  7858. buffer: attribute.buffer,
  7859. type: attribute.type,
  7860. bytesPerElement: attribute.elementSize,
  7861. version: attribute.version
  7862. });
  7863. }
  7864. return;
  7865. }
  7866. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7867. const data = buffers.get(attribute);
  7868. if (data === undefined) {
  7869. buffers.set(attribute, createBuffer(attribute, bufferType));
  7870. } else if (data.version < attribute.version) {
  7871. updateBuffer(data.buffer, attribute, bufferType);
  7872. data.version = attribute.version;
  7873. }
  7874. }
  7875. return {
  7876. get: get,
  7877. remove: remove,
  7878. update: update
  7879. };
  7880. }
  7881. class PlaneGeometry extends BufferGeometry {
  7882. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7883. super();
  7884. this.type = 'PlaneGeometry';
  7885. this.parameters = {
  7886. width: width,
  7887. height: height,
  7888. widthSegments: widthSegments,
  7889. heightSegments: heightSegments
  7890. };
  7891. const width_half = width / 2;
  7892. const height_half = height / 2;
  7893. const gridX = Math.floor(widthSegments);
  7894. const gridY = Math.floor(heightSegments);
  7895. const gridX1 = gridX + 1;
  7896. const gridY1 = gridY + 1;
  7897. const segment_width = width / gridX;
  7898. const segment_height = height / gridY; //
  7899. const indices = [];
  7900. const vertices = [];
  7901. const normals = [];
  7902. const uvs = [];
  7903. for (let iy = 0; iy < gridY1; iy++) {
  7904. const y = iy * segment_height - height_half;
  7905. for (let ix = 0; ix < gridX1; ix++) {
  7906. const x = ix * segment_width - width_half;
  7907. vertices.push(x, -y, 0);
  7908. normals.push(0, 0, 1);
  7909. uvs.push(ix / gridX);
  7910. uvs.push(1 - iy / gridY);
  7911. }
  7912. }
  7913. for (let iy = 0; iy < gridY; iy++) {
  7914. for (let ix = 0; ix < gridX; ix++) {
  7915. const a = ix + gridX1 * iy;
  7916. const b = ix + gridX1 * (iy + 1);
  7917. const c = ix + 1 + gridX1 * (iy + 1);
  7918. const d = ix + 1 + gridX1 * iy;
  7919. indices.push(a, b, d);
  7920. indices.push(b, c, d);
  7921. }
  7922. }
  7923. this.setIndex(indices);
  7924. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7925. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7926. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7927. }
  7928. static fromJSON(data) {
  7929. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7930. }
  7931. }
  7932. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7933. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7934. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7935. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7936. 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";
  7937. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7938. var begin_vertex = "vec3 transformed = vec3( position );";
  7939. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7940. 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";
  7941. 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";
  7942. 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";
  7943. 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";
  7944. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7945. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7946. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7947. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7948. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7949. 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";
  7950. 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";
  7951. 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}";
  7952. 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 r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + 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 ), 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";
  7953. 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";
  7954. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7955. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7956. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7957. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7958. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7959. 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}";
  7960. 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";
  7961. 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";
  7962. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\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";
  7963. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\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";
  7964. 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";
  7965. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7966. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7967. 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";
  7968. 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";
  7969. 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\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7970. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7971. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7972. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7973. 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";
  7974. 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";
  7975. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7976. 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)";
  7977. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7978. 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)";
  7979. 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\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( ( ior - 1.0 ) / ( 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";
  7980. 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};\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}";
  7981. 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";
  7982. 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";
  7983. 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";
  7984. 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";
  7985. 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";
  7986. 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";
  7987. 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";
  7988. 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";
  7989. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7990. 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";
  7991. 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";
  7992. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7993. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7994. 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";
  7995. 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";
  7996. 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";
  7997. 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";
  7998. 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;";
  7999. 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";
  8000. 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";
  8001. 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";
  8002. 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";
  8003. 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";
  8004. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8005. 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";
  8006. 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";
  8007. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8008. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8009. 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}";
  8010. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8011. 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;";
  8012. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8013. 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";
  8014. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8015. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8016. 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";
  8017. 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";
  8018. 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";
  8019. 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}";
  8020. 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";
  8021. 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";
  8022. 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";
  8023. 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";
  8024. 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";
  8025. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8026. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8027. 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; }";
  8028. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= 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, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
  8029. 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";
  8030. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8031. 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";
  8032. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8033. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8034. 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";
  8035. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8036. 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";
  8037. 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}";
  8038. 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}";
  8039. 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}";
  8040. 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}";
  8041. 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}";
  8042. 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}";
  8043. 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}";
  8044. 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}";
  8045. 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}";
  8046. 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}";
  8047. 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}";
  8048. 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}";
  8049. 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}";
  8050. 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 <cube_uv_reflection_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}";
  8051. const vertex$9 = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_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 <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 <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8052. const fragment$9 = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\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 <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_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 <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\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}";
  8053. 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}";
  8054. 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}";
  8055. 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}";
  8056. 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}";
  8057. 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}";
  8058. 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 <cube_uv_reflection_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}";
  8059. 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}";
  8060. 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}";
  8061. 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}";
  8062. 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}";
  8063. 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}";
  8064. 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}";
  8065. 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}";
  8066. 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}";
  8067. 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}";
  8068. 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}";
  8069. const ShaderChunk = {
  8070. alphamap_fragment: alphamap_fragment,
  8071. alphamap_pars_fragment: alphamap_pars_fragment,
  8072. alphatest_fragment: alphatest_fragment,
  8073. alphatest_pars_fragment: alphatest_pars_fragment,
  8074. aomap_fragment: aomap_fragment,
  8075. aomap_pars_fragment: aomap_pars_fragment,
  8076. begin_vertex: begin_vertex,
  8077. beginnormal_vertex: beginnormal_vertex,
  8078. bsdfs: bsdfs,
  8079. iridescence_fragment: iridescence_fragment,
  8080. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8081. clipping_planes_fragment: clipping_planes_fragment,
  8082. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8083. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8084. clipping_planes_vertex: clipping_planes_vertex,
  8085. color_fragment: color_fragment,
  8086. color_pars_fragment: color_pars_fragment,
  8087. color_pars_vertex: color_pars_vertex,
  8088. color_vertex: color_vertex,
  8089. common: common,
  8090. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8091. defaultnormal_vertex: defaultnormal_vertex,
  8092. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8093. displacementmap_vertex: displacementmap_vertex,
  8094. emissivemap_fragment: emissivemap_fragment,
  8095. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8096. encodings_fragment: encodings_fragment,
  8097. encodings_pars_fragment: encodings_pars_fragment,
  8098. envmap_fragment: envmap_fragment,
  8099. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8100. envmap_pars_fragment: envmap_pars_fragment,
  8101. envmap_pars_vertex: envmap_pars_vertex,
  8102. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8103. envmap_vertex: envmap_vertex,
  8104. fog_vertex: fog_vertex,
  8105. fog_pars_vertex: fog_pars_vertex,
  8106. fog_fragment: fog_fragment,
  8107. fog_pars_fragment: fog_pars_fragment,
  8108. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8109. lightmap_fragment: lightmap_fragment,
  8110. lightmap_pars_fragment: lightmap_pars_fragment,
  8111. lights_lambert_vertex: lights_lambert_vertex,
  8112. lights_pars_begin: lights_pars_begin,
  8113. lights_toon_fragment: lights_toon_fragment,
  8114. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8115. lights_phong_fragment: lights_phong_fragment,
  8116. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8117. lights_physical_fragment: lights_physical_fragment,
  8118. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8119. lights_fragment_begin: lights_fragment_begin,
  8120. lights_fragment_maps: lights_fragment_maps,
  8121. lights_fragment_end: lights_fragment_end,
  8122. logdepthbuf_fragment: logdepthbuf_fragment,
  8123. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8124. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8125. logdepthbuf_vertex: logdepthbuf_vertex,
  8126. map_fragment: map_fragment,
  8127. map_pars_fragment: map_pars_fragment,
  8128. map_particle_fragment: map_particle_fragment,
  8129. map_particle_pars_fragment: map_particle_pars_fragment,
  8130. metalnessmap_fragment: metalnessmap_fragment,
  8131. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8132. morphcolor_vertex: morphcolor_vertex,
  8133. morphnormal_vertex: morphnormal_vertex,
  8134. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8135. morphtarget_vertex: morphtarget_vertex,
  8136. normal_fragment_begin: normal_fragment_begin,
  8137. normal_fragment_maps: normal_fragment_maps,
  8138. normal_pars_fragment: normal_pars_fragment,
  8139. normal_pars_vertex: normal_pars_vertex,
  8140. normal_vertex: normal_vertex,
  8141. normalmap_pars_fragment: normalmap_pars_fragment,
  8142. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8143. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8144. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8145. iridescence_pars_fragment: iridescence_pars_fragment,
  8146. output_fragment: output_fragment,
  8147. packing: packing,
  8148. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8149. project_vertex: project_vertex,
  8150. dithering_fragment: dithering_fragment,
  8151. dithering_pars_fragment: dithering_pars_fragment,
  8152. roughnessmap_fragment: roughnessmap_fragment,
  8153. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8154. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8155. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8156. shadowmap_vertex: shadowmap_vertex,
  8157. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8158. skinbase_vertex: skinbase_vertex,
  8159. skinning_pars_vertex: skinning_pars_vertex,
  8160. skinning_vertex: skinning_vertex,
  8161. skinnormal_vertex: skinnormal_vertex,
  8162. specularmap_fragment: specularmap_fragment,
  8163. specularmap_pars_fragment: specularmap_pars_fragment,
  8164. tonemapping_fragment: tonemapping_fragment,
  8165. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8166. transmission_fragment: transmission_fragment,
  8167. transmission_pars_fragment: transmission_pars_fragment,
  8168. uv_pars_fragment: uv_pars_fragment,
  8169. uv_pars_vertex: uv_pars_vertex,
  8170. uv_vertex: uv_vertex,
  8171. uv2_pars_fragment: uv2_pars_fragment,
  8172. uv2_pars_vertex: uv2_pars_vertex,
  8173. uv2_vertex: uv2_vertex,
  8174. worldpos_vertex: worldpos_vertex,
  8175. background_vert: vertex$g,
  8176. background_frag: fragment$g,
  8177. cube_vert: vertex$f,
  8178. cube_frag: fragment$f,
  8179. depth_vert: vertex$e,
  8180. depth_frag: fragment$e,
  8181. distanceRGBA_vert: vertex$d,
  8182. distanceRGBA_frag: fragment$d,
  8183. equirect_vert: vertex$c,
  8184. equirect_frag: fragment$c,
  8185. linedashed_vert: vertex$b,
  8186. linedashed_frag: fragment$b,
  8187. meshbasic_vert: vertex$a,
  8188. meshbasic_frag: fragment$a,
  8189. meshlambert_vert: vertex$9,
  8190. meshlambert_frag: fragment$9,
  8191. meshmatcap_vert: vertex$8,
  8192. meshmatcap_frag: fragment$8,
  8193. meshnormal_vert: vertex$7,
  8194. meshnormal_frag: fragment$7,
  8195. meshphong_vert: vertex$6,
  8196. meshphong_frag: fragment$6,
  8197. meshphysical_vert: vertex$5,
  8198. meshphysical_frag: fragment$5,
  8199. meshtoon_vert: vertex$4,
  8200. meshtoon_frag: fragment$4,
  8201. points_vert: vertex$3,
  8202. points_frag: fragment$3,
  8203. shadow_vert: vertex$2,
  8204. shadow_frag: fragment$2,
  8205. sprite_vert: vertex$1,
  8206. sprite_frag: fragment$1
  8207. };
  8208. /**
  8209. * Uniforms library for shared webgl shaders
  8210. */
  8211. const UniformsLib = {
  8212. common: {
  8213. diffuse: {
  8214. value: /*@__PURE__*/new Color(0xffffff)
  8215. },
  8216. opacity: {
  8217. value: 1.0
  8218. },
  8219. map: {
  8220. value: null
  8221. },
  8222. uvTransform: {
  8223. value: /*@__PURE__*/new Matrix3()
  8224. },
  8225. uv2Transform: {
  8226. value: /*@__PURE__*/new Matrix3()
  8227. },
  8228. alphaMap: {
  8229. value: null
  8230. },
  8231. alphaTest: {
  8232. value: 0
  8233. }
  8234. },
  8235. specularmap: {
  8236. specularMap: {
  8237. value: null
  8238. }
  8239. },
  8240. envmap: {
  8241. envMap: {
  8242. value: null
  8243. },
  8244. flipEnvMap: {
  8245. value: -1
  8246. },
  8247. reflectivity: {
  8248. value: 1.0
  8249. },
  8250. // basic, lambert, phong
  8251. ior: {
  8252. value: 1.5
  8253. },
  8254. // physical
  8255. refractionRatio: {
  8256. value: 0.98
  8257. } // basic, lambert, phong
  8258. },
  8259. aomap: {
  8260. aoMap: {
  8261. value: null
  8262. },
  8263. aoMapIntensity: {
  8264. value: 1
  8265. }
  8266. },
  8267. lightmap: {
  8268. lightMap: {
  8269. value: null
  8270. },
  8271. lightMapIntensity: {
  8272. value: 1
  8273. }
  8274. },
  8275. emissivemap: {
  8276. emissiveMap: {
  8277. value: null
  8278. }
  8279. },
  8280. bumpmap: {
  8281. bumpMap: {
  8282. value: null
  8283. },
  8284. bumpScale: {
  8285. value: 1
  8286. }
  8287. },
  8288. normalmap: {
  8289. normalMap: {
  8290. value: null
  8291. },
  8292. normalScale: {
  8293. value: /*@__PURE__*/new Vector2(1, 1)
  8294. }
  8295. },
  8296. displacementmap: {
  8297. displacementMap: {
  8298. value: null
  8299. },
  8300. displacementScale: {
  8301. value: 1
  8302. },
  8303. displacementBias: {
  8304. value: 0
  8305. }
  8306. },
  8307. roughnessmap: {
  8308. roughnessMap: {
  8309. value: null
  8310. }
  8311. },
  8312. metalnessmap: {
  8313. metalnessMap: {
  8314. value: null
  8315. }
  8316. },
  8317. gradientmap: {
  8318. gradientMap: {
  8319. value: null
  8320. }
  8321. },
  8322. fog: {
  8323. fogDensity: {
  8324. value: 0.00025
  8325. },
  8326. fogNear: {
  8327. value: 1
  8328. },
  8329. fogFar: {
  8330. value: 2000
  8331. },
  8332. fogColor: {
  8333. value: /*@__PURE__*/new Color(0xffffff)
  8334. }
  8335. },
  8336. lights: {
  8337. ambientLightColor: {
  8338. value: []
  8339. },
  8340. lightProbe: {
  8341. value: []
  8342. },
  8343. directionalLights: {
  8344. value: [],
  8345. properties: {
  8346. direction: {},
  8347. color: {}
  8348. }
  8349. },
  8350. directionalLightShadows: {
  8351. value: [],
  8352. properties: {
  8353. shadowBias: {},
  8354. shadowNormalBias: {},
  8355. shadowRadius: {},
  8356. shadowMapSize: {}
  8357. }
  8358. },
  8359. directionalShadowMap: {
  8360. value: []
  8361. },
  8362. directionalShadowMatrix: {
  8363. value: []
  8364. },
  8365. spotLights: {
  8366. value: [],
  8367. properties: {
  8368. color: {},
  8369. position: {},
  8370. direction: {},
  8371. distance: {},
  8372. coneCos: {},
  8373. penumbraCos: {},
  8374. decay: {}
  8375. }
  8376. },
  8377. spotLightShadows: {
  8378. value: [],
  8379. properties: {
  8380. shadowBias: {},
  8381. shadowNormalBias: {},
  8382. shadowRadius: {},
  8383. shadowMapSize: {}
  8384. }
  8385. },
  8386. spotShadowMap: {
  8387. value: []
  8388. },
  8389. spotShadowMatrix: {
  8390. value: []
  8391. },
  8392. pointLights: {
  8393. value: [],
  8394. properties: {
  8395. color: {},
  8396. position: {},
  8397. decay: {},
  8398. distance: {}
  8399. }
  8400. },
  8401. pointLightShadows: {
  8402. value: [],
  8403. properties: {
  8404. shadowBias: {},
  8405. shadowNormalBias: {},
  8406. shadowRadius: {},
  8407. shadowMapSize: {},
  8408. shadowCameraNear: {},
  8409. shadowCameraFar: {}
  8410. }
  8411. },
  8412. pointShadowMap: {
  8413. value: []
  8414. },
  8415. pointShadowMatrix: {
  8416. value: []
  8417. },
  8418. hemisphereLights: {
  8419. value: [],
  8420. properties: {
  8421. direction: {},
  8422. skyColor: {},
  8423. groundColor: {}
  8424. }
  8425. },
  8426. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8427. rectAreaLights: {
  8428. value: [],
  8429. properties: {
  8430. color: {},
  8431. position: {},
  8432. width: {},
  8433. height: {}
  8434. }
  8435. },
  8436. ltc_1: {
  8437. value: null
  8438. },
  8439. ltc_2: {
  8440. value: null
  8441. }
  8442. },
  8443. points: {
  8444. diffuse: {
  8445. value: /*@__PURE__*/new Color(0xffffff)
  8446. },
  8447. opacity: {
  8448. value: 1.0
  8449. },
  8450. size: {
  8451. value: 1.0
  8452. },
  8453. scale: {
  8454. value: 1.0
  8455. },
  8456. map: {
  8457. value: null
  8458. },
  8459. alphaMap: {
  8460. value: null
  8461. },
  8462. alphaTest: {
  8463. value: 0
  8464. },
  8465. uvTransform: {
  8466. value: /*@__PURE__*/new Matrix3()
  8467. }
  8468. },
  8469. sprite: {
  8470. diffuse: {
  8471. value: /*@__PURE__*/new Color(0xffffff)
  8472. },
  8473. opacity: {
  8474. value: 1.0
  8475. },
  8476. center: {
  8477. value: /*@__PURE__*/new Vector2(0.5, 0.5)
  8478. },
  8479. rotation: {
  8480. value: 0.0
  8481. },
  8482. map: {
  8483. value: null
  8484. },
  8485. alphaMap: {
  8486. value: null
  8487. },
  8488. alphaTest: {
  8489. value: 0
  8490. },
  8491. uvTransform: {
  8492. value: /*@__PURE__*/new Matrix3()
  8493. }
  8494. }
  8495. };
  8496. const ShaderLib = {
  8497. basic: {
  8498. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8499. vertexShader: ShaderChunk.meshbasic_vert,
  8500. fragmentShader: ShaderChunk.meshbasic_frag
  8501. },
  8502. lambert: {
  8503. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8504. emissive: {
  8505. value: /*@__PURE__*/new Color(0x000000)
  8506. }
  8507. }]),
  8508. vertexShader: ShaderChunk.meshlambert_vert,
  8509. fragmentShader: ShaderChunk.meshlambert_frag
  8510. },
  8511. phong: {
  8512. 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, {
  8513. emissive: {
  8514. value: /*@__PURE__*/new Color(0x000000)
  8515. },
  8516. specular: {
  8517. value: /*@__PURE__*/new Color(0x111111)
  8518. },
  8519. shininess: {
  8520. value: 30
  8521. }
  8522. }]),
  8523. vertexShader: ShaderChunk.meshphong_vert,
  8524. fragmentShader: ShaderChunk.meshphong_frag
  8525. },
  8526. standard: {
  8527. 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, {
  8528. emissive: {
  8529. value: /*@__PURE__*/new Color(0x000000)
  8530. },
  8531. roughness: {
  8532. value: 1.0
  8533. },
  8534. metalness: {
  8535. value: 0.0
  8536. },
  8537. envMapIntensity: {
  8538. value: 1
  8539. } // temporary
  8540. }]),
  8541. vertexShader: ShaderChunk.meshphysical_vert,
  8542. fragmentShader: ShaderChunk.meshphysical_frag
  8543. },
  8544. toon: {
  8545. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8546. emissive: {
  8547. value: /*@__PURE__*/new Color(0x000000)
  8548. }
  8549. }]),
  8550. vertexShader: ShaderChunk.meshtoon_vert,
  8551. fragmentShader: ShaderChunk.meshtoon_frag
  8552. },
  8553. matcap: {
  8554. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8555. matcap: {
  8556. value: null
  8557. }
  8558. }]),
  8559. vertexShader: ShaderChunk.meshmatcap_vert,
  8560. fragmentShader: ShaderChunk.meshmatcap_frag
  8561. },
  8562. points: {
  8563. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8564. vertexShader: ShaderChunk.points_vert,
  8565. fragmentShader: ShaderChunk.points_frag
  8566. },
  8567. dashed: {
  8568. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8569. scale: {
  8570. value: 1
  8571. },
  8572. dashSize: {
  8573. value: 1
  8574. },
  8575. totalSize: {
  8576. value: 2
  8577. }
  8578. }]),
  8579. vertexShader: ShaderChunk.linedashed_vert,
  8580. fragmentShader: ShaderChunk.linedashed_frag
  8581. },
  8582. depth: {
  8583. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8584. vertexShader: ShaderChunk.depth_vert,
  8585. fragmentShader: ShaderChunk.depth_frag
  8586. },
  8587. normal: {
  8588. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8589. opacity: {
  8590. value: 1.0
  8591. }
  8592. }]),
  8593. vertexShader: ShaderChunk.meshnormal_vert,
  8594. fragmentShader: ShaderChunk.meshnormal_frag
  8595. },
  8596. sprite: {
  8597. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8598. vertexShader: ShaderChunk.sprite_vert,
  8599. fragmentShader: ShaderChunk.sprite_frag
  8600. },
  8601. background: {
  8602. uniforms: {
  8603. uvTransform: {
  8604. value: /*@__PURE__*/new Matrix3()
  8605. },
  8606. t2D: {
  8607. value: null
  8608. }
  8609. },
  8610. vertexShader: ShaderChunk.background_vert,
  8611. fragmentShader: ShaderChunk.background_frag
  8612. },
  8613. cube: {
  8614. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.envmap, {
  8615. opacity: {
  8616. value: 1.0
  8617. }
  8618. }]),
  8619. vertexShader: ShaderChunk.cube_vert,
  8620. fragmentShader: ShaderChunk.cube_frag
  8621. },
  8622. equirect: {
  8623. uniforms: {
  8624. tEquirect: {
  8625. value: null
  8626. }
  8627. },
  8628. vertexShader: ShaderChunk.equirect_vert,
  8629. fragmentShader: ShaderChunk.equirect_frag
  8630. },
  8631. distanceRGBA: {
  8632. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8633. referencePosition: {
  8634. value: /*@__PURE__*/new Vector3()
  8635. },
  8636. nearDistance: {
  8637. value: 1
  8638. },
  8639. farDistance: {
  8640. value: 1000
  8641. }
  8642. }]),
  8643. vertexShader: ShaderChunk.distanceRGBA_vert,
  8644. fragmentShader: ShaderChunk.distanceRGBA_frag
  8645. },
  8646. shadow: {
  8647. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8648. color: {
  8649. value: /*@__PURE__*/new Color(0x00000)
  8650. },
  8651. opacity: {
  8652. value: 1.0
  8653. }
  8654. }]),
  8655. vertexShader: ShaderChunk.shadow_vert,
  8656. fragmentShader: ShaderChunk.shadow_frag
  8657. }
  8658. };
  8659. ShaderLib.physical = {
  8660. uniforms: /*@__PURE__*/mergeUniforms([ShaderLib.standard.uniforms, {
  8661. clearcoat: {
  8662. value: 0
  8663. },
  8664. clearcoatMap: {
  8665. value: null
  8666. },
  8667. clearcoatRoughness: {
  8668. value: 0
  8669. },
  8670. clearcoatRoughnessMap: {
  8671. value: null
  8672. },
  8673. clearcoatNormalScale: {
  8674. value: /*@__PURE__*/new Vector2(1, 1)
  8675. },
  8676. clearcoatNormalMap: {
  8677. value: null
  8678. },
  8679. iridescence: {
  8680. value: 0
  8681. },
  8682. iridescenceMap: {
  8683. value: null
  8684. },
  8685. iridescenceIOR: {
  8686. value: 1.3
  8687. },
  8688. iridescenceThicknessMinimum: {
  8689. value: 100
  8690. },
  8691. iridescenceThicknessMaximum: {
  8692. value: 400
  8693. },
  8694. iridescenceThicknessMap: {
  8695. value: null
  8696. },
  8697. sheen: {
  8698. value: 0
  8699. },
  8700. sheenColor: {
  8701. value: /*@__PURE__*/new Color(0x000000)
  8702. },
  8703. sheenColorMap: {
  8704. value: null
  8705. },
  8706. sheenRoughness: {
  8707. value: 1
  8708. },
  8709. sheenRoughnessMap: {
  8710. value: null
  8711. },
  8712. transmission: {
  8713. value: 0
  8714. },
  8715. transmissionMap: {
  8716. value: null
  8717. },
  8718. transmissionSamplerSize: {
  8719. value: /*@__PURE__*/new Vector2()
  8720. },
  8721. transmissionSamplerMap: {
  8722. value: null
  8723. },
  8724. thickness: {
  8725. value: 0
  8726. },
  8727. thicknessMap: {
  8728. value: null
  8729. },
  8730. attenuationDistance: {
  8731. value: 0
  8732. },
  8733. attenuationColor: {
  8734. value: /*@__PURE__*/new Color(0x000000)
  8735. },
  8736. specularIntensity: {
  8737. value: 1
  8738. },
  8739. specularIntensityMap: {
  8740. value: null
  8741. },
  8742. specularColor: {
  8743. value: /*@__PURE__*/new Color(1, 1, 1)
  8744. },
  8745. specularColorMap: {
  8746. value: null
  8747. }
  8748. }]),
  8749. vertexShader: ShaderChunk.meshphysical_vert,
  8750. fragmentShader: ShaderChunk.meshphysical_frag
  8751. };
  8752. function WebGLBackground(renderer, cubemaps, state, objects, alpha, premultipliedAlpha) {
  8753. const clearColor = new Color(0x000000);
  8754. let clearAlpha = alpha === true ? 0 : 1;
  8755. let planeMesh;
  8756. let boxMesh;
  8757. let currentBackground = null;
  8758. let currentBackgroundVersion = 0;
  8759. let currentTonemapping = null;
  8760. function render(renderList, scene) {
  8761. let forceClear = false;
  8762. let background = scene.isScene === true ? scene.background : null;
  8763. if (background && background.isTexture) {
  8764. background = cubemaps.get(background);
  8765. } // Ignore background in AR
  8766. // TODO: Reconsider this.
  8767. const xr = renderer.xr;
  8768. const session = xr.getSession && xr.getSession();
  8769. if (session && session.environmentBlendMode === 'additive') {
  8770. background = null;
  8771. }
  8772. if (background === null) {
  8773. setClear(clearColor, clearAlpha);
  8774. } else if (background && background.isColor) {
  8775. setClear(background, 1);
  8776. forceClear = true;
  8777. }
  8778. if (renderer.autoClear || forceClear) {
  8779. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8780. }
  8781. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8782. if (boxMesh === undefined) {
  8783. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8784. name: 'BackgroundCubeMaterial',
  8785. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8786. vertexShader: ShaderLib.cube.vertexShader,
  8787. fragmentShader: ShaderLib.cube.fragmentShader,
  8788. side: BackSide,
  8789. depthTest: false,
  8790. depthWrite: false,
  8791. fog: false
  8792. }));
  8793. boxMesh.geometry.deleteAttribute('normal');
  8794. boxMesh.geometry.deleteAttribute('uv');
  8795. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8796. this.matrixWorld.copyPosition(camera.matrixWorld);
  8797. }; // enable code injection for non-built-in material
  8798. Object.defineProperty(boxMesh.material, 'envMap', {
  8799. get: function () {
  8800. return this.uniforms.envMap.value;
  8801. }
  8802. });
  8803. objects.update(boxMesh);
  8804. }
  8805. boxMesh.material.uniforms.envMap.value = background;
  8806. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8807. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8808. boxMesh.material.needsUpdate = true;
  8809. currentBackground = background;
  8810. currentBackgroundVersion = background.version;
  8811. currentTonemapping = renderer.toneMapping;
  8812. }
  8813. boxMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8814. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8815. } else if (background && background.isTexture) {
  8816. if (planeMesh === undefined) {
  8817. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8818. name: 'BackgroundMaterial',
  8819. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8820. vertexShader: ShaderLib.background.vertexShader,
  8821. fragmentShader: ShaderLib.background.fragmentShader,
  8822. side: FrontSide,
  8823. depthTest: false,
  8824. depthWrite: false,
  8825. fog: false
  8826. }));
  8827. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8828. Object.defineProperty(planeMesh.material, 'map', {
  8829. get: function () {
  8830. return this.uniforms.t2D.value;
  8831. }
  8832. });
  8833. objects.update(planeMesh);
  8834. }
  8835. planeMesh.material.uniforms.t2D.value = background;
  8836. if (background.matrixAutoUpdate === true) {
  8837. background.updateMatrix();
  8838. }
  8839. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8840. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8841. planeMesh.material.needsUpdate = true;
  8842. currentBackground = background;
  8843. currentBackgroundVersion = background.version;
  8844. currentTonemapping = renderer.toneMapping;
  8845. }
  8846. planeMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8847. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8848. }
  8849. }
  8850. function setClear(color, alpha) {
  8851. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8852. }
  8853. return {
  8854. getClearColor: function () {
  8855. return clearColor;
  8856. },
  8857. setClearColor: function (color, alpha = 1) {
  8858. clearColor.set(color);
  8859. clearAlpha = alpha;
  8860. setClear(clearColor, clearAlpha);
  8861. },
  8862. getClearAlpha: function () {
  8863. return clearAlpha;
  8864. },
  8865. setClearAlpha: function (alpha) {
  8866. clearAlpha = alpha;
  8867. setClear(clearColor, clearAlpha);
  8868. },
  8869. render: render
  8870. };
  8871. }
  8872. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8873. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8874. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8875. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8876. const bindingStates = {};
  8877. const defaultState = createBindingState(null);
  8878. let currentState = defaultState;
  8879. let forceUpdate = false;
  8880. function setup(object, material, program, geometry, index) {
  8881. let updateBuffers = false;
  8882. if (vaoAvailable) {
  8883. const state = getBindingState(geometry, program, material);
  8884. if (currentState !== state) {
  8885. currentState = state;
  8886. bindVertexArrayObject(currentState.object);
  8887. }
  8888. updateBuffers = needsUpdate(object, geometry, program, index);
  8889. if (updateBuffers) saveCache(object, geometry, program, index);
  8890. } else {
  8891. const wireframe = material.wireframe === true;
  8892. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8893. currentState.geometry = geometry.id;
  8894. currentState.program = program.id;
  8895. currentState.wireframe = wireframe;
  8896. updateBuffers = true;
  8897. }
  8898. }
  8899. if (index !== null) {
  8900. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8901. }
  8902. if (updateBuffers || forceUpdate) {
  8903. forceUpdate = false;
  8904. setupVertexAttributes(object, material, program, geometry);
  8905. if (index !== null) {
  8906. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8907. }
  8908. }
  8909. }
  8910. function createVertexArrayObject() {
  8911. if (capabilities.isWebGL2) return gl.createVertexArray();
  8912. return extension.createVertexArrayOES();
  8913. }
  8914. function bindVertexArrayObject(vao) {
  8915. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8916. return extension.bindVertexArrayOES(vao);
  8917. }
  8918. function deleteVertexArrayObject(vao) {
  8919. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8920. return extension.deleteVertexArrayOES(vao);
  8921. }
  8922. function getBindingState(geometry, program, material) {
  8923. const wireframe = material.wireframe === true;
  8924. let programMap = bindingStates[geometry.id];
  8925. if (programMap === undefined) {
  8926. programMap = {};
  8927. bindingStates[geometry.id] = programMap;
  8928. }
  8929. let stateMap = programMap[program.id];
  8930. if (stateMap === undefined) {
  8931. stateMap = {};
  8932. programMap[program.id] = stateMap;
  8933. }
  8934. let state = stateMap[wireframe];
  8935. if (state === undefined) {
  8936. state = createBindingState(createVertexArrayObject());
  8937. stateMap[wireframe] = state;
  8938. }
  8939. return state;
  8940. }
  8941. function createBindingState(vao) {
  8942. const newAttributes = [];
  8943. const enabledAttributes = [];
  8944. const attributeDivisors = [];
  8945. for (let i = 0; i < maxVertexAttributes; i++) {
  8946. newAttributes[i] = 0;
  8947. enabledAttributes[i] = 0;
  8948. attributeDivisors[i] = 0;
  8949. }
  8950. return {
  8951. // for backward compatibility on non-VAO support browser
  8952. geometry: null,
  8953. program: null,
  8954. wireframe: false,
  8955. newAttributes: newAttributes,
  8956. enabledAttributes: enabledAttributes,
  8957. attributeDivisors: attributeDivisors,
  8958. object: vao,
  8959. attributes: {},
  8960. index: null
  8961. };
  8962. }
  8963. function needsUpdate(object, geometry, program, index) {
  8964. const cachedAttributes = currentState.attributes;
  8965. const geometryAttributes = geometry.attributes;
  8966. let attributesNum = 0;
  8967. const programAttributes = program.getAttributes();
  8968. for (const name in programAttributes) {
  8969. const programAttribute = programAttributes[name];
  8970. if (programAttribute.location >= 0) {
  8971. const cachedAttribute = cachedAttributes[name];
  8972. let geometryAttribute = geometryAttributes[name];
  8973. if (geometryAttribute === undefined) {
  8974. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8975. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8976. }
  8977. if (cachedAttribute === undefined) return true;
  8978. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8979. if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true;
  8980. attributesNum++;
  8981. }
  8982. }
  8983. if (currentState.attributesNum !== attributesNum) return true;
  8984. if (currentState.index !== index) return true;
  8985. return false;
  8986. }
  8987. function saveCache(object, geometry, program, index) {
  8988. const cache = {};
  8989. const attributes = geometry.attributes;
  8990. let attributesNum = 0;
  8991. const programAttributes = program.getAttributes();
  8992. for (const name in programAttributes) {
  8993. const programAttribute = programAttributes[name];
  8994. if (programAttribute.location >= 0) {
  8995. let attribute = attributes[name];
  8996. if (attribute === undefined) {
  8997. if (name === 'instanceMatrix' && object.instanceMatrix) attribute = object.instanceMatrix;
  8998. if (name === 'instanceColor' && object.instanceColor) attribute = object.instanceColor;
  8999. }
  9000. const data = {};
  9001. data.attribute = attribute;
  9002. if (attribute && attribute.data) {
  9003. data.data = attribute.data;
  9004. }
  9005. cache[name] = data;
  9006. attributesNum++;
  9007. }
  9008. }
  9009. currentState.attributes = cache;
  9010. currentState.attributesNum = attributesNum;
  9011. currentState.index = index;
  9012. }
  9013. function initAttributes() {
  9014. const newAttributes = currentState.newAttributes;
  9015. for (let i = 0, il = newAttributes.length; i < il; i++) {
  9016. newAttributes[i] = 0;
  9017. }
  9018. }
  9019. function enableAttribute(attribute) {
  9020. enableAttributeAndDivisor(attribute, 0);
  9021. }
  9022. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  9023. const newAttributes = currentState.newAttributes;
  9024. const enabledAttributes = currentState.enabledAttributes;
  9025. const attributeDivisors = currentState.attributeDivisors;
  9026. newAttributes[attribute] = 1;
  9027. if (enabledAttributes[attribute] === 0) {
  9028. gl.enableVertexAttribArray(attribute);
  9029. enabledAttributes[attribute] = 1;
  9030. }
  9031. if (attributeDivisors[attribute] !== meshPerAttribute) {
  9032. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  9033. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  9034. attributeDivisors[attribute] = meshPerAttribute;
  9035. }
  9036. }
  9037. function disableUnusedAttributes() {
  9038. const newAttributes = currentState.newAttributes;
  9039. const enabledAttributes = currentState.enabledAttributes;
  9040. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  9041. if (enabledAttributes[i] !== newAttributes[i]) {
  9042. gl.disableVertexAttribArray(i);
  9043. enabledAttributes[i] = 0;
  9044. }
  9045. }
  9046. }
  9047. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9048. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  9049. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9050. } else {
  9051. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9052. }
  9053. }
  9054. function setupVertexAttributes(object, material, program, geometry) {
  9055. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9056. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9057. }
  9058. initAttributes();
  9059. const geometryAttributes = geometry.attributes;
  9060. const programAttributes = program.getAttributes();
  9061. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9062. for (const name in programAttributes) {
  9063. const programAttribute = programAttributes[name];
  9064. if (programAttribute.location >= 0) {
  9065. let geometryAttribute = geometryAttributes[name];
  9066. if (geometryAttribute === undefined) {
  9067. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9068. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9069. }
  9070. if (geometryAttribute !== undefined) {
  9071. const normalized = geometryAttribute.normalized;
  9072. const size = geometryAttribute.itemSize;
  9073. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  9074. if (attribute === undefined) continue;
  9075. const buffer = attribute.buffer;
  9076. const type = attribute.type;
  9077. const bytesPerElement = attribute.bytesPerElement;
  9078. if (geometryAttribute.isInterleavedBufferAttribute) {
  9079. const data = geometryAttribute.data;
  9080. const stride = data.stride;
  9081. const offset = geometryAttribute.offset;
  9082. if (data.isInstancedInterleavedBuffer) {
  9083. for (let i = 0; i < programAttribute.locationSize; i++) {
  9084. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  9085. }
  9086. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9087. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9088. }
  9089. } else {
  9090. for (let i = 0; i < programAttribute.locationSize; i++) {
  9091. enableAttribute(programAttribute.location + i);
  9092. }
  9093. }
  9094. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9095. for (let i = 0; i < programAttribute.locationSize; i++) {
  9096. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  9097. }
  9098. } else {
  9099. if (geometryAttribute.isInstancedBufferAttribute) {
  9100. for (let i = 0; i < programAttribute.locationSize; i++) {
  9101. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  9102. }
  9103. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9104. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9105. }
  9106. } else {
  9107. for (let i = 0; i < programAttribute.locationSize; i++) {
  9108. enableAttribute(programAttribute.location + i);
  9109. }
  9110. }
  9111. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9112. for (let i = 0; i < programAttribute.locationSize; i++) {
  9113. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  9114. }
  9115. }
  9116. } else if (materialDefaultAttributeValues !== undefined) {
  9117. const value = materialDefaultAttributeValues[name];
  9118. if (value !== undefined) {
  9119. switch (value.length) {
  9120. case 2:
  9121. gl.vertexAttrib2fv(programAttribute.location, value);
  9122. break;
  9123. case 3:
  9124. gl.vertexAttrib3fv(programAttribute.location, value);
  9125. break;
  9126. case 4:
  9127. gl.vertexAttrib4fv(programAttribute.location, value);
  9128. break;
  9129. default:
  9130. gl.vertexAttrib1fv(programAttribute.location, value);
  9131. }
  9132. }
  9133. }
  9134. }
  9135. }
  9136. disableUnusedAttributes();
  9137. }
  9138. function dispose() {
  9139. reset();
  9140. for (const geometryId in bindingStates) {
  9141. const programMap = bindingStates[geometryId];
  9142. for (const programId in programMap) {
  9143. const stateMap = programMap[programId];
  9144. for (const wireframe in stateMap) {
  9145. deleteVertexArrayObject(stateMap[wireframe].object);
  9146. delete stateMap[wireframe];
  9147. }
  9148. delete programMap[programId];
  9149. }
  9150. delete bindingStates[geometryId];
  9151. }
  9152. }
  9153. function releaseStatesOfGeometry(geometry) {
  9154. if (bindingStates[geometry.id] === undefined) return;
  9155. const programMap = bindingStates[geometry.id];
  9156. for (const programId in programMap) {
  9157. const stateMap = programMap[programId];
  9158. for (const wireframe in stateMap) {
  9159. deleteVertexArrayObject(stateMap[wireframe].object);
  9160. delete stateMap[wireframe];
  9161. }
  9162. delete programMap[programId];
  9163. }
  9164. delete bindingStates[geometry.id];
  9165. }
  9166. function releaseStatesOfProgram(program) {
  9167. for (const geometryId in bindingStates) {
  9168. const programMap = bindingStates[geometryId];
  9169. if (programMap[program.id] === undefined) continue;
  9170. const stateMap = programMap[program.id];
  9171. for (const wireframe in stateMap) {
  9172. deleteVertexArrayObject(stateMap[wireframe].object);
  9173. delete stateMap[wireframe];
  9174. }
  9175. delete programMap[program.id];
  9176. }
  9177. }
  9178. function reset() {
  9179. resetDefaultState();
  9180. forceUpdate = true;
  9181. if (currentState === defaultState) return;
  9182. currentState = defaultState;
  9183. bindVertexArrayObject(currentState.object);
  9184. } // for backward-compatibility
  9185. function resetDefaultState() {
  9186. defaultState.geometry = null;
  9187. defaultState.program = null;
  9188. defaultState.wireframe = false;
  9189. }
  9190. return {
  9191. setup: setup,
  9192. reset: reset,
  9193. resetDefaultState: resetDefaultState,
  9194. dispose: dispose,
  9195. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9196. releaseStatesOfProgram: releaseStatesOfProgram,
  9197. initAttributes: initAttributes,
  9198. enableAttribute: enableAttribute,
  9199. disableUnusedAttributes: disableUnusedAttributes
  9200. };
  9201. }
  9202. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9203. const isWebGL2 = capabilities.isWebGL2;
  9204. let mode;
  9205. function setMode(value) {
  9206. mode = value;
  9207. }
  9208. function render(start, count) {
  9209. gl.drawArrays(mode, start, count);
  9210. info.update(count, mode, 1);
  9211. }
  9212. function renderInstances(start, count, primcount) {
  9213. if (primcount === 0) return;
  9214. let extension, methodName;
  9215. if (isWebGL2) {
  9216. extension = gl;
  9217. methodName = 'drawArraysInstanced';
  9218. } else {
  9219. extension = extensions.get('ANGLE_instanced_arrays');
  9220. methodName = 'drawArraysInstancedANGLE';
  9221. if (extension === null) {
  9222. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9223. return;
  9224. }
  9225. }
  9226. extension[methodName](mode, start, count, primcount);
  9227. info.update(count, mode, primcount);
  9228. } //
  9229. this.setMode = setMode;
  9230. this.render = render;
  9231. this.renderInstances = renderInstances;
  9232. }
  9233. function WebGLCapabilities(gl, extensions, parameters) {
  9234. let maxAnisotropy;
  9235. function getMaxAnisotropy() {
  9236. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9237. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9238. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9239. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9240. } else {
  9241. maxAnisotropy = 0;
  9242. }
  9243. return maxAnisotropy;
  9244. }
  9245. function getMaxPrecision(precision) {
  9246. if (precision === 'highp') {
  9247. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9248. return 'highp';
  9249. }
  9250. precision = 'mediump';
  9251. }
  9252. if (precision === 'mediump') {
  9253. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9254. return 'mediump';
  9255. }
  9256. }
  9257. return 'lowp';
  9258. }
  9259. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9260. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9261. const maxPrecision = getMaxPrecision(precision);
  9262. if (maxPrecision !== precision) {
  9263. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9264. precision = maxPrecision;
  9265. }
  9266. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9267. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9268. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9269. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9270. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9271. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9272. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9273. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9274. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9275. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9276. const vertexTextures = maxVertexTextures > 0;
  9277. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9278. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9279. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9280. return {
  9281. isWebGL2: isWebGL2,
  9282. drawBuffers: drawBuffers,
  9283. getMaxAnisotropy: getMaxAnisotropy,
  9284. getMaxPrecision: getMaxPrecision,
  9285. precision: precision,
  9286. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9287. maxTextures: maxTextures,
  9288. maxVertexTextures: maxVertexTextures,
  9289. maxTextureSize: maxTextureSize,
  9290. maxCubemapSize: maxCubemapSize,
  9291. maxAttributes: maxAttributes,
  9292. maxVertexUniforms: maxVertexUniforms,
  9293. maxVaryings: maxVaryings,
  9294. maxFragmentUniforms: maxFragmentUniforms,
  9295. vertexTextures: vertexTextures,
  9296. floatFragmentTextures: floatFragmentTextures,
  9297. floatVertexTextures: floatVertexTextures,
  9298. maxSamples: maxSamples
  9299. };
  9300. }
  9301. function WebGLClipping(properties) {
  9302. const scope = this;
  9303. let globalState = null,
  9304. numGlobalPlanes = 0,
  9305. localClippingEnabled = false,
  9306. renderingShadows = false;
  9307. const plane = new Plane(),
  9308. viewNormalMatrix = new Matrix3(),
  9309. uniform = {
  9310. value: null,
  9311. needsUpdate: false
  9312. };
  9313. this.uniform = uniform;
  9314. this.numPlanes = 0;
  9315. this.numIntersection = 0;
  9316. this.init = function (planes, enableLocalClipping, camera) {
  9317. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9318. // run another frame in order to reset the state:
  9319. numGlobalPlanes !== 0 || localClippingEnabled;
  9320. localClippingEnabled = enableLocalClipping;
  9321. globalState = projectPlanes(planes, camera, 0);
  9322. numGlobalPlanes = planes.length;
  9323. return enabled;
  9324. };
  9325. this.beginShadows = function () {
  9326. renderingShadows = true;
  9327. projectPlanes(null);
  9328. };
  9329. this.endShadows = function () {
  9330. renderingShadows = false;
  9331. resetGlobalState();
  9332. };
  9333. this.setState = function (material, camera, useCache) {
  9334. const planes = material.clippingPlanes,
  9335. clipIntersection = material.clipIntersection,
  9336. clipShadows = material.clipShadows;
  9337. const materialProperties = properties.get(material);
  9338. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9339. // there's no local clipping
  9340. if (renderingShadows) {
  9341. // there's no global clipping
  9342. projectPlanes(null);
  9343. } else {
  9344. resetGlobalState();
  9345. }
  9346. } else {
  9347. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9348. lGlobal = nGlobal * 4;
  9349. let dstArray = materialProperties.clippingState || null;
  9350. uniform.value = dstArray; // ensure unique state
  9351. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9352. for (let i = 0; i !== lGlobal; ++i) {
  9353. dstArray[i] = globalState[i];
  9354. }
  9355. materialProperties.clippingState = dstArray;
  9356. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9357. this.numPlanes += nGlobal;
  9358. }
  9359. };
  9360. function resetGlobalState() {
  9361. if (uniform.value !== globalState) {
  9362. uniform.value = globalState;
  9363. uniform.needsUpdate = numGlobalPlanes > 0;
  9364. }
  9365. scope.numPlanes = numGlobalPlanes;
  9366. scope.numIntersection = 0;
  9367. }
  9368. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9369. const nPlanes = planes !== null ? planes.length : 0;
  9370. let dstArray = null;
  9371. if (nPlanes !== 0) {
  9372. dstArray = uniform.value;
  9373. if (skipTransform !== true || dstArray === null) {
  9374. const flatSize = dstOffset + nPlanes * 4,
  9375. viewMatrix = camera.matrixWorldInverse;
  9376. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9377. if (dstArray === null || dstArray.length < flatSize) {
  9378. dstArray = new Float32Array(flatSize);
  9379. }
  9380. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9381. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9382. plane.normal.toArray(dstArray, i4);
  9383. dstArray[i4 + 3] = plane.constant;
  9384. }
  9385. }
  9386. uniform.value = dstArray;
  9387. uniform.needsUpdate = true;
  9388. }
  9389. scope.numPlanes = nPlanes;
  9390. scope.numIntersection = 0;
  9391. return dstArray;
  9392. }
  9393. }
  9394. function WebGLCubeMaps(renderer) {
  9395. let cubemaps = new WeakMap();
  9396. function mapTextureMapping(texture, mapping) {
  9397. if (mapping === EquirectangularReflectionMapping) {
  9398. texture.mapping = CubeReflectionMapping;
  9399. } else if (mapping === EquirectangularRefractionMapping) {
  9400. texture.mapping = CubeRefractionMapping;
  9401. }
  9402. return texture;
  9403. }
  9404. function get(texture) {
  9405. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9406. const mapping = texture.mapping;
  9407. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9408. if (cubemaps.has(texture)) {
  9409. const cubemap = cubemaps.get(texture).texture;
  9410. return mapTextureMapping(cubemap, texture.mapping);
  9411. } else {
  9412. const image = texture.image;
  9413. if (image && image.height > 0) {
  9414. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9415. renderTarget.fromEquirectangularTexture(renderer, texture);
  9416. cubemaps.set(texture, renderTarget);
  9417. texture.addEventListener('dispose', onTextureDispose);
  9418. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9419. } else {
  9420. // image not yet ready. try the conversion next frame
  9421. return null;
  9422. }
  9423. }
  9424. }
  9425. }
  9426. return texture;
  9427. }
  9428. function onTextureDispose(event) {
  9429. const texture = event.target;
  9430. texture.removeEventListener('dispose', onTextureDispose);
  9431. const cubemap = cubemaps.get(texture);
  9432. if (cubemap !== undefined) {
  9433. cubemaps.delete(texture);
  9434. cubemap.dispose();
  9435. }
  9436. }
  9437. function dispose() {
  9438. cubemaps = new WeakMap();
  9439. }
  9440. return {
  9441. get: get,
  9442. dispose: dispose
  9443. };
  9444. }
  9445. class OrthographicCamera extends Camera {
  9446. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9447. super();
  9448. this.isOrthographicCamera = true;
  9449. this.type = 'OrthographicCamera';
  9450. this.zoom = 1;
  9451. this.view = null;
  9452. this.left = left;
  9453. this.right = right;
  9454. this.top = top;
  9455. this.bottom = bottom;
  9456. this.near = near;
  9457. this.far = far;
  9458. this.updateProjectionMatrix();
  9459. }
  9460. copy(source, recursive) {
  9461. super.copy(source, recursive);
  9462. this.left = source.left;
  9463. this.right = source.right;
  9464. this.top = source.top;
  9465. this.bottom = source.bottom;
  9466. this.near = source.near;
  9467. this.far = source.far;
  9468. this.zoom = source.zoom;
  9469. this.view = source.view === null ? null : Object.assign({}, source.view);
  9470. return this;
  9471. }
  9472. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9473. if (this.view === null) {
  9474. this.view = {
  9475. enabled: true,
  9476. fullWidth: 1,
  9477. fullHeight: 1,
  9478. offsetX: 0,
  9479. offsetY: 0,
  9480. width: 1,
  9481. height: 1
  9482. };
  9483. }
  9484. this.view.enabled = true;
  9485. this.view.fullWidth = fullWidth;
  9486. this.view.fullHeight = fullHeight;
  9487. this.view.offsetX = x;
  9488. this.view.offsetY = y;
  9489. this.view.width = width;
  9490. this.view.height = height;
  9491. this.updateProjectionMatrix();
  9492. }
  9493. clearViewOffset() {
  9494. if (this.view !== null) {
  9495. this.view.enabled = false;
  9496. }
  9497. this.updateProjectionMatrix();
  9498. }
  9499. updateProjectionMatrix() {
  9500. const dx = (this.right - this.left) / (2 * this.zoom);
  9501. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9502. const cx = (this.right + this.left) / 2;
  9503. const cy = (this.top + this.bottom) / 2;
  9504. let left = cx - dx;
  9505. let right = cx + dx;
  9506. let top = cy + dy;
  9507. let bottom = cy - dy;
  9508. if (this.view !== null && this.view.enabled) {
  9509. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9510. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9511. left += scaleW * this.view.offsetX;
  9512. right = left + scaleW * this.view.width;
  9513. top -= scaleH * this.view.offsetY;
  9514. bottom = top - scaleH * this.view.height;
  9515. }
  9516. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9517. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9518. }
  9519. toJSON(meta) {
  9520. const data = super.toJSON(meta);
  9521. data.object.zoom = this.zoom;
  9522. data.object.left = this.left;
  9523. data.object.right = this.right;
  9524. data.object.top = this.top;
  9525. data.object.bottom = this.bottom;
  9526. data.object.near = this.near;
  9527. data.object.far = this.far;
  9528. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9529. return data;
  9530. }
  9531. }
  9532. const LOD_MIN = 4; // The standard deviations (radians) associated with the extra mips. These are
  9533. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9534. // geometric shadowing function. These sigma values squared must match the
  9535. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9536. 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
  9537. // samples and exit early, but not recompile the shader.
  9538. const MAX_SAMPLES = 20;
  9539. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9540. const _clearColor = /*@__PURE__*/new Color();
  9541. let _oldTarget = null; // Golden Ratio
  9542. const PHI = (1 + Math.sqrt(5)) / 2;
  9543. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9544. // same axis), used as axis directions evenly spread on a sphere.
  9545. 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)];
  9546. /**
  9547. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9548. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9549. * blur to be quickly accessed based on material roughness. It is packed into a
  9550. * special CubeUV format that allows us to perform custom interpolation so that
  9551. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9552. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9553. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9554. * higher roughness levels. In this way we maintain resolution to smoothly
  9555. * interpolate diffuse lighting while limiting sampling computation.
  9556. *
  9557. * Paper: Fast, Accurate Image-Based Lighting
  9558. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9559. */
  9560. class PMREMGenerator {
  9561. constructor(renderer) {
  9562. this._renderer = renderer;
  9563. this._pingPongRenderTarget = null;
  9564. this._lodMax = 0;
  9565. this._cubeSize = 0;
  9566. this._lodPlanes = [];
  9567. this._sizeLods = [];
  9568. this._sigmas = [];
  9569. this._blurMaterial = null;
  9570. this._cubemapMaterial = null;
  9571. this._equirectMaterial = null;
  9572. this._compileMaterial(this._blurMaterial);
  9573. }
  9574. /**
  9575. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9576. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9577. * in radians to be applied to the scene before PMREM generation. Optional near
  9578. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9579. * is placed at the origin).
  9580. */
  9581. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9582. _oldTarget = this._renderer.getRenderTarget();
  9583. this._setSize(256);
  9584. const cubeUVRenderTarget = this._allocateTargets();
  9585. cubeUVRenderTarget.depthBuffer = true;
  9586. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9587. if (sigma > 0) {
  9588. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9589. }
  9590. this._applyPMREM(cubeUVRenderTarget);
  9591. this._cleanup(cubeUVRenderTarget);
  9592. return cubeUVRenderTarget;
  9593. }
  9594. /**
  9595. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9596. * or HDR. The ideal input image size is 1k (1024 x 512),
  9597. * as this matches best with the 256 x 256 cubemap output.
  9598. */
  9599. fromEquirectangular(equirectangular, renderTarget = null) {
  9600. return this._fromTexture(equirectangular, renderTarget);
  9601. }
  9602. /**
  9603. * Generates a PMREM from an cubemap texture, which can be either LDR
  9604. * or HDR. The ideal input cube size is 256 x 256,
  9605. * as this matches best with the 256 x 256 cubemap output.
  9606. */
  9607. fromCubemap(cubemap, renderTarget = null) {
  9608. return this._fromTexture(cubemap, renderTarget);
  9609. }
  9610. /**
  9611. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9612. * your texture's network fetch for increased concurrency.
  9613. */
  9614. compileCubemapShader() {
  9615. if (this._cubemapMaterial === null) {
  9616. this._cubemapMaterial = _getCubemapMaterial();
  9617. this._compileMaterial(this._cubemapMaterial);
  9618. }
  9619. }
  9620. /**
  9621. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9622. * your texture's network fetch for increased concurrency.
  9623. */
  9624. compileEquirectangularShader() {
  9625. if (this._equirectMaterial === null) {
  9626. this._equirectMaterial = _getEquirectMaterial();
  9627. this._compileMaterial(this._equirectMaterial);
  9628. }
  9629. }
  9630. /**
  9631. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9632. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9633. * one of them will cause any others to also become unusable.
  9634. */
  9635. dispose() {
  9636. this._dispose();
  9637. if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose();
  9638. if (this._equirectMaterial !== null) this._equirectMaterial.dispose();
  9639. } // private interface
  9640. _setSize(cubeSize) {
  9641. this._lodMax = Math.floor(Math.log2(cubeSize));
  9642. this._cubeSize = Math.pow(2, this._lodMax);
  9643. }
  9644. _dispose() {
  9645. if (this._blurMaterial !== null) this._blurMaterial.dispose();
  9646. if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
  9647. for (let i = 0; i < this._lodPlanes.length; i++) {
  9648. this._lodPlanes[i].dispose();
  9649. }
  9650. }
  9651. _cleanup(outputTarget) {
  9652. this._renderer.setRenderTarget(_oldTarget);
  9653. outputTarget.scissorTest = false;
  9654. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9655. }
  9656. _fromTexture(texture, renderTarget) {
  9657. if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) {
  9658. this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width);
  9659. } else {
  9660. // Equirectangular
  9661. this._setSize(texture.image.width / 4);
  9662. }
  9663. _oldTarget = this._renderer.getRenderTarget();
  9664. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9665. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9666. this._applyPMREM(cubeUVRenderTarget);
  9667. this._cleanup(cubeUVRenderTarget);
  9668. return cubeUVRenderTarget;
  9669. }
  9670. _allocateTargets() {
  9671. const width = 3 * Math.max(this._cubeSize, 16 * 7);
  9672. const height = 4 * this._cubeSize;
  9673. const params = {
  9674. magFilter: LinearFilter,
  9675. minFilter: LinearFilter,
  9676. generateMipmaps: false,
  9677. type: HalfFloatType,
  9678. format: RGBAFormat,
  9679. encoding: LinearEncoding,
  9680. depthBuffer: false
  9681. };
  9682. const cubeUVRenderTarget = _createRenderTarget(width, height, params);
  9683. if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width) {
  9684. if (this._pingPongRenderTarget !== null) {
  9685. this._dispose();
  9686. }
  9687. this._pingPongRenderTarget = _createRenderTarget(width, height, params);
  9688. const {
  9689. _lodMax
  9690. } = this;
  9691. ({
  9692. sizeLods: this._sizeLods,
  9693. lodPlanes: this._lodPlanes,
  9694. sigmas: this._sigmas
  9695. } = _createPlanes(_lodMax));
  9696. this._blurMaterial = _getBlurShader(_lodMax, width, height);
  9697. }
  9698. return cubeUVRenderTarget;
  9699. }
  9700. _compileMaterial(material) {
  9701. const tmpMesh = new Mesh(this._lodPlanes[0], material);
  9702. this._renderer.compile(tmpMesh, _flatCamera);
  9703. }
  9704. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9705. const fov = 90;
  9706. const aspect = 1;
  9707. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9708. const upSign = [1, -1, 1, 1, 1, 1];
  9709. const forwardSign = [1, 1, 1, -1, -1, -1];
  9710. const renderer = this._renderer;
  9711. const originalAutoClear = renderer.autoClear;
  9712. const toneMapping = renderer.toneMapping;
  9713. renderer.getClearColor(_clearColor);
  9714. renderer.toneMapping = NoToneMapping;
  9715. renderer.autoClear = false;
  9716. const backgroundMaterial = new MeshBasicMaterial({
  9717. name: 'PMREM.Background',
  9718. side: BackSide,
  9719. depthWrite: false,
  9720. depthTest: false
  9721. });
  9722. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9723. let useSolidColor = false;
  9724. const background = scene.background;
  9725. if (background) {
  9726. if (background.isColor) {
  9727. backgroundMaterial.color.copy(background);
  9728. scene.background = null;
  9729. useSolidColor = true;
  9730. }
  9731. } else {
  9732. backgroundMaterial.color.copy(_clearColor);
  9733. useSolidColor = true;
  9734. }
  9735. for (let i = 0; i < 6; i++) {
  9736. const col = i % 3;
  9737. if (col === 0) {
  9738. cubeCamera.up.set(0, upSign[i], 0);
  9739. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9740. } else if (col === 1) {
  9741. cubeCamera.up.set(0, 0, upSign[i]);
  9742. cubeCamera.lookAt(0, forwardSign[i], 0);
  9743. } else {
  9744. cubeCamera.up.set(0, upSign[i], 0);
  9745. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9746. }
  9747. const size = this._cubeSize;
  9748. _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size);
  9749. renderer.setRenderTarget(cubeUVRenderTarget);
  9750. if (useSolidColor) {
  9751. renderer.render(backgroundBox, cubeCamera);
  9752. }
  9753. renderer.render(scene, cubeCamera);
  9754. }
  9755. backgroundBox.geometry.dispose();
  9756. backgroundBox.material.dispose();
  9757. renderer.toneMapping = toneMapping;
  9758. renderer.autoClear = originalAutoClear;
  9759. scene.background = background;
  9760. }
  9761. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9762. const renderer = this._renderer;
  9763. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9764. if (isCubeTexture) {
  9765. if (this._cubemapMaterial === null) {
  9766. this._cubemapMaterial = _getCubemapMaterial();
  9767. }
  9768. this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
  9769. } else {
  9770. if (this._equirectMaterial === null) {
  9771. this._equirectMaterial = _getEquirectMaterial();
  9772. }
  9773. }
  9774. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9775. const mesh = new Mesh(this._lodPlanes[0], material);
  9776. const uniforms = material.uniforms;
  9777. uniforms['envMap'].value = texture;
  9778. const size = this._cubeSize;
  9779. _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size);
  9780. renderer.setRenderTarget(cubeUVRenderTarget);
  9781. renderer.render(mesh, _flatCamera);
  9782. }
  9783. _applyPMREM(cubeUVRenderTarget) {
  9784. const renderer = this._renderer;
  9785. const autoClear = renderer.autoClear;
  9786. renderer.autoClear = false;
  9787. for (let i = 1; i < this._lodPlanes.length; i++) {
  9788. const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]);
  9789. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9790. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9791. }
  9792. renderer.autoClear = autoClear;
  9793. }
  9794. /**
  9795. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9796. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9797. * the blur latitudinally (around the poles), and then longitudinally (towards
  9798. * the poles) to approximate the orthogonally-separable blur. It is least
  9799. * accurate at the poles, but still does a decent job.
  9800. */
  9801. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9802. const pingPongRenderTarget = this._pingPongRenderTarget;
  9803. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9804. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9805. }
  9806. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9807. const renderer = this._renderer;
  9808. const blurMaterial = this._blurMaterial;
  9809. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9810. console.error('blur direction must be either latitudinal or longitudinal!');
  9811. } // Number of standard deviations at which to cut off the discrete approximation.
  9812. const STANDARD_DEVIATIONS = 3;
  9813. const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial);
  9814. const blurUniforms = blurMaterial.uniforms;
  9815. const pixels = this._sizeLods[lodIn] - 1;
  9816. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9817. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9818. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9819. if (samples > MAX_SAMPLES) {
  9820. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9821. }
  9822. const weights = [];
  9823. let sum = 0;
  9824. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9825. const x = i / sigmaPixels;
  9826. const weight = Math.exp(-x * x / 2);
  9827. weights.push(weight);
  9828. if (i === 0) {
  9829. sum += weight;
  9830. } else if (i < samples) {
  9831. sum += 2 * weight;
  9832. }
  9833. }
  9834. for (let i = 0; i < weights.length; i++) {
  9835. weights[i] = weights[i] / sum;
  9836. }
  9837. blurUniforms['envMap'].value = targetIn.texture;
  9838. blurUniforms['samples'].value = samples;
  9839. blurUniforms['weights'].value = weights;
  9840. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9841. if (poleAxis) {
  9842. blurUniforms['poleAxis'].value = poleAxis;
  9843. }
  9844. const {
  9845. _lodMax
  9846. } = this;
  9847. blurUniforms['dTheta'].value = radiansPerPixel;
  9848. blurUniforms['mipInt'].value = _lodMax - lodIn;
  9849. const outputSize = this._sizeLods[lodOut];
  9850. const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0);
  9851. const y = 4 * (this._cubeSize - outputSize);
  9852. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9853. renderer.setRenderTarget(targetOut);
  9854. renderer.render(blurMesh, _flatCamera);
  9855. }
  9856. }
  9857. function _createPlanes(lodMax) {
  9858. const lodPlanes = [];
  9859. const sizeLods = [];
  9860. const sigmas = [];
  9861. let lod = lodMax;
  9862. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9863. for (let i = 0; i < totalLods; i++) {
  9864. const sizeLod = Math.pow(2, lod);
  9865. sizeLods.push(sizeLod);
  9866. let sigma = 1.0 / sizeLod;
  9867. if (i > lodMax - LOD_MIN) {
  9868. sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1];
  9869. } else if (i === 0) {
  9870. sigma = 0;
  9871. }
  9872. sigmas.push(sigma);
  9873. const texelSize = 1.0 / (sizeLod - 2);
  9874. const min = -texelSize;
  9875. const max = 1 + texelSize;
  9876. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9877. const cubeFaces = 6;
  9878. const vertices = 6;
  9879. const positionSize = 3;
  9880. const uvSize = 2;
  9881. const faceIndexSize = 1;
  9882. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9883. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9884. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9885. for (let face = 0; face < cubeFaces; face++) {
  9886. const x = face % 3 * 2 / 3 - 1;
  9887. const y = face > 2 ? 0 : -1;
  9888. 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];
  9889. position.set(coordinates, positionSize * vertices * face);
  9890. uv.set(uv1, uvSize * vertices * face);
  9891. const fill = [face, face, face, face, face, face];
  9892. faceIndex.set(fill, faceIndexSize * vertices * face);
  9893. }
  9894. const planes = new BufferGeometry();
  9895. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9896. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9897. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9898. lodPlanes.push(planes);
  9899. if (lod > LOD_MIN) {
  9900. lod--;
  9901. }
  9902. }
  9903. return {
  9904. lodPlanes,
  9905. sizeLods,
  9906. sigmas
  9907. };
  9908. }
  9909. function _createRenderTarget(width, height, params) {
  9910. const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params);
  9911. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9912. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9913. cubeUVRenderTarget.scissorTest = true;
  9914. return cubeUVRenderTarget;
  9915. }
  9916. function _setViewport(target, x, y, width, height) {
  9917. target.viewport.set(x, y, width, height);
  9918. target.scissor.set(x, y, width, height);
  9919. }
  9920. function _getBlurShader(lodMax, width, height) {
  9921. const weights = new Float32Array(MAX_SAMPLES);
  9922. const poleAxis = new Vector3(0, 1, 0);
  9923. const shaderMaterial = new ShaderMaterial({
  9924. name: 'SphericalGaussianBlur',
  9925. defines: {
  9926. 'n': MAX_SAMPLES,
  9927. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9928. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9929. 'CUBEUV_MAX_MIP': `${lodMax}.0`
  9930. },
  9931. uniforms: {
  9932. 'envMap': {
  9933. value: null
  9934. },
  9935. 'samples': {
  9936. value: 1
  9937. },
  9938. 'weights': {
  9939. value: weights
  9940. },
  9941. 'latitudinal': {
  9942. value: false
  9943. },
  9944. 'dTheta': {
  9945. value: 0
  9946. },
  9947. 'mipInt': {
  9948. value: 0
  9949. },
  9950. 'poleAxis': {
  9951. value: poleAxis
  9952. }
  9953. },
  9954. vertexShader: _getCommonVertexShader(),
  9955. fragmentShader:
  9956. /* glsl */
  9957. `
  9958. precision mediump float;
  9959. precision mediump int;
  9960. varying vec3 vOutputDirection;
  9961. uniform sampler2D envMap;
  9962. uniform int samples;
  9963. uniform float weights[ n ];
  9964. uniform bool latitudinal;
  9965. uniform float dTheta;
  9966. uniform float mipInt;
  9967. uniform vec3 poleAxis;
  9968. #define ENVMAP_TYPE_CUBE_UV
  9969. #include <cube_uv_reflection_fragment>
  9970. vec3 getSample( float theta, vec3 axis ) {
  9971. float cosTheta = cos( theta );
  9972. // Rodrigues' axis-angle rotation
  9973. vec3 sampleDirection = vOutputDirection * cosTheta
  9974. + cross( axis, vOutputDirection ) * sin( theta )
  9975. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9976. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9977. }
  9978. void main() {
  9979. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9980. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9981. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9982. }
  9983. axis = normalize( axis );
  9984. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9985. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9986. for ( int i = 1; i < n; i++ ) {
  9987. if ( i >= samples ) {
  9988. break;
  9989. }
  9990. float theta = dTheta * float( i );
  9991. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9992. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9993. }
  9994. }
  9995. `,
  9996. blending: NoBlending,
  9997. depthTest: false,
  9998. depthWrite: false
  9999. });
  10000. return shaderMaterial;
  10001. }
  10002. function _getEquirectMaterial() {
  10003. return new ShaderMaterial({
  10004. name: 'EquirectangularToCubeUV',
  10005. uniforms: {
  10006. 'envMap': {
  10007. value: null
  10008. }
  10009. },
  10010. vertexShader: _getCommonVertexShader(),
  10011. fragmentShader:
  10012. /* glsl */
  10013. `
  10014. precision mediump float;
  10015. precision mediump int;
  10016. varying vec3 vOutputDirection;
  10017. uniform sampler2D envMap;
  10018. #include <common>
  10019. void main() {
  10020. vec3 outputDirection = normalize( vOutputDirection );
  10021. vec2 uv = equirectUv( outputDirection );
  10022. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10023. }
  10024. `,
  10025. blending: NoBlending,
  10026. depthTest: false,
  10027. depthWrite: false
  10028. });
  10029. }
  10030. function _getCubemapMaterial() {
  10031. return new ShaderMaterial({
  10032. name: 'CubemapToCubeUV',
  10033. uniforms: {
  10034. 'envMap': {
  10035. value: null
  10036. },
  10037. 'flipEnvMap': {
  10038. value: -1
  10039. }
  10040. },
  10041. vertexShader: _getCommonVertexShader(),
  10042. fragmentShader:
  10043. /* glsl */
  10044. `
  10045. precision mediump float;
  10046. precision mediump int;
  10047. uniform float flipEnvMap;
  10048. varying vec3 vOutputDirection;
  10049. uniform samplerCube envMap;
  10050. void main() {
  10051. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10052. }
  10053. `,
  10054. blending: NoBlending,
  10055. depthTest: false,
  10056. depthWrite: false
  10057. });
  10058. }
  10059. function _getCommonVertexShader() {
  10060. return (
  10061. /* glsl */
  10062. `
  10063. precision mediump float;
  10064. precision mediump int;
  10065. attribute float faceIndex;
  10066. varying vec3 vOutputDirection;
  10067. // RH coordinate system; PMREM face-indexing convention
  10068. vec3 getDirection( vec2 uv, float face ) {
  10069. uv = 2.0 * uv - 1.0;
  10070. vec3 direction = vec3( uv, 1.0 );
  10071. if ( face == 0.0 ) {
  10072. direction = direction.zyx; // ( 1, v, u ) pos x
  10073. } else if ( face == 1.0 ) {
  10074. direction = direction.xzy;
  10075. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10076. } else if ( face == 2.0 ) {
  10077. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10078. } else if ( face == 3.0 ) {
  10079. direction = direction.zyx;
  10080. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10081. } else if ( face == 4.0 ) {
  10082. direction = direction.xzy;
  10083. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10084. } else if ( face == 5.0 ) {
  10085. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10086. }
  10087. return direction;
  10088. }
  10089. void main() {
  10090. vOutputDirection = getDirection( uv, faceIndex );
  10091. gl_Position = vec4( position, 1.0 );
  10092. }
  10093. `
  10094. );
  10095. }
  10096. function WebGLCubeUVMaps(renderer) {
  10097. let cubeUVmaps = new WeakMap();
  10098. let pmremGenerator = null;
  10099. function get(texture) {
  10100. if (texture && texture.isTexture) {
  10101. const mapping = texture.mapping;
  10102. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10103. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; // equirect/cube map to cubeUV conversion
  10104. if (isEquirectMap || isCubeMap) {
  10105. if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
  10106. texture.needsPMREMUpdate = false;
  10107. let renderTarget = cubeUVmaps.get(texture);
  10108. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10109. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
  10110. cubeUVmaps.set(texture, renderTarget);
  10111. return renderTarget.texture;
  10112. } else {
  10113. if (cubeUVmaps.has(texture)) {
  10114. return cubeUVmaps.get(texture).texture;
  10115. } else {
  10116. const image = texture.image;
  10117. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10118. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10119. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10120. cubeUVmaps.set(texture, renderTarget);
  10121. texture.addEventListener('dispose', onTextureDispose);
  10122. return renderTarget.texture;
  10123. } else {
  10124. // image not yet ready. try the conversion next frame
  10125. return null;
  10126. }
  10127. }
  10128. }
  10129. }
  10130. }
  10131. return texture;
  10132. }
  10133. function isCubeTextureComplete(image) {
  10134. let count = 0;
  10135. const length = 6;
  10136. for (let i = 0; i < length; i++) {
  10137. if (image[i] !== undefined) count++;
  10138. }
  10139. return count === length;
  10140. }
  10141. function onTextureDispose(event) {
  10142. const texture = event.target;
  10143. texture.removeEventListener('dispose', onTextureDispose);
  10144. const cubemapUV = cubeUVmaps.get(texture);
  10145. if (cubemapUV !== undefined) {
  10146. cubeUVmaps.delete(texture);
  10147. cubemapUV.dispose();
  10148. }
  10149. }
  10150. function dispose() {
  10151. cubeUVmaps = new WeakMap();
  10152. if (pmremGenerator !== null) {
  10153. pmremGenerator.dispose();
  10154. pmremGenerator = null;
  10155. }
  10156. }
  10157. return {
  10158. get: get,
  10159. dispose: dispose
  10160. };
  10161. }
  10162. function WebGLExtensions(gl) {
  10163. const extensions = {};
  10164. function getExtension(name) {
  10165. if (extensions[name] !== undefined) {
  10166. return extensions[name];
  10167. }
  10168. let extension;
  10169. switch (name) {
  10170. case 'WEBGL_depth_texture':
  10171. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10172. break;
  10173. case 'EXT_texture_filter_anisotropic':
  10174. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10175. break;
  10176. case 'WEBGL_compressed_texture_s3tc':
  10177. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10178. break;
  10179. case 'WEBGL_compressed_texture_pvrtc':
  10180. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10181. break;
  10182. default:
  10183. extension = gl.getExtension(name);
  10184. }
  10185. extensions[name] = extension;
  10186. return extension;
  10187. }
  10188. return {
  10189. has: function (name) {
  10190. return getExtension(name) !== null;
  10191. },
  10192. init: function (capabilities) {
  10193. if (capabilities.isWebGL2) {
  10194. getExtension('EXT_color_buffer_float');
  10195. } else {
  10196. getExtension('WEBGL_depth_texture');
  10197. getExtension('OES_texture_float');
  10198. getExtension('OES_texture_half_float');
  10199. getExtension('OES_texture_half_float_linear');
  10200. getExtension('OES_standard_derivatives');
  10201. getExtension('OES_element_index_uint');
  10202. getExtension('OES_vertex_array_object');
  10203. getExtension('ANGLE_instanced_arrays');
  10204. }
  10205. getExtension('OES_texture_float_linear');
  10206. getExtension('EXT_color_buffer_half_float');
  10207. getExtension('WEBGL_multisampled_render_to_texture');
  10208. },
  10209. get: function (name) {
  10210. const extension = getExtension(name);
  10211. if (extension === null) {
  10212. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10213. }
  10214. return extension;
  10215. }
  10216. };
  10217. }
  10218. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10219. const geometries = {};
  10220. const wireframeAttributes = new WeakMap();
  10221. function onGeometryDispose(event) {
  10222. const geometry = event.target;
  10223. if (geometry.index !== null) {
  10224. attributes.remove(geometry.index);
  10225. }
  10226. for (const name in geometry.attributes) {
  10227. attributes.remove(geometry.attributes[name]);
  10228. }
  10229. geometry.removeEventListener('dispose', onGeometryDispose);
  10230. delete geometries[geometry.id];
  10231. const attribute = wireframeAttributes.get(geometry);
  10232. if (attribute) {
  10233. attributes.remove(attribute);
  10234. wireframeAttributes.delete(geometry);
  10235. }
  10236. bindingStates.releaseStatesOfGeometry(geometry);
  10237. if (geometry.isInstancedBufferGeometry === true) {
  10238. delete geometry._maxInstanceCount;
  10239. } //
  10240. info.memory.geometries--;
  10241. }
  10242. function get(object, geometry) {
  10243. if (geometries[geometry.id] === true) return geometry;
  10244. geometry.addEventListener('dispose', onGeometryDispose);
  10245. geometries[geometry.id] = true;
  10246. info.memory.geometries++;
  10247. return geometry;
  10248. }
  10249. function update(geometry) {
  10250. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10251. for (const name in geometryAttributes) {
  10252. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10253. } // morph targets
  10254. const morphAttributes = geometry.morphAttributes;
  10255. for (const name in morphAttributes) {
  10256. const array = morphAttributes[name];
  10257. for (let i = 0, l = array.length; i < l; i++) {
  10258. attributes.update(array[i], gl.ARRAY_BUFFER);
  10259. }
  10260. }
  10261. }
  10262. function updateWireframeAttribute(geometry) {
  10263. const indices = [];
  10264. const geometryIndex = geometry.index;
  10265. const geometryPosition = geometry.attributes.position;
  10266. let version = 0;
  10267. if (geometryIndex !== null) {
  10268. const array = geometryIndex.array;
  10269. version = geometryIndex.version;
  10270. for (let i = 0, l = array.length; i < l; i += 3) {
  10271. const a = array[i + 0];
  10272. const b = array[i + 1];
  10273. const c = array[i + 2];
  10274. indices.push(a, b, b, c, c, a);
  10275. }
  10276. } else {
  10277. const array = geometryPosition.array;
  10278. version = geometryPosition.version;
  10279. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10280. const a = i + 0;
  10281. const b = i + 1;
  10282. const c = i + 2;
  10283. indices.push(a, b, b, c, c, a);
  10284. }
  10285. }
  10286. const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10287. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10288. //
  10289. const previousAttribute = wireframeAttributes.get(geometry);
  10290. if (previousAttribute) attributes.remove(previousAttribute); //
  10291. wireframeAttributes.set(geometry, attribute);
  10292. }
  10293. function getWireframeAttribute(geometry) {
  10294. const currentAttribute = wireframeAttributes.get(geometry);
  10295. if (currentAttribute) {
  10296. const geometryIndex = geometry.index;
  10297. if (geometryIndex !== null) {
  10298. // if the attribute is obsolete, create a new one
  10299. if (currentAttribute.version < geometryIndex.version) {
  10300. updateWireframeAttribute(geometry);
  10301. }
  10302. }
  10303. } else {
  10304. updateWireframeAttribute(geometry);
  10305. }
  10306. return wireframeAttributes.get(geometry);
  10307. }
  10308. return {
  10309. get: get,
  10310. update: update,
  10311. getWireframeAttribute: getWireframeAttribute
  10312. };
  10313. }
  10314. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10315. const isWebGL2 = capabilities.isWebGL2;
  10316. let mode;
  10317. function setMode(value) {
  10318. mode = value;
  10319. }
  10320. let type, bytesPerElement;
  10321. function setIndex(value) {
  10322. type = value.type;
  10323. bytesPerElement = value.bytesPerElement;
  10324. }
  10325. function render(start, count) {
  10326. gl.drawElements(mode, count, type, start * bytesPerElement);
  10327. info.update(count, mode, 1);
  10328. }
  10329. function renderInstances(start, count, primcount) {
  10330. if (primcount === 0) return;
  10331. let extension, methodName;
  10332. if (isWebGL2) {
  10333. extension = gl;
  10334. methodName = 'drawElementsInstanced';
  10335. } else {
  10336. extension = extensions.get('ANGLE_instanced_arrays');
  10337. methodName = 'drawElementsInstancedANGLE';
  10338. if (extension === null) {
  10339. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10340. return;
  10341. }
  10342. }
  10343. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10344. info.update(count, mode, primcount);
  10345. } //
  10346. this.setMode = setMode;
  10347. this.setIndex = setIndex;
  10348. this.render = render;
  10349. this.renderInstances = renderInstances;
  10350. }
  10351. function WebGLInfo(gl) {
  10352. const memory = {
  10353. geometries: 0,
  10354. textures: 0
  10355. };
  10356. const render = {
  10357. frame: 0,
  10358. calls: 0,
  10359. triangles: 0,
  10360. points: 0,
  10361. lines: 0
  10362. };
  10363. function update(count, mode, instanceCount) {
  10364. render.calls++;
  10365. switch (mode) {
  10366. case gl.TRIANGLES:
  10367. render.triangles += instanceCount * (count / 3);
  10368. break;
  10369. case gl.LINES:
  10370. render.lines += instanceCount * (count / 2);
  10371. break;
  10372. case gl.LINE_STRIP:
  10373. render.lines += instanceCount * (count - 1);
  10374. break;
  10375. case gl.LINE_LOOP:
  10376. render.lines += instanceCount * count;
  10377. break;
  10378. case gl.POINTS:
  10379. render.points += instanceCount * count;
  10380. break;
  10381. default:
  10382. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10383. break;
  10384. }
  10385. }
  10386. function reset() {
  10387. render.frame++;
  10388. render.calls = 0;
  10389. render.triangles = 0;
  10390. render.points = 0;
  10391. render.lines = 0;
  10392. }
  10393. return {
  10394. memory: memory,
  10395. render: render,
  10396. programs: null,
  10397. autoReset: true,
  10398. reset: reset,
  10399. update: update
  10400. };
  10401. }
  10402. function numericalSort(a, b) {
  10403. return a[0] - b[0];
  10404. }
  10405. function absNumericalSort(a, b) {
  10406. return Math.abs(b[1]) - Math.abs(a[1]);
  10407. }
  10408. function denormalize(morph, attribute) {
  10409. let denominator = 1;
  10410. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10411. if (array instanceof Int8Array) denominator = 127;else if (array instanceof Uint8Array) denominator = 255;else if (array instanceof Uint16Array) denominator = 65535;else if (array instanceof Int16Array) denominator = 32767;else if (array instanceof Int32Array) denominator = 2147483647;else console.error('THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array);
  10412. morph.divideScalar(denominator);
  10413. }
  10414. function WebGLMorphtargets(gl, capabilities, textures) {
  10415. const influencesList = {};
  10416. const morphInfluences = new Float32Array(8);
  10417. const morphTextures = new WeakMap();
  10418. const morph = new Vector4();
  10419. const workInfluences = [];
  10420. for (let i = 0; i < 8; i++) {
  10421. workInfluences[i] = [i, 0];
  10422. }
  10423. function update(object, geometry, material, program) {
  10424. const objectInfluences = object.morphTargetInfluences;
  10425. if (capabilities.isWebGL2 === true) {
  10426. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10427. // into an array of data textures. Each layer represents a single morph target.
  10428. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10429. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  10430. let entry = morphTextures.get(geometry);
  10431. if (entry === undefined || entry.count !== morphTargetsCount) {
  10432. if (entry !== undefined) entry.texture.dispose();
  10433. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10434. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10435. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10436. const morphTargets = geometry.morphAttributes.position || [];
  10437. const morphNormals = geometry.morphAttributes.normal || [];
  10438. const morphColors = geometry.morphAttributes.color || [];
  10439. let vertexDataCount = 0;
  10440. if (hasMorphPosition === true) vertexDataCount = 1;
  10441. if (hasMorphNormals === true) vertexDataCount = 2;
  10442. if (hasMorphColors === true) vertexDataCount = 3;
  10443. let width = geometry.attributes.position.count * vertexDataCount;
  10444. let height = 1;
  10445. if (width > capabilities.maxTextureSize) {
  10446. height = Math.ceil(width / capabilities.maxTextureSize);
  10447. width = capabilities.maxTextureSize;
  10448. }
  10449. const buffer = new Float32Array(width * height * 4 * morphTargetsCount);
  10450. const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount);
  10451. texture.type = FloatType;
  10452. texture.needsUpdate = true; // fill buffer
  10453. const vertexDataStride = vertexDataCount * 4;
  10454. for (let i = 0; i < morphTargetsCount; i++) {
  10455. const morphTarget = morphTargets[i];
  10456. const morphNormal = morphNormals[i];
  10457. const morphColor = morphColors[i];
  10458. const offset = width * height * 4 * i;
  10459. for (let j = 0; j < morphTarget.count; j++) {
  10460. const stride = j * vertexDataStride;
  10461. if (hasMorphPosition === true) {
  10462. morph.fromBufferAttribute(morphTarget, j);
  10463. if (morphTarget.normalized === true) denormalize(morph, morphTarget);
  10464. buffer[offset + stride + 0] = morph.x;
  10465. buffer[offset + stride + 1] = morph.y;
  10466. buffer[offset + stride + 2] = morph.z;
  10467. buffer[offset + stride + 3] = 0;
  10468. }
  10469. if (hasMorphNormals === true) {
  10470. morph.fromBufferAttribute(morphNormal, j);
  10471. if (morphNormal.normalized === true) denormalize(morph, morphNormal);
  10472. buffer[offset + stride + 4] = morph.x;
  10473. buffer[offset + stride + 5] = morph.y;
  10474. buffer[offset + stride + 6] = morph.z;
  10475. buffer[offset + stride + 7] = 0;
  10476. }
  10477. if (hasMorphColors === true) {
  10478. morph.fromBufferAttribute(morphColor, j);
  10479. if (morphColor.normalized === true) denormalize(morph, morphColor);
  10480. buffer[offset + stride + 8] = morph.x;
  10481. buffer[offset + stride + 9] = morph.y;
  10482. buffer[offset + stride + 10] = morph.z;
  10483. buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1;
  10484. }
  10485. }
  10486. }
  10487. entry = {
  10488. count: morphTargetsCount,
  10489. texture: texture,
  10490. size: new Vector2(width, height)
  10491. };
  10492. morphTextures.set(geometry, entry);
  10493. function disposeTexture() {
  10494. texture.dispose();
  10495. morphTextures.delete(geometry);
  10496. geometry.removeEventListener('dispose', disposeTexture);
  10497. }
  10498. geometry.addEventListener('dispose', disposeTexture);
  10499. } //
  10500. let morphInfluencesSum = 0;
  10501. for (let i = 0; i < objectInfluences.length; i++) {
  10502. morphInfluencesSum += objectInfluences[i];
  10503. }
  10504. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10505. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10506. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10507. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10508. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10509. } else {
  10510. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10511. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10512. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10513. let influences = influencesList[geometry.id];
  10514. if (influences === undefined || influences.length !== length) {
  10515. // initialise list
  10516. influences = [];
  10517. for (let i = 0; i < length; i++) {
  10518. influences[i] = [i, 0];
  10519. }
  10520. influencesList[geometry.id] = influences;
  10521. } // Collect influences
  10522. for (let i = 0; i < length; i++) {
  10523. const influence = influences[i];
  10524. influence[0] = i;
  10525. influence[1] = objectInfluences[i];
  10526. }
  10527. influences.sort(absNumericalSort);
  10528. for (let i = 0; i < 8; i++) {
  10529. if (i < length && influences[i][1]) {
  10530. workInfluences[i][0] = influences[i][0];
  10531. workInfluences[i][1] = influences[i][1];
  10532. } else {
  10533. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10534. workInfluences[i][1] = 0;
  10535. }
  10536. }
  10537. workInfluences.sort(numericalSort);
  10538. const morphTargets = geometry.morphAttributes.position;
  10539. const morphNormals = geometry.morphAttributes.normal;
  10540. let morphInfluencesSum = 0;
  10541. for (let i = 0; i < 8; i++) {
  10542. const influence = workInfluences[i];
  10543. const index = influence[0];
  10544. const value = influence[1];
  10545. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10546. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10547. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10548. }
  10549. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10550. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10551. }
  10552. morphInfluences[i] = value;
  10553. morphInfluencesSum += value;
  10554. } else {
  10555. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10556. geometry.deleteAttribute('morphTarget' + i);
  10557. }
  10558. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10559. geometry.deleteAttribute('morphNormal' + i);
  10560. }
  10561. morphInfluences[i] = 0;
  10562. }
  10563. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10564. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10565. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10566. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10567. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10568. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10569. }
  10570. }
  10571. return {
  10572. update: update
  10573. };
  10574. }
  10575. function WebGLObjects(gl, geometries, attributes, info) {
  10576. let updateMap = new WeakMap();
  10577. function update(object) {
  10578. const frame = info.render.frame;
  10579. const geometry = object.geometry;
  10580. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10581. if (updateMap.get(buffergeometry) !== frame) {
  10582. geometries.update(buffergeometry);
  10583. updateMap.set(buffergeometry, frame);
  10584. }
  10585. if (object.isInstancedMesh) {
  10586. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10587. object.addEventListener('dispose', onInstancedMeshDispose);
  10588. }
  10589. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10590. if (object.instanceColor !== null) {
  10591. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10592. }
  10593. }
  10594. return buffergeometry;
  10595. }
  10596. function dispose() {
  10597. updateMap = new WeakMap();
  10598. }
  10599. function onInstancedMeshDispose(event) {
  10600. const instancedMesh = event.target;
  10601. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10602. attributes.remove(instancedMesh.instanceMatrix);
  10603. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10604. }
  10605. return {
  10606. update: update,
  10607. dispose: dispose
  10608. };
  10609. }
  10610. /**
  10611. * Uniforms of a program.
  10612. * Those form a tree structure with a special top-level container for the root,
  10613. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10614. *
  10615. *
  10616. * Properties of inner nodes including the top-level container:
  10617. *
  10618. * .seq - array of nested uniforms
  10619. * .map - nested uniforms by name
  10620. *
  10621. *
  10622. * Methods of all nodes except the top-level container:
  10623. *
  10624. * .setValue( gl, value, [textures] )
  10625. *
  10626. * uploads a uniform value(s)
  10627. * the 'textures' parameter is needed for sampler uniforms
  10628. *
  10629. *
  10630. * Static methods of the top-level container (textures factorizations):
  10631. *
  10632. * .upload( gl, seq, values, textures )
  10633. *
  10634. * sets uniforms in 'seq' to 'values[id].value'
  10635. *
  10636. * .seqWithValue( seq, values ) : filteredSeq
  10637. *
  10638. * filters 'seq' entries with corresponding entry in values
  10639. *
  10640. *
  10641. * Methods of the top-level container (textures factorizations):
  10642. *
  10643. * .setValue( gl, name, value, textures )
  10644. *
  10645. * sets uniform with name 'name' to 'value'
  10646. *
  10647. * .setOptional( gl, obj, prop )
  10648. *
  10649. * like .set for an optional property of the object
  10650. *
  10651. */
  10652. const emptyTexture = /*@__PURE__*/new Texture();
  10653. const emptyArrayTexture = /*@__PURE__*/new DataArrayTexture();
  10654. const empty3dTexture = /*@__PURE__*/new Data3DTexture();
  10655. const emptyCubeTexture = /*@__PURE__*/new CubeTexture(); // --- Utilities ---
  10656. // Array Caches (provide typed arrays for temporary by size)
  10657. const arrayCacheF32 = [];
  10658. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10659. const mat4array = new Float32Array(16);
  10660. const mat3array = new Float32Array(9);
  10661. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10662. function flatten(array, nBlocks, blockSize) {
  10663. const firstElem = array[0];
  10664. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10665. // see http://jacksondunstan.com/articles/983
  10666. const n = nBlocks * blockSize;
  10667. let r = arrayCacheF32[n];
  10668. if (r === undefined) {
  10669. r = new Float32Array(n);
  10670. arrayCacheF32[n] = r;
  10671. }
  10672. if (nBlocks !== 0) {
  10673. firstElem.toArray(r, 0);
  10674. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10675. offset += blockSize;
  10676. array[i].toArray(r, offset);
  10677. }
  10678. }
  10679. return r;
  10680. }
  10681. function arraysEqual(a, b) {
  10682. if (a.length !== b.length) return false;
  10683. for (let i = 0, l = a.length; i < l; i++) {
  10684. if (a[i] !== b[i]) return false;
  10685. }
  10686. return true;
  10687. }
  10688. function copyArray(a, b) {
  10689. for (let i = 0, l = b.length; i < l; i++) {
  10690. a[i] = b[i];
  10691. }
  10692. } // Texture unit allocation
  10693. function allocTexUnits(textures, n) {
  10694. let r = arrayCacheI32[n];
  10695. if (r === undefined) {
  10696. r = new Int32Array(n);
  10697. arrayCacheI32[n] = r;
  10698. }
  10699. for (let i = 0; i !== n; ++i) {
  10700. r[i] = textures.allocateTextureUnit();
  10701. }
  10702. return r;
  10703. } // --- Setters ---
  10704. // Note: Defining these methods externally, because they come in a bunch
  10705. // and this way their names minify.
  10706. // Single scalar
  10707. function setValueV1f(gl, v) {
  10708. const cache = this.cache;
  10709. if (cache[0] === v) return;
  10710. gl.uniform1f(this.addr, v);
  10711. cache[0] = v;
  10712. } // Single float vector (from flat array or THREE.VectorN)
  10713. function setValueV2f(gl, v) {
  10714. const cache = this.cache;
  10715. if (v.x !== undefined) {
  10716. if (cache[0] !== v.x || cache[1] !== v.y) {
  10717. gl.uniform2f(this.addr, v.x, v.y);
  10718. cache[0] = v.x;
  10719. cache[1] = v.y;
  10720. }
  10721. } else {
  10722. if (arraysEqual(cache, v)) return;
  10723. gl.uniform2fv(this.addr, v);
  10724. copyArray(cache, v);
  10725. }
  10726. }
  10727. function setValueV3f(gl, v) {
  10728. const cache = this.cache;
  10729. if (v.x !== undefined) {
  10730. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10731. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10732. cache[0] = v.x;
  10733. cache[1] = v.y;
  10734. cache[2] = v.z;
  10735. }
  10736. } else if (v.r !== undefined) {
  10737. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10738. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10739. cache[0] = v.r;
  10740. cache[1] = v.g;
  10741. cache[2] = v.b;
  10742. }
  10743. } else {
  10744. if (arraysEqual(cache, v)) return;
  10745. gl.uniform3fv(this.addr, v);
  10746. copyArray(cache, v);
  10747. }
  10748. }
  10749. function setValueV4f(gl, v) {
  10750. const cache = this.cache;
  10751. if (v.x !== undefined) {
  10752. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10753. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10754. cache[0] = v.x;
  10755. cache[1] = v.y;
  10756. cache[2] = v.z;
  10757. cache[3] = v.w;
  10758. }
  10759. } else {
  10760. if (arraysEqual(cache, v)) return;
  10761. gl.uniform4fv(this.addr, v);
  10762. copyArray(cache, v);
  10763. }
  10764. } // Single matrix (from flat array or THREE.MatrixN)
  10765. function setValueM2(gl, v) {
  10766. const cache = this.cache;
  10767. const elements = v.elements;
  10768. if (elements === undefined) {
  10769. if (arraysEqual(cache, v)) return;
  10770. gl.uniformMatrix2fv(this.addr, false, v);
  10771. copyArray(cache, v);
  10772. } else {
  10773. if (arraysEqual(cache, elements)) return;
  10774. mat2array.set(elements);
  10775. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10776. copyArray(cache, elements);
  10777. }
  10778. }
  10779. function setValueM3(gl, v) {
  10780. const cache = this.cache;
  10781. const elements = v.elements;
  10782. if (elements === undefined) {
  10783. if (arraysEqual(cache, v)) return;
  10784. gl.uniformMatrix3fv(this.addr, false, v);
  10785. copyArray(cache, v);
  10786. } else {
  10787. if (arraysEqual(cache, elements)) return;
  10788. mat3array.set(elements);
  10789. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10790. copyArray(cache, elements);
  10791. }
  10792. }
  10793. function setValueM4(gl, v) {
  10794. const cache = this.cache;
  10795. const elements = v.elements;
  10796. if (elements === undefined) {
  10797. if (arraysEqual(cache, v)) return;
  10798. gl.uniformMatrix4fv(this.addr, false, v);
  10799. copyArray(cache, v);
  10800. } else {
  10801. if (arraysEqual(cache, elements)) return;
  10802. mat4array.set(elements);
  10803. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10804. copyArray(cache, elements);
  10805. }
  10806. } // Single integer / boolean
  10807. function setValueV1i(gl, v) {
  10808. const cache = this.cache;
  10809. if (cache[0] === v) return;
  10810. gl.uniform1i(this.addr, v);
  10811. cache[0] = v;
  10812. } // Single integer / boolean vector (from flat array)
  10813. function setValueV2i(gl, v) {
  10814. const cache = this.cache;
  10815. if (arraysEqual(cache, v)) return;
  10816. gl.uniform2iv(this.addr, v);
  10817. copyArray(cache, v);
  10818. }
  10819. function setValueV3i(gl, v) {
  10820. const cache = this.cache;
  10821. if (arraysEqual(cache, v)) return;
  10822. gl.uniform3iv(this.addr, v);
  10823. copyArray(cache, v);
  10824. }
  10825. function setValueV4i(gl, v) {
  10826. const cache = this.cache;
  10827. if (arraysEqual(cache, v)) return;
  10828. gl.uniform4iv(this.addr, v);
  10829. copyArray(cache, v);
  10830. } // Single unsigned integer
  10831. function setValueV1ui(gl, v) {
  10832. const cache = this.cache;
  10833. if (cache[0] === v) return;
  10834. gl.uniform1ui(this.addr, v);
  10835. cache[0] = v;
  10836. } // Single unsigned integer vector (from flat array)
  10837. function setValueV2ui(gl, v) {
  10838. const cache = this.cache;
  10839. if (arraysEqual(cache, v)) return;
  10840. gl.uniform2uiv(this.addr, v);
  10841. copyArray(cache, v);
  10842. }
  10843. function setValueV3ui(gl, v) {
  10844. const cache = this.cache;
  10845. if (arraysEqual(cache, v)) return;
  10846. gl.uniform3uiv(this.addr, v);
  10847. copyArray(cache, v);
  10848. }
  10849. function setValueV4ui(gl, v) {
  10850. const cache = this.cache;
  10851. if (arraysEqual(cache, v)) return;
  10852. gl.uniform4uiv(this.addr, v);
  10853. copyArray(cache, v);
  10854. } // Single texture (2D / Cube)
  10855. function setValueT1(gl, v, textures) {
  10856. const cache = this.cache;
  10857. const unit = textures.allocateTextureUnit();
  10858. if (cache[0] !== unit) {
  10859. gl.uniform1i(this.addr, unit);
  10860. cache[0] = unit;
  10861. }
  10862. textures.setTexture2D(v || emptyTexture, unit);
  10863. }
  10864. function setValueT3D1(gl, v, textures) {
  10865. const cache = this.cache;
  10866. const unit = textures.allocateTextureUnit();
  10867. if (cache[0] !== unit) {
  10868. gl.uniform1i(this.addr, unit);
  10869. cache[0] = unit;
  10870. }
  10871. textures.setTexture3D(v || empty3dTexture, unit);
  10872. }
  10873. function setValueT6(gl, v, textures) {
  10874. const cache = this.cache;
  10875. const unit = textures.allocateTextureUnit();
  10876. if (cache[0] !== unit) {
  10877. gl.uniform1i(this.addr, unit);
  10878. cache[0] = unit;
  10879. }
  10880. textures.setTextureCube(v || emptyCubeTexture, unit);
  10881. }
  10882. function setValueT2DArray1(gl, v, textures) {
  10883. const cache = this.cache;
  10884. const unit = textures.allocateTextureUnit();
  10885. if (cache[0] !== unit) {
  10886. gl.uniform1i(this.addr, unit);
  10887. cache[0] = unit;
  10888. }
  10889. textures.setTexture2DArray(v || emptyArrayTexture, unit);
  10890. } // Helper to pick the right setter for the singular case
  10891. function getSingularSetter(type) {
  10892. switch (type) {
  10893. case 0x1406:
  10894. return setValueV1f;
  10895. // FLOAT
  10896. case 0x8b50:
  10897. return setValueV2f;
  10898. // _VEC2
  10899. case 0x8b51:
  10900. return setValueV3f;
  10901. // _VEC3
  10902. case 0x8b52:
  10903. return setValueV4f;
  10904. // _VEC4
  10905. case 0x8b5a:
  10906. return setValueM2;
  10907. // _MAT2
  10908. case 0x8b5b:
  10909. return setValueM3;
  10910. // _MAT3
  10911. case 0x8b5c:
  10912. return setValueM4;
  10913. // _MAT4
  10914. case 0x1404:
  10915. case 0x8b56:
  10916. return setValueV1i;
  10917. // INT, BOOL
  10918. case 0x8b53:
  10919. case 0x8b57:
  10920. return setValueV2i;
  10921. // _VEC2
  10922. case 0x8b54:
  10923. case 0x8b58:
  10924. return setValueV3i;
  10925. // _VEC3
  10926. case 0x8b55:
  10927. case 0x8b59:
  10928. return setValueV4i;
  10929. // _VEC4
  10930. case 0x1405:
  10931. return setValueV1ui;
  10932. // UINT
  10933. case 0x8dc6:
  10934. return setValueV2ui;
  10935. // _VEC2
  10936. case 0x8dc7:
  10937. return setValueV3ui;
  10938. // _VEC3
  10939. case 0x8dc8:
  10940. return setValueV4ui;
  10941. // _VEC4
  10942. case 0x8b5e: // SAMPLER_2D
  10943. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10944. case 0x8dca: // INT_SAMPLER_2D
  10945. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10946. case 0x8b62:
  10947. // SAMPLER_2D_SHADOW
  10948. return setValueT1;
  10949. case 0x8b5f: // SAMPLER_3D
  10950. case 0x8dcb: // INT_SAMPLER_3D
  10951. case 0x8dd3:
  10952. // UNSIGNED_INT_SAMPLER_3D
  10953. return setValueT3D1;
  10954. case 0x8b60: // SAMPLER_CUBE
  10955. case 0x8dcc: // INT_SAMPLER_CUBE
  10956. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10957. case 0x8dc5:
  10958. // SAMPLER_CUBE_SHADOW
  10959. return setValueT6;
  10960. case 0x8dc1: // SAMPLER_2D_ARRAY
  10961. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10962. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10963. case 0x8dc4:
  10964. // SAMPLER_2D_ARRAY_SHADOW
  10965. return setValueT2DArray1;
  10966. }
  10967. } // Array of scalars
  10968. function setValueV1fArray(gl, v) {
  10969. gl.uniform1fv(this.addr, v);
  10970. } // Array of vectors (from flat array or array of THREE.VectorN)
  10971. function setValueV2fArray(gl, v) {
  10972. const data = flatten(v, this.size, 2);
  10973. gl.uniform2fv(this.addr, data);
  10974. }
  10975. function setValueV3fArray(gl, v) {
  10976. const data = flatten(v, this.size, 3);
  10977. gl.uniform3fv(this.addr, data);
  10978. }
  10979. function setValueV4fArray(gl, v) {
  10980. const data = flatten(v, this.size, 4);
  10981. gl.uniform4fv(this.addr, data);
  10982. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10983. function setValueM2Array(gl, v) {
  10984. const data = flatten(v, this.size, 4);
  10985. gl.uniformMatrix2fv(this.addr, false, data);
  10986. }
  10987. function setValueM3Array(gl, v) {
  10988. const data = flatten(v, this.size, 9);
  10989. gl.uniformMatrix3fv(this.addr, false, data);
  10990. }
  10991. function setValueM4Array(gl, v) {
  10992. const data = flatten(v, this.size, 16);
  10993. gl.uniformMatrix4fv(this.addr, false, data);
  10994. } // Array of integer / boolean
  10995. function setValueV1iArray(gl, v) {
  10996. gl.uniform1iv(this.addr, v);
  10997. } // Array of integer / boolean vectors (from flat array)
  10998. function setValueV2iArray(gl, v) {
  10999. gl.uniform2iv(this.addr, v);
  11000. }
  11001. function setValueV3iArray(gl, v) {
  11002. gl.uniform3iv(this.addr, v);
  11003. }
  11004. function setValueV4iArray(gl, v) {
  11005. gl.uniform4iv(this.addr, v);
  11006. } // Array of unsigned integer
  11007. function setValueV1uiArray(gl, v) {
  11008. gl.uniform1uiv(this.addr, v);
  11009. } // Array of unsigned integer vectors (from flat array)
  11010. function setValueV2uiArray(gl, v) {
  11011. gl.uniform2uiv(this.addr, v);
  11012. }
  11013. function setValueV3uiArray(gl, v) {
  11014. gl.uniform3uiv(this.addr, v);
  11015. }
  11016. function setValueV4uiArray(gl, v) {
  11017. gl.uniform4uiv(this.addr, v);
  11018. } // Array of textures (2D / 3D / Cube / 2DArray)
  11019. function setValueT1Array(gl, v, textures) {
  11020. const n = v.length;
  11021. const units = allocTexUnits(textures, n);
  11022. gl.uniform1iv(this.addr, units);
  11023. for (let i = 0; i !== n; ++i) {
  11024. textures.setTexture2D(v[i] || emptyTexture, units[i]);
  11025. }
  11026. }
  11027. function setValueT3DArray(gl, v, textures) {
  11028. const n = v.length;
  11029. const units = allocTexUnits(textures, n);
  11030. gl.uniform1iv(this.addr, units);
  11031. for (let i = 0; i !== n; ++i) {
  11032. textures.setTexture3D(v[i] || empty3dTexture, units[i]);
  11033. }
  11034. }
  11035. function setValueT6Array(gl, v, textures) {
  11036. const n = v.length;
  11037. const units = allocTexUnits(textures, n);
  11038. gl.uniform1iv(this.addr, units);
  11039. for (let i = 0; i !== n; ++i) {
  11040. textures.setTextureCube(v[i] || emptyCubeTexture, units[i]);
  11041. }
  11042. }
  11043. function setValueT2DArrayArray(gl, v, textures) {
  11044. const n = v.length;
  11045. const units = allocTexUnits(textures, n);
  11046. gl.uniform1iv(this.addr, units);
  11047. for (let i = 0; i !== n; ++i) {
  11048. textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]);
  11049. }
  11050. } // Helper to pick the right setter for a pure (bottom-level) array
  11051. function getPureArraySetter(type) {
  11052. switch (type) {
  11053. case 0x1406:
  11054. return setValueV1fArray;
  11055. // FLOAT
  11056. case 0x8b50:
  11057. return setValueV2fArray;
  11058. // _VEC2
  11059. case 0x8b51:
  11060. return setValueV3fArray;
  11061. // _VEC3
  11062. case 0x8b52:
  11063. return setValueV4fArray;
  11064. // _VEC4
  11065. case 0x8b5a:
  11066. return setValueM2Array;
  11067. // _MAT2
  11068. case 0x8b5b:
  11069. return setValueM3Array;
  11070. // _MAT3
  11071. case 0x8b5c:
  11072. return setValueM4Array;
  11073. // _MAT4
  11074. case 0x1404:
  11075. case 0x8b56:
  11076. return setValueV1iArray;
  11077. // INT, BOOL
  11078. case 0x8b53:
  11079. case 0x8b57:
  11080. return setValueV2iArray;
  11081. // _VEC2
  11082. case 0x8b54:
  11083. case 0x8b58:
  11084. return setValueV3iArray;
  11085. // _VEC3
  11086. case 0x8b55:
  11087. case 0x8b59:
  11088. return setValueV4iArray;
  11089. // _VEC4
  11090. case 0x1405:
  11091. return setValueV1uiArray;
  11092. // UINT
  11093. case 0x8dc6:
  11094. return setValueV2uiArray;
  11095. // _VEC2
  11096. case 0x8dc7:
  11097. return setValueV3uiArray;
  11098. // _VEC3
  11099. case 0x8dc8:
  11100. return setValueV4uiArray;
  11101. // _VEC4
  11102. case 0x8b5e: // SAMPLER_2D
  11103. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11104. case 0x8dca: // INT_SAMPLER_2D
  11105. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11106. case 0x8b62:
  11107. // SAMPLER_2D_SHADOW
  11108. return setValueT1Array;
  11109. case 0x8b5f: // SAMPLER_3D
  11110. case 0x8dcb: // INT_SAMPLER_3D
  11111. case 0x8dd3:
  11112. // UNSIGNED_INT_SAMPLER_3D
  11113. return setValueT3DArray;
  11114. case 0x8b60: // SAMPLER_CUBE
  11115. case 0x8dcc: // INT_SAMPLER_CUBE
  11116. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11117. case 0x8dc5:
  11118. // SAMPLER_CUBE_SHADOW
  11119. return setValueT6Array;
  11120. case 0x8dc1: // SAMPLER_2D_ARRAY
  11121. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11122. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11123. case 0x8dc4:
  11124. // SAMPLER_2D_ARRAY_SHADOW
  11125. return setValueT2DArrayArray;
  11126. }
  11127. } // --- Uniform Classes ---
  11128. class SingleUniform {
  11129. constructor(id, activeInfo, addr) {
  11130. this.id = id;
  11131. this.addr = addr;
  11132. this.cache = [];
  11133. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11134. }
  11135. }
  11136. class PureArrayUniform {
  11137. constructor(id, activeInfo, addr) {
  11138. this.id = id;
  11139. this.addr = addr;
  11140. this.cache = [];
  11141. this.size = activeInfo.size;
  11142. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11143. }
  11144. }
  11145. class StructuredUniform {
  11146. constructor(id) {
  11147. this.id = id;
  11148. this.seq = [];
  11149. this.map = {};
  11150. }
  11151. setValue(gl, value, textures) {
  11152. const seq = this.seq;
  11153. for (let i = 0, n = seq.length; i !== n; ++i) {
  11154. const u = seq[i];
  11155. u.setValue(gl, value[u.id], textures);
  11156. }
  11157. }
  11158. } // --- Top-level ---
  11159. // Parser - builds up the property tree from the path strings
  11160. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  11161. // - the identifier (member name or array index)
  11162. // - followed by an optional right bracket (found when array index)
  11163. // - followed by an optional left bracket or dot (type of subscript)
  11164. //
  11165. // Note: These portions can be read in a non-overlapping fashion and
  11166. // allow straightforward parsing of the hierarchy that WebGL encodes
  11167. // in the uniform names.
  11168. function addUniform(container, uniformObject) {
  11169. container.seq.push(uniformObject);
  11170. container.map[uniformObject.id] = uniformObject;
  11171. }
  11172. function parseUniform(activeInfo, addr, container) {
  11173. const path = activeInfo.name,
  11174. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11175. RePathPart.lastIndex = 0;
  11176. while (true) {
  11177. const match = RePathPart.exec(path),
  11178. matchEnd = RePathPart.lastIndex;
  11179. let id = match[1];
  11180. const idIsIndex = match[2] === ']',
  11181. subscript = match[3];
  11182. if (idIsIndex) id = id | 0; // convert to integer
  11183. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11184. // bare name or "pure" bottom-level array "[0]" suffix
  11185. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11186. break;
  11187. } else {
  11188. // step into inner node / create it in case it doesn't exist
  11189. const map = container.map;
  11190. let next = map[id];
  11191. if (next === undefined) {
  11192. next = new StructuredUniform(id);
  11193. addUniform(container, next);
  11194. }
  11195. container = next;
  11196. }
  11197. }
  11198. } // Root Container
  11199. class WebGLUniforms {
  11200. constructor(gl, program) {
  11201. this.seq = [];
  11202. this.map = {};
  11203. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11204. for (let i = 0; i < n; ++i) {
  11205. const info = gl.getActiveUniform(program, i),
  11206. addr = gl.getUniformLocation(program, info.name);
  11207. parseUniform(info, addr, this);
  11208. }
  11209. }
  11210. setValue(gl, name, value, textures) {
  11211. const u = this.map[name];
  11212. if (u !== undefined) u.setValue(gl, value, textures);
  11213. }
  11214. setOptional(gl, object, name) {
  11215. const v = object[name];
  11216. if (v !== undefined) this.setValue(gl, name, v);
  11217. }
  11218. static upload(gl, seq, values, textures) {
  11219. for (let i = 0, n = seq.length; i !== n; ++i) {
  11220. const u = seq[i],
  11221. v = values[u.id];
  11222. if (v.needsUpdate !== false) {
  11223. // note: always updating when .needsUpdate is undefined
  11224. u.setValue(gl, v.value, textures);
  11225. }
  11226. }
  11227. }
  11228. static seqWithValue(seq, values) {
  11229. const r = [];
  11230. for (let i = 0, n = seq.length; i !== n; ++i) {
  11231. const u = seq[i];
  11232. if (u.id in values) r.push(u);
  11233. }
  11234. return r;
  11235. }
  11236. }
  11237. function WebGLShader(gl, type, string) {
  11238. const shader = gl.createShader(type);
  11239. gl.shaderSource(shader, string);
  11240. gl.compileShader(shader);
  11241. return shader;
  11242. }
  11243. let programIdCount = 0;
  11244. function handleSource(string, errorLine) {
  11245. const lines = string.split('\n');
  11246. const lines2 = [];
  11247. const from = Math.max(errorLine - 6, 0);
  11248. const to = Math.min(errorLine + 6, lines.length);
  11249. for (let i = from; i < to; i++) {
  11250. const line = i + 1;
  11251. lines2.push(`${line === errorLine ? '>' : ' '} ${line}: ${lines[i]}`);
  11252. }
  11253. return lines2.join('\n');
  11254. }
  11255. function getEncodingComponents(encoding) {
  11256. switch (encoding) {
  11257. case LinearEncoding:
  11258. return ['Linear', '( value )'];
  11259. case sRGBEncoding:
  11260. return ['sRGB', '( value )'];
  11261. default:
  11262. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11263. return ['Linear', '( value )'];
  11264. }
  11265. }
  11266. function getShaderErrors(gl, shader, type) {
  11267. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11268. const errors = gl.getShaderInfoLog(shader).trim();
  11269. if (status && errors === '') return '';
  11270. const errorMatches = /ERROR: 0:(\d+)/.exec(errors);
  11271. if (errorMatches) {
  11272. // --enable-privileged-webgl-extension
  11273. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11274. const errorLine = parseInt(errorMatches[1]);
  11275. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource(gl.getShaderSource(shader), errorLine);
  11276. } else {
  11277. return errors;
  11278. }
  11279. }
  11280. function getTexelEncodingFunction(functionName, encoding) {
  11281. const components = getEncodingComponents(encoding);
  11282. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11283. }
  11284. function getToneMappingFunction(functionName, toneMapping) {
  11285. let toneMappingName;
  11286. switch (toneMapping) {
  11287. case LinearToneMapping:
  11288. toneMappingName = 'Linear';
  11289. break;
  11290. case ReinhardToneMapping:
  11291. toneMappingName = 'Reinhard';
  11292. break;
  11293. case CineonToneMapping:
  11294. toneMappingName = 'OptimizedCineon';
  11295. break;
  11296. case ACESFilmicToneMapping:
  11297. toneMappingName = 'ACESFilmic';
  11298. break;
  11299. case CustomToneMapping:
  11300. toneMappingName = 'Custom';
  11301. break;
  11302. default:
  11303. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11304. toneMappingName = 'Linear';
  11305. }
  11306. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11307. }
  11308. function generateExtensions(parameters) {
  11309. 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' : ''];
  11310. return chunks.filter(filterEmptyLine).join('\n');
  11311. }
  11312. function generateDefines(defines) {
  11313. const chunks = [];
  11314. for (const name in defines) {
  11315. const value = defines[name];
  11316. if (value === false) continue;
  11317. chunks.push('#define ' + name + ' ' + value);
  11318. }
  11319. return chunks.join('\n');
  11320. }
  11321. function fetchAttributeLocations(gl, program) {
  11322. const attributes = {};
  11323. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11324. for (let i = 0; i < n; i++) {
  11325. const info = gl.getActiveAttrib(program, i);
  11326. const name = info.name;
  11327. let locationSize = 1;
  11328. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11329. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11330. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11331. attributes[name] = {
  11332. type: info.type,
  11333. location: gl.getAttribLocation(program, name),
  11334. locationSize: locationSize
  11335. };
  11336. }
  11337. return attributes;
  11338. }
  11339. function filterEmptyLine(string) {
  11340. return string !== '';
  11341. }
  11342. function replaceLightNums(string, parameters) {
  11343. 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);
  11344. }
  11345. function replaceClippingPlaneNums(string, parameters) {
  11346. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11347. } // Resolve Includes
  11348. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11349. function resolveIncludes(string) {
  11350. return string.replace(includePattern, includeReplacer);
  11351. }
  11352. function includeReplacer(match, include) {
  11353. const string = ShaderChunk[include];
  11354. if (string === undefined) {
  11355. throw new Error('Can not resolve #include <' + include + '>');
  11356. }
  11357. return resolveIncludes(string);
  11358. } // Unroll Loops
  11359. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11360. 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;
  11361. function unrollLoops(string) {
  11362. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11363. }
  11364. function deprecatedLoopReplacer(match, start, end, snippet) {
  11365. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11366. return loopReplacer(match, start, end, snippet);
  11367. }
  11368. function loopReplacer(match, start, end, snippet) {
  11369. let string = '';
  11370. for (let i = parseInt(start); i < parseInt(end); i++) {
  11371. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11372. }
  11373. return string;
  11374. } //
  11375. function generatePrecision(parameters) {
  11376. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11377. if (parameters.precision === 'highp') {
  11378. precisionstring += '\n#define HIGH_PRECISION';
  11379. } else if (parameters.precision === 'mediump') {
  11380. precisionstring += '\n#define MEDIUM_PRECISION';
  11381. } else if (parameters.precision === 'lowp') {
  11382. precisionstring += '\n#define LOW_PRECISION';
  11383. }
  11384. return precisionstring;
  11385. }
  11386. function generateShadowMapTypeDefine(parameters) {
  11387. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11388. if (parameters.shadowMapType === PCFShadowMap) {
  11389. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11390. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11391. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11392. } else if (parameters.shadowMapType === VSMShadowMap) {
  11393. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11394. }
  11395. return shadowMapTypeDefine;
  11396. }
  11397. function generateEnvMapTypeDefine(parameters) {
  11398. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11399. if (parameters.envMap) {
  11400. switch (parameters.envMapMode) {
  11401. case CubeReflectionMapping:
  11402. case CubeRefractionMapping:
  11403. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11404. break;
  11405. case CubeUVReflectionMapping:
  11406. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11407. break;
  11408. }
  11409. }
  11410. return envMapTypeDefine;
  11411. }
  11412. function generateEnvMapModeDefine(parameters) {
  11413. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11414. if (parameters.envMap) {
  11415. switch (parameters.envMapMode) {
  11416. case CubeRefractionMapping:
  11417. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11418. break;
  11419. }
  11420. }
  11421. return envMapModeDefine;
  11422. }
  11423. function generateEnvMapBlendingDefine(parameters) {
  11424. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11425. if (parameters.envMap) {
  11426. switch (parameters.combine) {
  11427. case MultiplyOperation:
  11428. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11429. break;
  11430. case MixOperation:
  11431. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11432. break;
  11433. case AddOperation:
  11434. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11435. break;
  11436. }
  11437. }
  11438. return envMapBlendingDefine;
  11439. }
  11440. function generateCubeUVSize(parameters) {
  11441. const imageHeight = parameters.envMapCubeUVHeight;
  11442. if (imageHeight === null) return null;
  11443. const maxMip = Math.log2(imageHeight) - 2;
  11444. const texelHeight = 1.0 / imageHeight;
  11445. const texelWidth = 1.0 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16));
  11446. return {
  11447. texelWidth,
  11448. texelHeight,
  11449. maxMip
  11450. };
  11451. }
  11452. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11453. // TODO Send this event to Three.js DevTools
  11454. // console.log( 'WebGLProgram', cacheKey );
  11455. const gl = renderer.getContext();
  11456. const defines = parameters.defines;
  11457. let vertexShader = parameters.vertexShader;
  11458. let fragmentShader = parameters.fragmentShader;
  11459. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11460. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11461. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11462. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11463. const envMapCubeUVSize = generateCubeUVSize(parameters);
  11464. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11465. const customDefines = generateDefines(defines);
  11466. const program = gl.createProgram();
  11467. let prefixVertex, prefixFragment;
  11468. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11469. if (parameters.isRawShaderMaterial) {
  11470. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11471. if (prefixVertex.length > 0) {
  11472. prefixVertex += '\n';
  11473. }
  11474. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11475. if (prefixFragment.length > 0) {
  11476. prefixFragment += '\n';
  11477. }
  11478. } else {
  11479. 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');
  11480. 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
  11481. 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
  11482. getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11483. }
  11484. vertexShader = resolveIncludes(vertexShader);
  11485. vertexShader = replaceLightNums(vertexShader, parameters);
  11486. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11487. fragmentShader = resolveIncludes(fragmentShader);
  11488. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11489. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11490. vertexShader = unrollLoops(vertexShader);
  11491. fragmentShader = unrollLoops(fragmentShader);
  11492. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11493. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11494. versionString = '#version 300 es\n';
  11495. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11496. 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;
  11497. }
  11498. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11499. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11500. // console.log( '*FRAGMENT*', fragmentGlsl );
  11501. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11502. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11503. gl.attachShader(program, glVertexShader);
  11504. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11505. if (parameters.index0AttributeName !== undefined) {
  11506. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11507. } else if (parameters.morphTargets === true) {
  11508. // programs with morphTargets displace position out of attribute 0
  11509. gl.bindAttribLocation(program, 0, 'position');
  11510. }
  11511. gl.linkProgram(program); // check for link errors
  11512. if (renderer.debug.checkShaderErrors) {
  11513. const programLog = gl.getProgramInfoLog(program).trim();
  11514. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11515. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11516. let runnable = true;
  11517. let haveDiagnostics = true;
  11518. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11519. runnable = false;
  11520. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11521. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11522. 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);
  11523. } else if (programLog !== '') {
  11524. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11525. } else if (vertexLog === '' || fragmentLog === '') {
  11526. haveDiagnostics = false;
  11527. }
  11528. if (haveDiagnostics) {
  11529. this.diagnostics = {
  11530. runnable: runnable,
  11531. programLog: programLog,
  11532. vertexShader: {
  11533. log: vertexLog,
  11534. prefix: prefixVertex
  11535. },
  11536. fragmentShader: {
  11537. log: fragmentLog,
  11538. prefix: prefixFragment
  11539. }
  11540. };
  11541. }
  11542. } // Clean up
  11543. // Crashes in iOS9 and iOS10. #18402
  11544. // gl.detachShader( program, glVertexShader );
  11545. // gl.detachShader( program, glFragmentShader );
  11546. gl.deleteShader(glVertexShader);
  11547. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11548. let cachedUniforms;
  11549. this.getUniforms = function () {
  11550. if (cachedUniforms === undefined) {
  11551. cachedUniforms = new WebGLUniforms(gl, program);
  11552. }
  11553. return cachedUniforms;
  11554. }; // set up caching for attribute locations
  11555. let cachedAttributes;
  11556. this.getAttributes = function () {
  11557. if (cachedAttributes === undefined) {
  11558. cachedAttributes = fetchAttributeLocations(gl, program);
  11559. }
  11560. return cachedAttributes;
  11561. }; // free resource
  11562. this.destroy = function () {
  11563. bindingStates.releaseStatesOfProgram(this);
  11564. gl.deleteProgram(program);
  11565. this.program = undefined;
  11566. }; //
  11567. this.name = parameters.shaderName;
  11568. this.id = programIdCount++;
  11569. this.cacheKey = cacheKey;
  11570. this.usedTimes = 1;
  11571. this.program = program;
  11572. this.vertexShader = glVertexShader;
  11573. this.fragmentShader = glFragmentShader;
  11574. return this;
  11575. }
  11576. let _id = 0;
  11577. class WebGLShaderCache {
  11578. constructor() {
  11579. this.shaderCache = new Map();
  11580. this.materialCache = new Map();
  11581. }
  11582. update(material) {
  11583. const vertexShader = material.vertexShader;
  11584. const fragmentShader = material.fragmentShader;
  11585. const vertexShaderStage = this._getShaderStage(vertexShader);
  11586. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11587. const materialShaders = this._getShaderCacheForMaterial(material);
  11588. if (materialShaders.has(vertexShaderStage) === false) {
  11589. materialShaders.add(vertexShaderStage);
  11590. vertexShaderStage.usedTimes++;
  11591. }
  11592. if (materialShaders.has(fragmentShaderStage) === false) {
  11593. materialShaders.add(fragmentShaderStage);
  11594. fragmentShaderStage.usedTimes++;
  11595. }
  11596. return this;
  11597. }
  11598. remove(material) {
  11599. const materialShaders = this.materialCache.get(material);
  11600. for (const shaderStage of materialShaders) {
  11601. shaderStage.usedTimes--;
  11602. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code);
  11603. }
  11604. this.materialCache.delete(material);
  11605. return this;
  11606. }
  11607. getVertexShaderID(material) {
  11608. return this._getShaderStage(material.vertexShader).id;
  11609. }
  11610. getFragmentShaderID(material) {
  11611. return this._getShaderStage(material.fragmentShader).id;
  11612. }
  11613. dispose() {
  11614. this.shaderCache.clear();
  11615. this.materialCache.clear();
  11616. }
  11617. _getShaderCacheForMaterial(material) {
  11618. const cache = this.materialCache;
  11619. if (cache.has(material) === false) {
  11620. cache.set(material, new Set());
  11621. }
  11622. return cache.get(material);
  11623. }
  11624. _getShaderStage(code) {
  11625. const cache = this.shaderCache;
  11626. if (cache.has(code) === false) {
  11627. const stage = new WebGLShaderStage(code);
  11628. cache.set(code, stage);
  11629. }
  11630. return cache.get(code);
  11631. }
  11632. }
  11633. class WebGLShaderStage {
  11634. constructor(code) {
  11635. this.id = _id++;
  11636. this.code = code;
  11637. this.usedTimes = 0;
  11638. }
  11639. }
  11640. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11641. const _programLayers = new Layers();
  11642. const _customShaders = new WebGLShaderCache();
  11643. const programs = [];
  11644. const isWebGL2 = capabilities.isWebGL2;
  11645. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11646. const vertexTextures = capabilities.vertexTextures;
  11647. let precision = capabilities.precision;
  11648. const shaderIDs = {
  11649. MeshDepthMaterial: 'depth',
  11650. MeshDistanceMaterial: 'distanceRGBA',
  11651. MeshNormalMaterial: 'normal',
  11652. MeshBasicMaterial: 'basic',
  11653. MeshLambertMaterial: 'lambert',
  11654. MeshPhongMaterial: 'phong',
  11655. MeshToonMaterial: 'toon',
  11656. MeshStandardMaterial: 'physical',
  11657. MeshPhysicalMaterial: 'physical',
  11658. MeshMatcapMaterial: 'matcap',
  11659. LineBasicMaterial: 'basic',
  11660. LineDashedMaterial: 'dashed',
  11661. PointsMaterial: 'points',
  11662. ShadowMaterial: 'shadow',
  11663. SpriteMaterial: 'sprite'
  11664. };
  11665. function getParameters(material, lights, shadows, scene, object) {
  11666. const fog = scene.fog;
  11667. const geometry = object.geometry;
  11668. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11669. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11670. const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null;
  11671. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11672. // (not to blow over maxLights budget)
  11673. if (material.precision !== null) {
  11674. precision = capabilities.getMaxPrecision(material.precision);
  11675. if (precision !== material.precision) {
  11676. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11677. }
  11678. } //
  11679. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11680. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  11681. let morphTextureStride = 0;
  11682. if (geometry.morphAttributes.position !== undefined) morphTextureStride = 1;
  11683. if (geometry.morphAttributes.normal !== undefined) morphTextureStride = 2;
  11684. if (geometry.morphAttributes.color !== undefined) morphTextureStride = 3; //
  11685. let vertexShader, fragmentShader;
  11686. let customVertexShaderID, customFragmentShaderID;
  11687. if (shaderID) {
  11688. const shader = ShaderLib[shaderID];
  11689. vertexShader = shader.vertexShader;
  11690. fragmentShader = shader.fragmentShader;
  11691. } else {
  11692. vertexShader = material.vertexShader;
  11693. fragmentShader = material.fragmentShader;
  11694. _customShaders.update(material);
  11695. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11696. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11697. }
  11698. const currentRenderTarget = renderer.getRenderTarget();
  11699. const useAlphaTest = material.alphaTest > 0;
  11700. const useClearcoat = material.clearcoat > 0;
  11701. const useIridescence = material.iridescence > 0;
  11702. const parameters = {
  11703. isWebGL2: isWebGL2,
  11704. shaderID: shaderID,
  11705. shaderName: material.type,
  11706. vertexShader: vertexShader,
  11707. fragmentShader: fragmentShader,
  11708. defines: material.defines,
  11709. customVertexShaderID: customVertexShaderID,
  11710. customFragmentShaderID: customFragmentShaderID,
  11711. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11712. glslVersion: material.glslVersion,
  11713. precision: precision,
  11714. instancing: object.isInstancedMesh === true,
  11715. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11716. supportsVertexTextures: vertexTextures,
  11717. outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding,
  11718. map: !!material.map,
  11719. matcap: !!material.matcap,
  11720. envMap: !!envMap,
  11721. envMapMode: envMap && envMap.mapping,
  11722. envMapCubeUVHeight: envMapCubeUVHeight,
  11723. lightMap: !!material.lightMap,
  11724. aoMap: !!material.aoMap,
  11725. emissiveMap: !!material.emissiveMap,
  11726. bumpMap: !!material.bumpMap,
  11727. normalMap: !!material.normalMap,
  11728. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11729. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11730. decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding,
  11731. clearcoat: useClearcoat,
  11732. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11733. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11734. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11735. iridescence: useIridescence,
  11736. iridescenceMap: useIridescence && !!material.iridescenceMap,
  11737. iridescenceThicknessMap: useIridescence && !!material.iridescenceThicknessMap,
  11738. displacementMap: !!material.displacementMap,
  11739. roughnessMap: !!material.roughnessMap,
  11740. metalnessMap: !!material.metalnessMap,
  11741. specularMap: !!material.specularMap,
  11742. specularIntensityMap: !!material.specularIntensityMap,
  11743. specularColorMap: !!material.specularColorMap,
  11744. opaque: material.transparent === false && material.blending === NormalBlending,
  11745. alphaMap: !!material.alphaMap,
  11746. alphaTest: useAlphaTest,
  11747. gradientMap: !!material.gradientMap,
  11748. sheen: material.sheen > 0,
  11749. sheenColorMap: !!material.sheenColorMap,
  11750. sheenRoughnessMap: !!material.sheenRoughnessMap,
  11751. transmission: material.transmission > 0,
  11752. transmissionMap: !!material.transmissionMap,
  11753. thicknessMap: !!material.thicknessMap,
  11754. combine: material.combine,
  11755. vertexTangents: !!material.normalMap && !!geometry.attributes.tangent,
  11756. vertexColors: material.vertexColors,
  11757. vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11758. 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,
  11759. 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,
  11760. fog: !!fog,
  11761. useFog: material.fog === true,
  11762. fogExp2: fog && fog.isFogExp2,
  11763. flatShading: !!material.flatShading,
  11764. sizeAttenuation: material.sizeAttenuation,
  11765. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11766. skinning: object.isSkinnedMesh === true,
  11767. morphTargets: geometry.morphAttributes.position !== undefined,
  11768. morphNormals: geometry.morphAttributes.normal !== undefined,
  11769. morphColors: geometry.morphAttributes.color !== undefined,
  11770. morphTargetsCount: morphTargetsCount,
  11771. morphTextureStride: morphTextureStride,
  11772. numDirLights: lights.directional.length,
  11773. numPointLights: lights.point.length,
  11774. numSpotLights: lights.spot.length,
  11775. numRectAreaLights: lights.rectArea.length,
  11776. numHemiLights: lights.hemi.length,
  11777. numDirLightShadows: lights.directionalShadowMap.length,
  11778. numPointLightShadows: lights.pointShadowMap.length,
  11779. numSpotLightShadows: lights.spotShadowMap.length,
  11780. numClippingPlanes: clipping.numPlanes,
  11781. numClipIntersection: clipping.numIntersection,
  11782. dithering: material.dithering,
  11783. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11784. shadowMapType: renderer.shadowMap.type,
  11785. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11786. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11787. premultipliedAlpha: material.premultipliedAlpha,
  11788. doubleSided: material.side === DoubleSide,
  11789. flipSided: material.side === BackSide,
  11790. useDepthPacking: !!material.depthPacking,
  11791. depthPacking: material.depthPacking || 0,
  11792. index0AttributeName: material.index0AttributeName,
  11793. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11794. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11795. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11796. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11797. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11798. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11799. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11800. customProgramCacheKey: material.customProgramCacheKey()
  11801. };
  11802. return parameters;
  11803. }
  11804. function getProgramCacheKey(parameters) {
  11805. const array = [];
  11806. if (parameters.shaderID) {
  11807. array.push(parameters.shaderID);
  11808. } else {
  11809. array.push(parameters.customVertexShaderID);
  11810. array.push(parameters.customFragmentShaderID);
  11811. }
  11812. if (parameters.defines !== undefined) {
  11813. for (const name in parameters.defines) {
  11814. array.push(name);
  11815. array.push(parameters.defines[name]);
  11816. }
  11817. }
  11818. if (parameters.isRawShaderMaterial === false) {
  11819. getProgramCacheKeyParameters(array, parameters);
  11820. getProgramCacheKeyBooleans(array, parameters);
  11821. array.push(renderer.outputEncoding);
  11822. }
  11823. array.push(parameters.customProgramCacheKey);
  11824. return array.join();
  11825. }
  11826. function getProgramCacheKeyParameters(array, parameters) {
  11827. array.push(parameters.precision);
  11828. array.push(parameters.outputEncoding);
  11829. array.push(parameters.envMapMode);
  11830. array.push(parameters.envMapCubeUVHeight);
  11831. array.push(parameters.combine);
  11832. array.push(parameters.vertexUvs);
  11833. array.push(parameters.fogExp2);
  11834. array.push(parameters.sizeAttenuation);
  11835. array.push(parameters.morphTargetsCount);
  11836. array.push(parameters.morphAttributeCount);
  11837. array.push(parameters.numDirLights);
  11838. array.push(parameters.numPointLights);
  11839. array.push(parameters.numSpotLights);
  11840. array.push(parameters.numHemiLights);
  11841. array.push(parameters.numRectAreaLights);
  11842. array.push(parameters.numDirLightShadows);
  11843. array.push(parameters.numPointLightShadows);
  11844. array.push(parameters.numSpotLightShadows);
  11845. array.push(parameters.shadowMapType);
  11846. array.push(parameters.toneMapping);
  11847. array.push(parameters.numClippingPlanes);
  11848. array.push(parameters.numClipIntersection);
  11849. array.push(parameters.depthPacking);
  11850. }
  11851. function getProgramCacheKeyBooleans(array, parameters) {
  11852. _programLayers.disableAll();
  11853. if (parameters.isWebGL2) _programLayers.enable(0);
  11854. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  11855. if (parameters.instancing) _programLayers.enable(2);
  11856. if (parameters.instancingColor) _programLayers.enable(3);
  11857. if (parameters.map) _programLayers.enable(4);
  11858. if (parameters.matcap) _programLayers.enable(5);
  11859. if (parameters.envMap) _programLayers.enable(6);
  11860. if (parameters.lightMap) _programLayers.enable(7);
  11861. if (parameters.aoMap) _programLayers.enable(8);
  11862. if (parameters.emissiveMap) _programLayers.enable(9);
  11863. if (parameters.bumpMap) _programLayers.enable(10);
  11864. if (parameters.normalMap) _programLayers.enable(11);
  11865. if (parameters.objectSpaceNormalMap) _programLayers.enable(12);
  11866. if (parameters.tangentSpaceNormalMap) _programLayers.enable(13);
  11867. if (parameters.clearcoat) _programLayers.enable(14);
  11868. if (parameters.clearcoatMap) _programLayers.enable(15);
  11869. if (parameters.clearcoatRoughnessMap) _programLayers.enable(16);
  11870. if (parameters.clearcoatNormalMap) _programLayers.enable(17);
  11871. if (parameters.iridescence) _programLayers.enable(18);
  11872. if (parameters.iridescenceMap) _programLayers.enable(19);
  11873. if (parameters.iridescenceThicknessMap) _programLayers.enable(20);
  11874. if (parameters.displacementMap) _programLayers.enable(21);
  11875. if (parameters.specularMap) _programLayers.enable(22);
  11876. if (parameters.roughnessMap) _programLayers.enable(23);
  11877. if (parameters.metalnessMap) _programLayers.enable(24);
  11878. if (parameters.gradientMap) _programLayers.enable(25);
  11879. if (parameters.alphaMap) _programLayers.enable(26);
  11880. if (parameters.alphaTest) _programLayers.enable(27);
  11881. if (parameters.vertexColors) _programLayers.enable(28);
  11882. if (parameters.vertexAlphas) _programLayers.enable(29);
  11883. if (parameters.vertexUvs) _programLayers.enable(30);
  11884. if (parameters.vertexTangents) _programLayers.enable(31);
  11885. if (parameters.uvsVertexOnly) _programLayers.enable(32);
  11886. if (parameters.fog) _programLayers.enable(33);
  11887. array.push(_programLayers.mask);
  11888. _programLayers.disableAll();
  11889. if (parameters.useFog) _programLayers.enable(0);
  11890. if (parameters.flatShading) _programLayers.enable(1);
  11891. if (parameters.logarithmicDepthBuffer) _programLayers.enable(2);
  11892. if (parameters.skinning) _programLayers.enable(3);
  11893. if (parameters.morphTargets) _programLayers.enable(4);
  11894. if (parameters.morphNormals) _programLayers.enable(5);
  11895. if (parameters.morphColors) _programLayers.enable(6);
  11896. if (parameters.premultipliedAlpha) _programLayers.enable(7);
  11897. if (parameters.shadowMapEnabled) _programLayers.enable(8);
  11898. if (parameters.physicallyCorrectLights) _programLayers.enable(9);
  11899. if (parameters.doubleSided) _programLayers.enable(10);
  11900. if (parameters.flipSided) _programLayers.enable(11);
  11901. if (parameters.useDepthPacking) _programLayers.enable(12);
  11902. if (parameters.dithering) _programLayers.enable(13);
  11903. if (parameters.specularIntensityMap) _programLayers.enable(14);
  11904. if (parameters.specularColorMap) _programLayers.enable(15);
  11905. if (parameters.transmission) _programLayers.enable(16);
  11906. if (parameters.transmissionMap) _programLayers.enable(17);
  11907. if (parameters.thicknessMap) _programLayers.enable(18);
  11908. if (parameters.sheen) _programLayers.enable(19);
  11909. if (parameters.sheenColorMap) _programLayers.enable(20);
  11910. if (parameters.sheenRoughnessMap) _programLayers.enable(21);
  11911. if (parameters.decodeVideoTexture) _programLayers.enable(22);
  11912. if (parameters.opaque) _programLayers.enable(23);
  11913. array.push(_programLayers.mask);
  11914. }
  11915. function getUniforms(material) {
  11916. const shaderID = shaderIDs[material.type];
  11917. let uniforms;
  11918. if (shaderID) {
  11919. const shader = ShaderLib[shaderID];
  11920. uniforms = UniformsUtils.clone(shader.uniforms);
  11921. } else {
  11922. uniforms = material.uniforms;
  11923. }
  11924. return uniforms;
  11925. }
  11926. function acquireProgram(parameters, cacheKey) {
  11927. let program; // Check if code has been already compiled
  11928. for (let p = 0, pl = programs.length; p < pl; p++) {
  11929. const preexistingProgram = programs[p];
  11930. if (preexistingProgram.cacheKey === cacheKey) {
  11931. program = preexistingProgram;
  11932. ++program.usedTimes;
  11933. break;
  11934. }
  11935. }
  11936. if (program === undefined) {
  11937. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11938. programs.push(program);
  11939. }
  11940. return program;
  11941. }
  11942. function releaseProgram(program) {
  11943. if (--program.usedTimes === 0) {
  11944. // Remove from unordered set
  11945. const i = programs.indexOf(program);
  11946. programs[i] = programs[programs.length - 1];
  11947. programs.pop(); // Free WebGL resources
  11948. program.destroy();
  11949. }
  11950. }
  11951. function releaseShaderCache(material) {
  11952. _customShaders.remove(material);
  11953. }
  11954. function dispose() {
  11955. _customShaders.dispose();
  11956. }
  11957. return {
  11958. getParameters: getParameters,
  11959. getProgramCacheKey: getProgramCacheKey,
  11960. getUniforms: getUniforms,
  11961. acquireProgram: acquireProgram,
  11962. releaseProgram: releaseProgram,
  11963. releaseShaderCache: releaseShaderCache,
  11964. // Exposed for resource monitoring & error feedback via renderer.info:
  11965. programs: programs,
  11966. dispose: dispose
  11967. };
  11968. }
  11969. function WebGLProperties() {
  11970. let properties = new WeakMap();
  11971. function get(object) {
  11972. let map = properties.get(object);
  11973. if (map === undefined) {
  11974. map = {};
  11975. properties.set(object, map);
  11976. }
  11977. return map;
  11978. }
  11979. function remove(object) {
  11980. properties.delete(object);
  11981. }
  11982. function update(object, key, value) {
  11983. properties.get(object)[key] = value;
  11984. }
  11985. function dispose() {
  11986. properties = new WeakMap();
  11987. }
  11988. return {
  11989. get: get,
  11990. remove: remove,
  11991. update: update,
  11992. dispose: dispose
  11993. };
  11994. }
  11995. function painterSortStable(a, b) {
  11996. if (a.groupOrder !== b.groupOrder) {
  11997. return a.groupOrder - b.groupOrder;
  11998. } else if (a.renderOrder !== b.renderOrder) {
  11999. return a.renderOrder - b.renderOrder;
  12000. } else if (a.material.id !== b.material.id) {
  12001. return a.material.id - b.material.id;
  12002. } else if (a.z !== b.z) {
  12003. return a.z - b.z;
  12004. } else {
  12005. return a.id - b.id;
  12006. }
  12007. }
  12008. function reversePainterSortStable(a, b) {
  12009. if (a.groupOrder !== b.groupOrder) {
  12010. return a.groupOrder - b.groupOrder;
  12011. } else if (a.renderOrder !== b.renderOrder) {
  12012. return a.renderOrder - b.renderOrder;
  12013. } else if (a.z !== b.z) {
  12014. return b.z - a.z;
  12015. } else {
  12016. return a.id - b.id;
  12017. }
  12018. }
  12019. function WebGLRenderList() {
  12020. const renderItems = [];
  12021. let renderItemsIndex = 0;
  12022. const opaque = [];
  12023. const transmissive = [];
  12024. const transparent = [];
  12025. function init() {
  12026. renderItemsIndex = 0;
  12027. opaque.length = 0;
  12028. transmissive.length = 0;
  12029. transparent.length = 0;
  12030. }
  12031. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12032. let renderItem = renderItems[renderItemsIndex];
  12033. if (renderItem === undefined) {
  12034. renderItem = {
  12035. id: object.id,
  12036. object: object,
  12037. geometry: geometry,
  12038. material: material,
  12039. groupOrder: groupOrder,
  12040. renderOrder: object.renderOrder,
  12041. z: z,
  12042. group: group
  12043. };
  12044. renderItems[renderItemsIndex] = renderItem;
  12045. } else {
  12046. renderItem.id = object.id;
  12047. renderItem.object = object;
  12048. renderItem.geometry = geometry;
  12049. renderItem.material = material;
  12050. renderItem.groupOrder = groupOrder;
  12051. renderItem.renderOrder = object.renderOrder;
  12052. renderItem.z = z;
  12053. renderItem.group = group;
  12054. }
  12055. renderItemsIndex++;
  12056. return renderItem;
  12057. }
  12058. function push(object, geometry, material, groupOrder, z, group) {
  12059. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12060. if (material.transmission > 0.0) {
  12061. transmissive.push(renderItem);
  12062. } else if (material.transparent === true) {
  12063. transparent.push(renderItem);
  12064. } else {
  12065. opaque.push(renderItem);
  12066. }
  12067. }
  12068. function unshift(object, geometry, material, groupOrder, z, group) {
  12069. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12070. if (material.transmission > 0.0) {
  12071. transmissive.unshift(renderItem);
  12072. } else if (material.transparent === true) {
  12073. transparent.unshift(renderItem);
  12074. } else {
  12075. opaque.unshift(renderItem);
  12076. }
  12077. }
  12078. function sort(customOpaqueSort, customTransparentSort) {
  12079. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12080. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  12081. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12082. }
  12083. function finish() {
  12084. // Clear references from inactive renderItems in the list
  12085. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12086. const renderItem = renderItems[i];
  12087. if (renderItem.id === null) break;
  12088. renderItem.id = null;
  12089. renderItem.object = null;
  12090. renderItem.geometry = null;
  12091. renderItem.material = null;
  12092. renderItem.group = null;
  12093. }
  12094. }
  12095. return {
  12096. opaque: opaque,
  12097. transmissive: transmissive,
  12098. transparent: transparent,
  12099. init: init,
  12100. push: push,
  12101. unshift: unshift,
  12102. finish: finish,
  12103. sort: sort
  12104. };
  12105. }
  12106. function WebGLRenderLists() {
  12107. let lists = new WeakMap();
  12108. function get(scene, renderCallDepth) {
  12109. let list;
  12110. if (lists.has(scene) === false) {
  12111. list = new WebGLRenderList();
  12112. lists.set(scene, [list]);
  12113. } else {
  12114. if (renderCallDepth >= lists.get(scene).length) {
  12115. list = new WebGLRenderList();
  12116. lists.get(scene).push(list);
  12117. } else {
  12118. list = lists.get(scene)[renderCallDepth];
  12119. }
  12120. }
  12121. return list;
  12122. }
  12123. function dispose() {
  12124. lists = new WeakMap();
  12125. }
  12126. return {
  12127. get: get,
  12128. dispose: dispose
  12129. };
  12130. }
  12131. function UniformsCache() {
  12132. const lights = {};
  12133. return {
  12134. get: function (light) {
  12135. if (lights[light.id] !== undefined) {
  12136. return lights[light.id];
  12137. }
  12138. let uniforms;
  12139. switch (light.type) {
  12140. case 'DirectionalLight':
  12141. uniforms = {
  12142. direction: new Vector3(),
  12143. color: new Color()
  12144. };
  12145. break;
  12146. case 'SpotLight':
  12147. uniforms = {
  12148. position: new Vector3(),
  12149. direction: new Vector3(),
  12150. color: new Color(),
  12151. distance: 0,
  12152. coneCos: 0,
  12153. penumbraCos: 0,
  12154. decay: 0
  12155. };
  12156. break;
  12157. case 'PointLight':
  12158. uniforms = {
  12159. position: new Vector3(),
  12160. color: new Color(),
  12161. distance: 0,
  12162. decay: 0
  12163. };
  12164. break;
  12165. case 'HemisphereLight':
  12166. uniforms = {
  12167. direction: new Vector3(),
  12168. skyColor: new Color(),
  12169. groundColor: new Color()
  12170. };
  12171. break;
  12172. case 'RectAreaLight':
  12173. uniforms = {
  12174. color: new Color(),
  12175. position: new Vector3(),
  12176. halfWidth: new Vector3(),
  12177. halfHeight: new Vector3()
  12178. };
  12179. break;
  12180. }
  12181. lights[light.id] = uniforms;
  12182. return uniforms;
  12183. }
  12184. };
  12185. }
  12186. function ShadowUniformsCache() {
  12187. const lights = {};
  12188. return {
  12189. get: function (light) {
  12190. if (lights[light.id] !== undefined) {
  12191. return lights[light.id];
  12192. }
  12193. let uniforms;
  12194. switch (light.type) {
  12195. case 'DirectionalLight':
  12196. uniforms = {
  12197. shadowBias: 0,
  12198. shadowNormalBias: 0,
  12199. shadowRadius: 1,
  12200. shadowMapSize: new Vector2()
  12201. };
  12202. break;
  12203. case 'SpotLight':
  12204. uniforms = {
  12205. shadowBias: 0,
  12206. shadowNormalBias: 0,
  12207. shadowRadius: 1,
  12208. shadowMapSize: new Vector2()
  12209. };
  12210. break;
  12211. case 'PointLight':
  12212. uniforms = {
  12213. shadowBias: 0,
  12214. shadowNormalBias: 0,
  12215. shadowRadius: 1,
  12216. shadowMapSize: new Vector2(),
  12217. shadowCameraNear: 1,
  12218. shadowCameraFar: 1000
  12219. };
  12220. break;
  12221. // TODO (abelnation): set RectAreaLight shadow uniforms
  12222. }
  12223. lights[light.id] = uniforms;
  12224. return uniforms;
  12225. }
  12226. };
  12227. }
  12228. let nextVersion = 0;
  12229. function shadowCastingLightsFirst(lightA, lightB) {
  12230. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12231. }
  12232. function WebGLLights(extensions, capabilities) {
  12233. const cache = new UniformsCache();
  12234. const shadowCache = ShadowUniformsCache();
  12235. const state = {
  12236. version: 0,
  12237. hash: {
  12238. directionalLength: -1,
  12239. pointLength: -1,
  12240. spotLength: -1,
  12241. rectAreaLength: -1,
  12242. hemiLength: -1,
  12243. numDirectionalShadows: -1,
  12244. numPointShadows: -1,
  12245. numSpotShadows: -1
  12246. },
  12247. ambient: [0, 0, 0],
  12248. probe: [],
  12249. directional: [],
  12250. directionalShadow: [],
  12251. directionalShadowMap: [],
  12252. directionalShadowMatrix: [],
  12253. spot: [],
  12254. spotShadow: [],
  12255. spotShadowMap: [],
  12256. spotShadowMatrix: [],
  12257. rectArea: [],
  12258. rectAreaLTC1: null,
  12259. rectAreaLTC2: null,
  12260. point: [],
  12261. pointShadow: [],
  12262. pointShadowMap: [],
  12263. pointShadowMatrix: [],
  12264. hemi: []
  12265. };
  12266. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12267. const vector3 = new Vector3();
  12268. const matrix4 = new Matrix4();
  12269. const matrix42 = new Matrix4();
  12270. function setup(lights, physicallyCorrectLights) {
  12271. let r = 0,
  12272. g = 0,
  12273. b = 0;
  12274. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12275. let directionalLength = 0;
  12276. let pointLength = 0;
  12277. let spotLength = 0;
  12278. let rectAreaLength = 0;
  12279. let hemiLength = 0;
  12280. let numDirectionalShadows = 0;
  12281. let numPointShadows = 0;
  12282. let numSpotShadows = 0;
  12283. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  12284. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12285. for (let i = 0, l = lights.length; i < l; i++) {
  12286. const light = lights[i];
  12287. const color = light.color;
  12288. const intensity = light.intensity;
  12289. const distance = light.distance;
  12290. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12291. if (light.isAmbientLight) {
  12292. r += color.r * intensity * scaleFactor;
  12293. g += color.g * intensity * scaleFactor;
  12294. b += color.b * intensity * scaleFactor;
  12295. } else if (light.isLightProbe) {
  12296. for (let j = 0; j < 9; j++) {
  12297. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12298. }
  12299. } else if (light.isDirectionalLight) {
  12300. const uniforms = cache.get(light);
  12301. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12302. if (light.castShadow) {
  12303. const shadow = light.shadow;
  12304. const shadowUniforms = shadowCache.get(light);
  12305. shadowUniforms.shadowBias = shadow.bias;
  12306. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12307. shadowUniforms.shadowRadius = shadow.radius;
  12308. shadowUniforms.shadowMapSize = shadow.mapSize;
  12309. state.directionalShadow[directionalLength] = shadowUniforms;
  12310. state.directionalShadowMap[directionalLength] = shadowMap;
  12311. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12312. numDirectionalShadows++;
  12313. }
  12314. state.directional[directionalLength] = uniforms;
  12315. directionalLength++;
  12316. } else if (light.isSpotLight) {
  12317. const uniforms = cache.get(light);
  12318. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12319. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12320. uniforms.distance = distance;
  12321. uniforms.coneCos = Math.cos(light.angle);
  12322. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12323. uniforms.decay = light.decay;
  12324. if (light.castShadow) {
  12325. const shadow = light.shadow;
  12326. const shadowUniforms = shadowCache.get(light);
  12327. shadowUniforms.shadowBias = shadow.bias;
  12328. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12329. shadowUniforms.shadowRadius = shadow.radius;
  12330. shadowUniforms.shadowMapSize = shadow.mapSize;
  12331. state.spotShadow[spotLength] = shadowUniforms;
  12332. state.spotShadowMap[spotLength] = shadowMap;
  12333. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12334. numSpotShadows++;
  12335. }
  12336. state.spot[spotLength] = uniforms;
  12337. spotLength++;
  12338. } else if (light.isRectAreaLight) {
  12339. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12340. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12341. // (b) intensity is the brightness of the light
  12342. uniforms.color.copy(color).multiplyScalar(intensity);
  12343. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12344. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12345. state.rectArea[rectAreaLength] = uniforms;
  12346. rectAreaLength++;
  12347. } else if (light.isPointLight) {
  12348. const uniforms = cache.get(light);
  12349. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12350. uniforms.distance = light.distance;
  12351. uniforms.decay = light.decay;
  12352. if (light.castShadow) {
  12353. const shadow = light.shadow;
  12354. const shadowUniforms = shadowCache.get(light);
  12355. shadowUniforms.shadowBias = shadow.bias;
  12356. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12357. shadowUniforms.shadowRadius = shadow.radius;
  12358. shadowUniforms.shadowMapSize = shadow.mapSize;
  12359. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12360. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12361. state.pointShadow[pointLength] = shadowUniforms;
  12362. state.pointShadowMap[pointLength] = shadowMap;
  12363. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12364. numPointShadows++;
  12365. }
  12366. state.point[pointLength] = uniforms;
  12367. pointLength++;
  12368. } else if (light.isHemisphereLight) {
  12369. const uniforms = cache.get(light);
  12370. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12371. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12372. state.hemi[hemiLength] = uniforms;
  12373. hemiLength++;
  12374. }
  12375. }
  12376. if (rectAreaLength > 0) {
  12377. if (capabilities.isWebGL2) {
  12378. // WebGL 2
  12379. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12380. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12381. } else {
  12382. // WebGL 1
  12383. if (extensions.has('OES_texture_float_linear') === true) {
  12384. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12385. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12386. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12387. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12388. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12389. } else {
  12390. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12391. }
  12392. }
  12393. }
  12394. state.ambient[0] = r;
  12395. state.ambient[1] = g;
  12396. state.ambient[2] = b;
  12397. const hash = state.hash;
  12398. 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) {
  12399. state.directional.length = directionalLength;
  12400. state.spot.length = spotLength;
  12401. state.rectArea.length = rectAreaLength;
  12402. state.point.length = pointLength;
  12403. state.hemi.length = hemiLength;
  12404. state.directionalShadow.length = numDirectionalShadows;
  12405. state.directionalShadowMap.length = numDirectionalShadows;
  12406. state.pointShadow.length = numPointShadows;
  12407. state.pointShadowMap.length = numPointShadows;
  12408. state.spotShadow.length = numSpotShadows;
  12409. state.spotShadowMap.length = numSpotShadows;
  12410. state.directionalShadowMatrix.length = numDirectionalShadows;
  12411. state.pointShadowMatrix.length = numPointShadows;
  12412. state.spotShadowMatrix.length = numSpotShadows;
  12413. hash.directionalLength = directionalLength;
  12414. hash.pointLength = pointLength;
  12415. hash.spotLength = spotLength;
  12416. hash.rectAreaLength = rectAreaLength;
  12417. hash.hemiLength = hemiLength;
  12418. hash.numDirectionalShadows = numDirectionalShadows;
  12419. hash.numPointShadows = numPointShadows;
  12420. hash.numSpotShadows = numSpotShadows;
  12421. state.version = nextVersion++;
  12422. }
  12423. }
  12424. function setupView(lights, camera) {
  12425. let directionalLength = 0;
  12426. let pointLength = 0;
  12427. let spotLength = 0;
  12428. let rectAreaLength = 0;
  12429. let hemiLength = 0;
  12430. const viewMatrix = camera.matrixWorldInverse;
  12431. for (let i = 0, l = lights.length; i < l; i++) {
  12432. const light = lights[i];
  12433. if (light.isDirectionalLight) {
  12434. const uniforms = state.directional[directionalLength];
  12435. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12436. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12437. uniforms.direction.sub(vector3);
  12438. uniforms.direction.transformDirection(viewMatrix);
  12439. directionalLength++;
  12440. } else if (light.isSpotLight) {
  12441. const uniforms = state.spot[spotLength];
  12442. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12443. uniforms.position.applyMatrix4(viewMatrix);
  12444. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12445. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12446. uniforms.direction.sub(vector3);
  12447. uniforms.direction.transformDirection(viewMatrix);
  12448. spotLength++;
  12449. } else if (light.isRectAreaLight) {
  12450. const uniforms = state.rectArea[rectAreaLength];
  12451. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12452. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12453. matrix42.identity();
  12454. matrix4.copy(light.matrixWorld);
  12455. matrix4.premultiply(viewMatrix);
  12456. matrix42.extractRotation(matrix4);
  12457. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12458. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12459. uniforms.halfWidth.applyMatrix4(matrix42);
  12460. uniforms.halfHeight.applyMatrix4(matrix42);
  12461. rectAreaLength++;
  12462. } else if (light.isPointLight) {
  12463. const uniforms = state.point[pointLength];
  12464. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12465. uniforms.position.applyMatrix4(viewMatrix);
  12466. pointLength++;
  12467. } else if (light.isHemisphereLight) {
  12468. const uniforms = state.hemi[hemiLength];
  12469. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12470. uniforms.direction.transformDirection(viewMatrix);
  12471. hemiLength++;
  12472. }
  12473. }
  12474. }
  12475. return {
  12476. setup: setup,
  12477. setupView: setupView,
  12478. state: state
  12479. };
  12480. }
  12481. function WebGLRenderState(extensions, capabilities) {
  12482. const lights = new WebGLLights(extensions, capabilities);
  12483. const lightsArray = [];
  12484. const shadowsArray = [];
  12485. function init() {
  12486. lightsArray.length = 0;
  12487. shadowsArray.length = 0;
  12488. }
  12489. function pushLight(light) {
  12490. lightsArray.push(light);
  12491. }
  12492. function pushShadow(shadowLight) {
  12493. shadowsArray.push(shadowLight);
  12494. }
  12495. function setupLights(physicallyCorrectLights) {
  12496. lights.setup(lightsArray, physicallyCorrectLights);
  12497. }
  12498. function setupLightsView(camera) {
  12499. lights.setupView(lightsArray, camera);
  12500. }
  12501. const state = {
  12502. lightsArray: lightsArray,
  12503. shadowsArray: shadowsArray,
  12504. lights: lights
  12505. };
  12506. return {
  12507. init: init,
  12508. state: state,
  12509. setupLights: setupLights,
  12510. setupLightsView: setupLightsView,
  12511. pushLight: pushLight,
  12512. pushShadow: pushShadow
  12513. };
  12514. }
  12515. function WebGLRenderStates(extensions, capabilities) {
  12516. let renderStates = new WeakMap();
  12517. function get(scene, renderCallDepth = 0) {
  12518. let renderState;
  12519. if (renderStates.has(scene) === false) {
  12520. renderState = new WebGLRenderState(extensions, capabilities);
  12521. renderStates.set(scene, [renderState]);
  12522. } else {
  12523. if (renderCallDepth >= renderStates.get(scene).length) {
  12524. renderState = new WebGLRenderState(extensions, capabilities);
  12525. renderStates.get(scene).push(renderState);
  12526. } else {
  12527. renderState = renderStates.get(scene)[renderCallDepth];
  12528. }
  12529. }
  12530. return renderState;
  12531. }
  12532. function dispose() {
  12533. renderStates = new WeakMap();
  12534. }
  12535. return {
  12536. get: get,
  12537. dispose: dispose
  12538. };
  12539. }
  12540. class MeshDepthMaterial extends Material {
  12541. constructor(parameters) {
  12542. super();
  12543. this.isMeshDepthMaterial = true;
  12544. this.type = 'MeshDepthMaterial';
  12545. this.depthPacking = BasicDepthPacking;
  12546. this.map = null;
  12547. this.alphaMap = null;
  12548. this.displacementMap = null;
  12549. this.displacementScale = 1;
  12550. this.displacementBias = 0;
  12551. this.wireframe = false;
  12552. this.wireframeLinewidth = 1;
  12553. this.setValues(parameters);
  12554. }
  12555. copy(source) {
  12556. super.copy(source);
  12557. this.depthPacking = source.depthPacking;
  12558. this.map = source.map;
  12559. this.alphaMap = source.alphaMap;
  12560. this.displacementMap = source.displacementMap;
  12561. this.displacementScale = source.displacementScale;
  12562. this.displacementBias = source.displacementBias;
  12563. this.wireframe = source.wireframe;
  12564. this.wireframeLinewidth = source.wireframeLinewidth;
  12565. return this;
  12566. }
  12567. }
  12568. class MeshDistanceMaterial extends Material {
  12569. constructor(parameters) {
  12570. super();
  12571. this.isMeshDistanceMaterial = true;
  12572. this.type = 'MeshDistanceMaterial';
  12573. this.referencePosition = new Vector3();
  12574. this.nearDistance = 1;
  12575. this.farDistance = 1000;
  12576. this.map = null;
  12577. this.alphaMap = null;
  12578. this.displacementMap = null;
  12579. this.displacementScale = 1;
  12580. this.displacementBias = 0;
  12581. this.setValues(parameters);
  12582. }
  12583. copy(source) {
  12584. super.copy(source);
  12585. this.referencePosition.copy(source.referencePosition);
  12586. this.nearDistance = source.nearDistance;
  12587. this.farDistance = source.farDistance;
  12588. this.map = source.map;
  12589. this.alphaMap = source.alphaMap;
  12590. this.displacementMap = source.displacementMap;
  12591. this.displacementScale = source.displacementScale;
  12592. this.displacementBias = source.displacementBias;
  12593. return this;
  12594. }
  12595. }
  12596. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12597. 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}";
  12598. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12599. let _frustum = new Frustum();
  12600. const _shadowMapSize = new Vector2(),
  12601. _viewportSize = new Vector2(),
  12602. _viewport = new Vector4(),
  12603. _depthMaterial = new MeshDepthMaterial({
  12604. depthPacking: RGBADepthPacking
  12605. }),
  12606. _distanceMaterial = new MeshDistanceMaterial(),
  12607. _materialCache = {},
  12608. _maxTextureSize = _capabilities.maxTextureSize;
  12609. const shadowSide = {
  12610. 0: BackSide,
  12611. 1: FrontSide,
  12612. 2: DoubleSide
  12613. };
  12614. const shadowMaterialVertical = new ShaderMaterial({
  12615. defines: {
  12616. VSM_SAMPLES: 8
  12617. },
  12618. uniforms: {
  12619. shadow_pass: {
  12620. value: null
  12621. },
  12622. resolution: {
  12623. value: new Vector2()
  12624. },
  12625. radius: {
  12626. value: 4.0
  12627. }
  12628. },
  12629. vertexShader: vertex,
  12630. fragmentShader: fragment
  12631. });
  12632. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12633. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12634. const fullScreenTri = new BufferGeometry();
  12635. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12636. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12637. const scope = this;
  12638. this.enabled = false;
  12639. this.autoUpdate = true;
  12640. this.needsUpdate = false;
  12641. this.type = PCFShadowMap;
  12642. this.render = function (lights, scene, camera) {
  12643. if (scope.enabled === false) return;
  12644. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12645. if (lights.length === 0) return;
  12646. const currentRenderTarget = _renderer.getRenderTarget();
  12647. const activeCubeFace = _renderer.getActiveCubeFace();
  12648. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12649. const _state = _renderer.state; // Set GL state for depth map.
  12650. _state.setBlending(NoBlending);
  12651. _state.buffers.color.setClear(1, 1, 1, 1);
  12652. _state.buffers.depth.setTest(true);
  12653. _state.setScissorTest(false); // render depth map
  12654. for (let i = 0, il = lights.length; i < il; i++) {
  12655. const light = lights[i];
  12656. const shadow = light.shadow;
  12657. if (shadow === undefined) {
  12658. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12659. continue;
  12660. }
  12661. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12662. _shadowMapSize.copy(shadow.mapSize);
  12663. const shadowFrameExtents = shadow.getFrameExtents();
  12664. _shadowMapSize.multiply(shadowFrameExtents);
  12665. _viewportSize.copy(shadow.mapSize);
  12666. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12667. if (_shadowMapSize.x > _maxTextureSize) {
  12668. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12669. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12670. shadow.mapSize.x = _viewportSize.x;
  12671. }
  12672. if (_shadowMapSize.y > _maxTextureSize) {
  12673. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12674. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12675. shadow.mapSize.y = _viewportSize.y;
  12676. }
  12677. }
  12678. if (shadow.map === null) {
  12679. const pars = this.type !== VSMShadowMap ? {
  12680. minFilter: NearestFilter,
  12681. magFilter: NearestFilter
  12682. } : {};
  12683. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12684. shadow.map.texture.name = light.name + '.shadowMap';
  12685. shadow.camera.updateProjectionMatrix();
  12686. }
  12687. _renderer.setRenderTarget(shadow.map);
  12688. _renderer.clear();
  12689. const viewportCount = shadow.getViewportCount();
  12690. for (let vp = 0; vp < viewportCount; vp++) {
  12691. const viewport = shadow.getViewport(vp);
  12692. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12693. _state.viewport(_viewport);
  12694. shadow.updateMatrices(light, vp);
  12695. _frustum = shadow.getFrustum();
  12696. renderObject(scene, camera, shadow.camera, light, this.type);
  12697. } // do blur pass for VSM
  12698. if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) {
  12699. VSMPass(shadow, camera);
  12700. }
  12701. shadow.needsUpdate = false;
  12702. }
  12703. scope.needsUpdate = false;
  12704. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12705. };
  12706. function VSMPass(shadow, camera) {
  12707. const geometry = _objects.update(fullScreenMesh);
  12708. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  12709. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12710. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12711. shadowMaterialVertical.needsUpdate = true;
  12712. shadowMaterialHorizontal.needsUpdate = true;
  12713. }
  12714. if (shadow.mapPass === null) {
  12715. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y);
  12716. } // vertical pass
  12717. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12718. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12719. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12720. _renderer.setRenderTarget(shadow.mapPass);
  12721. _renderer.clear();
  12722. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12723. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12724. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12725. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12726. _renderer.setRenderTarget(shadow.map);
  12727. _renderer.clear();
  12728. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12729. }
  12730. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12731. let result = null;
  12732. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12733. if (customMaterial !== undefined) {
  12734. result = customMaterial;
  12735. } else {
  12736. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12737. }
  12738. if (_renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12739. // in this case we need a unique material instance reflecting the
  12740. // appropriate state
  12741. const keyA = result.uuid,
  12742. keyB = material.uuid;
  12743. let materialsForVariant = _materialCache[keyA];
  12744. if (materialsForVariant === undefined) {
  12745. materialsForVariant = {};
  12746. _materialCache[keyA] = materialsForVariant;
  12747. }
  12748. let cachedMaterial = materialsForVariant[keyB];
  12749. if (cachedMaterial === undefined) {
  12750. cachedMaterial = result.clone();
  12751. materialsForVariant[keyB] = cachedMaterial;
  12752. }
  12753. result = cachedMaterial;
  12754. }
  12755. result.visible = material.visible;
  12756. result.wireframe = material.wireframe;
  12757. if (type === VSMShadowMap) {
  12758. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12759. } else {
  12760. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12761. }
  12762. result.alphaMap = material.alphaMap;
  12763. result.alphaTest = material.alphaTest;
  12764. result.clipShadows = material.clipShadows;
  12765. result.clippingPlanes = material.clippingPlanes;
  12766. result.clipIntersection = material.clipIntersection;
  12767. result.displacementMap = material.displacementMap;
  12768. result.displacementScale = material.displacementScale;
  12769. result.displacementBias = material.displacementBias;
  12770. result.wireframeLinewidth = material.wireframeLinewidth;
  12771. result.linewidth = material.linewidth;
  12772. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12773. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12774. result.nearDistance = shadowCameraNear;
  12775. result.farDistance = shadowCameraFar;
  12776. }
  12777. return result;
  12778. }
  12779. function renderObject(object, camera, shadowCamera, light, type) {
  12780. if (object.visible === false) return;
  12781. const visible = object.layers.test(camera.layers);
  12782. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12783. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12784. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12785. const geometry = _objects.update(object);
  12786. const material = object.material;
  12787. if (Array.isArray(material)) {
  12788. const groups = geometry.groups;
  12789. for (let k = 0, kl = groups.length; k < kl; k++) {
  12790. const group = groups[k];
  12791. const groupMaterial = material[group.materialIndex];
  12792. if (groupMaterial && groupMaterial.visible) {
  12793. const depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12794. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12795. }
  12796. }
  12797. } else if (material.visible) {
  12798. const depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12799. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12800. }
  12801. }
  12802. }
  12803. const children = object.children;
  12804. for (let i = 0, l = children.length; i < l; i++) {
  12805. renderObject(children[i], camera, shadowCamera, light, type);
  12806. }
  12807. }
  12808. }
  12809. function WebGLState(gl, extensions, capabilities) {
  12810. const isWebGL2 = capabilities.isWebGL2;
  12811. function ColorBuffer() {
  12812. let locked = false;
  12813. const color = new Vector4();
  12814. let currentColorMask = null;
  12815. const currentColorClear = new Vector4(0, 0, 0, 0);
  12816. return {
  12817. setMask: function (colorMask) {
  12818. if (currentColorMask !== colorMask && !locked) {
  12819. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12820. currentColorMask = colorMask;
  12821. }
  12822. },
  12823. setLocked: function (lock) {
  12824. locked = lock;
  12825. },
  12826. setClear: function (r, g, b, a, premultipliedAlpha) {
  12827. if (premultipliedAlpha === true) {
  12828. r *= a;
  12829. g *= a;
  12830. b *= a;
  12831. }
  12832. color.set(r, g, b, a);
  12833. if (currentColorClear.equals(color) === false) {
  12834. gl.clearColor(r, g, b, a);
  12835. currentColorClear.copy(color);
  12836. }
  12837. },
  12838. reset: function () {
  12839. locked = false;
  12840. currentColorMask = null;
  12841. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12842. }
  12843. };
  12844. }
  12845. function DepthBuffer() {
  12846. let locked = false;
  12847. let currentDepthMask = null;
  12848. let currentDepthFunc = null;
  12849. let currentDepthClear = null;
  12850. return {
  12851. setTest: function (depthTest) {
  12852. if (depthTest) {
  12853. enable(gl.DEPTH_TEST);
  12854. } else {
  12855. disable(gl.DEPTH_TEST);
  12856. }
  12857. },
  12858. setMask: function (depthMask) {
  12859. if (currentDepthMask !== depthMask && !locked) {
  12860. gl.depthMask(depthMask);
  12861. currentDepthMask = depthMask;
  12862. }
  12863. },
  12864. setFunc: function (depthFunc) {
  12865. if (currentDepthFunc !== depthFunc) {
  12866. if (depthFunc) {
  12867. switch (depthFunc) {
  12868. case NeverDepth:
  12869. gl.depthFunc(gl.NEVER);
  12870. break;
  12871. case AlwaysDepth:
  12872. gl.depthFunc(gl.ALWAYS);
  12873. break;
  12874. case LessDepth:
  12875. gl.depthFunc(gl.LESS);
  12876. break;
  12877. case LessEqualDepth:
  12878. gl.depthFunc(gl.LEQUAL);
  12879. break;
  12880. case EqualDepth:
  12881. gl.depthFunc(gl.EQUAL);
  12882. break;
  12883. case GreaterEqualDepth:
  12884. gl.depthFunc(gl.GEQUAL);
  12885. break;
  12886. case GreaterDepth:
  12887. gl.depthFunc(gl.GREATER);
  12888. break;
  12889. case NotEqualDepth:
  12890. gl.depthFunc(gl.NOTEQUAL);
  12891. break;
  12892. default:
  12893. gl.depthFunc(gl.LEQUAL);
  12894. }
  12895. } else {
  12896. gl.depthFunc(gl.LEQUAL);
  12897. }
  12898. currentDepthFunc = depthFunc;
  12899. }
  12900. },
  12901. setLocked: function (lock) {
  12902. locked = lock;
  12903. },
  12904. setClear: function (depth) {
  12905. if (currentDepthClear !== depth) {
  12906. gl.clearDepth(depth);
  12907. currentDepthClear = depth;
  12908. }
  12909. },
  12910. reset: function () {
  12911. locked = false;
  12912. currentDepthMask = null;
  12913. currentDepthFunc = null;
  12914. currentDepthClear = null;
  12915. }
  12916. };
  12917. }
  12918. function StencilBuffer() {
  12919. let locked = false;
  12920. let currentStencilMask = null;
  12921. let currentStencilFunc = null;
  12922. let currentStencilRef = null;
  12923. let currentStencilFuncMask = null;
  12924. let currentStencilFail = null;
  12925. let currentStencilZFail = null;
  12926. let currentStencilZPass = null;
  12927. let currentStencilClear = null;
  12928. return {
  12929. setTest: function (stencilTest) {
  12930. if (!locked) {
  12931. if (stencilTest) {
  12932. enable(gl.STENCIL_TEST);
  12933. } else {
  12934. disable(gl.STENCIL_TEST);
  12935. }
  12936. }
  12937. },
  12938. setMask: function (stencilMask) {
  12939. if (currentStencilMask !== stencilMask && !locked) {
  12940. gl.stencilMask(stencilMask);
  12941. currentStencilMask = stencilMask;
  12942. }
  12943. },
  12944. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12945. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12946. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12947. currentStencilFunc = stencilFunc;
  12948. currentStencilRef = stencilRef;
  12949. currentStencilFuncMask = stencilMask;
  12950. }
  12951. },
  12952. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12953. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12954. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12955. currentStencilFail = stencilFail;
  12956. currentStencilZFail = stencilZFail;
  12957. currentStencilZPass = stencilZPass;
  12958. }
  12959. },
  12960. setLocked: function (lock) {
  12961. locked = lock;
  12962. },
  12963. setClear: function (stencil) {
  12964. if (currentStencilClear !== stencil) {
  12965. gl.clearStencil(stencil);
  12966. currentStencilClear = stencil;
  12967. }
  12968. },
  12969. reset: function () {
  12970. locked = false;
  12971. currentStencilMask = null;
  12972. currentStencilFunc = null;
  12973. currentStencilRef = null;
  12974. currentStencilFuncMask = null;
  12975. currentStencilFail = null;
  12976. currentStencilZFail = null;
  12977. currentStencilZPass = null;
  12978. currentStencilClear = null;
  12979. }
  12980. };
  12981. } //
  12982. const colorBuffer = new ColorBuffer();
  12983. const depthBuffer = new DepthBuffer();
  12984. const stencilBuffer = new StencilBuffer();
  12985. const uboBindings = new WeakMap();
  12986. const uboProgamMap = new WeakMap();
  12987. let enabledCapabilities = {};
  12988. let currentBoundFramebuffers = {};
  12989. let currentDrawbuffers = new WeakMap();
  12990. let defaultDrawbuffers = [];
  12991. let currentProgram = null;
  12992. let currentBlendingEnabled = false;
  12993. let currentBlending = null;
  12994. let currentBlendEquation = null;
  12995. let currentBlendSrc = null;
  12996. let currentBlendDst = null;
  12997. let currentBlendEquationAlpha = null;
  12998. let currentBlendSrcAlpha = null;
  12999. let currentBlendDstAlpha = null;
  13000. let currentPremultipledAlpha = false;
  13001. let currentFlipSided = null;
  13002. let currentCullFace = null;
  13003. let currentLineWidth = null;
  13004. let currentPolygonOffsetFactor = null;
  13005. let currentPolygonOffsetUnits = null;
  13006. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  13007. let lineWidthAvailable = false;
  13008. let version = 0;
  13009. const glVersion = gl.getParameter(gl.VERSION);
  13010. if (glVersion.indexOf('WebGL') !== -1) {
  13011. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  13012. lineWidthAvailable = version >= 1.0;
  13013. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13014. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  13015. lineWidthAvailable = version >= 2.0;
  13016. }
  13017. let currentTextureSlot = null;
  13018. let currentBoundTextures = {};
  13019. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  13020. const viewportParam = gl.getParameter(gl.VIEWPORT);
  13021. const currentScissor = new Vector4().fromArray(scissorParam);
  13022. const currentViewport = new Vector4().fromArray(viewportParam);
  13023. function createTexture(type, target, count) {
  13024. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13025. const texture = gl.createTexture();
  13026. gl.bindTexture(type, texture);
  13027. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13028. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13029. for (let i = 0; i < count; i++) {
  13030. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  13031. }
  13032. return texture;
  13033. }
  13034. const emptyTextures = {};
  13035. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  13036. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  13037. colorBuffer.setClear(0, 0, 0, 1);
  13038. depthBuffer.setClear(1);
  13039. stencilBuffer.setClear(0);
  13040. enable(gl.DEPTH_TEST);
  13041. depthBuffer.setFunc(LessEqualDepth);
  13042. setFlipSided(false);
  13043. setCullFace(CullFaceBack);
  13044. enable(gl.CULL_FACE);
  13045. setBlending(NoBlending); //
  13046. function enable(id) {
  13047. if (enabledCapabilities[id] !== true) {
  13048. gl.enable(id);
  13049. enabledCapabilities[id] = true;
  13050. }
  13051. }
  13052. function disable(id) {
  13053. if (enabledCapabilities[id] !== false) {
  13054. gl.disable(id);
  13055. enabledCapabilities[id] = false;
  13056. }
  13057. }
  13058. function bindFramebuffer(target, framebuffer) {
  13059. if (currentBoundFramebuffers[target] !== framebuffer) {
  13060. gl.bindFramebuffer(target, framebuffer);
  13061. currentBoundFramebuffers[target] = framebuffer;
  13062. if (isWebGL2) {
  13063. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13064. if (target === gl.DRAW_FRAMEBUFFER) {
  13065. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13066. }
  13067. if (target === gl.FRAMEBUFFER) {
  13068. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13069. }
  13070. }
  13071. return true;
  13072. }
  13073. return false;
  13074. }
  13075. function drawBuffers(renderTarget, framebuffer) {
  13076. let drawBuffers = defaultDrawbuffers;
  13077. let needsUpdate = false;
  13078. if (renderTarget) {
  13079. drawBuffers = currentDrawbuffers.get(framebuffer);
  13080. if (drawBuffers === undefined) {
  13081. drawBuffers = [];
  13082. currentDrawbuffers.set(framebuffer, drawBuffers);
  13083. }
  13084. if (renderTarget.isWebGLMultipleRenderTargets) {
  13085. const textures = renderTarget.texture;
  13086. if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13087. for (let i = 0, il = textures.length; i < il; i++) {
  13088. drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i;
  13089. }
  13090. drawBuffers.length = textures.length;
  13091. needsUpdate = true;
  13092. }
  13093. } else {
  13094. if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13095. drawBuffers[0] = gl.COLOR_ATTACHMENT0;
  13096. needsUpdate = true;
  13097. }
  13098. }
  13099. } else {
  13100. if (drawBuffers[0] !== gl.BACK) {
  13101. drawBuffers[0] = gl.BACK;
  13102. needsUpdate = true;
  13103. }
  13104. }
  13105. if (needsUpdate) {
  13106. if (capabilities.isWebGL2) {
  13107. gl.drawBuffers(drawBuffers);
  13108. } else {
  13109. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers);
  13110. }
  13111. }
  13112. }
  13113. function useProgram(program) {
  13114. if (currentProgram !== program) {
  13115. gl.useProgram(program);
  13116. currentProgram = program;
  13117. return true;
  13118. }
  13119. return false;
  13120. }
  13121. const equationToGL = {
  13122. [AddEquation]: gl.FUNC_ADD,
  13123. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13124. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13125. };
  13126. if (isWebGL2) {
  13127. equationToGL[MinEquation] = gl.MIN;
  13128. equationToGL[MaxEquation] = gl.MAX;
  13129. } else {
  13130. const extension = extensions.get('EXT_blend_minmax');
  13131. if (extension !== null) {
  13132. equationToGL[MinEquation] = extension.MIN_EXT;
  13133. equationToGL[MaxEquation] = extension.MAX_EXT;
  13134. }
  13135. }
  13136. const factorToGL = {
  13137. [ZeroFactor]: gl.ZERO,
  13138. [OneFactor]: gl.ONE,
  13139. [SrcColorFactor]: gl.SRC_COLOR,
  13140. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13141. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13142. [DstColorFactor]: gl.DST_COLOR,
  13143. [DstAlphaFactor]: gl.DST_ALPHA,
  13144. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13145. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13146. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13147. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13148. };
  13149. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13150. if (blending === NoBlending) {
  13151. if (currentBlendingEnabled === true) {
  13152. disable(gl.BLEND);
  13153. currentBlendingEnabled = false;
  13154. }
  13155. return;
  13156. }
  13157. if (currentBlendingEnabled === false) {
  13158. enable(gl.BLEND);
  13159. currentBlendingEnabled = true;
  13160. }
  13161. if (blending !== CustomBlending) {
  13162. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13163. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13164. gl.blendEquation(gl.FUNC_ADD);
  13165. currentBlendEquation = AddEquation;
  13166. currentBlendEquationAlpha = AddEquation;
  13167. }
  13168. if (premultipliedAlpha) {
  13169. switch (blending) {
  13170. case NormalBlending:
  13171. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13172. break;
  13173. case AdditiveBlending:
  13174. gl.blendFunc(gl.ONE, gl.ONE);
  13175. break;
  13176. case SubtractiveBlending:
  13177. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13178. break;
  13179. case MultiplyBlending:
  13180. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13181. break;
  13182. default:
  13183. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13184. break;
  13185. }
  13186. } else {
  13187. switch (blending) {
  13188. case NormalBlending:
  13189. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13190. break;
  13191. case AdditiveBlending:
  13192. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13193. break;
  13194. case SubtractiveBlending:
  13195. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13196. break;
  13197. case MultiplyBlending:
  13198. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13199. break;
  13200. default:
  13201. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13202. break;
  13203. }
  13204. }
  13205. currentBlendSrc = null;
  13206. currentBlendDst = null;
  13207. currentBlendSrcAlpha = null;
  13208. currentBlendDstAlpha = null;
  13209. currentBlending = blending;
  13210. currentPremultipledAlpha = premultipliedAlpha;
  13211. }
  13212. return;
  13213. } // custom blending
  13214. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13215. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13216. blendDstAlpha = blendDstAlpha || blendDst;
  13217. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13218. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13219. currentBlendEquation = blendEquation;
  13220. currentBlendEquationAlpha = blendEquationAlpha;
  13221. }
  13222. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13223. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13224. currentBlendSrc = blendSrc;
  13225. currentBlendDst = blendDst;
  13226. currentBlendSrcAlpha = blendSrcAlpha;
  13227. currentBlendDstAlpha = blendDstAlpha;
  13228. }
  13229. currentBlending = blending;
  13230. currentPremultipledAlpha = null;
  13231. }
  13232. function setMaterial(material, frontFaceCW) {
  13233. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13234. let flipSided = material.side === BackSide;
  13235. if (frontFaceCW) flipSided = !flipSided;
  13236. setFlipSided(flipSided);
  13237. 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);
  13238. depthBuffer.setFunc(material.depthFunc);
  13239. depthBuffer.setTest(material.depthTest);
  13240. depthBuffer.setMask(material.depthWrite);
  13241. colorBuffer.setMask(material.colorWrite);
  13242. const stencilWrite = material.stencilWrite;
  13243. stencilBuffer.setTest(stencilWrite);
  13244. if (stencilWrite) {
  13245. stencilBuffer.setMask(material.stencilWriteMask);
  13246. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13247. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13248. }
  13249. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13250. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13251. } //
  13252. function setFlipSided(flipSided) {
  13253. if (currentFlipSided !== flipSided) {
  13254. if (flipSided) {
  13255. gl.frontFace(gl.CW);
  13256. } else {
  13257. gl.frontFace(gl.CCW);
  13258. }
  13259. currentFlipSided = flipSided;
  13260. }
  13261. }
  13262. function setCullFace(cullFace) {
  13263. if (cullFace !== CullFaceNone) {
  13264. enable(gl.CULL_FACE);
  13265. if (cullFace !== currentCullFace) {
  13266. if (cullFace === CullFaceBack) {
  13267. gl.cullFace(gl.BACK);
  13268. } else if (cullFace === CullFaceFront) {
  13269. gl.cullFace(gl.FRONT);
  13270. } else {
  13271. gl.cullFace(gl.FRONT_AND_BACK);
  13272. }
  13273. }
  13274. } else {
  13275. disable(gl.CULL_FACE);
  13276. }
  13277. currentCullFace = cullFace;
  13278. }
  13279. function setLineWidth(width) {
  13280. if (width !== currentLineWidth) {
  13281. if (lineWidthAvailable) gl.lineWidth(width);
  13282. currentLineWidth = width;
  13283. }
  13284. }
  13285. function setPolygonOffset(polygonOffset, factor, units) {
  13286. if (polygonOffset) {
  13287. enable(gl.POLYGON_OFFSET_FILL);
  13288. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13289. gl.polygonOffset(factor, units);
  13290. currentPolygonOffsetFactor = factor;
  13291. currentPolygonOffsetUnits = units;
  13292. }
  13293. } else {
  13294. disable(gl.POLYGON_OFFSET_FILL);
  13295. }
  13296. }
  13297. function setScissorTest(scissorTest) {
  13298. if (scissorTest) {
  13299. enable(gl.SCISSOR_TEST);
  13300. } else {
  13301. disable(gl.SCISSOR_TEST);
  13302. }
  13303. } // texture
  13304. function activeTexture(webglSlot) {
  13305. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13306. if (currentTextureSlot !== webglSlot) {
  13307. gl.activeTexture(webglSlot);
  13308. currentTextureSlot = webglSlot;
  13309. }
  13310. }
  13311. function bindTexture(webglType, webglTexture) {
  13312. if (currentTextureSlot === null) {
  13313. activeTexture();
  13314. }
  13315. let boundTexture = currentBoundTextures[currentTextureSlot];
  13316. if (boundTexture === undefined) {
  13317. boundTexture = {
  13318. type: undefined,
  13319. texture: undefined
  13320. };
  13321. currentBoundTextures[currentTextureSlot] = boundTexture;
  13322. }
  13323. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13324. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13325. boundTexture.type = webglType;
  13326. boundTexture.texture = webglTexture;
  13327. }
  13328. }
  13329. function unbindTexture() {
  13330. const boundTexture = currentBoundTextures[currentTextureSlot];
  13331. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13332. gl.bindTexture(boundTexture.type, null);
  13333. boundTexture.type = undefined;
  13334. boundTexture.texture = undefined;
  13335. }
  13336. }
  13337. function compressedTexImage2D() {
  13338. try {
  13339. gl.compressedTexImage2D.apply(gl, arguments);
  13340. } catch (error) {
  13341. console.error('THREE.WebGLState:', error);
  13342. }
  13343. }
  13344. function texSubImage2D() {
  13345. try {
  13346. gl.texSubImage2D.apply(gl, arguments);
  13347. } catch (error) {
  13348. console.error('THREE.WebGLState:', error);
  13349. }
  13350. }
  13351. function texSubImage3D() {
  13352. try {
  13353. gl.texSubImage3D.apply(gl, arguments);
  13354. } catch (error) {
  13355. console.error('THREE.WebGLState:', error);
  13356. }
  13357. }
  13358. function compressedTexSubImage2D() {
  13359. try {
  13360. gl.compressedTexSubImage2D.apply(gl, arguments);
  13361. } catch (error) {
  13362. console.error('THREE.WebGLState:', error);
  13363. }
  13364. }
  13365. function texStorage2D() {
  13366. try {
  13367. gl.texStorage2D.apply(gl, arguments);
  13368. } catch (error) {
  13369. console.error('THREE.WebGLState:', error);
  13370. }
  13371. }
  13372. function texStorage3D() {
  13373. try {
  13374. gl.texStorage3D.apply(gl, arguments);
  13375. } catch (error) {
  13376. console.error('THREE.WebGLState:', error);
  13377. }
  13378. }
  13379. function texImage2D() {
  13380. try {
  13381. gl.texImage2D.apply(gl, arguments);
  13382. } catch (error) {
  13383. console.error('THREE.WebGLState:', error);
  13384. }
  13385. }
  13386. function texImage3D() {
  13387. try {
  13388. gl.texImage3D.apply(gl, arguments);
  13389. } catch (error) {
  13390. console.error('THREE.WebGLState:', error);
  13391. }
  13392. } //
  13393. function scissor(scissor) {
  13394. if (currentScissor.equals(scissor) === false) {
  13395. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13396. currentScissor.copy(scissor);
  13397. }
  13398. }
  13399. function viewport(viewport) {
  13400. if (currentViewport.equals(viewport) === false) {
  13401. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13402. currentViewport.copy(viewport);
  13403. }
  13404. }
  13405. function updateUBOMapping(uniformsGroup, program) {
  13406. let mapping = uboProgamMap.get(program);
  13407. if (mapping === undefined) {
  13408. mapping = new WeakMap();
  13409. uboProgamMap.set(program, mapping);
  13410. }
  13411. let blockIndex = mapping.get(uniformsGroup);
  13412. if (blockIndex === undefined) {
  13413. blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name);
  13414. mapping.set(uniformsGroup, blockIndex);
  13415. }
  13416. }
  13417. function uniformBlockBinding(uniformsGroup, program) {
  13418. const mapping = uboProgamMap.get(program);
  13419. const blockIndex = mapping.get(uniformsGroup);
  13420. if (uboBindings.get(uniformsGroup) !== blockIndex) {
  13421. // bind shader specific block index to global block point
  13422. gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex);
  13423. uboBindings.set(uniformsGroup, blockIndex);
  13424. }
  13425. } //
  13426. function reset() {
  13427. // reset state
  13428. gl.disable(gl.BLEND);
  13429. gl.disable(gl.CULL_FACE);
  13430. gl.disable(gl.DEPTH_TEST);
  13431. gl.disable(gl.POLYGON_OFFSET_FILL);
  13432. gl.disable(gl.SCISSOR_TEST);
  13433. gl.disable(gl.STENCIL_TEST);
  13434. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13435. gl.blendEquation(gl.FUNC_ADD);
  13436. gl.blendFunc(gl.ONE, gl.ZERO);
  13437. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13438. gl.colorMask(true, true, true, true);
  13439. gl.clearColor(0, 0, 0, 0);
  13440. gl.depthMask(true);
  13441. gl.depthFunc(gl.LESS);
  13442. gl.clearDepth(1);
  13443. gl.stencilMask(0xffffffff);
  13444. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13445. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13446. gl.clearStencil(0);
  13447. gl.cullFace(gl.BACK);
  13448. gl.frontFace(gl.CCW);
  13449. gl.polygonOffset(0, 0);
  13450. gl.activeTexture(gl.TEXTURE0);
  13451. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13452. if (isWebGL2 === true) {
  13453. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13454. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13455. }
  13456. gl.useProgram(null);
  13457. gl.lineWidth(1);
  13458. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13459. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13460. enabledCapabilities = {};
  13461. currentTextureSlot = null;
  13462. currentBoundTextures = {};
  13463. currentBoundFramebuffers = {};
  13464. currentDrawbuffers = new WeakMap();
  13465. defaultDrawbuffers = [];
  13466. currentProgram = null;
  13467. currentBlendingEnabled = false;
  13468. currentBlending = null;
  13469. currentBlendEquation = null;
  13470. currentBlendSrc = null;
  13471. currentBlendDst = null;
  13472. currentBlendEquationAlpha = null;
  13473. currentBlendSrcAlpha = null;
  13474. currentBlendDstAlpha = null;
  13475. currentPremultipledAlpha = false;
  13476. currentFlipSided = null;
  13477. currentCullFace = null;
  13478. currentLineWidth = null;
  13479. currentPolygonOffsetFactor = null;
  13480. currentPolygonOffsetUnits = null;
  13481. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13482. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13483. colorBuffer.reset();
  13484. depthBuffer.reset();
  13485. stencilBuffer.reset();
  13486. }
  13487. return {
  13488. buffers: {
  13489. color: colorBuffer,
  13490. depth: depthBuffer,
  13491. stencil: stencilBuffer
  13492. },
  13493. enable: enable,
  13494. disable: disable,
  13495. bindFramebuffer: bindFramebuffer,
  13496. drawBuffers: drawBuffers,
  13497. useProgram: useProgram,
  13498. setBlending: setBlending,
  13499. setMaterial: setMaterial,
  13500. setFlipSided: setFlipSided,
  13501. setCullFace: setCullFace,
  13502. setLineWidth: setLineWidth,
  13503. setPolygonOffset: setPolygonOffset,
  13504. setScissorTest: setScissorTest,
  13505. activeTexture: activeTexture,
  13506. bindTexture: bindTexture,
  13507. unbindTexture: unbindTexture,
  13508. compressedTexImage2D: compressedTexImage2D,
  13509. texImage2D: texImage2D,
  13510. texImage3D: texImage3D,
  13511. updateUBOMapping: updateUBOMapping,
  13512. uniformBlockBinding: uniformBlockBinding,
  13513. texStorage2D: texStorage2D,
  13514. texStorage3D: texStorage3D,
  13515. texSubImage2D: texSubImage2D,
  13516. texSubImage3D: texSubImage3D,
  13517. compressedTexSubImage2D: compressedTexSubImage2D,
  13518. scissor: scissor,
  13519. viewport: viewport,
  13520. reset: reset
  13521. };
  13522. }
  13523. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13524. const isWebGL2 = capabilities.isWebGL2;
  13525. const maxTextures = capabilities.maxTextures;
  13526. const maxCubemapSize = capabilities.maxCubemapSize;
  13527. const maxTextureSize = capabilities.maxTextureSize;
  13528. const maxSamples = capabilities.maxSamples;
  13529. const multisampledRTTExt = extensions.has('WEBGL_multisampled_render_to_texture') ? extensions.get('WEBGL_multisampled_render_to_texture') : null;
  13530. const supportsInvalidateFramebuffer = /OculusBrowser/g.test(navigator.userAgent);
  13531. const _videoTextures = new WeakMap();
  13532. let _canvas;
  13533. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13534. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13535. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13536. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13537. let useOffscreenCanvas = false;
  13538. try {
  13539. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' // eslint-disable-next-line compat/compat
  13540. && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13541. } catch (err) {// Ignore any errors
  13542. }
  13543. function createCanvas(width, height) {
  13544. // Use OffscreenCanvas when available. Specially needed in web workers
  13545. return useOffscreenCanvas ? // eslint-disable-next-line compat/compat
  13546. new OffscreenCanvas(width, height) : createElementNS('canvas');
  13547. }
  13548. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13549. let scale = 1; // handle case if texture exceeds max size
  13550. if (image.width > maxSize || image.height > maxSize) {
  13551. scale = maxSize / Math.max(image.width, image.height);
  13552. } // only perform resize if necessary
  13553. if (scale < 1 || needsPowerOfTwo === true) {
  13554. // only perform resize for certain image types
  13555. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13556. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13557. const width = floor(scale * image.width);
  13558. const height = floor(scale * image.height);
  13559. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13560. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13561. canvas.width = width;
  13562. canvas.height = height;
  13563. const context = canvas.getContext('2d');
  13564. context.drawImage(image, 0, 0, width, height);
  13565. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13566. return canvas;
  13567. } else {
  13568. if ('data' in image) {
  13569. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13570. }
  13571. return image;
  13572. }
  13573. }
  13574. return image;
  13575. }
  13576. function isPowerOfTwo$1(image) {
  13577. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13578. }
  13579. function textureNeedsPowerOfTwo(texture) {
  13580. if (isWebGL2) return false;
  13581. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13582. }
  13583. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13584. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13585. }
  13586. function generateMipmap(target) {
  13587. _gl.generateMipmap(target);
  13588. }
  13589. function getInternalFormat(internalFormatName, glFormat, glType, encoding, isVideoTexture = false) {
  13590. if (isWebGL2 === false) return glFormat;
  13591. if (internalFormatName !== null) {
  13592. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13593. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13594. }
  13595. let internalFormat = glFormat;
  13596. if (glFormat === _gl.RED) {
  13597. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13598. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13599. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13600. }
  13601. if (glFormat === _gl.RG) {
  13602. if (glType === _gl.FLOAT) internalFormat = _gl.RG32F;
  13603. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F;
  13604. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8;
  13605. }
  13606. if (glFormat === _gl.RGBA) {
  13607. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13608. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13609. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && isVideoTexture === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13610. if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4;
  13611. if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1;
  13612. }
  13613. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13614. extensions.get('EXT_color_buffer_float');
  13615. }
  13616. return internalFormat;
  13617. }
  13618. function getMipLevels(texture, image, supportsMips) {
  13619. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13620. return Math.log2(Math.max(image.width, image.height)) + 1;
  13621. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13622. // user-defined mipmaps
  13623. return texture.mipmaps.length;
  13624. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13625. return image.mipmaps.length;
  13626. } else {
  13627. // texture without mipmaps (only base level)
  13628. return 1;
  13629. }
  13630. } // Fallback filters for non-power-of-2 textures
  13631. function filterFallback(f) {
  13632. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13633. return _gl.NEAREST;
  13634. }
  13635. return _gl.LINEAR;
  13636. } //
  13637. function onTextureDispose(event) {
  13638. const texture = event.target;
  13639. texture.removeEventListener('dispose', onTextureDispose);
  13640. deallocateTexture(texture);
  13641. if (texture.isVideoTexture) {
  13642. _videoTextures.delete(texture);
  13643. }
  13644. }
  13645. function onRenderTargetDispose(event) {
  13646. const renderTarget = event.target;
  13647. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13648. deallocateRenderTarget(renderTarget);
  13649. } //
  13650. function deallocateTexture(texture) {
  13651. const textureProperties = properties.get(texture);
  13652. if (textureProperties.__webglInit === undefined) return; // check if it's necessary to remove the WebGLTexture object
  13653. const source = texture.source;
  13654. const webglTextures = _sources.get(source);
  13655. if (webglTextures) {
  13656. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13657. webglTexture.usedTimes--; // the WebGLTexture object is not used anymore, remove it
  13658. if (webglTexture.usedTimes === 0) {
  13659. deleteTexture(texture);
  13660. } // remove the weak map entry if no WebGLTexture uses the source anymore
  13661. if (Object.keys(webglTextures).length === 0) {
  13662. _sources.delete(source);
  13663. }
  13664. }
  13665. properties.remove(texture);
  13666. }
  13667. function deleteTexture(texture) {
  13668. const textureProperties = properties.get(texture);
  13669. _gl.deleteTexture(textureProperties.__webglTexture);
  13670. const source = texture.source;
  13671. const webglTextures = _sources.get(source);
  13672. delete webglTextures[textureProperties.__cacheKey];
  13673. info.memory.textures--;
  13674. }
  13675. function deallocateRenderTarget(renderTarget) {
  13676. const texture = renderTarget.texture;
  13677. const renderTargetProperties = properties.get(renderTarget);
  13678. const textureProperties = properties.get(texture);
  13679. if (textureProperties.__webglTexture !== undefined) {
  13680. _gl.deleteTexture(textureProperties.__webglTexture);
  13681. info.memory.textures--;
  13682. }
  13683. if (renderTarget.depthTexture) {
  13684. renderTarget.depthTexture.dispose();
  13685. }
  13686. if (renderTarget.isWebGLCubeRenderTarget) {
  13687. for (let i = 0; i < 6; i++) {
  13688. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13689. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13690. }
  13691. } else {
  13692. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13693. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13694. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13695. if (renderTargetProperties.__webglColorRenderbuffer) {
  13696. for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) {
  13697. if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]);
  13698. }
  13699. }
  13700. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13701. }
  13702. if (renderTarget.isWebGLMultipleRenderTargets) {
  13703. for (let i = 0, il = texture.length; i < il; i++) {
  13704. const attachmentProperties = properties.get(texture[i]);
  13705. if (attachmentProperties.__webglTexture) {
  13706. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13707. info.memory.textures--;
  13708. }
  13709. properties.remove(texture[i]);
  13710. }
  13711. }
  13712. properties.remove(texture);
  13713. properties.remove(renderTarget);
  13714. } //
  13715. let textureUnits = 0;
  13716. function resetTextureUnits() {
  13717. textureUnits = 0;
  13718. }
  13719. function allocateTextureUnit() {
  13720. const textureUnit = textureUnits;
  13721. if (textureUnit >= maxTextures) {
  13722. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13723. }
  13724. textureUnits += 1;
  13725. return textureUnit;
  13726. }
  13727. function getTextureCacheKey(texture) {
  13728. const array = [];
  13729. array.push(texture.wrapS);
  13730. array.push(texture.wrapT);
  13731. array.push(texture.magFilter);
  13732. array.push(texture.minFilter);
  13733. array.push(texture.anisotropy);
  13734. array.push(texture.internalFormat);
  13735. array.push(texture.format);
  13736. array.push(texture.type);
  13737. array.push(texture.generateMipmaps);
  13738. array.push(texture.premultiplyAlpha);
  13739. array.push(texture.flipY);
  13740. array.push(texture.unpackAlignment);
  13741. array.push(texture.encoding);
  13742. return array.join();
  13743. } //
  13744. function setTexture2D(texture, slot) {
  13745. const textureProperties = properties.get(texture);
  13746. if (texture.isVideoTexture) updateVideoTexture(texture);
  13747. if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) {
  13748. const image = texture.image;
  13749. if (image === null) {
  13750. console.warn('THREE.WebGLRenderer: Texture marked for update but no image data found.');
  13751. } else if (image.complete === false) {
  13752. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13753. } else {
  13754. uploadTexture(textureProperties, texture, slot);
  13755. return;
  13756. }
  13757. }
  13758. state.activeTexture(_gl.TEXTURE0 + slot);
  13759. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13760. }
  13761. function setTexture2DArray(texture, slot) {
  13762. const textureProperties = properties.get(texture);
  13763. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13764. uploadTexture(textureProperties, texture, slot);
  13765. return;
  13766. }
  13767. state.activeTexture(_gl.TEXTURE0 + slot);
  13768. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13769. }
  13770. function setTexture3D(texture, slot) {
  13771. const textureProperties = properties.get(texture);
  13772. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13773. uploadTexture(textureProperties, texture, slot);
  13774. return;
  13775. }
  13776. state.activeTexture(_gl.TEXTURE0 + slot);
  13777. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13778. }
  13779. function setTextureCube(texture, slot) {
  13780. const textureProperties = properties.get(texture);
  13781. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13782. uploadCubeTexture(textureProperties, texture, slot);
  13783. return;
  13784. }
  13785. state.activeTexture(_gl.TEXTURE0 + slot);
  13786. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13787. }
  13788. const wrappingToGL = {
  13789. [RepeatWrapping]: _gl.REPEAT,
  13790. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13791. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13792. };
  13793. const filterToGL = {
  13794. [NearestFilter]: _gl.NEAREST,
  13795. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13796. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13797. [LinearFilter]: _gl.LINEAR,
  13798. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13799. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13800. };
  13801. function setTextureParameters(textureType, texture, supportsMips) {
  13802. if (supportsMips) {
  13803. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13804. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13805. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13806. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13807. }
  13808. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13809. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13810. } else {
  13811. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13812. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13813. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13814. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13815. }
  13816. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13817. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13818. }
  13819. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13820. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13821. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13822. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13823. }
  13824. }
  13825. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13826. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13827. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13828. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13829. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13830. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13831. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13832. }
  13833. }
  13834. }
  13835. function initTexture(textureProperties, texture) {
  13836. let forceUpload = false;
  13837. if (textureProperties.__webglInit === undefined) {
  13838. textureProperties.__webglInit = true;
  13839. texture.addEventListener('dispose', onTextureDispose);
  13840. } // create Source <-> WebGLTextures mapping if necessary
  13841. const source = texture.source;
  13842. let webglTextures = _sources.get(source);
  13843. if (webglTextures === undefined) {
  13844. webglTextures = {};
  13845. _sources.set(source, webglTextures);
  13846. } // check if there is already a WebGLTexture object for the given texture parameters
  13847. const textureCacheKey = getTextureCacheKey(texture);
  13848. if (textureCacheKey !== textureProperties.__cacheKey) {
  13849. // if not, create a new instance of WebGLTexture
  13850. if (webglTextures[textureCacheKey] === undefined) {
  13851. // create new entry
  13852. webglTextures[textureCacheKey] = {
  13853. texture: _gl.createTexture(),
  13854. usedTimes: 0
  13855. };
  13856. info.memory.textures++; // when a new instance of WebGLTexture was created, a texture upload is required
  13857. // even if the image contents are identical
  13858. forceUpload = true;
  13859. }
  13860. webglTextures[textureCacheKey].usedTimes++; // every time the texture cache key changes, it's necessary to check if an instance of
  13861. // WebGLTexture can be deleted in order to avoid a memory leak.
  13862. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13863. if (webglTexture !== undefined) {
  13864. webglTextures[textureProperties.__cacheKey].usedTimes--;
  13865. if (webglTexture.usedTimes === 0) {
  13866. deleteTexture(texture);
  13867. }
  13868. } // store references to cache key and WebGLTexture object
  13869. textureProperties.__cacheKey = textureCacheKey;
  13870. textureProperties.__webglTexture = webglTextures[textureCacheKey].texture;
  13871. }
  13872. return forceUpload;
  13873. }
  13874. function uploadTexture(textureProperties, texture, slot) {
  13875. let textureType = _gl.TEXTURE_2D;
  13876. if (texture.isDataArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY;
  13877. if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D;
  13878. const forceUpload = initTexture(textureProperties, texture);
  13879. const source = texture.source;
  13880. state.activeTexture(_gl.TEXTURE0 + slot);
  13881. state.bindTexture(textureType, textureProperties.__webglTexture);
  13882. if (source.version !== source.__currentVersion || forceUpload === true) {
  13883. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13884. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13885. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13886. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13887. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13888. let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13889. image = verifyColorSpace(texture, image);
  13890. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13891. glFormat = utils.convert(texture.format, texture.encoding);
  13892. let glType = utils.convert(texture.type),
  13893. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture);
  13894. setTextureParameters(textureType, texture, supportsMips);
  13895. let mipmap;
  13896. const mipmaps = texture.mipmaps;
  13897. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13898. const allocateMemory = source.__currentVersion === undefined || forceUpload === true;
  13899. const levels = getMipLevels(texture, image, supportsMips);
  13900. if (texture.isDepthTexture) {
  13901. // populate depth texture with dummy data
  13902. glInternalFormat = _gl.DEPTH_COMPONENT;
  13903. if (isWebGL2) {
  13904. if (texture.type === FloatType) {
  13905. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13906. } else if (texture.type === UnsignedIntType) {
  13907. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13908. } else if (texture.type === UnsignedInt248Type) {
  13909. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13910. } else {
  13911. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13912. }
  13913. } else {
  13914. if (texture.type === FloatType) {
  13915. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13916. }
  13917. } // validation checks for WebGL 1
  13918. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13919. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13920. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13921. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13922. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13923. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13924. texture.type = UnsignedIntType;
  13925. glType = utils.convert(texture.type);
  13926. }
  13927. }
  13928. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13929. // Depth stencil textures need the DEPTH_STENCIL internal format
  13930. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13931. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13932. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13933. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13934. if (texture.type !== UnsignedInt248Type) {
  13935. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13936. texture.type = UnsignedInt248Type;
  13937. glType = utils.convert(texture.type);
  13938. }
  13939. } //
  13940. if (allocateMemory) {
  13941. if (useTexStorage) {
  13942. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  13943. } else {
  13944. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13945. }
  13946. }
  13947. } else if (texture.isDataTexture) {
  13948. // use manually created mipmaps if available
  13949. // if there are no manual mipmaps
  13950. // set 0 level mipmap and then use GL to generate other mipmap levels
  13951. if (mipmaps.length > 0 && supportsMips) {
  13952. if (useTexStorage && allocateMemory) {
  13953. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13954. }
  13955. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13956. mipmap = mipmaps[i];
  13957. if (useTexStorage) {
  13958. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13959. } else {
  13960. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13961. }
  13962. }
  13963. texture.generateMipmaps = false;
  13964. } else {
  13965. if (useTexStorage) {
  13966. if (allocateMemory) {
  13967. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13968. }
  13969. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  13970. } else {
  13971. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13972. }
  13973. }
  13974. } else if (texture.isCompressedTexture) {
  13975. if (useTexStorage && allocateMemory) {
  13976. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13977. }
  13978. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13979. mipmap = mipmaps[i];
  13980. if (texture.format !== RGBAFormat) {
  13981. if (glFormat !== null) {
  13982. if (useTexStorage) {
  13983. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  13984. } else {
  13985. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13986. }
  13987. } else {
  13988. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13989. }
  13990. } else {
  13991. if (useTexStorage) {
  13992. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13993. } else {
  13994. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13995. }
  13996. }
  13997. }
  13998. } else if (texture.isDataArrayTexture) {
  13999. if (useTexStorage) {
  14000. if (allocateMemory) {
  14001. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  14002. }
  14003. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14004. } else {
  14005. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14006. }
  14007. } else if (texture.isData3DTexture) {
  14008. if (useTexStorage) {
  14009. if (allocateMemory) {
  14010. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  14011. }
  14012. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14013. } else {
  14014. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14015. }
  14016. } else if (texture.isFramebufferTexture) {
  14017. if (allocateMemory) {
  14018. if (useTexStorage) {
  14019. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14020. } else {
  14021. let width = image.width,
  14022. height = image.height;
  14023. for (let i = 0; i < levels; i++) {
  14024. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null);
  14025. width >>= 1;
  14026. height >>= 1;
  14027. }
  14028. }
  14029. }
  14030. } else {
  14031. // regular Texture (image, video, canvas)
  14032. // use manually created mipmaps if available
  14033. // if there are no manual mipmaps
  14034. // set 0 level mipmap and then use GL to generate other mipmap levels
  14035. if (mipmaps.length > 0 && supportsMips) {
  14036. if (useTexStorage && allocateMemory) {
  14037. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14038. }
  14039. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14040. mipmap = mipmaps[i];
  14041. if (useTexStorage) {
  14042. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  14043. } else {
  14044. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  14045. }
  14046. }
  14047. texture.generateMipmaps = false;
  14048. } else {
  14049. if (useTexStorage) {
  14050. if (allocateMemory) {
  14051. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14052. }
  14053. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  14054. } else {
  14055. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  14056. }
  14057. }
  14058. }
  14059. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14060. generateMipmap(textureType);
  14061. }
  14062. source.__currentVersion = source.version;
  14063. if (texture.onUpdate) texture.onUpdate(texture);
  14064. }
  14065. textureProperties.__version = texture.version;
  14066. }
  14067. function uploadCubeTexture(textureProperties, texture, slot) {
  14068. if (texture.image.length !== 6) return;
  14069. const forceUpload = initTexture(textureProperties, texture);
  14070. const source = texture.source;
  14071. state.activeTexture(_gl.TEXTURE0 + slot);
  14072. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14073. if (source.version !== source.__currentVersion || forceUpload === true) {
  14074. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  14075. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  14076. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  14077. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  14078. const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture;
  14079. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14080. const cubeImage = [];
  14081. for (let i = 0; i < 6; i++) {
  14082. if (!isCompressed && !isDataTexture) {
  14083. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  14084. } else {
  14085. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14086. }
  14087. cubeImage[i] = verifyColorSpace(texture, cubeImage[i]);
  14088. }
  14089. const image = cubeImage[0],
  14090. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  14091. glFormat = utils.convert(texture.format, texture.encoding),
  14092. glType = utils.convert(texture.type),
  14093. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14094. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  14095. const allocateMemory = source.__currentVersion === undefined || forceUpload === true;
  14096. let levels = getMipLevels(texture, image, supportsMips);
  14097. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14098. let mipmaps;
  14099. if (isCompressed) {
  14100. if (useTexStorage && allocateMemory) {
  14101. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  14102. }
  14103. for (let i = 0; i < 6; i++) {
  14104. mipmaps = cubeImage[i].mipmaps;
  14105. for (let j = 0; j < mipmaps.length; j++) {
  14106. const mipmap = mipmaps[j];
  14107. if (texture.format !== RGBAFormat) {
  14108. if (glFormat !== null) {
  14109. if (useTexStorage) {
  14110. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14111. } else {
  14112. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14113. }
  14114. } else {
  14115. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14116. }
  14117. } else {
  14118. if (useTexStorage) {
  14119. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14120. } else {
  14121. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14122. }
  14123. }
  14124. }
  14125. }
  14126. } else {
  14127. mipmaps = texture.mipmaps;
  14128. if (useTexStorage && allocateMemory) {
  14129. // TODO: Uniformly handle mipmap definitions
  14130. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14131. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14132. if (mipmaps.length > 0) levels++;
  14133. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  14134. }
  14135. for (let i = 0; i < 6; i++) {
  14136. if (isDataTexture) {
  14137. if (useTexStorage) {
  14138. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  14139. } else {
  14140. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14141. }
  14142. for (let j = 0; j < mipmaps.length; j++) {
  14143. const mipmap = mipmaps[j];
  14144. const mipmapImage = mipmap.image[i].image;
  14145. if (useTexStorage) {
  14146. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  14147. } else {
  14148. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14149. }
  14150. }
  14151. } else {
  14152. if (useTexStorage) {
  14153. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  14154. } else {
  14155. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14156. }
  14157. for (let j = 0; j < mipmaps.length; j++) {
  14158. const mipmap = mipmaps[j];
  14159. if (useTexStorage) {
  14160. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  14161. } else {
  14162. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14163. }
  14164. }
  14165. }
  14166. }
  14167. }
  14168. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14169. // We assume images for cube map have the same size.
  14170. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14171. }
  14172. source.__currentVersion = source.version;
  14173. if (texture.onUpdate) texture.onUpdate(texture);
  14174. }
  14175. textureProperties.__version = texture.version;
  14176. } // Render targets
  14177. // Setup storage for target texture and bind it to correct framebuffer
  14178. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  14179. const glFormat = utils.convert(texture.format, texture.encoding);
  14180. const glType = utils.convert(texture.type);
  14181. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14182. const renderTargetProperties = properties.get(renderTarget);
  14183. if (!renderTargetProperties.__hasExternalTextures) {
  14184. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  14185. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  14186. } else {
  14187. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14188. }
  14189. }
  14190. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14191. if (useMultisampledRTT(renderTarget)) {
  14192. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  14193. } else {
  14194. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  14195. }
  14196. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14197. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14198. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14199. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  14200. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14201. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14202. if (isMultisample || useMultisampledRTT(renderTarget)) {
  14203. const depthTexture = renderTarget.depthTexture;
  14204. if (depthTexture && depthTexture.isDepthTexture) {
  14205. if (depthTexture.type === FloatType) {
  14206. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14207. } else if (depthTexture.type === UnsignedIntType) {
  14208. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14209. }
  14210. }
  14211. const samples = getRenderTargetSamples(renderTarget);
  14212. if (useMultisampledRTT(renderTarget)) {
  14213. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14214. } else {
  14215. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14216. }
  14217. } else {
  14218. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14219. }
  14220. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14221. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14222. const samples = getRenderTargetSamples(renderTarget);
  14223. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14224. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14225. } else if (useMultisampledRTT(renderTarget)) {
  14226. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14227. } else {
  14228. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14229. }
  14230. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14231. } else {
  14232. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14233. for (let i = 0; i < textures.length; i++) {
  14234. const texture = textures[i];
  14235. const glFormat = utils.convert(texture.format, texture.encoding);
  14236. const glType = utils.convert(texture.type);
  14237. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14238. const samples = getRenderTargetSamples(renderTarget);
  14239. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14240. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14241. } else if (useMultisampledRTT(renderTarget)) {
  14242. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14243. } else {
  14244. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14245. }
  14246. }
  14247. }
  14248. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14249. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14250. function setupDepthTexture(framebuffer, renderTarget) {
  14251. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14252. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14253. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14254. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14255. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14256. } // upload an empty depth texture with framebuffer size
  14257. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14258. renderTarget.depthTexture.image.width = renderTarget.width;
  14259. renderTarget.depthTexture.image.height = renderTarget.height;
  14260. renderTarget.depthTexture.needsUpdate = true;
  14261. }
  14262. setTexture2D(renderTarget.depthTexture, 0);
  14263. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14264. const samples = getRenderTargetSamples(renderTarget);
  14265. if (renderTarget.depthTexture.format === DepthFormat) {
  14266. if (useMultisampledRTT(renderTarget)) {
  14267. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14268. } else {
  14269. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14270. }
  14271. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14272. if (useMultisampledRTT(renderTarget)) {
  14273. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14274. } else {
  14275. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14276. }
  14277. } else {
  14278. throw new Error('Unknown depthTexture format');
  14279. }
  14280. } // Setup GL resources for a non-texture depth buffer
  14281. function setupDepthRenderbuffer(renderTarget) {
  14282. const renderTargetProperties = properties.get(renderTarget);
  14283. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14284. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14285. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14286. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14287. } else {
  14288. if (isCube) {
  14289. renderTargetProperties.__webglDepthbuffer = [];
  14290. for (let i = 0; i < 6; i++) {
  14291. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14292. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14293. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14294. }
  14295. } else {
  14296. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14297. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14298. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14299. }
  14300. }
  14301. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14302. } // rebind framebuffer with external textures
  14303. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14304. const renderTargetProperties = properties.get(renderTarget);
  14305. if (colorTexture !== undefined) {
  14306. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14307. }
  14308. if (depthTexture !== undefined) {
  14309. setupDepthRenderbuffer(renderTarget);
  14310. }
  14311. } // Set up GL resources for the render target
  14312. function setupRenderTarget(renderTarget) {
  14313. const texture = renderTarget.texture;
  14314. const renderTargetProperties = properties.get(renderTarget);
  14315. const textureProperties = properties.get(texture);
  14316. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14317. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14318. if (textureProperties.__webglTexture === undefined) {
  14319. textureProperties.__webglTexture = _gl.createTexture();
  14320. }
  14321. textureProperties.__version = texture.version;
  14322. info.memory.textures++;
  14323. }
  14324. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14325. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14326. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Setup framebuffer
  14327. if (isCube) {
  14328. renderTargetProperties.__webglFramebuffer = [];
  14329. for (let i = 0; i < 6; i++) {
  14330. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14331. }
  14332. } else {
  14333. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14334. if (isMultipleRenderTargets) {
  14335. if (capabilities.drawBuffers) {
  14336. const textures = renderTarget.texture;
  14337. for (let i = 0, il = textures.length; i < il; i++) {
  14338. const attachmentProperties = properties.get(textures[i]);
  14339. if (attachmentProperties.__webglTexture === undefined) {
  14340. attachmentProperties.__webglTexture = _gl.createTexture();
  14341. info.memory.textures++;
  14342. }
  14343. }
  14344. } else {
  14345. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14346. }
  14347. }
  14348. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14349. const textures = isMultipleRenderTargets ? texture : [texture];
  14350. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14351. renderTargetProperties.__webglColorRenderbuffer = [];
  14352. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14353. for (let i = 0; i < textures.length; i++) {
  14354. const texture = textures[i];
  14355. renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer();
  14356. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14357. const glFormat = utils.convert(texture.format, texture.encoding);
  14358. const glType = utils.convert(texture.type);
  14359. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14360. const samples = getRenderTargetSamples(renderTarget);
  14361. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14362. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14363. }
  14364. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14365. if (renderTarget.depthBuffer) {
  14366. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14367. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14368. }
  14369. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14370. }
  14371. } // Setup color buffer
  14372. if (isCube) {
  14373. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14374. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14375. for (let i = 0; i < 6; i++) {
  14376. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14377. }
  14378. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14379. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14380. }
  14381. state.unbindTexture();
  14382. } else if (isMultipleRenderTargets) {
  14383. const textures = renderTarget.texture;
  14384. for (let i = 0, il = textures.length; i < il; i++) {
  14385. const attachment = textures[i];
  14386. const attachmentProperties = properties.get(attachment);
  14387. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14388. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14389. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14390. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14391. generateMipmap(_gl.TEXTURE_2D);
  14392. }
  14393. }
  14394. state.unbindTexture();
  14395. } else {
  14396. let glTextureType = _gl.TEXTURE_2D;
  14397. if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) {
  14398. if (isWebGL2) {
  14399. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14400. } else {
  14401. console.error('THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.');
  14402. }
  14403. }
  14404. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14405. setTextureParameters(glTextureType, texture, supportsMips);
  14406. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14407. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14408. generateMipmap(glTextureType);
  14409. }
  14410. state.unbindTexture();
  14411. } // Setup depth and stencil buffers
  14412. if (renderTarget.depthBuffer) {
  14413. setupDepthRenderbuffer(renderTarget);
  14414. }
  14415. }
  14416. function updateRenderTargetMipmap(renderTarget) {
  14417. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14418. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14419. for (let i = 0, il = textures.length; i < il; i++) {
  14420. const texture = textures[i];
  14421. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14422. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14423. const webglTexture = properties.get(texture).__webglTexture;
  14424. state.bindTexture(target, webglTexture);
  14425. generateMipmap(target);
  14426. state.unbindTexture();
  14427. }
  14428. }
  14429. }
  14430. function updateMultisampleRenderTarget(renderTarget) {
  14431. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14432. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [renderTarget.texture];
  14433. const width = renderTarget.width;
  14434. const height = renderTarget.height;
  14435. let mask = _gl.COLOR_BUFFER_BIT;
  14436. const invalidationArray = [];
  14437. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14438. const renderTargetProperties = properties.get(renderTarget);
  14439. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; // If MRT we need to remove FBO attachments
  14440. if (isMultipleRenderTargets) {
  14441. for (let i = 0; i < textures.length; i++) {
  14442. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14443. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null);
  14444. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14445. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0);
  14446. }
  14447. }
  14448. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14449. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14450. for (let i = 0; i < textures.length; i++) {
  14451. invalidationArray.push(_gl.COLOR_ATTACHMENT0 + i);
  14452. if (renderTarget.depthBuffer) {
  14453. invalidationArray.push(depthStyle);
  14454. }
  14455. const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== undefined ? renderTargetProperties.__ignoreDepthValues : false;
  14456. if (ignoreDepthValues === false) {
  14457. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14458. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14459. }
  14460. if (isMultipleRenderTargets) {
  14461. _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14462. }
  14463. if (ignoreDepthValues === true) {
  14464. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14465. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14466. }
  14467. if (isMultipleRenderTargets) {
  14468. const webglTexture = properties.get(textures[i]).__webglTexture;
  14469. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0);
  14470. }
  14471. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14472. if (supportsInvalidateFramebuffer) {
  14473. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14474. }
  14475. }
  14476. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14477. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14478. if (isMultipleRenderTargets) {
  14479. for (let i = 0; i < textures.length; i++) {
  14480. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14481. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14482. const webglTexture = properties.get(textures[i]).__webglTexture;
  14483. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14484. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0);
  14485. }
  14486. }
  14487. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14488. }
  14489. }
  14490. function getRenderTargetSamples(renderTarget) {
  14491. return Math.min(maxSamples, renderTarget.samples);
  14492. }
  14493. function useMultisampledRTT(renderTarget) {
  14494. const renderTargetProperties = properties.get(renderTarget);
  14495. return isWebGL2 && renderTarget.samples > 0 && extensions.has('WEBGL_multisampled_render_to_texture') === true && renderTargetProperties.__useRenderToTexture !== false;
  14496. }
  14497. function updateVideoTexture(texture) {
  14498. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14499. if (_videoTextures.get(texture) !== frame) {
  14500. _videoTextures.set(texture, frame);
  14501. texture.update();
  14502. }
  14503. }
  14504. function verifyColorSpace(texture, image) {
  14505. const encoding = texture.encoding;
  14506. const format = texture.format;
  14507. const type = texture.type;
  14508. if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image;
  14509. if (encoding !== LinearEncoding) {
  14510. // sRGB
  14511. if (encoding === sRGBEncoding) {
  14512. if (isWebGL2 === false) {
  14513. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14514. if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) {
  14515. texture.format = _SRGBAFormat; // it's not possible to generate mips in WebGL 1 with this extension
  14516. texture.minFilter = LinearFilter;
  14517. texture.generateMipmaps = false;
  14518. } else {
  14519. // slow fallback (CPU decode)
  14520. image = ImageUtils.sRGBToLinear(image);
  14521. }
  14522. } else {
  14523. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14524. if (format !== RGBAFormat || type !== UnsignedByteType) {
  14525. console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.');
  14526. }
  14527. }
  14528. } else {
  14529. console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding);
  14530. }
  14531. }
  14532. return image;
  14533. } //
  14534. this.allocateTextureUnit = allocateTextureUnit;
  14535. this.resetTextureUnits = resetTextureUnits;
  14536. this.setTexture2D = setTexture2D;
  14537. this.setTexture2DArray = setTexture2DArray;
  14538. this.setTexture3D = setTexture3D;
  14539. this.setTextureCube = setTextureCube;
  14540. this.rebindTextures = rebindTextures;
  14541. this.setupRenderTarget = setupRenderTarget;
  14542. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14543. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14544. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14545. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14546. this.useMultisampledRTT = useMultisampledRTT;
  14547. }
  14548. function WebGLUtils(gl, extensions, capabilities) {
  14549. const isWebGL2 = capabilities.isWebGL2;
  14550. function convert(p, encoding = null) {
  14551. let extension;
  14552. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14553. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14554. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14555. if (p === ByteType) return gl.BYTE;
  14556. if (p === ShortType) return gl.SHORT;
  14557. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14558. if (p === IntType) return gl.INT;
  14559. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14560. if (p === FloatType) return gl.FLOAT;
  14561. if (p === HalfFloatType) {
  14562. if (isWebGL2) return gl.HALF_FLOAT;
  14563. extension = extensions.get('OES_texture_half_float');
  14564. if (extension !== null) {
  14565. return extension.HALF_FLOAT_OES;
  14566. } else {
  14567. return null;
  14568. }
  14569. }
  14570. if (p === AlphaFormat) return gl.ALPHA;
  14571. if (p === RGBAFormat) return gl.RGBA;
  14572. if (p === LuminanceFormat) return gl.LUMINANCE;
  14573. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14574. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14575. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14576. if (p === RedFormat) return gl.RED;
  14577. if (p === RGBFormat) {
  14578. console.warn('THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228');
  14579. return gl.RGBA;
  14580. } // WebGL 1 sRGB fallback
  14581. if (p === _SRGBAFormat) {
  14582. extension = extensions.get('EXT_sRGB');
  14583. if (extension !== null) {
  14584. return extension.SRGB_ALPHA_EXT;
  14585. } else {
  14586. return null;
  14587. }
  14588. } // WebGL2 formats.
  14589. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14590. if (p === RGFormat) return gl.RG;
  14591. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14592. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER; // S3TC
  14593. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14594. if (encoding === sRGBEncoding) {
  14595. extension = extensions.get('WEBGL_compressed_texture_s3tc_srgb');
  14596. if (extension !== null) {
  14597. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14598. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14599. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14600. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14601. } else {
  14602. return null;
  14603. }
  14604. } else {
  14605. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14606. if (extension !== null) {
  14607. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14608. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14609. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14610. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14611. } else {
  14612. return null;
  14613. }
  14614. }
  14615. } // PVRTC
  14616. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14617. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14618. if (extension !== null) {
  14619. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14620. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14621. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14622. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14623. } else {
  14624. return null;
  14625. }
  14626. } // ETC1
  14627. if (p === RGB_ETC1_Format) {
  14628. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14629. if (extension !== null) {
  14630. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14631. } else {
  14632. return null;
  14633. }
  14634. } // ETC2
  14635. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14636. extension = extensions.get('WEBGL_compressed_texture_etc');
  14637. if (extension !== null) {
  14638. if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14639. if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14640. } else {
  14641. return null;
  14642. }
  14643. } // ASTC
  14644. 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) {
  14645. extension = extensions.get('WEBGL_compressed_texture_astc');
  14646. if (extension !== null) {
  14647. if (p === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14648. if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14649. if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14650. if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14651. if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14652. if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14653. if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14654. if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14655. if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14656. if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14657. if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14658. if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14659. if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14660. if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14661. } else {
  14662. return null;
  14663. }
  14664. } // BPTC
  14665. if (p === RGBA_BPTC_Format) {
  14666. extension = extensions.get('EXT_texture_compression_bptc');
  14667. if (extension !== null) {
  14668. if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14669. } else {
  14670. return null;
  14671. }
  14672. } //
  14673. if (p === UnsignedInt248Type) {
  14674. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  14675. extension = extensions.get('WEBGL_depth_texture');
  14676. if (extension !== null) {
  14677. return extension.UNSIGNED_INT_24_8_WEBGL;
  14678. } else {
  14679. return null;
  14680. }
  14681. } // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14682. return gl[p] !== undefined ? gl[p] : null;
  14683. }
  14684. return {
  14685. convert: convert
  14686. };
  14687. }
  14688. class ArrayCamera extends PerspectiveCamera {
  14689. constructor(array = []) {
  14690. super();
  14691. this.isArrayCamera = true;
  14692. this.cameras = array;
  14693. }
  14694. }
  14695. class Group extends Object3D {
  14696. constructor() {
  14697. super();
  14698. this.isGroup = true;
  14699. this.type = 'Group';
  14700. }
  14701. }
  14702. const _moveEvent = {
  14703. type: 'move'
  14704. };
  14705. class WebXRController {
  14706. constructor() {
  14707. this._targetRay = null;
  14708. this._grip = null;
  14709. this._hand = null;
  14710. }
  14711. getHandSpace() {
  14712. if (this._hand === null) {
  14713. this._hand = new Group();
  14714. this._hand.matrixAutoUpdate = false;
  14715. this._hand.visible = false;
  14716. this._hand.joints = {};
  14717. this._hand.inputState = {
  14718. pinching: false
  14719. };
  14720. }
  14721. return this._hand;
  14722. }
  14723. getTargetRaySpace() {
  14724. if (this._targetRay === null) {
  14725. this._targetRay = new Group();
  14726. this._targetRay.matrixAutoUpdate = false;
  14727. this._targetRay.visible = false;
  14728. this._targetRay.hasLinearVelocity = false;
  14729. this._targetRay.linearVelocity = new Vector3();
  14730. this._targetRay.hasAngularVelocity = false;
  14731. this._targetRay.angularVelocity = new Vector3();
  14732. }
  14733. return this._targetRay;
  14734. }
  14735. getGripSpace() {
  14736. if (this._grip === null) {
  14737. this._grip = new Group();
  14738. this._grip.matrixAutoUpdate = false;
  14739. this._grip.visible = false;
  14740. this._grip.hasLinearVelocity = false;
  14741. this._grip.linearVelocity = new Vector3();
  14742. this._grip.hasAngularVelocity = false;
  14743. this._grip.angularVelocity = new Vector3();
  14744. }
  14745. return this._grip;
  14746. }
  14747. dispatchEvent(event) {
  14748. if (this._targetRay !== null) {
  14749. this._targetRay.dispatchEvent(event);
  14750. }
  14751. if (this._grip !== null) {
  14752. this._grip.dispatchEvent(event);
  14753. }
  14754. if (this._hand !== null) {
  14755. this._hand.dispatchEvent(event);
  14756. }
  14757. return this;
  14758. }
  14759. disconnect(inputSource) {
  14760. this.dispatchEvent({
  14761. type: 'disconnected',
  14762. data: inputSource
  14763. });
  14764. if (this._targetRay !== null) {
  14765. this._targetRay.visible = false;
  14766. }
  14767. if (this._grip !== null) {
  14768. this._grip.visible = false;
  14769. }
  14770. if (this._hand !== null) {
  14771. this._hand.visible = false;
  14772. }
  14773. return this;
  14774. }
  14775. update(inputSource, frame, referenceSpace) {
  14776. let inputPose = null;
  14777. let gripPose = null;
  14778. let handPose = null;
  14779. const targetRay = this._targetRay;
  14780. const grip = this._grip;
  14781. const hand = this._hand;
  14782. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14783. if (hand && inputSource.hand) {
  14784. handPose = true;
  14785. for (const inputjoint of inputSource.hand.values()) {
  14786. // Update the joints groups with the XRJoint poses
  14787. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14788. if (hand.joints[inputjoint.jointName] === undefined) {
  14789. // The transform of this joint will be updated with the joint pose on each frame
  14790. const joint = new Group();
  14791. joint.matrixAutoUpdate = false;
  14792. joint.visible = false;
  14793. hand.joints[inputjoint.jointName] = joint; // ??
  14794. hand.add(joint);
  14795. }
  14796. const joint = hand.joints[inputjoint.jointName];
  14797. if (jointPose !== null) {
  14798. joint.matrix.fromArray(jointPose.transform.matrix);
  14799. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14800. joint.jointRadius = jointPose.radius;
  14801. }
  14802. joint.visible = jointPose !== null;
  14803. } // Custom events
  14804. // Check pinchz
  14805. const indexTip = hand.joints['index-finger-tip'];
  14806. const thumbTip = hand.joints['thumb-tip'];
  14807. const distance = indexTip.position.distanceTo(thumbTip.position);
  14808. const distanceToPinch = 0.02;
  14809. const threshold = 0.005;
  14810. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14811. hand.inputState.pinching = false;
  14812. this.dispatchEvent({
  14813. type: 'pinchend',
  14814. handedness: inputSource.handedness,
  14815. target: this
  14816. });
  14817. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14818. hand.inputState.pinching = true;
  14819. this.dispatchEvent({
  14820. type: 'pinchstart',
  14821. handedness: inputSource.handedness,
  14822. target: this
  14823. });
  14824. }
  14825. } else {
  14826. if (grip !== null && inputSource.gripSpace) {
  14827. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14828. if (gripPose !== null) {
  14829. grip.matrix.fromArray(gripPose.transform.matrix);
  14830. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14831. if (gripPose.linearVelocity) {
  14832. grip.hasLinearVelocity = true;
  14833. grip.linearVelocity.copy(gripPose.linearVelocity);
  14834. } else {
  14835. grip.hasLinearVelocity = false;
  14836. }
  14837. if (gripPose.angularVelocity) {
  14838. grip.hasAngularVelocity = true;
  14839. grip.angularVelocity.copy(gripPose.angularVelocity);
  14840. } else {
  14841. grip.hasAngularVelocity = false;
  14842. }
  14843. }
  14844. }
  14845. }
  14846. if (targetRay !== null) {
  14847. 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
  14848. if (inputPose === null && gripPose !== null) {
  14849. inputPose = gripPose;
  14850. }
  14851. if (inputPose !== null) {
  14852. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14853. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14854. if (inputPose.linearVelocity) {
  14855. targetRay.hasLinearVelocity = true;
  14856. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14857. } else {
  14858. targetRay.hasLinearVelocity = false;
  14859. }
  14860. if (inputPose.angularVelocity) {
  14861. targetRay.hasAngularVelocity = true;
  14862. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14863. } else {
  14864. targetRay.hasAngularVelocity = false;
  14865. }
  14866. this.dispatchEvent(_moveEvent);
  14867. }
  14868. }
  14869. }
  14870. if (targetRay !== null) {
  14871. targetRay.visible = inputPose !== null;
  14872. }
  14873. if (grip !== null) {
  14874. grip.visible = gripPose !== null;
  14875. }
  14876. if (hand !== null) {
  14877. hand.visible = handPose !== null;
  14878. }
  14879. return this;
  14880. }
  14881. }
  14882. class DepthTexture extends Texture {
  14883. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  14884. format = format !== undefined ? format : DepthFormat;
  14885. if (format !== DepthFormat && format !== DepthStencilFormat) {
  14886. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  14887. }
  14888. if (type === undefined && format === DepthFormat) type = UnsignedIntType;
  14889. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  14890. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  14891. this.isDepthTexture = true;
  14892. this.image = {
  14893. width: width,
  14894. height: height
  14895. };
  14896. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14897. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14898. this.flipY = false;
  14899. this.generateMipmaps = false;
  14900. }
  14901. }
  14902. class WebXRManager extends EventDispatcher {
  14903. constructor(renderer, gl) {
  14904. super();
  14905. const scope = this;
  14906. let session = null;
  14907. let framebufferScaleFactor = 1.0;
  14908. let referenceSpace = null;
  14909. let referenceSpaceType = 'local-floor';
  14910. let customReferenceSpace = null;
  14911. let pose = null;
  14912. let glBinding = null;
  14913. let glProjLayer = null;
  14914. let glBaseLayer = null;
  14915. let xrFrame = null;
  14916. const attributes = gl.getContextAttributes();
  14917. let initialRenderTarget = null;
  14918. let newRenderTarget = null;
  14919. const controllers = [];
  14920. const controllerInputSources = []; //
  14921. const cameraL = new PerspectiveCamera();
  14922. cameraL.layers.enable(1);
  14923. cameraL.viewport = new Vector4();
  14924. const cameraR = new PerspectiveCamera();
  14925. cameraR.layers.enable(2);
  14926. cameraR.viewport = new Vector4();
  14927. const cameras = [cameraL, cameraR];
  14928. const cameraVR = new ArrayCamera();
  14929. cameraVR.layers.enable(1);
  14930. cameraVR.layers.enable(2);
  14931. let _currentDepthNear = null;
  14932. let _currentDepthFar = null; //
  14933. this.cameraAutoUpdate = true;
  14934. this.enabled = false;
  14935. this.isPresenting = false;
  14936. this.getController = function (index) {
  14937. let controller = controllers[index];
  14938. if (controller === undefined) {
  14939. controller = new WebXRController();
  14940. controllers[index] = controller;
  14941. }
  14942. return controller.getTargetRaySpace();
  14943. };
  14944. this.getControllerGrip = function (index) {
  14945. let controller = controllers[index];
  14946. if (controller === undefined) {
  14947. controller = new WebXRController();
  14948. controllers[index] = controller;
  14949. }
  14950. return controller.getGripSpace();
  14951. };
  14952. this.getHand = function (index) {
  14953. let controller = controllers[index];
  14954. if (controller === undefined) {
  14955. controller = new WebXRController();
  14956. controllers[index] = controller;
  14957. }
  14958. return controller.getHandSpace();
  14959. }; //
  14960. function onSessionEvent(event) {
  14961. const controllerIndex = controllerInputSources.indexOf(event.inputSource);
  14962. if (controllerIndex === -1) {
  14963. return;
  14964. }
  14965. const controller = controllers[controllerIndex];
  14966. if (controller !== undefined) {
  14967. controller.dispatchEvent({
  14968. type: event.type,
  14969. data: event.inputSource
  14970. });
  14971. }
  14972. }
  14973. function onSessionEnd() {
  14974. session.removeEventListener('select', onSessionEvent);
  14975. session.removeEventListener('selectstart', onSessionEvent);
  14976. session.removeEventListener('selectend', onSessionEvent);
  14977. session.removeEventListener('squeeze', onSessionEvent);
  14978. session.removeEventListener('squeezestart', onSessionEvent);
  14979. session.removeEventListener('squeezeend', onSessionEvent);
  14980. session.removeEventListener('end', onSessionEnd);
  14981. session.removeEventListener('inputsourceschange', onInputSourcesChange);
  14982. for (let i = 0; i < controllers.length; i++) {
  14983. const inputSource = controllerInputSources[i];
  14984. if (inputSource === null) continue;
  14985. controllerInputSources[i] = null;
  14986. controllers[i].disconnect(inputSource);
  14987. }
  14988. _currentDepthNear = null;
  14989. _currentDepthFar = null; // restore framebuffer/rendering state
  14990. renderer.setRenderTarget(initialRenderTarget);
  14991. glBaseLayer = null;
  14992. glProjLayer = null;
  14993. glBinding = null;
  14994. session = null;
  14995. newRenderTarget = null; //
  14996. animation.stop();
  14997. scope.isPresenting = false;
  14998. scope.dispatchEvent({
  14999. type: 'sessionend'
  15000. });
  15001. }
  15002. this.setFramebufferScaleFactor = function (value) {
  15003. framebufferScaleFactor = value;
  15004. if (scope.isPresenting === true) {
  15005. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  15006. }
  15007. };
  15008. this.setReferenceSpaceType = function (value) {
  15009. referenceSpaceType = value;
  15010. if (scope.isPresenting === true) {
  15011. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  15012. }
  15013. };
  15014. this.getReferenceSpace = function () {
  15015. return customReferenceSpace || referenceSpace;
  15016. };
  15017. this.setReferenceSpace = function (space) {
  15018. customReferenceSpace = space;
  15019. };
  15020. this.getBaseLayer = function () {
  15021. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15022. };
  15023. this.getBinding = function () {
  15024. return glBinding;
  15025. };
  15026. this.getFrame = function () {
  15027. return xrFrame;
  15028. };
  15029. this.getSession = function () {
  15030. return session;
  15031. };
  15032. this.setSession = async function (value) {
  15033. session = value;
  15034. if (session !== null) {
  15035. initialRenderTarget = renderer.getRenderTarget();
  15036. session.addEventListener('select', onSessionEvent);
  15037. session.addEventListener('selectstart', onSessionEvent);
  15038. session.addEventListener('selectend', onSessionEvent);
  15039. session.addEventListener('squeeze', onSessionEvent);
  15040. session.addEventListener('squeezestart', onSessionEvent);
  15041. session.addEventListener('squeezeend', onSessionEvent);
  15042. session.addEventListener('end', onSessionEnd);
  15043. session.addEventListener('inputsourceschange', onInputSourcesChange);
  15044. if (attributes.xrCompatible !== true) {
  15045. await gl.makeXRCompatible();
  15046. }
  15047. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  15048. const layerInit = {
  15049. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  15050. alpha: attributes.alpha,
  15051. depth: attributes.depth,
  15052. stencil: attributes.stencil,
  15053. framebufferScaleFactor: framebufferScaleFactor
  15054. };
  15055. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  15056. session.updateRenderState({
  15057. baseLayer: glBaseLayer
  15058. });
  15059. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  15060. format: RGBAFormat,
  15061. type: UnsignedByteType,
  15062. encoding: renderer.outputEncoding
  15063. });
  15064. } else {
  15065. let depthFormat = null;
  15066. let depthType = null;
  15067. let glDepthFormat = null;
  15068. if (attributes.depth) {
  15069. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15070. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15071. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15072. }
  15073. const projectionlayerInit = {
  15074. colorFormat: gl.RGBA8,
  15075. depthFormat: glDepthFormat,
  15076. scaleFactor: framebufferScaleFactor
  15077. };
  15078. glBinding = new XRWebGLBinding(session, gl);
  15079. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  15080. session.updateRenderState({
  15081. layers: [glProjLayer]
  15082. });
  15083. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  15084. format: RGBAFormat,
  15085. type: UnsignedByteType,
  15086. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  15087. stencilBuffer: attributes.stencil,
  15088. encoding: renderer.outputEncoding,
  15089. samples: attributes.antialias ? 4 : 0
  15090. });
  15091. const renderTargetProperties = renderer.properties.get(newRenderTarget);
  15092. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15093. }
  15094. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15095. // Set foveation to maximum.
  15096. this.setFoveation(1.0);
  15097. customReferenceSpace = null;
  15098. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  15099. animation.setContext(session);
  15100. animation.start();
  15101. scope.isPresenting = true;
  15102. scope.dispatchEvent({
  15103. type: 'sessionstart'
  15104. });
  15105. }
  15106. };
  15107. function onInputSourcesChange(event) {
  15108. // Notify disconnected
  15109. for (let i = 0; i < event.removed.length; i++) {
  15110. const inputSource = event.removed[i];
  15111. const index = controllerInputSources.indexOf(inputSource);
  15112. if (index >= 0) {
  15113. controllerInputSources[index] = null;
  15114. controllers[index].dispatchEvent({
  15115. type: 'disconnected',
  15116. data: inputSource
  15117. });
  15118. }
  15119. } // Notify connected
  15120. for (let i = 0; i < event.added.length; i++) {
  15121. const inputSource = event.added[i];
  15122. let controllerIndex = controllerInputSources.indexOf(inputSource);
  15123. if (controllerIndex === -1) {
  15124. // Assign input source a controller that currently has no input source
  15125. for (let i = 0; i < controllers.length; i++) {
  15126. if (i >= controllerInputSources.length) {
  15127. controllerInputSources.push(inputSource);
  15128. controllerIndex = i;
  15129. break;
  15130. } else if (controllerInputSources[i] === null) {
  15131. controllerInputSources[i] = inputSource;
  15132. controllerIndex = i;
  15133. break;
  15134. }
  15135. } // If all controllers do currently receive input we ignore new ones
  15136. if (controllerIndex === -1) break;
  15137. }
  15138. const controller = controllers[controllerIndex];
  15139. if (controller) {
  15140. controller.dispatchEvent({
  15141. type: 'connected',
  15142. data: inputSource
  15143. });
  15144. }
  15145. }
  15146. } //
  15147. const cameraLPos = new Vector3();
  15148. const cameraRPos = new Vector3();
  15149. /**
  15150. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15151. * the cameras' projection and world matrices have already been set.
  15152. * And that near and far planes are identical for both cameras.
  15153. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15154. */
  15155. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15156. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15157. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15158. const ipd = cameraLPos.distanceTo(cameraRPos);
  15159. const projL = cameraL.projectionMatrix.elements;
  15160. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15161. // most likely identical top and bottom frustum extents.
  15162. // Use the left camera for these values.
  15163. const near = projL[14] / (projL[10] - 1);
  15164. const far = projL[14] / (projL[10] + 1);
  15165. const topFov = (projL[9] + 1) / projL[5];
  15166. const bottomFov = (projL[9] - 1) / projL[5];
  15167. const leftFov = (projL[8] - 1) / projL[0];
  15168. const rightFov = (projR[8] + 1) / projR[0];
  15169. const left = near * leftFov;
  15170. const right = near * rightFov; // Calculate the new camera's position offset from the
  15171. // left camera. xOffset should be roughly half `ipd`.
  15172. const zOffset = ipd / (-leftFov + rightFov);
  15173. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15174. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15175. camera.translateX(xOffset);
  15176. camera.translateZ(zOffset);
  15177. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15178. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  15179. // the values so that the near plane's position does not change in world space,
  15180. // although must now be relative to the new union camera.
  15181. const near2 = near + zOffset;
  15182. const far2 = far + zOffset;
  15183. const left2 = left - xOffset;
  15184. const right2 = right + (ipd - xOffset);
  15185. const top2 = topFov * far / far2 * near2;
  15186. const bottom2 = bottomFov * far / far2 * near2;
  15187. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15188. }
  15189. function updateCamera(camera, parent) {
  15190. if (parent === null) {
  15191. camera.matrixWorld.copy(camera.matrix);
  15192. } else {
  15193. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15194. }
  15195. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  15196. }
  15197. this.updateCamera = function (camera) {
  15198. if (session === null) return;
  15199. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15200. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15201. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  15202. // Note that the new renderState won't apply until the next frame. See #18320
  15203. session.updateRenderState({
  15204. depthNear: cameraVR.near,
  15205. depthFar: cameraVR.far
  15206. });
  15207. _currentDepthNear = cameraVR.near;
  15208. _currentDepthFar = cameraVR.far;
  15209. }
  15210. const parent = camera.parent;
  15211. const cameras = cameraVR.cameras;
  15212. updateCamera(cameraVR, parent);
  15213. for (let i = 0; i < cameras.length; i++) {
  15214. updateCamera(cameras[i], parent);
  15215. }
  15216. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  15217. camera.position.copy(cameraVR.position);
  15218. camera.quaternion.copy(cameraVR.quaternion);
  15219. camera.scale.copy(cameraVR.scale);
  15220. camera.matrix.copy(cameraVR.matrix);
  15221. camera.matrixWorld.copy(cameraVR.matrixWorld);
  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. }
  16784. if (refreshMaterial) {
  16785. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16786. if (materialProperties.needsLights) {
  16787. // the current material requires lighting info
  16788. // note: all lighting uniforms are always set correctly
  16789. // they simply reference the renderer's state for their
  16790. // values
  16791. //
  16792. // use the current material's .needsUpdate flags to set
  16793. // the GL state when required
  16794. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16795. } // refresh uniforms common to several materials
  16796. if (fog && material.fog === true) {
  16797. materials.refreshFogUniforms(m_uniforms, fog);
  16798. }
  16799. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  16800. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16801. }
  16802. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16803. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16804. material.uniformsNeedUpdate = false;
  16805. }
  16806. if (material.isSpriteMaterial) {
  16807. p_uniforms.setValue(_gl, 'center', object.center);
  16808. } // common matrices
  16809. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16810. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16811. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld); // UBOs
  16812. if (material.isShaderMaterial || material.isRawShaderMaterial) {
  16813. const groups = material.uniformsGroups;
  16814. for (let i = 0, l = groups.length; i < l; i++) {
  16815. if (capabilities.isWebGL2) {
  16816. const group = groups[i];
  16817. uniformsGroups.update(group, program);
  16818. uniformsGroups.bind(group, program);
  16819. } else {
  16820. console.warn('THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.');
  16821. }
  16822. }
  16823. }
  16824. return program;
  16825. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16826. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16827. uniforms.ambientLightColor.needsUpdate = value;
  16828. uniforms.lightProbe.needsUpdate = value;
  16829. uniforms.directionalLights.needsUpdate = value;
  16830. uniforms.directionalLightShadows.needsUpdate = value;
  16831. uniforms.pointLights.needsUpdate = value;
  16832. uniforms.pointLightShadows.needsUpdate = value;
  16833. uniforms.spotLights.needsUpdate = value;
  16834. uniforms.spotLightShadows.needsUpdate = value;
  16835. uniforms.rectAreaLights.needsUpdate = value;
  16836. uniforms.hemisphereLights.needsUpdate = value;
  16837. }
  16838. function materialNeedsLights(material) {
  16839. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16840. }
  16841. this.getActiveCubeFace = function () {
  16842. return _currentActiveCubeFace;
  16843. };
  16844. this.getActiveMipmapLevel = function () {
  16845. return _currentActiveMipmapLevel;
  16846. };
  16847. this.getRenderTarget = function () {
  16848. return _currentRenderTarget;
  16849. };
  16850. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  16851. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  16852. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  16853. const renderTargetProperties = properties.get(renderTarget);
  16854. renderTargetProperties.__hasExternalTextures = true;
  16855. if (renderTargetProperties.__hasExternalTextures) {
  16856. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16857. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  16858. // The multisample_render_to_texture extension doesn't work properly if there
  16859. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16860. if (extensions.has('WEBGL_multisampled_render_to_texture') === true) {
  16861. console.warn('THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided');
  16862. renderTargetProperties.__useRenderToTexture = false;
  16863. }
  16864. }
  16865. }
  16866. };
  16867. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  16868. const renderTargetProperties = properties.get(renderTarget);
  16869. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16870. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16871. };
  16872. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16873. _currentRenderTarget = renderTarget;
  16874. _currentActiveCubeFace = activeCubeFace;
  16875. _currentActiveMipmapLevel = activeMipmapLevel;
  16876. let useDefaultFramebuffer = true;
  16877. if (renderTarget) {
  16878. const renderTargetProperties = properties.get(renderTarget);
  16879. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  16880. // We need to make sure to rebind the framebuffer.
  16881. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  16882. useDefaultFramebuffer = false;
  16883. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  16884. textures.setupRenderTarget(renderTarget);
  16885. } else if (renderTargetProperties.__hasExternalTextures) {
  16886. // Color and depth texture must be rebound in order for the swapchain to update.
  16887. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  16888. }
  16889. }
  16890. let framebuffer = null;
  16891. let isCube = false;
  16892. let isRenderTarget3D = false;
  16893. if (renderTarget) {
  16894. const texture = renderTarget.texture;
  16895. if (texture.isData3DTexture || texture.isDataArrayTexture) {
  16896. isRenderTarget3D = true;
  16897. }
  16898. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16899. if (renderTarget.isWebGLCubeRenderTarget) {
  16900. framebuffer = __webglFramebuffer[activeCubeFace];
  16901. isCube = true;
  16902. } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) {
  16903. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16904. } else {
  16905. framebuffer = __webglFramebuffer;
  16906. }
  16907. _currentViewport.copy(renderTarget.viewport);
  16908. _currentScissor.copy(renderTarget.scissor);
  16909. _currentScissorTest = renderTarget.scissorTest;
  16910. } else {
  16911. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16912. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16913. _currentScissorTest = _scissorTest;
  16914. }
  16915. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16916. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  16917. state.drawBuffers(renderTarget, framebuffer);
  16918. }
  16919. state.viewport(_currentViewport);
  16920. state.scissor(_currentScissor);
  16921. state.setScissorTest(_currentScissorTest);
  16922. if (isCube) {
  16923. const textureProperties = properties.get(renderTarget.texture);
  16924. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16925. } else if (isRenderTarget3D) {
  16926. const textureProperties = properties.get(renderTarget.texture);
  16927. const layer = activeCubeFace || 0;
  16928. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16929. }
  16930. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16931. };
  16932. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16933. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16934. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16935. return;
  16936. }
  16937. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16938. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16939. framebuffer = framebuffer[activeCubeFaceIndex];
  16940. }
  16941. if (framebuffer) {
  16942. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16943. try {
  16944. const texture = renderTarget.texture;
  16945. const textureFormat = texture.format;
  16946. const textureType = texture.type;
  16947. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16948. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16949. return;
  16950. }
  16951. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16952. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16953. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16954. !halfFloatSupportedByExt) {
  16955. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16956. return;
  16957. } // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16958. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16959. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16960. }
  16961. } finally {
  16962. // restore framebuffer of current render target if necessary
  16963. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16964. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16965. }
  16966. }
  16967. };
  16968. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16969. const levelScale = Math.pow(2, -level);
  16970. const width = Math.floor(texture.image.width * levelScale);
  16971. const height = Math.floor(texture.image.height * levelScale);
  16972. textures.setTexture2D(texture, 0);
  16973. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  16974. state.unbindTexture();
  16975. };
  16976. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16977. const width = srcTexture.image.width;
  16978. const height = srcTexture.image.height;
  16979. const glFormat = utils.convert(dstTexture.format);
  16980. const glType = utils.convert(dstTexture.type);
  16981. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16982. // parameters, make sure they are correct for the dstTexture
  16983. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16984. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16985. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16986. if (srcTexture.isDataTexture) {
  16987. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16988. } else {
  16989. if (srcTexture.isCompressedTexture) {
  16990. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16991. } else {
  16992. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16993. }
  16994. } // Generate mipmaps only when copying level 0
  16995. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16996. state.unbindTexture();
  16997. };
  16998. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  16999. if (_this.isWebGL1Renderer) {
  17000. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  17001. return;
  17002. }
  17003. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17004. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17005. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17006. const glFormat = utils.convert(dstTexture.format);
  17007. const glType = utils.convert(dstTexture.type);
  17008. let glTarget;
  17009. if (dstTexture.isData3DTexture) {
  17010. textures.setTexture3D(dstTexture, 0);
  17011. glTarget = _gl.TEXTURE_3D;
  17012. } else if (dstTexture.isDataArrayTexture) {
  17013. textures.setTexture2DArray(dstTexture, 0);
  17014. glTarget = _gl.TEXTURE_2D_ARRAY;
  17015. } else {
  17016. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  17017. return;
  17018. }
  17019. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  17020. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  17021. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  17022. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  17023. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  17024. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  17025. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  17026. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  17027. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  17028. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  17029. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  17030. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  17031. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  17032. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  17033. if (srcTexture.isDataTexture || srcTexture.isData3DTexture) {
  17034. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  17035. } else {
  17036. if (srcTexture.isCompressedTexture) {
  17037. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  17038. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  17039. } else {
  17040. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  17041. }
  17042. }
  17043. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  17044. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  17045. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  17046. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  17047. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  17048. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  17049. state.unbindTexture();
  17050. };
  17051. this.initTexture = function (texture) {
  17052. if (texture.isCubeTexture) {
  17053. textures.setTextureCube(texture, 0);
  17054. } else if (texture.isData3DTexture) {
  17055. textures.setTexture3D(texture, 0);
  17056. } else if (texture.isDataArrayTexture) {
  17057. textures.setTexture2DArray(texture, 0);
  17058. } else {
  17059. textures.setTexture2D(texture, 0);
  17060. }
  17061. state.unbindTexture();
  17062. };
  17063. this.resetState = function () {
  17064. _currentActiveCubeFace = 0;
  17065. _currentActiveMipmapLevel = 0;
  17066. _currentRenderTarget = null;
  17067. state.reset();
  17068. bindingStates.reset();
  17069. };
  17070. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17071. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17072. detail: this
  17073. }));
  17074. }
  17075. }
  17076. class WebGL1Renderer extends WebGLRenderer {}
  17077. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17078. class FogExp2 {
  17079. constructor(color, density = 0.00025) {
  17080. this.isFogExp2 = true;
  17081. this.name = '';
  17082. this.color = new Color(color);
  17083. this.density = density;
  17084. }
  17085. clone() {
  17086. return new FogExp2(this.color, this.density);
  17087. }
  17088. toJSON() {
  17089. return {
  17090. type: 'FogExp2',
  17091. color: this.color.getHex(),
  17092. density: this.density
  17093. };
  17094. }
  17095. }
  17096. class Fog {
  17097. constructor(color, near = 1, far = 1000) {
  17098. this.isFog = true;
  17099. this.name = '';
  17100. this.color = new Color(color);
  17101. this.near = near;
  17102. this.far = far;
  17103. }
  17104. clone() {
  17105. return new Fog(this.color, this.near, this.far);
  17106. }
  17107. toJSON() {
  17108. return {
  17109. type: 'Fog',
  17110. color: this.color.getHex(),
  17111. near: this.near,
  17112. far: this.far
  17113. };
  17114. }
  17115. }
  17116. class Scene extends Object3D {
  17117. constructor() {
  17118. super();
  17119. this.isScene = true;
  17120. this.type = 'Scene';
  17121. this.background = null;
  17122. this.environment = null;
  17123. this.fog = null;
  17124. this.overrideMaterial = null;
  17125. this.autoUpdate = true; // checked by the renderer
  17126. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17127. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17128. detail: this
  17129. }));
  17130. }
  17131. }
  17132. copy(source, recursive) {
  17133. super.copy(source, recursive);
  17134. if (source.background !== null) this.background = source.background.clone();
  17135. if (source.environment !== null) this.environment = source.environment.clone();
  17136. if (source.fog !== null) this.fog = source.fog.clone();
  17137. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  17138. this.autoUpdate = source.autoUpdate;
  17139. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17140. return this;
  17141. }
  17142. toJSON(meta) {
  17143. const data = super.toJSON(meta);
  17144. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  17145. return data;
  17146. }
  17147. }
  17148. class InterleavedBuffer {
  17149. constructor(array, stride) {
  17150. this.isInterleavedBuffer = true;
  17151. this.array = array;
  17152. this.stride = stride;
  17153. this.count = array !== undefined ? array.length / stride : 0;
  17154. this.usage = StaticDrawUsage;
  17155. this.updateRange = {
  17156. offset: 0,
  17157. count: -1
  17158. };
  17159. this.version = 0;
  17160. this.uuid = generateUUID();
  17161. }
  17162. onUploadCallback() {}
  17163. set needsUpdate(value) {
  17164. if (value === true) this.version++;
  17165. }
  17166. setUsage(value) {
  17167. this.usage = value;
  17168. return this;
  17169. }
  17170. copy(source) {
  17171. this.array = new source.array.constructor(source.array);
  17172. this.count = source.count;
  17173. this.stride = source.stride;
  17174. this.usage = source.usage;
  17175. return this;
  17176. }
  17177. copyAt(index1, attribute, index2) {
  17178. index1 *= this.stride;
  17179. index2 *= attribute.stride;
  17180. for (let i = 0, l = this.stride; i < l; i++) {
  17181. this.array[index1 + i] = attribute.array[index2 + i];
  17182. }
  17183. return this;
  17184. }
  17185. set(value, offset = 0) {
  17186. this.array.set(value, offset);
  17187. return this;
  17188. }
  17189. clone(data) {
  17190. if (data.arrayBuffers === undefined) {
  17191. data.arrayBuffers = {};
  17192. }
  17193. if (this.array.buffer._uuid === undefined) {
  17194. this.array.buffer._uuid = generateUUID();
  17195. }
  17196. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17197. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  17198. }
  17199. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  17200. const ib = new this.constructor(array, this.stride);
  17201. ib.setUsage(this.usage);
  17202. return ib;
  17203. }
  17204. onUpload(callback) {
  17205. this.onUploadCallback = callback;
  17206. return this;
  17207. }
  17208. toJSON(data) {
  17209. if (data.arrayBuffers === undefined) {
  17210. data.arrayBuffers = {};
  17211. } // generate UUID for array buffer if necessary
  17212. if (this.array.buffer._uuid === undefined) {
  17213. this.array.buffer._uuid = generateUUID();
  17214. }
  17215. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17216. data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer));
  17217. } //
  17218. return {
  17219. uuid: this.uuid,
  17220. buffer: this.array.buffer._uuid,
  17221. type: this.array.constructor.name,
  17222. stride: this.stride
  17223. };
  17224. }
  17225. }
  17226. const _vector$6 = /*@__PURE__*/new Vector3();
  17227. class InterleavedBufferAttribute {
  17228. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  17229. this.isInterleavedBufferAttribute = true;
  17230. this.name = '';
  17231. this.data = interleavedBuffer;
  17232. this.itemSize = itemSize;
  17233. this.offset = offset;
  17234. this.normalized = normalized === true;
  17235. }
  17236. get count() {
  17237. return this.data.count;
  17238. }
  17239. get array() {
  17240. return this.data.array;
  17241. }
  17242. set needsUpdate(value) {
  17243. this.data.needsUpdate = value;
  17244. }
  17245. applyMatrix4(m) {
  17246. for (let i = 0, l = this.data.count; i < l; i++) {
  17247. _vector$6.fromBufferAttribute(this, i);
  17248. _vector$6.applyMatrix4(m);
  17249. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17250. }
  17251. return this;
  17252. }
  17253. applyNormalMatrix(m) {
  17254. for (let i = 0, l = this.count; i < l; i++) {
  17255. _vector$6.fromBufferAttribute(this, i);
  17256. _vector$6.applyNormalMatrix(m);
  17257. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17258. }
  17259. return this;
  17260. }
  17261. transformDirection(m) {
  17262. for (let i = 0, l = this.count; i < l; i++) {
  17263. _vector$6.fromBufferAttribute(this, i);
  17264. _vector$6.transformDirection(m);
  17265. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17266. }
  17267. return this;
  17268. }
  17269. setX(index, x) {
  17270. this.data.array[index * this.data.stride + this.offset] = x;
  17271. return this;
  17272. }
  17273. setY(index, y) {
  17274. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17275. return this;
  17276. }
  17277. setZ(index, z) {
  17278. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17279. return this;
  17280. }
  17281. setW(index, w) {
  17282. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17283. return this;
  17284. }
  17285. getX(index) {
  17286. return this.data.array[index * this.data.stride + this.offset];
  17287. }
  17288. getY(index) {
  17289. return this.data.array[index * this.data.stride + this.offset + 1];
  17290. }
  17291. getZ(index) {
  17292. return this.data.array[index * this.data.stride + this.offset + 2];
  17293. }
  17294. getW(index) {
  17295. return this.data.array[index * this.data.stride + this.offset + 3];
  17296. }
  17297. setXY(index, x, y) {
  17298. index = index * this.data.stride + this.offset;
  17299. this.data.array[index + 0] = x;
  17300. this.data.array[index + 1] = y;
  17301. return this;
  17302. }
  17303. setXYZ(index, x, y, z) {
  17304. index = index * this.data.stride + this.offset;
  17305. this.data.array[index + 0] = x;
  17306. this.data.array[index + 1] = y;
  17307. this.data.array[index + 2] = z;
  17308. return this;
  17309. }
  17310. setXYZW(index, x, y, z, w) {
  17311. index = index * this.data.stride + this.offset;
  17312. this.data.array[index + 0] = x;
  17313. this.data.array[index + 1] = y;
  17314. this.data.array[index + 2] = z;
  17315. this.data.array[index + 3] = w;
  17316. return this;
  17317. }
  17318. clone(data) {
  17319. if (data === undefined) {
  17320. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.');
  17321. const array = [];
  17322. for (let i = 0; i < this.count; i++) {
  17323. const index = i * this.data.stride + this.offset;
  17324. for (let j = 0; j < this.itemSize; j++) {
  17325. array.push(this.data.array[index + j]);
  17326. }
  17327. }
  17328. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  17329. } else {
  17330. if (data.interleavedBuffers === undefined) {
  17331. data.interleavedBuffers = {};
  17332. }
  17333. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17334. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  17335. }
  17336. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  17337. }
  17338. }
  17339. toJSON(data) {
  17340. if (data === undefined) {
  17341. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.');
  17342. const array = [];
  17343. for (let i = 0; i < this.count; i++) {
  17344. const index = i * this.data.stride + this.offset;
  17345. for (let j = 0; j < this.itemSize; j++) {
  17346. array.push(this.data.array[index + j]);
  17347. }
  17348. } // deinterleave data and save it as an ordinary buffer attribute for now
  17349. return {
  17350. itemSize: this.itemSize,
  17351. type: this.array.constructor.name,
  17352. array: array,
  17353. normalized: this.normalized
  17354. };
  17355. } else {
  17356. // save as true interleaved attribtue
  17357. if (data.interleavedBuffers === undefined) {
  17358. data.interleavedBuffers = {};
  17359. }
  17360. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17361. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  17362. }
  17363. return {
  17364. isInterleavedBufferAttribute: true,
  17365. itemSize: this.itemSize,
  17366. data: this.data.uuid,
  17367. offset: this.offset,
  17368. normalized: this.normalized
  17369. };
  17370. }
  17371. }
  17372. }
  17373. class SpriteMaterial extends Material {
  17374. constructor(parameters) {
  17375. super();
  17376. this.isSpriteMaterial = true;
  17377. this.type = 'SpriteMaterial';
  17378. this.color = new Color(0xffffff);
  17379. this.map = null;
  17380. this.alphaMap = null;
  17381. this.rotation = 0;
  17382. this.sizeAttenuation = true;
  17383. this.transparent = true;
  17384. this.fog = true;
  17385. this.setValues(parameters);
  17386. }
  17387. copy(source) {
  17388. super.copy(source);
  17389. this.color.copy(source.color);
  17390. this.map = source.map;
  17391. this.alphaMap = source.alphaMap;
  17392. this.rotation = source.rotation;
  17393. this.sizeAttenuation = source.sizeAttenuation;
  17394. this.fog = source.fog;
  17395. return this;
  17396. }
  17397. }
  17398. let _geometry;
  17399. const _intersectPoint = /*@__PURE__*/new Vector3();
  17400. const _worldScale = /*@__PURE__*/new Vector3();
  17401. const _mvPosition = /*@__PURE__*/new Vector3();
  17402. const _alignedPosition = /*@__PURE__*/new Vector2();
  17403. const _rotatedPosition = /*@__PURE__*/new Vector2();
  17404. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  17405. const _vA = /*@__PURE__*/new Vector3();
  17406. const _vB = /*@__PURE__*/new Vector3();
  17407. const _vC = /*@__PURE__*/new Vector3();
  17408. const _uvA = /*@__PURE__*/new Vector2();
  17409. const _uvB = /*@__PURE__*/new Vector2();
  17410. const _uvC = /*@__PURE__*/new Vector2();
  17411. class Sprite extends Object3D {
  17412. constructor(material) {
  17413. super();
  17414. this.isSprite = true;
  17415. this.type = 'Sprite';
  17416. if (_geometry === undefined) {
  17417. _geometry = new BufferGeometry();
  17418. 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]);
  17419. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17420. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17421. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17422. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17423. }
  17424. this.geometry = _geometry;
  17425. this.material = material !== undefined ? material : new SpriteMaterial();
  17426. this.center = new Vector2(0.5, 0.5);
  17427. }
  17428. raycast(raycaster, intersects) {
  17429. if (raycaster.camera === null) {
  17430. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17431. }
  17432. _worldScale.setFromMatrixScale(this.matrixWorld);
  17433. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17434. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17435. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17436. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17437. _worldScale.multiplyScalar(-_mvPosition.z);
  17438. }
  17439. const rotation = this.material.rotation;
  17440. let sin, cos;
  17441. if (rotation !== 0) {
  17442. cos = Math.cos(rotation);
  17443. sin = Math.sin(rotation);
  17444. }
  17445. const center = this.center;
  17446. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17447. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17448. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17449. _uvA.set(0, 0);
  17450. _uvB.set(1, 0);
  17451. _uvC.set(1, 1); // check first triangle
  17452. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  17453. if (intersect === null) {
  17454. // check second triangle
  17455. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17456. _uvB.set(0, 1);
  17457. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  17458. if (intersect === null) {
  17459. return;
  17460. }
  17461. }
  17462. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17463. if (distance < raycaster.near || distance > raycaster.far) return;
  17464. intersects.push({
  17465. distance: distance,
  17466. point: _intersectPoint.clone(),
  17467. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  17468. face: null,
  17469. object: this
  17470. });
  17471. }
  17472. copy(source, recursive) {
  17473. super.copy(source, recursive);
  17474. if (source.center !== undefined) this.center.copy(source.center);
  17475. this.material = source.material;
  17476. return this;
  17477. }
  17478. }
  17479. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17480. // compute position in camera space
  17481. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17482. if (sin !== undefined) {
  17483. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17484. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17485. } else {
  17486. _rotatedPosition.copy(_alignedPosition);
  17487. }
  17488. vertexPosition.copy(mvPosition);
  17489. vertexPosition.x += _rotatedPosition.x;
  17490. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17491. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17492. }
  17493. const _v1$2 = /*@__PURE__*/new Vector3();
  17494. const _v2$1 = /*@__PURE__*/new Vector3();
  17495. class LOD extends Object3D {
  17496. constructor() {
  17497. super();
  17498. this._currentLevel = 0;
  17499. this.type = 'LOD';
  17500. Object.defineProperties(this, {
  17501. levels: {
  17502. enumerable: true,
  17503. value: []
  17504. },
  17505. isLOD: {
  17506. value: true
  17507. }
  17508. });
  17509. this.autoUpdate = true;
  17510. }
  17511. copy(source) {
  17512. super.copy(source, false);
  17513. const levels = source.levels;
  17514. for (let i = 0, l = levels.length; i < l; i++) {
  17515. const level = levels[i];
  17516. this.addLevel(level.object.clone(), level.distance);
  17517. }
  17518. this.autoUpdate = source.autoUpdate;
  17519. return this;
  17520. }
  17521. addLevel(object, distance = 0) {
  17522. distance = Math.abs(distance);
  17523. const levels = this.levels;
  17524. let l;
  17525. for (l = 0; l < levels.length; l++) {
  17526. if (distance < levels[l].distance) {
  17527. break;
  17528. }
  17529. }
  17530. levels.splice(l, 0, {
  17531. distance: distance,
  17532. object: object
  17533. });
  17534. this.add(object);
  17535. return this;
  17536. }
  17537. getCurrentLevel() {
  17538. return this._currentLevel;
  17539. }
  17540. getObjectForDistance(distance) {
  17541. const levels = this.levels;
  17542. if (levels.length > 0) {
  17543. let i, l;
  17544. for (i = 1, l = levels.length; i < l; i++) {
  17545. if (distance < levels[i].distance) {
  17546. break;
  17547. }
  17548. }
  17549. return levels[i - 1].object;
  17550. }
  17551. return null;
  17552. }
  17553. raycast(raycaster, intersects) {
  17554. const levels = this.levels;
  17555. if (levels.length > 0) {
  17556. _v1$2.setFromMatrixPosition(this.matrixWorld);
  17557. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  17558. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17559. }
  17560. }
  17561. update(camera) {
  17562. const levels = this.levels;
  17563. if (levels.length > 1) {
  17564. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  17565. _v2$1.setFromMatrixPosition(this.matrixWorld);
  17566. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  17567. levels[0].object.visible = true;
  17568. let i, l;
  17569. for (i = 1, l = levels.length; i < l; i++) {
  17570. if (distance >= levels[i].distance) {
  17571. levels[i - 1].object.visible = false;
  17572. levels[i].object.visible = true;
  17573. } else {
  17574. break;
  17575. }
  17576. }
  17577. this._currentLevel = i - 1;
  17578. for (; i < l; i++) {
  17579. levels[i].object.visible = false;
  17580. }
  17581. }
  17582. }
  17583. toJSON(meta) {
  17584. const data = super.toJSON(meta);
  17585. if (this.autoUpdate === false) data.object.autoUpdate = false;
  17586. data.object.levels = [];
  17587. const levels = this.levels;
  17588. for (let i = 0, l = levels.length; i < l; i++) {
  17589. const level = levels[i];
  17590. data.object.levels.push({
  17591. object: level.object.uuid,
  17592. distance: level.distance
  17593. });
  17594. }
  17595. return data;
  17596. }
  17597. }
  17598. const _basePosition = /*@__PURE__*/new Vector3();
  17599. const _skinIndex = /*@__PURE__*/new Vector4();
  17600. const _skinWeight = /*@__PURE__*/new Vector4();
  17601. const _vector$5 = /*@__PURE__*/new Vector3();
  17602. const _matrix = /*@__PURE__*/new Matrix4();
  17603. class SkinnedMesh extends Mesh {
  17604. constructor(geometry, material) {
  17605. super(geometry, material);
  17606. this.isSkinnedMesh = true;
  17607. this.type = 'SkinnedMesh';
  17608. this.bindMode = 'attached';
  17609. this.bindMatrix = new Matrix4();
  17610. this.bindMatrixInverse = new Matrix4();
  17611. }
  17612. copy(source, recursive) {
  17613. super.copy(source, recursive);
  17614. this.bindMode = source.bindMode;
  17615. this.bindMatrix.copy(source.bindMatrix);
  17616. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  17617. this.skeleton = source.skeleton;
  17618. return this;
  17619. }
  17620. bind(skeleton, bindMatrix) {
  17621. this.skeleton = skeleton;
  17622. if (bindMatrix === undefined) {
  17623. this.updateMatrixWorld(true);
  17624. this.skeleton.calculateInverses();
  17625. bindMatrix = this.matrixWorld;
  17626. }
  17627. this.bindMatrix.copy(bindMatrix);
  17628. this.bindMatrixInverse.copy(bindMatrix).invert();
  17629. }
  17630. pose() {
  17631. this.skeleton.pose();
  17632. }
  17633. normalizeSkinWeights() {
  17634. const vector = new Vector4();
  17635. const skinWeight = this.geometry.attributes.skinWeight;
  17636. for (let i = 0, l = skinWeight.count; i < l; i++) {
  17637. vector.fromBufferAttribute(skinWeight, i);
  17638. const scale = 1.0 / vector.manhattanLength();
  17639. if (scale !== Infinity) {
  17640. vector.multiplyScalar(scale);
  17641. } else {
  17642. vector.set(1, 0, 0, 0); // do something reasonable
  17643. }
  17644. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17645. }
  17646. }
  17647. updateMatrixWorld(force) {
  17648. super.updateMatrixWorld(force);
  17649. if (this.bindMode === 'attached') {
  17650. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  17651. } else if (this.bindMode === 'detached') {
  17652. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  17653. } else {
  17654. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17655. }
  17656. }
  17657. boneTransform(index, target) {
  17658. const skeleton = this.skeleton;
  17659. const geometry = this.geometry;
  17660. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  17661. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  17662. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  17663. target.set(0, 0, 0);
  17664. for (let i = 0; i < 4; i++) {
  17665. const weight = _skinWeight.getComponent(i);
  17666. if (weight !== 0) {
  17667. const boneIndex = _skinIndex.getComponent(i);
  17668. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  17669. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  17670. }
  17671. }
  17672. return target.applyMatrix4(this.bindMatrixInverse);
  17673. }
  17674. }
  17675. class Bone extends Object3D {
  17676. constructor() {
  17677. super();
  17678. this.isBone = true;
  17679. this.type = 'Bone';
  17680. }
  17681. }
  17682. class DataTexture extends Texture {
  17683. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  17684. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17685. this.isDataTexture = true;
  17686. this.image = {
  17687. data: data,
  17688. width: width,
  17689. height: height
  17690. };
  17691. this.generateMipmaps = false;
  17692. this.flipY = false;
  17693. this.unpackAlignment = 1;
  17694. }
  17695. }
  17696. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  17697. const _identityMatrix = /*@__PURE__*/new Matrix4();
  17698. class Skeleton {
  17699. constructor(bones = [], boneInverses = []) {
  17700. this.uuid = generateUUID();
  17701. this.bones = bones.slice(0);
  17702. this.boneInverses = boneInverses;
  17703. this.boneMatrices = null;
  17704. this.boneTexture = null;
  17705. this.boneTextureSize = 0;
  17706. this.frame = -1;
  17707. this.init();
  17708. }
  17709. init() {
  17710. const bones = this.bones;
  17711. const boneInverses = this.boneInverses;
  17712. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  17713. if (boneInverses.length === 0) {
  17714. this.calculateInverses();
  17715. } else {
  17716. // handle special case
  17717. if (bones.length !== boneInverses.length) {
  17718. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  17719. this.boneInverses = [];
  17720. for (let i = 0, il = this.bones.length; i < il; i++) {
  17721. this.boneInverses.push(new Matrix4());
  17722. }
  17723. }
  17724. }
  17725. }
  17726. calculateInverses() {
  17727. this.boneInverses.length = 0;
  17728. for (let i = 0, il = this.bones.length; i < il; i++) {
  17729. const inverse = new Matrix4();
  17730. if (this.bones[i]) {
  17731. inverse.copy(this.bones[i].matrixWorld).invert();
  17732. }
  17733. this.boneInverses.push(inverse);
  17734. }
  17735. }
  17736. pose() {
  17737. // recover the bind-time world matrices
  17738. for (let i = 0, il = this.bones.length; i < il; i++) {
  17739. const bone = this.bones[i];
  17740. if (bone) {
  17741. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  17742. }
  17743. } // compute the local matrices, positions, rotations and scales
  17744. for (let i = 0, il = this.bones.length; i < il; i++) {
  17745. const bone = this.bones[i];
  17746. if (bone) {
  17747. if (bone.parent && bone.parent.isBone) {
  17748. bone.matrix.copy(bone.parent.matrixWorld).invert();
  17749. bone.matrix.multiply(bone.matrixWorld);
  17750. } else {
  17751. bone.matrix.copy(bone.matrixWorld);
  17752. }
  17753. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17754. }
  17755. }
  17756. }
  17757. update() {
  17758. const bones = this.bones;
  17759. const boneInverses = this.boneInverses;
  17760. const boneMatrices = this.boneMatrices;
  17761. const boneTexture = this.boneTexture; // flatten bone matrices to array
  17762. for (let i = 0, il = bones.length; i < il; i++) {
  17763. // compute the offset between the current and the original transform
  17764. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17765. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17766. _offsetMatrix.toArray(boneMatrices, i * 16);
  17767. }
  17768. if (boneTexture !== null) {
  17769. boneTexture.needsUpdate = true;
  17770. }
  17771. }
  17772. clone() {
  17773. return new Skeleton(this.bones, this.boneInverses);
  17774. }
  17775. computeBoneTexture() {
  17776. // layout (1 matrix = 4 pixels)
  17777. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17778. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17779. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17780. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17781. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17782. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  17783. size = ceilPowerOfTwo(size);
  17784. size = Math.max(size, 4);
  17785. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  17786. boneMatrices.set(this.boneMatrices); // copy current values
  17787. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  17788. boneTexture.needsUpdate = true;
  17789. this.boneMatrices = boneMatrices;
  17790. this.boneTexture = boneTexture;
  17791. this.boneTextureSize = size;
  17792. return this;
  17793. }
  17794. getBoneByName(name) {
  17795. for (let i = 0, il = this.bones.length; i < il; i++) {
  17796. const bone = this.bones[i];
  17797. if (bone.name === name) {
  17798. return bone;
  17799. }
  17800. }
  17801. return undefined;
  17802. }
  17803. dispose() {
  17804. if (this.boneTexture !== null) {
  17805. this.boneTexture.dispose();
  17806. this.boneTexture = null;
  17807. }
  17808. }
  17809. fromJSON(json, bones) {
  17810. this.uuid = json.uuid;
  17811. for (let i = 0, l = json.bones.length; i < l; i++) {
  17812. const uuid = json.bones[i];
  17813. let bone = bones[uuid];
  17814. if (bone === undefined) {
  17815. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  17816. bone = new Bone();
  17817. }
  17818. this.bones.push(bone);
  17819. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  17820. }
  17821. this.init();
  17822. return this;
  17823. }
  17824. toJSON() {
  17825. const data = {
  17826. metadata: {
  17827. version: 4.5,
  17828. type: 'Skeleton',
  17829. generator: 'Skeleton.toJSON'
  17830. },
  17831. bones: [],
  17832. boneInverses: []
  17833. };
  17834. data.uuid = this.uuid;
  17835. const bones = this.bones;
  17836. const boneInverses = this.boneInverses;
  17837. for (let i = 0, l = bones.length; i < l; i++) {
  17838. const bone = bones[i];
  17839. data.bones.push(bone.uuid);
  17840. const boneInverse = boneInverses[i];
  17841. data.boneInverses.push(boneInverse.toArray());
  17842. }
  17843. return data;
  17844. }
  17845. }
  17846. class InstancedBufferAttribute extends BufferAttribute {
  17847. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17848. if (typeof normalized === 'number') {
  17849. meshPerAttribute = normalized;
  17850. normalized = false;
  17851. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  17852. }
  17853. super(array, itemSize, normalized);
  17854. this.isInstancedBufferAttribute = true;
  17855. this.meshPerAttribute = meshPerAttribute;
  17856. }
  17857. copy(source) {
  17858. super.copy(source);
  17859. this.meshPerAttribute = source.meshPerAttribute;
  17860. return this;
  17861. }
  17862. toJSON() {
  17863. const data = super.toJSON();
  17864. data.meshPerAttribute = this.meshPerAttribute;
  17865. data.isInstancedBufferAttribute = true;
  17866. return data;
  17867. }
  17868. }
  17869. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17870. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17871. const _instanceIntersects = [];
  17872. const _mesh = /*@__PURE__*/new Mesh();
  17873. class InstancedMesh extends Mesh {
  17874. constructor(geometry, material, count) {
  17875. super(geometry, material);
  17876. this.isInstancedMesh = true;
  17877. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17878. this.instanceColor = null;
  17879. this.count = count;
  17880. this.frustumCulled = false;
  17881. }
  17882. copy(source, recursive) {
  17883. super.copy(source, recursive);
  17884. this.instanceMatrix.copy(source.instanceMatrix);
  17885. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17886. this.count = source.count;
  17887. return this;
  17888. }
  17889. getColorAt(index, color) {
  17890. color.fromArray(this.instanceColor.array, index * 3);
  17891. }
  17892. getMatrixAt(index, matrix) {
  17893. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17894. }
  17895. raycast(raycaster, intersects) {
  17896. const matrixWorld = this.matrixWorld;
  17897. const raycastTimes = this.count;
  17898. _mesh.geometry = this.geometry;
  17899. _mesh.material = this.material;
  17900. if (_mesh.material === undefined) return;
  17901. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17902. // calculate the world matrix for each instance
  17903. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17904. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17905. _mesh.matrixWorld = _instanceWorldMatrix;
  17906. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17907. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17908. const intersect = _instanceIntersects[i];
  17909. intersect.instanceId = instanceId;
  17910. intersect.object = this;
  17911. intersects.push(intersect);
  17912. }
  17913. _instanceIntersects.length = 0;
  17914. }
  17915. }
  17916. setColorAt(index, color) {
  17917. if (this.instanceColor === null) {
  17918. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17919. }
  17920. color.toArray(this.instanceColor.array, index * 3);
  17921. }
  17922. setMatrixAt(index, matrix) {
  17923. matrix.toArray(this.instanceMatrix.array, index * 16);
  17924. }
  17925. updateMorphTargets() {}
  17926. dispose() {
  17927. this.dispatchEvent({
  17928. type: 'dispose'
  17929. });
  17930. }
  17931. }
  17932. class LineBasicMaterial extends Material {
  17933. constructor(parameters) {
  17934. super();
  17935. this.isLineBasicMaterial = true;
  17936. this.type = 'LineBasicMaterial';
  17937. this.color = new Color(0xffffff);
  17938. this.linewidth = 1;
  17939. this.linecap = 'round';
  17940. this.linejoin = 'round';
  17941. this.fog = true;
  17942. this.setValues(parameters);
  17943. }
  17944. copy(source) {
  17945. super.copy(source);
  17946. this.color.copy(source.color);
  17947. this.linewidth = source.linewidth;
  17948. this.linecap = source.linecap;
  17949. this.linejoin = source.linejoin;
  17950. this.fog = source.fog;
  17951. return this;
  17952. }
  17953. }
  17954. const _start$1 = /*@__PURE__*/new Vector3();
  17955. const _end$1 = /*@__PURE__*/new Vector3();
  17956. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17957. const _ray$1 = /*@__PURE__*/new Ray();
  17958. const _sphere$1 = /*@__PURE__*/new Sphere();
  17959. class Line extends Object3D {
  17960. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17961. super();
  17962. this.isLine = true;
  17963. this.type = 'Line';
  17964. this.geometry = geometry;
  17965. this.material = material;
  17966. this.updateMorphTargets();
  17967. }
  17968. copy(source, recursive) {
  17969. super.copy(source, recursive);
  17970. this.material = source.material;
  17971. this.geometry = source.geometry;
  17972. return this;
  17973. }
  17974. computeLineDistances() {
  17975. const geometry = this.geometry; // we assume non-indexed geometry
  17976. if (geometry.index === null) {
  17977. const positionAttribute = geometry.attributes.position;
  17978. const lineDistances = [0];
  17979. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  17980. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  17981. _end$1.fromBufferAttribute(positionAttribute, i);
  17982. lineDistances[i] = lineDistances[i - 1];
  17983. lineDistances[i] += _start$1.distanceTo(_end$1);
  17984. }
  17985. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17986. } else {
  17987. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17988. }
  17989. return this;
  17990. }
  17991. raycast(raycaster, intersects) {
  17992. const geometry = this.geometry;
  17993. const matrixWorld = this.matrixWorld;
  17994. const threshold = raycaster.params.Line.threshold;
  17995. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17996. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17997. _sphere$1.copy(geometry.boundingSphere);
  17998. _sphere$1.applyMatrix4(matrixWorld);
  17999. _sphere$1.radius += threshold;
  18000. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  18001. _inverseMatrix$1.copy(matrixWorld).invert();
  18002. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  18003. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18004. const localThresholdSq = localThreshold * localThreshold;
  18005. const vStart = new Vector3();
  18006. const vEnd = new Vector3();
  18007. const interSegment = new Vector3();
  18008. const interRay = new Vector3();
  18009. const step = this.isLineSegments ? 2 : 1;
  18010. const index = geometry.index;
  18011. const attributes = geometry.attributes;
  18012. const positionAttribute = attributes.position;
  18013. if (index !== null) {
  18014. const start = Math.max(0, drawRange.start);
  18015. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18016. for (let i = start, l = end - 1; i < l; i += step) {
  18017. const a = index.getX(i);
  18018. const b = index.getX(i + 1);
  18019. vStart.fromBufferAttribute(positionAttribute, a);
  18020. vEnd.fromBufferAttribute(positionAttribute, b);
  18021. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18022. if (distSq > localThresholdSq) continue;
  18023. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18024. const distance = raycaster.ray.origin.distanceTo(interRay);
  18025. if (distance < raycaster.near || distance > raycaster.far) continue;
  18026. intersects.push({
  18027. distance: distance,
  18028. // What do we want? intersection point on the ray or on the segment??
  18029. // point: raycaster.ray.at( distance ),
  18030. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18031. index: i,
  18032. face: null,
  18033. faceIndex: null,
  18034. object: this
  18035. });
  18036. }
  18037. } else {
  18038. const start = Math.max(0, drawRange.start);
  18039. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18040. for (let i = start, l = end - 1; i < l; i += step) {
  18041. vStart.fromBufferAttribute(positionAttribute, i);
  18042. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  18043. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18044. if (distSq > localThresholdSq) continue;
  18045. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18046. const distance = raycaster.ray.origin.distanceTo(interRay);
  18047. if (distance < raycaster.near || distance > raycaster.far) continue;
  18048. intersects.push({
  18049. distance: distance,
  18050. // What do we want? intersection point on the ray or on the segment??
  18051. // point: raycaster.ray.at( distance ),
  18052. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18053. index: i,
  18054. face: null,
  18055. faceIndex: null,
  18056. object: this
  18057. });
  18058. }
  18059. }
  18060. }
  18061. updateMorphTargets() {
  18062. const geometry = this.geometry;
  18063. const morphAttributes = geometry.morphAttributes;
  18064. const keys = Object.keys(morphAttributes);
  18065. if (keys.length > 0) {
  18066. const morphAttribute = morphAttributes[keys[0]];
  18067. if (morphAttribute !== undefined) {
  18068. this.morphTargetInfluences = [];
  18069. this.morphTargetDictionary = {};
  18070. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18071. const name = morphAttribute[m].name || String(m);
  18072. this.morphTargetInfluences.push(0);
  18073. this.morphTargetDictionary[name] = m;
  18074. }
  18075. }
  18076. }
  18077. }
  18078. }
  18079. const _start = /*@__PURE__*/new Vector3();
  18080. const _end = /*@__PURE__*/new Vector3();
  18081. class LineSegments extends Line {
  18082. constructor(geometry, material) {
  18083. super(geometry, material);
  18084. this.isLineSegments = true;
  18085. this.type = 'LineSegments';
  18086. }
  18087. computeLineDistances() {
  18088. const geometry = this.geometry; // we assume non-indexed geometry
  18089. if (geometry.index === null) {
  18090. const positionAttribute = geometry.attributes.position;
  18091. const lineDistances = [];
  18092. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  18093. _start.fromBufferAttribute(positionAttribute, i);
  18094. _end.fromBufferAttribute(positionAttribute, i + 1);
  18095. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  18096. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  18097. }
  18098. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18099. } else {
  18100. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18101. }
  18102. return this;
  18103. }
  18104. }
  18105. class LineLoop extends Line {
  18106. constructor(geometry, material) {
  18107. super(geometry, material);
  18108. this.isLineLoop = true;
  18109. this.type = 'LineLoop';
  18110. }
  18111. }
  18112. class PointsMaterial extends Material {
  18113. constructor(parameters) {
  18114. super();
  18115. this.isPointsMaterial = true;
  18116. this.type = 'PointsMaterial';
  18117. this.color = new Color(0xffffff);
  18118. this.map = null;
  18119. this.alphaMap = null;
  18120. this.size = 1;
  18121. this.sizeAttenuation = true;
  18122. this.fog = true;
  18123. this.setValues(parameters);
  18124. }
  18125. copy(source) {
  18126. super.copy(source);
  18127. this.color.copy(source.color);
  18128. this.map = source.map;
  18129. this.alphaMap = source.alphaMap;
  18130. this.size = source.size;
  18131. this.sizeAttenuation = source.sizeAttenuation;
  18132. this.fog = source.fog;
  18133. return this;
  18134. }
  18135. }
  18136. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  18137. const _ray = /*@__PURE__*/new Ray();
  18138. const _sphere = /*@__PURE__*/new Sphere();
  18139. const _position$2 = /*@__PURE__*/new Vector3();
  18140. class Points extends Object3D {
  18141. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  18142. super();
  18143. this.isPoints = true;
  18144. this.type = 'Points';
  18145. this.geometry = geometry;
  18146. this.material = material;
  18147. this.updateMorphTargets();
  18148. }
  18149. copy(source, recursive) {
  18150. super.copy(source, recursive);
  18151. this.material = source.material;
  18152. this.geometry = source.geometry;
  18153. return this;
  18154. }
  18155. raycast(raycaster, intersects) {
  18156. const geometry = this.geometry;
  18157. const matrixWorld = this.matrixWorld;
  18158. const threshold = raycaster.params.Points.threshold;
  18159. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  18160. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18161. _sphere.copy(geometry.boundingSphere);
  18162. _sphere.applyMatrix4(matrixWorld);
  18163. _sphere.radius += threshold;
  18164. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  18165. _inverseMatrix.copy(matrixWorld).invert();
  18166. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  18167. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18168. const localThresholdSq = localThreshold * localThreshold;
  18169. const index = geometry.index;
  18170. const attributes = geometry.attributes;
  18171. const positionAttribute = attributes.position;
  18172. if (index !== null) {
  18173. const start = Math.max(0, drawRange.start);
  18174. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18175. for (let i = start, il = end; i < il; i++) {
  18176. const a = index.getX(i);
  18177. _position$2.fromBufferAttribute(positionAttribute, a);
  18178. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18179. }
  18180. } else {
  18181. const start = Math.max(0, drawRange.start);
  18182. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18183. for (let i = start, l = end; i < l; i++) {
  18184. _position$2.fromBufferAttribute(positionAttribute, i);
  18185. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18186. }
  18187. }
  18188. }
  18189. updateMorphTargets() {
  18190. const geometry = this.geometry;
  18191. const morphAttributes = geometry.morphAttributes;
  18192. const keys = Object.keys(morphAttributes);
  18193. if (keys.length > 0) {
  18194. const morphAttribute = morphAttributes[keys[0]];
  18195. if (morphAttribute !== undefined) {
  18196. this.morphTargetInfluences = [];
  18197. this.morphTargetDictionary = {};
  18198. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18199. const name = morphAttribute[m].name || String(m);
  18200. this.morphTargetInfluences.push(0);
  18201. this.morphTargetDictionary[name] = m;
  18202. }
  18203. }
  18204. }
  18205. }
  18206. }
  18207. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  18208. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  18209. if (rayPointDistanceSq < localThresholdSq) {
  18210. const intersectPoint = new Vector3();
  18211. _ray.closestPointToPoint(point, intersectPoint);
  18212. intersectPoint.applyMatrix4(matrixWorld);
  18213. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  18214. if (distance < raycaster.near || distance > raycaster.far) return;
  18215. intersects.push({
  18216. distance: distance,
  18217. distanceToRay: Math.sqrt(rayPointDistanceSq),
  18218. point: intersectPoint,
  18219. index: index,
  18220. face: null,
  18221. object: object
  18222. });
  18223. }
  18224. }
  18225. class VideoTexture extends Texture {
  18226. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18227. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18228. this.isVideoTexture = true;
  18229. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18230. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18231. this.generateMipmaps = false;
  18232. const scope = this;
  18233. function updateVideo() {
  18234. scope.needsUpdate = true;
  18235. video.requestVideoFrameCallback(updateVideo);
  18236. }
  18237. if ('requestVideoFrameCallback' in video) {
  18238. video.requestVideoFrameCallback(updateVideo);
  18239. }
  18240. }
  18241. clone() {
  18242. return new this.constructor(this.image).copy(this);
  18243. }
  18244. update() {
  18245. const video = this.image;
  18246. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  18247. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  18248. this.needsUpdate = true;
  18249. }
  18250. }
  18251. }
  18252. class FramebufferTexture extends Texture {
  18253. constructor(width, height, format) {
  18254. super({
  18255. width,
  18256. height
  18257. });
  18258. this.isFramebufferTexture = true;
  18259. this.format = format;
  18260. this.magFilter = NearestFilter;
  18261. this.minFilter = NearestFilter;
  18262. this.generateMipmaps = false;
  18263. this.needsUpdate = true;
  18264. }
  18265. }
  18266. class CompressedTexture extends Texture {
  18267. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  18268. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18269. this.isCompressedTexture = true;
  18270. this.image = {
  18271. width: width,
  18272. height: height
  18273. };
  18274. this.mipmaps = mipmaps; // no flipping for cube textures
  18275. // (also flipping doesn't work for compressed textures )
  18276. this.flipY = false; // can't generate mipmaps for compressed textures
  18277. // mips must be embedded in DDS files
  18278. this.generateMipmaps = false;
  18279. }
  18280. }
  18281. class CanvasTexture extends Texture {
  18282. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18283. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18284. this.isCanvasTexture = true;
  18285. this.needsUpdate = true;
  18286. }
  18287. }
  18288. /**
  18289. * Extensible curve object.
  18290. *
  18291. * Some common of curve methods:
  18292. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18293. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18294. * .getPoints(), .getSpacedPoints()
  18295. * .getLength()
  18296. * .updateArcLengths()
  18297. *
  18298. * This following curves inherit from THREE.Curve:
  18299. *
  18300. * -- 2D curves --
  18301. * THREE.ArcCurve
  18302. * THREE.CubicBezierCurve
  18303. * THREE.EllipseCurve
  18304. * THREE.LineCurve
  18305. * THREE.QuadraticBezierCurve
  18306. * THREE.SplineCurve
  18307. *
  18308. * -- 3D curves --
  18309. * THREE.CatmullRomCurve3
  18310. * THREE.CubicBezierCurve3
  18311. * THREE.LineCurve3
  18312. * THREE.QuadraticBezierCurve3
  18313. *
  18314. * A series of curves can be represented as a THREE.CurvePath.
  18315. *
  18316. **/
  18317. class Curve {
  18318. constructor() {
  18319. this.type = 'Curve';
  18320. this.arcLengthDivisions = 200;
  18321. } // Virtual base class method to overwrite and implement in subclasses
  18322. // - t [0 .. 1]
  18323. getPoint() {
  18324. console.warn('THREE.Curve: .getPoint() not implemented.');
  18325. return null;
  18326. } // Get point at relative position in curve according to arc length
  18327. // - u [0 .. 1]
  18328. getPointAt(u, optionalTarget) {
  18329. const t = this.getUtoTmapping(u);
  18330. return this.getPoint(t, optionalTarget);
  18331. } // Get sequence of points using getPoint( t )
  18332. getPoints(divisions = 5) {
  18333. const points = [];
  18334. for (let d = 0; d <= divisions; d++) {
  18335. points.push(this.getPoint(d / divisions));
  18336. }
  18337. return points;
  18338. } // Get sequence of points using getPointAt( u )
  18339. getSpacedPoints(divisions = 5) {
  18340. const points = [];
  18341. for (let d = 0; d <= divisions; d++) {
  18342. points.push(this.getPointAt(d / divisions));
  18343. }
  18344. return points;
  18345. } // Get total curve arc length
  18346. getLength() {
  18347. const lengths = this.getLengths();
  18348. return lengths[lengths.length - 1];
  18349. } // Get list of cumulative segment lengths
  18350. getLengths(divisions = this.arcLengthDivisions) {
  18351. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18352. return this.cacheArcLengths;
  18353. }
  18354. this.needsUpdate = false;
  18355. const cache = [];
  18356. let current,
  18357. last = this.getPoint(0);
  18358. let sum = 0;
  18359. cache.push(0);
  18360. for (let p = 1; p <= divisions; p++) {
  18361. current = this.getPoint(p / divisions);
  18362. sum += current.distanceTo(last);
  18363. cache.push(sum);
  18364. last = current;
  18365. }
  18366. this.cacheArcLengths = cache;
  18367. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18368. }
  18369. updateArcLengths() {
  18370. this.needsUpdate = true;
  18371. this.getLengths();
  18372. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18373. getUtoTmapping(u, distance) {
  18374. const arcLengths = this.getLengths();
  18375. let i = 0;
  18376. const il = arcLengths.length;
  18377. let targetArcLength; // The targeted u distance value to get
  18378. if (distance) {
  18379. targetArcLength = distance;
  18380. } else {
  18381. targetArcLength = u * arcLengths[il - 1];
  18382. } // binary search for the index with largest value smaller than target u distance
  18383. let low = 0,
  18384. high = il - 1,
  18385. comparison;
  18386. while (low <= high) {
  18387. 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
  18388. comparison = arcLengths[i] - targetArcLength;
  18389. if (comparison < 0) {
  18390. low = i + 1;
  18391. } else if (comparison > 0) {
  18392. high = i - 1;
  18393. } else {
  18394. high = i;
  18395. break; // DONE
  18396. }
  18397. }
  18398. i = high;
  18399. if (arcLengths[i] === targetArcLength) {
  18400. return i / (il - 1);
  18401. } // we could get finer grain at lengths, or use simple interpolation between two points
  18402. const lengthBefore = arcLengths[i];
  18403. const lengthAfter = arcLengths[i + 1];
  18404. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18405. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18406. const t = (i + segmentFraction) / (il - 1);
  18407. return t;
  18408. } // Returns a unit vector tangent at t
  18409. // In case any sub curve does not implement its tangent derivation,
  18410. // 2 points a small delta apart will be used to find its gradient
  18411. // which seems to give a reasonable approximation
  18412. getTangent(t, optionalTarget) {
  18413. const delta = 0.0001;
  18414. let t1 = t - delta;
  18415. let t2 = t + delta; // Capping in case of danger
  18416. if (t1 < 0) t1 = 0;
  18417. if (t2 > 1) t2 = 1;
  18418. const pt1 = this.getPoint(t1);
  18419. const pt2 = this.getPoint(t2);
  18420. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18421. tangent.copy(pt2).sub(pt1).normalize();
  18422. return tangent;
  18423. }
  18424. getTangentAt(u, optionalTarget) {
  18425. const t = this.getUtoTmapping(u);
  18426. return this.getTangent(t, optionalTarget);
  18427. }
  18428. computeFrenetFrames(segments, closed) {
  18429. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18430. const normal = new Vector3();
  18431. const tangents = [];
  18432. const normals = [];
  18433. const binormals = [];
  18434. const vec = new Vector3();
  18435. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18436. for (let i = 0; i <= segments; i++) {
  18437. const u = i / segments;
  18438. tangents[i] = this.getTangentAt(u, new Vector3());
  18439. } // select an initial normal vector perpendicular to the first tangent vector,
  18440. // and in the direction of the minimum tangent xyz component
  18441. normals[0] = new Vector3();
  18442. binormals[0] = new Vector3();
  18443. let min = Number.MAX_VALUE;
  18444. const tx = Math.abs(tangents[0].x);
  18445. const ty = Math.abs(tangents[0].y);
  18446. const tz = Math.abs(tangents[0].z);
  18447. if (tx <= min) {
  18448. min = tx;
  18449. normal.set(1, 0, 0);
  18450. }
  18451. if (ty <= min) {
  18452. min = ty;
  18453. normal.set(0, 1, 0);
  18454. }
  18455. if (tz <= min) {
  18456. normal.set(0, 0, 1);
  18457. }
  18458. vec.crossVectors(tangents[0], normal).normalize();
  18459. normals[0].crossVectors(tangents[0], vec);
  18460. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18461. for (let i = 1; i <= segments; i++) {
  18462. normals[i] = normals[i - 1].clone();
  18463. binormals[i] = binormals[i - 1].clone();
  18464. vec.crossVectors(tangents[i - 1], tangents[i]);
  18465. if (vec.length() > Number.EPSILON) {
  18466. vec.normalize();
  18467. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18468. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18469. }
  18470. binormals[i].crossVectors(tangents[i], normals[i]);
  18471. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18472. if (closed === true) {
  18473. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18474. theta /= segments;
  18475. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18476. theta = -theta;
  18477. }
  18478. for (let i = 1; i <= segments; i++) {
  18479. // twist a little...
  18480. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18481. binormals[i].crossVectors(tangents[i], normals[i]);
  18482. }
  18483. }
  18484. return {
  18485. tangents: tangents,
  18486. normals: normals,
  18487. binormals: binormals
  18488. };
  18489. }
  18490. clone() {
  18491. return new this.constructor().copy(this);
  18492. }
  18493. copy(source) {
  18494. this.arcLengthDivisions = source.arcLengthDivisions;
  18495. return this;
  18496. }
  18497. toJSON() {
  18498. const data = {
  18499. metadata: {
  18500. version: 4.5,
  18501. type: 'Curve',
  18502. generator: 'Curve.toJSON'
  18503. }
  18504. };
  18505. data.arcLengthDivisions = this.arcLengthDivisions;
  18506. data.type = this.type;
  18507. return data;
  18508. }
  18509. fromJSON(json) {
  18510. this.arcLengthDivisions = json.arcLengthDivisions;
  18511. return this;
  18512. }
  18513. }
  18514. class EllipseCurve extends Curve {
  18515. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18516. super();
  18517. this.isEllipseCurve = true;
  18518. this.type = 'EllipseCurve';
  18519. this.aX = aX;
  18520. this.aY = aY;
  18521. this.xRadius = xRadius;
  18522. this.yRadius = yRadius;
  18523. this.aStartAngle = aStartAngle;
  18524. this.aEndAngle = aEndAngle;
  18525. this.aClockwise = aClockwise;
  18526. this.aRotation = aRotation;
  18527. }
  18528. getPoint(t, optionalTarget) {
  18529. const point = optionalTarget || new Vector2();
  18530. const twoPi = Math.PI * 2;
  18531. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18532. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18533. while (deltaAngle < 0) deltaAngle += twoPi;
  18534. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18535. if (deltaAngle < Number.EPSILON) {
  18536. if (samePoints) {
  18537. deltaAngle = 0;
  18538. } else {
  18539. deltaAngle = twoPi;
  18540. }
  18541. }
  18542. if (this.aClockwise === true && !samePoints) {
  18543. if (deltaAngle === twoPi) {
  18544. deltaAngle = -twoPi;
  18545. } else {
  18546. deltaAngle = deltaAngle - twoPi;
  18547. }
  18548. }
  18549. const angle = this.aStartAngle + t * deltaAngle;
  18550. let x = this.aX + this.xRadius * Math.cos(angle);
  18551. let y = this.aY + this.yRadius * Math.sin(angle);
  18552. if (this.aRotation !== 0) {
  18553. const cos = Math.cos(this.aRotation);
  18554. const sin = Math.sin(this.aRotation);
  18555. const tx = x - this.aX;
  18556. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18557. x = tx * cos - ty * sin + this.aX;
  18558. y = tx * sin + ty * cos + this.aY;
  18559. }
  18560. return point.set(x, y);
  18561. }
  18562. copy(source) {
  18563. super.copy(source);
  18564. this.aX = source.aX;
  18565. this.aY = source.aY;
  18566. this.xRadius = source.xRadius;
  18567. this.yRadius = source.yRadius;
  18568. this.aStartAngle = source.aStartAngle;
  18569. this.aEndAngle = source.aEndAngle;
  18570. this.aClockwise = source.aClockwise;
  18571. this.aRotation = source.aRotation;
  18572. return this;
  18573. }
  18574. toJSON() {
  18575. const data = super.toJSON();
  18576. data.aX = this.aX;
  18577. data.aY = this.aY;
  18578. data.xRadius = this.xRadius;
  18579. data.yRadius = this.yRadius;
  18580. data.aStartAngle = this.aStartAngle;
  18581. data.aEndAngle = this.aEndAngle;
  18582. data.aClockwise = this.aClockwise;
  18583. data.aRotation = this.aRotation;
  18584. return data;
  18585. }
  18586. fromJSON(json) {
  18587. super.fromJSON(json);
  18588. this.aX = json.aX;
  18589. this.aY = json.aY;
  18590. this.xRadius = json.xRadius;
  18591. this.yRadius = json.yRadius;
  18592. this.aStartAngle = json.aStartAngle;
  18593. this.aEndAngle = json.aEndAngle;
  18594. this.aClockwise = json.aClockwise;
  18595. this.aRotation = json.aRotation;
  18596. return this;
  18597. }
  18598. }
  18599. class ArcCurve extends EllipseCurve {
  18600. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18601. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18602. this.isArcCurve = true;
  18603. this.type = 'ArcCurve';
  18604. }
  18605. }
  18606. /**
  18607. * Centripetal CatmullRom Curve - which is useful for avoiding
  18608. * cusps and self-intersections in non-uniform catmull rom curves.
  18609. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18610. *
  18611. * curve.type accepts centripetal(default), chordal and catmullrom
  18612. * curve.tension is used for catmullrom which defaults to 0.5
  18613. */
  18614. /*
  18615. Based on an optimized c++ solution in
  18616. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18617. - http://ideone.com/NoEbVM
  18618. This CubicPoly class could be used for reusing some variables and calculations,
  18619. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18620. which can be placed in CurveUtils.
  18621. */
  18622. function CubicPoly() {
  18623. let c0 = 0,
  18624. c1 = 0,
  18625. c2 = 0,
  18626. c3 = 0;
  18627. /*
  18628. * Compute coefficients for a cubic polynomial
  18629. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18630. * such that
  18631. * p(0) = x0, p(1) = x1
  18632. * and
  18633. * p'(0) = t0, p'(1) = t1.
  18634. */
  18635. function init(x0, x1, t0, t1) {
  18636. c0 = x0;
  18637. c1 = t0;
  18638. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18639. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18640. }
  18641. return {
  18642. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18643. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18644. },
  18645. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18646. // compute tangents when parameterized in [t1,t2]
  18647. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18648. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18649. t1 *= dt1;
  18650. t2 *= dt1;
  18651. init(x1, x2, t1, t2);
  18652. },
  18653. calc: function (t) {
  18654. const t2 = t * t;
  18655. const t3 = t2 * t;
  18656. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18657. }
  18658. };
  18659. } //
  18660. const tmp = /*@__PURE__*/new Vector3();
  18661. const px = /*@__PURE__*/new CubicPoly();
  18662. const py = /*@__PURE__*/new CubicPoly();
  18663. const pz = /*@__PURE__*/new CubicPoly();
  18664. class CatmullRomCurve3 extends Curve {
  18665. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18666. super();
  18667. this.isCatmullRomCurve3 = true;
  18668. this.type = 'CatmullRomCurve3';
  18669. this.points = points;
  18670. this.closed = closed;
  18671. this.curveType = curveType;
  18672. this.tension = tension;
  18673. }
  18674. getPoint(t, optionalTarget = new Vector3()) {
  18675. const point = optionalTarget;
  18676. const points = this.points;
  18677. const l = points.length;
  18678. const p = (l - (this.closed ? 0 : 1)) * t;
  18679. let intPoint = Math.floor(p);
  18680. let weight = p - intPoint;
  18681. if (this.closed) {
  18682. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18683. } else if (weight === 0 && intPoint === l - 1) {
  18684. intPoint = l - 2;
  18685. weight = 1;
  18686. }
  18687. let p0, p3; // 4 points (p1 & p2 defined below)
  18688. if (this.closed || intPoint > 0) {
  18689. p0 = points[(intPoint - 1) % l];
  18690. } else {
  18691. // extrapolate first point
  18692. tmp.subVectors(points[0], points[1]).add(points[0]);
  18693. p0 = tmp;
  18694. }
  18695. const p1 = points[intPoint % l];
  18696. const p2 = points[(intPoint + 1) % l];
  18697. if (this.closed || intPoint + 2 < l) {
  18698. p3 = points[(intPoint + 2) % l];
  18699. } else {
  18700. // extrapolate last point
  18701. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18702. p3 = tmp;
  18703. }
  18704. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18705. // init Centripetal / Chordal Catmull-Rom
  18706. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18707. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18708. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18709. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18710. if (dt1 < 1e-4) dt1 = 1.0;
  18711. if (dt0 < 1e-4) dt0 = dt1;
  18712. if (dt2 < 1e-4) dt2 = dt1;
  18713. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18714. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18715. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18716. } else if (this.curveType === 'catmullrom') {
  18717. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18718. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18719. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18720. }
  18721. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18722. return point;
  18723. }
  18724. copy(source) {
  18725. super.copy(source);
  18726. this.points = [];
  18727. for (let i = 0, l = source.points.length; i < l; i++) {
  18728. const point = source.points[i];
  18729. this.points.push(point.clone());
  18730. }
  18731. this.closed = source.closed;
  18732. this.curveType = source.curveType;
  18733. this.tension = source.tension;
  18734. return this;
  18735. }
  18736. toJSON() {
  18737. const data = super.toJSON();
  18738. data.points = [];
  18739. for (let i = 0, l = this.points.length; i < l; i++) {
  18740. const point = this.points[i];
  18741. data.points.push(point.toArray());
  18742. }
  18743. data.closed = this.closed;
  18744. data.curveType = this.curveType;
  18745. data.tension = this.tension;
  18746. return data;
  18747. }
  18748. fromJSON(json) {
  18749. super.fromJSON(json);
  18750. this.points = [];
  18751. for (let i = 0, l = json.points.length; i < l; i++) {
  18752. const point = json.points[i];
  18753. this.points.push(new Vector3().fromArray(point));
  18754. }
  18755. this.closed = json.closed;
  18756. this.curveType = json.curveType;
  18757. this.tension = json.tension;
  18758. return this;
  18759. }
  18760. }
  18761. /**
  18762. * Bezier Curves formulas obtained from
  18763. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18764. */
  18765. function CatmullRom(t, p0, p1, p2, p3) {
  18766. const v0 = (p2 - p0) * 0.5;
  18767. const v1 = (p3 - p1) * 0.5;
  18768. const t2 = t * t;
  18769. const t3 = t * t2;
  18770. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18771. } //
  18772. function QuadraticBezierP0(t, p) {
  18773. const k = 1 - t;
  18774. return k * k * p;
  18775. }
  18776. function QuadraticBezierP1(t, p) {
  18777. return 2 * (1 - t) * t * p;
  18778. }
  18779. function QuadraticBezierP2(t, p) {
  18780. return t * t * p;
  18781. }
  18782. function QuadraticBezier(t, p0, p1, p2) {
  18783. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18784. } //
  18785. function CubicBezierP0(t, p) {
  18786. const k = 1 - t;
  18787. return k * k * k * p;
  18788. }
  18789. function CubicBezierP1(t, p) {
  18790. const k = 1 - t;
  18791. return 3 * k * k * t * p;
  18792. }
  18793. function CubicBezierP2(t, p) {
  18794. return 3 * (1 - t) * t * t * p;
  18795. }
  18796. function CubicBezierP3(t, p) {
  18797. return t * t * t * p;
  18798. }
  18799. function CubicBezier(t, p0, p1, p2, p3) {
  18800. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18801. }
  18802. class CubicBezierCurve extends Curve {
  18803. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18804. super();
  18805. this.isCubicBezierCurve = true;
  18806. this.type = 'CubicBezierCurve';
  18807. this.v0 = v0;
  18808. this.v1 = v1;
  18809. this.v2 = v2;
  18810. this.v3 = v3;
  18811. }
  18812. getPoint(t, optionalTarget = new Vector2()) {
  18813. const point = optionalTarget;
  18814. const v0 = this.v0,
  18815. v1 = this.v1,
  18816. v2 = this.v2,
  18817. v3 = this.v3;
  18818. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18819. return point;
  18820. }
  18821. copy(source) {
  18822. super.copy(source);
  18823. this.v0.copy(source.v0);
  18824. this.v1.copy(source.v1);
  18825. this.v2.copy(source.v2);
  18826. this.v3.copy(source.v3);
  18827. return this;
  18828. }
  18829. toJSON() {
  18830. const data = super.toJSON();
  18831. data.v0 = this.v0.toArray();
  18832. data.v1 = this.v1.toArray();
  18833. data.v2 = this.v2.toArray();
  18834. data.v3 = this.v3.toArray();
  18835. return data;
  18836. }
  18837. fromJSON(json) {
  18838. super.fromJSON(json);
  18839. this.v0.fromArray(json.v0);
  18840. this.v1.fromArray(json.v1);
  18841. this.v2.fromArray(json.v2);
  18842. this.v3.fromArray(json.v3);
  18843. return this;
  18844. }
  18845. }
  18846. class CubicBezierCurve3 extends Curve {
  18847. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18848. super();
  18849. this.isCubicBezierCurve3 = true;
  18850. this.type = 'CubicBezierCurve3';
  18851. this.v0 = v0;
  18852. this.v1 = v1;
  18853. this.v2 = v2;
  18854. this.v3 = v3;
  18855. }
  18856. getPoint(t, optionalTarget = new Vector3()) {
  18857. const point = optionalTarget;
  18858. const v0 = this.v0,
  18859. v1 = this.v1,
  18860. v2 = this.v2,
  18861. v3 = this.v3;
  18862. 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));
  18863. return point;
  18864. }
  18865. copy(source) {
  18866. super.copy(source);
  18867. this.v0.copy(source.v0);
  18868. this.v1.copy(source.v1);
  18869. this.v2.copy(source.v2);
  18870. this.v3.copy(source.v3);
  18871. return this;
  18872. }
  18873. toJSON() {
  18874. const data = super.toJSON();
  18875. data.v0 = this.v0.toArray();
  18876. data.v1 = this.v1.toArray();
  18877. data.v2 = this.v2.toArray();
  18878. data.v3 = this.v3.toArray();
  18879. return data;
  18880. }
  18881. fromJSON(json) {
  18882. super.fromJSON(json);
  18883. this.v0.fromArray(json.v0);
  18884. this.v1.fromArray(json.v1);
  18885. this.v2.fromArray(json.v2);
  18886. this.v3.fromArray(json.v3);
  18887. return this;
  18888. }
  18889. }
  18890. class LineCurve extends Curve {
  18891. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18892. super();
  18893. this.isLineCurve = true;
  18894. this.type = 'LineCurve';
  18895. this.v1 = v1;
  18896. this.v2 = v2;
  18897. }
  18898. getPoint(t, optionalTarget = new Vector2()) {
  18899. const point = optionalTarget;
  18900. if (t === 1) {
  18901. point.copy(this.v2);
  18902. } else {
  18903. point.copy(this.v2).sub(this.v1);
  18904. point.multiplyScalar(t).add(this.v1);
  18905. }
  18906. return point;
  18907. } // Line curve is linear, so we can overwrite default getPointAt
  18908. getPointAt(u, optionalTarget) {
  18909. return this.getPoint(u, optionalTarget);
  18910. }
  18911. getTangent(t, optionalTarget) {
  18912. const tangent = optionalTarget || new Vector2();
  18913. tangent.copy(this.v2).sub(this.v1).normalize();
  18914. return tangent;
  18915. }
  18916. copy(source) {
  18917. super.copy(source);
  18918. this.v1.copy(source.v1);
  18919. this.v2.copy(source.v2);
  18920. return this;
  18921. }
  18922. toJSON() {
  18923. const data = super.toJSON();
  18924. data.v1 = this.v1.toArray();
  18925. data.v2 = this.v2.toArray();
  18926. return data;
  18927. }
  18928. fromJSON(json) {
  18929. super.fromJSON(json);
  18930. this.v1.fromArray(json.v1);
  18931. this.v2.fromArray(json.v2);
  18932. return this;
  18933. }
  18934. }
  18935. class LineCurve3 extends Curve {
  18936. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  18937. super();
  18938. this.isLineCurve3 = true;
  18939. this.type = 'LineCurve3';
  18940. this.v1 = v1;
  18941. this.v2 = v2;
  18942. }
  18943. getPoint(t, optionalTarget = new Vector3()) {
  18944. const point = optionalTarget;
  18945. if (t === 1) {
  18946. point.copy(this.v2);
  18947. } else {
  18948. point.copy(this.v2).sub(this.v1);
  18949. point.multiplyScalar(t).add(this.v1);
  18950. }
  18951. return point;
  18952. } // Line curve is linear, so we can overwrite default getPointAt
  18953. getPointAt(u, optionalTarget) {
  18954. return this.getPoint(u, optionalTarget);
  18955. }
  18956. copy(source) {
  18957. super.copy(source);
  18958. this.v1.copy(source.v1);
  18959. this.v2.copy(source.v2);
  18960. return this;
  18961. }
  18962. toJSON() {
  18963. const data = super.toJSON();
  18964. data.v1 = this.v1.toArray();
  18965. data.v2 = this.v2.toArray();
  18966. return data;
  18967. }
  18968. fromJSON(json) {
  18969. super.fromJSON(json);
  18970. this.v1.fromArray(json.v1);
  18971. this.v2.fromArray(json.v2);
  18972. return this;
  18973. }
  18974. }
  18975. class QuadraticBezierCurve extends Curve {
  18976. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  18977. super();
  18978. this.isQuadraticBezierCurve = true;
  18979. this.type = 'QuadraticBezierCurve';
  18980. this.v0 = v0;
  18981. this.v1 = v1;
  18982. this.v2 = v2;
  18983. }
  18984. getPoint(t, optionalTarget = new Vector2()) {
  18985. const point = optionalTarget;
  18986. const v0 = this.v0,
  18987. v1 = this.v1,
  18988. v2 = this.v2;
  18989. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  18990. return point;
  18991. }
  18992. copy(source) {
  18993. super.copy(source);
  18994. this.v0.copy(source.v0);
  18995. this.v1.copy(source.v1);
  18996. this.v2.copy(source.v2);
  18997. return this;
  18998. }
  18999. toJSON() {
  19000. const data = super.toJSON();
  19001. data.v0 = this.v0.toArray();
  19002. data.v1 = this.v1.toArray();
  19003. data.v2 = this.v2.toArray();
  19004. return data;
  19005. }
  19006. fromJSON(json) {
  19007. super.fromJSON(json);
  19008. this.v0.fromArray(json.v0);
  19009. this.v1.fromArray(json.v1);
  19010. this.v2.fromArray(json.v2);
  19011. return this;
  19012. }
  19013. }
  19014. class QuadraticBezierCurve3 extends Curve {
  19015. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  19016. super();
  19017. this.isQuadraticBezierCurve3 = true;
  19018. this.type = 'QuadraticBezierCurve3';
  19019. this.v0 = v0;
  19020. this.v1 = v1;
  19021. this.v2 = v2;
  19022. }
  19023. getPoint(t, optionalTarget = new Vector3()) {
  19024. const point = optionalTarget;
  19025. const v0 = this.v0,
  19026. v1 = this.v1,
  19027. v2 = this.v2;
  19028. 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));
  19029. return point;
  19030. }
  19031. copy(source) {
  19032. super.copy(source);
  19033. this.v0.copy(source.v0);
  19034. this.v1.copy(source.v1);
  19035. this.v2.copy(source.v2);
  19036. return this;
  19037. }
  19038. toJSON() {
  19039. const data = super.toJSON();
  19040. data.v0 = this.v0.toArray();
  19041. data.v1 = this.v1.toArray();
  19042. data.v2 = this.v2.toArray();
  19043. return data;
  19044. }
  19045. fromJSON(json) {
  19046. super.fromJSON(json);
  19047. this.v0.fromArray(json.v0);
  19048. this.v1.fromArray(json.v1);
  19049. this.v2.fromArray(json.v2);
  19050. return this;
  19051. }
  19052. }
  19053. class SplineCurve extends Curve {
  19054. constructor(points = []) {
  19055. super();
  19056. this.isSplineCurve = true;
  19057. this.type = 'SplineCurve';
  19058. this.points = points;
  19059. }
  19060. getPoint(t, optionalTarget = new Vector2()) {
  19061. const point = optionalTarget;
  19062. const points = this.points;
  19063. const p = (points.length - 1) * t;
  19064. const intPoint = Math.floor(p);
  19065. const weight = p - intPoint;
  19066. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  19067. const p1 = points[intPoint];
  19068. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  19069. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  19070. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  19071. return point;
  19072. }
  19073. copy(source) {
  19074. super.copy(source);
  19075. this.points = [];
  19076. for (let i = 0, l = source.points.length; i < l; i++) {
  19077. const point = source.points[i];
  19078. this.points.push(point.clone());
  19079. }
  19080. return this;
  19081. }
  19082. toJSON() {
  19083. const data = super.toJSON();
  19084. data.points = [];
  19085. for (let i = 0, l = this.points.length; i < l; i++) {
  19086. const point = this.points[i];
  19087. data.points.push(point.toArray());
  19088. }
  19089. return data;
  19090. }
  19091. fromJSON(json) {
  19092. super.fromJSON(json);
  19093. this.points = [];
  19094. for (let i = 0, l = json.points.length; i < l; i++) {
  19095. const point = json.points[i];
  19096. this.points.push(new Vector2().fromArray(point));
  19097. }
  19098. return this;
  19099. }
  19100. }
  19101. var Curves = /*#__PURE__*/Object.freeze({
  19102. __proto__: null,
  19103. ArcCurve: ArcCurve,
  19104. CatmullRomCurve3: CatmullRomCurve3,
  19105. CubicBezierCurve: CubicBezierCurve,
  19106. CubicBezierCurve3: CubicBezierCurve3,
  19107. EllipseCurve: EllipseCurve,
  19108. LineCurve: LineCurve,
  19109. LineCurve3: LineCurve3,
  19110. QuadraticBezierCurve: QuadraticBezierCurve,
  19111. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19112. SplineCurve: SplineCurve
  19113. });
  19114. /**************************************************************
  19115. * Curved Path - a curve path is simply a array of connected
  19116. * curves, but retains the api of a curve
  19117. **************************************************************/
  19118. class CurvePath extends Curve {
  19119. constructor() {
  19120. super();
  19121. this.type = 'CurvePath';
  19122. this.curves = [];
  19123. this.autoClose = false; // Automatically closes the path
  19124. }
  19125. add(curve) {
  19126. this.curves.push(curve);
  19127. }
  19128. closePath() {
  19129. // Add a line curve if start and end of lines are not connected
  19130. const startPoint = this.curves[0].getPoint(0);
  19131. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  19132. if (!startPoint.equals(endPoint)) {
  19133. this.curves.push(new LineCurve(endPoint, startPoint));
  19134. }
  19135. } // To get accurate point with reference to
  19136. // entire path distance at time t,
  19137. // following has to be done:
  19138. // 1. Length of each sub path have to be known
  19139. // 2. Locate and identify type of curve
  19140. // 3. Get t for the curve
  19141. // 4. Return curve.getPointAt(t')
  19142. getPoint(t, optionalTarget) {
  19143. const d = t * this.getLength();
  19144. const curveLengths = this.getCurveLengths();
  19145. let i = 0; // To think about boundaries points.
  19146. while (i < curveLengths.length) {
  19147. if (curveLengths[i] >= d) {
  19148. const diff = curveLengths[i] - d;
  19149. const curve = this.curves[i];
  19150. const segmentLength = curve.getLength();
  19151. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19152. return curve.getPointAt(u, optionalTarget);
  19153. }
  19154. i++;
  19155. }
  19156. return null; // loop where sum != 0, sum > d , sum+1 <d
  19157. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19158. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19159. // getPoint() depends on getLength
  19160. getLength() {
  19161. const lens = this.getCurveLengths();
  19162. return lens[lens.length - 1];
  19163. } // cacheLengths must be recalculated.
  19164. updateArcLengths() {
  19165. this.needsUpdate = true;
  19166. this.cacheLengths = null;
  19167. this.getCurveLengths();
  19168. } // Compute lengths and cache them
  19169. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19170. getCurveLengths() {
  19171. // We use cache values if curves and cache array are same length
  19172. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  19173. return this.cacheLengths;
  19174. } // Get length of sub-curve
  19175. // Push sums into cached array
  19176. const lengths = [];
  19177. let sums = 0;
  19178. for (let i = 0, l = this.curves.length; i < l; i++) {
  19179. sums += this.curves[i].getLength();
  19180. lengths.push(sums);
  19181. }
  19182. this.cacheLengths = lengths;
  19183. return lengths;
  19184. }
  19185. getSpacedPoints(divisions = 40) {
  19186. const points = [];
  19187. for (let i = 0; i <= divisions; i++) {
  19188. points.push(this.getPoint(i / divisions));
  19189. }
  19190. if (this.autoClose) {
  19191. points.push(points[0]);
  19192. }
  19193. return points;
  19194. }
  19195. getPoints(divisions = 12) {
  19196. const points = [];
  19197. let last;
  19198. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19199. const curve = curves[i];
  19200. const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19201. const pts = curve.getPoints(resolution);
  19202. for (let j = 0; j < pts.length; j++) {
  19203. const point = pts[j];
  19204. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19205. points.push(point);
  19206. last = point;
  19207. }
  19208. }
  19209. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19210. points.push(points[0]);
  19211. }
  19212. return points;
  19213. }
  19214. copy(source) {
  19215. super.copy(source);
  19216. this.curves = [];
  19217. for (let i = 0, l = source.curves.length; i < l; i++) {
  19218. const curve = source.curves[i];
  19219. this.curves.push(curve.clone());
  19220. }
  19221. this.autoClose = source.autoClose;
  19222. return this;
  19223. }
  19224. toJSON() {
  19225. const data = super.toJSON();
  19226. data.autoClose = this.autoClose;
  19227. data.curves = [];
  19228. for (let i = 0, l = this.curves.length; i < l; i++) {
  19229. const curve = this.curves[i];
  19230. data.curves.push(curve.toJSON());
  19231. }
  19232. return data;
  19233. }
  19234. fromJSON(json) {
  19235. super.fromJSON(json);
  19236. this.autoClose = json.autoClose;
  19237. this.curves = [];
  19238. for (let i = 0, l = json.curves.length; i < l; i++) {
  19239. const curve = json.curves[i];
  19240. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19241. }
  19242. return this;
  19243. }
  19244. }
  19245. class Path extends CurvePath {
  19246. constructor(points) {
  19247. super();
  19248. this.type = 'Path';
  19249. this.currentPoint = new Vector2();
  19250. if (points) {
  19251. this.setFromPoints(points);
  19252. }
  19253. }
  19254. setFromPoints(points) {
  19255. this.moveTo(points[0].x, points[0].y);
  19256. for (let i = 1, l = points.length; i < l; i++) {
  19257. this.lineTo(points[i].x, points[i].y);
  19258. }
  19259. return this;
  19260. }
  19261. moveTo(x, y) {
  19262. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19263. return this;
  19264. }
  19265. lineTo(x, y) {
  19266. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19267. this.curves.push(curve);
  19268. this.currentPoint.set(x, y);
  19269. return this;
  19270. }
  19271. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19272. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19273. this.curves.push(curve);
  19274. this.currentPoint.set(aX, aY);
  19275. return this;
  19276. }
  19277. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19278. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19279. this.curves.push(curve);
  19280. this.currentPoint.set(aX, aY);
  19281. return this;
  19282. }
  19283. splineThru(pts
  19284. /*Array of Vector*/
  19285. ) {
  19286. const npts = [this.currentPoint.clone()].concat(pts);
  19287. const curve = new SplineCurve(npts);
  19288. this.curves.push(curve);
  19289. this.currentPoint.copy(pts[pts.length - 1]);
  19290. return this;
  19291. }
  19292. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19293. const x0 = this.currentPoint.x;
  19294. const y0 = this.currentPoint.y;
  19295. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19296. return this;
  19297. }
  19298. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19299. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19300. return this;
  19301. }
  19302. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19303. const x0 = this.currentPoint.x;
  19304. const y0 = this.currentPoint.y;
  19305. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19306. return this;
  19307. }
  19308. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19309. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19310. if (this.curves.length > 0) {
  19311. // if a previous curve is present, attempt to join
  19312. const firstPoint = curve.getPoint(0);
  19313. if (!firstPoint.equals(this.currentPoint)) {
  19314. this.lineTo(firstPoint.x, firstPoint.y);
  19315. }
  19316. }
  19317. this.curves.push(curve);
  19318. const lastPoint = curve.getPoint(1);
  19319. this.currentPoint.copy(lastPoint);
  19320. return this;
  19321. }
  19322. copy(source) {
  19323. super.copy(source);
  19324. this.currentPoint.copy(source.currentPoint);
  19325. return this;
  19326. }
  19327. toJSON() {
  19328. const data = super.toJSON();
  19329. data.currentPoint = this.currentPoint.toArray();
  19330. return data;
  19331. }
  19332. fromJSON(json) {
  19333. super.fromJSON(json);
  19334. this.currentPoint.fromArray(json.currentPoint);
  19335. return this;
  19336. }
  19337. }
  19338. class LatheGeometry extends BufferGeometry {
  19339. 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) {
  19340. super();
  19341. this.type = 'LatheGeometry';
  19342. this.parameters = {
  19343. points: points,
  19344. segments: segments,
  19345. phiStart: phiStart,
  19346. phiLength: phiLength
  19347. };
  19348. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19349. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  19350. const indices = [];
  19351. const vertices = [];
  19352. const uvs = [];
  19353. const initNormals = [];
  19354. const normals = []; // helper variables
  19355. const inverseSegments = 1.0 / segments;
  19356. const vertex = new Vector3();
  19357. const uv = new Vector2();
  19358. const normal = new Vector3();
  19359. const curNormal = new Vector3();
  19360. const prevNormal = new Vector3();
  19361. let dx = 0;
  19362. let dy = 0; // pre-compute normals for initial "meridian"
  19363. for (let j = 0; j <= points.length - 1; j++) {
  19364. switch (j) {
  19365. case 0:
  19366. // special handling for 1st vertex on path
  19367. dx = points[j + 1].x - points[j].x;
  19368. dy = points[j + 1].y - points[j].y;
  19369. normal.x = dy * 1.0;
  19370. normal.y = -dx;
  19371. normal.z = dy * 0.0;
  19372. prevNormal.copy(normal);
  19373. normal.normalize();
  19374. initNormals.push(normal.x, normal.y, normal.z);
  19375. break;
  19376. case points.length - 1:
  19377. // special handling for last Vertex on path
  19378. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  19379. break;
  19380. default:
  19381. // default handling for all vertices in between
  19382. dx = points[j + 1].x - points[j].x;
  19383. dy = points[j + 1].y - points[j].y;
  19384. normal.x = dy * 1.0;
  19385. normal.y = -dx;
  19386. normal.z = dy * 0.0;
  19387. curNormal.copy(normal);
  19388. normal.x += prevNormal.x;
  19389. normal.y += prevNormal.y;
  19390. normal.z += prevNormal.z;
  19391. normal.normalize();
  19392. initNormals.push(normal.x, normal.y, normal.z);
  19393. prevNormal.copy(curNormal);
  19394. }
  19395. } // generate vertices, uvs and normals
  19396. for (let i = 0; i <= segments; i++) {
  19397. const phi = phiStart + i * inverseSegments * phiLength;
  19398. const sin = Math.sin(phi);
  19399. const cos = Math.cos(phi);
  19400. for (let j = 0; j <= points.length - 1; j++) {
  19401. // vertex
  19402. vertex.x = points[j].x * sin;
  19403. vertex.y = points[j].y;
  19404. vertex.z = points[j].x * cos;
  19405. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19406. uv.x = i / segments;
  19407. uv.y = j / (points.length - 1);
  19408. uvs.push(uv.x, uv.y); // normal
  19409. const x = initNormals[3 * j + 0] * sin;
  19410. const y = initNormals[3 * j + 1];
  19411. const z = initNormals[3 * j + 0] * cos;
  19412. normals.push(x, y, z);
  19413. }
  19414. } // indices
  19415. for (let i = 0; i < segments; i++) {
  19416. for (let j = 0; j < points.length - 1; j++) {
  19417. const base = j + i * points.length;
  19418. const a = base;
  19419. const b = base + points.length;
  19420. const c = base + points.length + 1;
  19421. const d = base + 1; // faces
  19422. indices.push(a, b, d);
  19423. indices.push(c, d, b);
  19424. }
  19425. } // build geometry
  19426. this.setIndex(indices);
  19427. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19428. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19429. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19430. }
  19431. static fromJSON(data) {
  19432. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  19433. }
  19434. }
  19435. class CapsuleGeometry extends LatheGeometry {
  19436. constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) {
  19437. const path = new Path();
  19438. path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0);
  19439. path.absarc(0, length / 2, radius, 0, Math.PI * 0.5);
  19440. super(path.getPoints(capSegments), radialSegments);
  19441. this.type = 'CapsuleGeometry';
  19442. this.parameters = {
  19443. radius: radius,
  19444. height: length,
  19445. capSegments: capSegments,
  19446. radialSegments: radialSegments
  19447. };
  19448. }
  19449. static fromJSON(data) {
  19450. return new CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments);
  19451. }
  19452. }
  19453. class CircleGeometry extends BufferGeometry {
  19454. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  19455. super();
  19456. this.type = 'CircleGeometry';
  19457. this.parameters = {
  19458. radius: radius,
  19459. segments: segments,
  19460. thetaStart: thetaStart,
  19461. thetaLength: thetaLength
  19462. };
  19463. segments = Math.max(3, segments); // buffers
  19464. const indices = [];
  19465. const vertices = [];
  19466. const normals = [];
  19467. const uvs = []; // helper variables
  19468. const vertex = new Vector3();
  19469. const uv = new Vector2(); // center point
  19470. vertices.push(0, 0, 0);
  19471. normals.push(0, 0, 1);
  19472. uvs.push(0.5, 0.5);
  19473. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  19474. const segment = thetaStart + s / segments * thetaLength; // vertex
  19475. vertex.x = radius * Math.cos(segment);
  19476. vertex.y = radius * Math.sin(segment);
  19477. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19478. normals.push(0, 0, 1); // uvs
  19479. uv.x = (vertices[i] / radius + 1) / 2;
  19480. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19481. uvs.push(uv.x, uv.y);
  19482. } // indices
  19483. for (let i = 1; i <= segments; i++) {
  19484. indices.push(i, i + 1, 0);
  19485. } // build geometry
  19486. this.setIndex(indices);
  19487. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19488. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19489. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19490. }
  19491. static fromJSON(data) {
  19492. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  19493. }
  19494. }
  19495. class CylinderGeometry extends BufferGeometry {
  19496. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19497. super();
  19498. this.type = 'CylinderGeometry';
  19499. this.parameters = {
  19500. radiusTop: radiusTop,
  19501. radiusBottom: radiusBottom,
  19502. height: height,
  19503. radialSegments: radialSegments,
  19504. heightSegments: heightSegments,
  19505. openEnded: openEnded,
  19506. thetaStart: thetaStart,
  19507. thetaLength: thetaLength
  19508. };
  19509. const scope = this;
  19510. radialSegments = Math.floor(radialSegments);
  19511. heightSegments = Math.floor(heightSegments); // buffers
  19512. const indices = [];
  19513. const vertices = [];
  19514. const normals = [];
  19515. const uvs = []; // helper variables
  19516. let index = 0;
  19517. const indexArray = [];
  19518. const halfHeight = height / 2;
  19519. let groupStart = 0; // generate geometry
  19520. generateTorso();
  19521. if (openEnded === false) {
  19522. if (radiusTop > 0) generateCap(true);
  19523. if (radiusBottom > 0) generateCap(false);
  19524. } // build geometry
  19525. this.setIndex(indices);
  19526. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19527. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19528. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19529. function generateTorso() {
  19530. const normal = new Vector3();
  19531. const vertex = new Vector3();
  19532. let groupCount = 0; // this will be used to calculate the normal
  19533. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19534. for (let y = 0; y <= heightSegments; y++) {
  19535. const indexRow = [];
  19536. const v = y / heightSegments; // calculate the radius of the current row
  19537. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  19538. for (let x = 0; x <= radialSegments; x++) {
  19539. const u = x / radialSegments;
  19540. const theta = u * thetaLength + thetaStart;
  19541. const sinTheta = Math.sin(theta);
  19542. const cosTheta = Math.cos(theta); // vertex
  19543. vertex.x = radius * sinTheta;
  19544. vertex.y = -v * height + halfHeight;
  19545. vertex.z = radius * cosTheta;
  19546. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19547. normal.set(sinTheta, slope, cosTheta).normalize();
  19548. normals.push(normal.x, normal.y, normal.z); // uv
  19549. uvs.push(u, 1 - v); // save index of vertex in respective row
  19550. indexRow.push(index++);
  19551. } // now save vertices of the row in our index array
  19552. indexArray.push(indexRow);
  19553. } // generate indices
  19554. for (let x = 0; x < radialSegments; x++) {
  19555. for (let y = 0; y < heightSegments; y++) {
  19556. // we use the index array to access the correct indices
  19557. const a = indexArray[y][x];
  19558. const b = indexArray[y + 1][x];
  19559. const c = indexArray[y + 1][x + 1];
  19560. const d = indexArray[y][x + 1]; // faces
  19561. indices.push(a, b, d);
  19562. indices.push(b, c, d); // update group counter
  19563. groupCount += 6;
  19564. }
  19565. } // add a group to the geometry. this will ensure multi material support
  19566. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19567. groupStart += groupCount;
  19568. }
  19569. function generateCap(top) {
  19570. // save the index of the first center vertex
  19571. const centerIndexStart = index;
  19572. const uv = new Vector2();
  19573. const vertex = new Vector3();
  19574. let groupCount = 0;
  19575. const radius = top === true ? radiusTop : radiusBottom;
  19576. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  19577. // because the geometry needs one set of uvs per face,
  19578. // we must generate a center vertex per face/segment
  19579. for (let x = 1; x <= radialSegments; x++) {
  19580. // vertex
  19581. vertices.push(0, halfHeight * sign, 0); // normal
  19582. normals.push(0, sign, 0); // uv
  19583. uvs.push(0.5, 0.5); // increase index
  19584. index++;
  19585. } // save the index of the last center vertex
  19586. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19587. for (let x = 0; x <= radialSegments; x++) {
  19588. const u = x / radialSegments;
  19589. const theta = u * thetaLength + thetaStart;
  19590. const cosTheta = Math.cos(theta);
  19591. const sinTheta = Math.sin(theta); // vertex
  19592. vertex.x = radius * sinTheta;
  19593. vertex.y = halfHeight * sign;
  19594. vertex.z = radius * cosTheta;
  19595. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19596. normals.push(0, sign, 0); // uv
  19597. uv.x = cosTheta * 0.5 + 0.5;
  19598. uv.y = sinTheta * 0.5 * sign + 0.5;
  19599. uvs.push(uv.x, uv.y); // increase index
  19600. index++;
  19601. } // generate indices
  19602. for (let x = 0; x < radialSegments; x++) {
  19603. const c = centerIndexStart + x;
  19604. const i = centerIndexEnd + x;
  19605. if (top === true) {
  19606. // face top
  19607. indices.push(i, i + 1, c);
  19608. } else {
  19609. // face bottom
  19610. indices.push(i + 1, i, c);
  19611. }
  19612. groupCount += 3;
  19613. } // add a group to the geometry. this will ensure multi material support
  19614. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19615. groupStart += groupCount;
  19616. }
  19617. }
  19618. static fromJSON(data) {
  19619. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19620. }
  19621. }
  19622. class ConeGeometry extends CylinderGeometry {
  19623. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19624. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19625. this.type = 'ConeGeometry';
  19626. this.parameters = {
  19627. radius: radius,
  19628. height: height,
  19629. radialSegments: radialSegments,
  19630. heightSegments: heightSegments,
  19631. openEnded: openEnded,
  19632. thetaStart: thetaStart,
  19633. thetaLength: thetaLength
  19634. };
  19635. }
  19636. static fromJSON(data) {
  19637. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19638. }
  19639. }
  19640. class PolyhedronGeometry extends BufferGeometry {
  19641. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  19642. super();
  19643. this.type = 'PolyhedronGeometry';
  19644. this.parameters = {
  19645. vertices: vertices,
  19646. indices: indices,
  19647. radius: radius,
  19648. detail: detail
  19649. }; // default buffer data
  19650. const vertexBuffer = [];
  19651. const uvBuffer = []; // the subdivision creates the vertex buffer data
  19652. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  19653. applyRadius(radius); // finally, create the uv data
  19654. generateUVs(); // build non-indexed geometry
  19655. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  19656. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  19657. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  19658. if (detail === 0) {
  19659. this.computeVertexNormals(); // flat normals
  19660. } else {
  19661. this.normalizeNormals(); // smooth normals
  19662. } // helper functions
  19663. function subdivide(detail) {
  19664. const a = new Vector3();
  19665. const b = new Vector3();
  19666. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  19667. for (let i = 0; i < indices.length; i += 3) {
  19668. // get the vertices of the face
  19669. getVertexByIndex(indices[i + 0], a);
  19670. getVertexByIndex(indices[i + 1], b);
  19671. getVertexByIndex(indices[i + 2], c); // perform subdivision
  19672. subdivideFace(a, b, c, detail);
  19673. }
  19674. }
  19675. function subdivideFace(a, b, c, detail) {
  19676. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  19677. const v = []; // construct all of the vertices for this subdivision
  19678. for (let i = 0; i <= cols; i++) {
  19679. v[i] = [];
  19680. const aj = a.clone().lerp(c, i / cols);
  19681. const bj = b.clone().lerp(c, i / cols);
  19682. const rows = cols - i;
  19683. for (let j = 0; j <= rows; j++) {
  19684. if (j === 0 && i === cols) {
  19685. v[i][j] = aj;
  19686. } else {
  19687. v[i][j] = aj.clone().lerp(bj, j / rows);
  19688. }
  19689. }
  19690. } // construct all of the faces
  19691. for (let i = 0; i < cols; i++) {
  19692. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  19693. const k = Math.floor(j / 2);
  19694. if (j % 2 === 0) {
  19695. pushVertex(v[i][k + 1]);
  19696. pushVertex(v[i + 1][k]);
  19697. pushVertex(v[i][k]);
  19698. } else {
  19699. pushVertex(v[i][k + 1]);
  19700. pushVertex(v[i + 1][k + 1]);
  19701. pushVertex(v[i + 1][k]);
  19702. }
  19703. }
  19704. }
  19705. }
  19706. function applyRadius(radius) {
  19707. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  19708. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19709. vertex.x = vertexBuffer[i + 0];
  19710. vertex.y = vertexBuffer[i + 1];
  19711. vertex.z = vertexBuffer[i + 2];
  19712. vertex.normalize().multiplyScalar(radius);
  19713. vertexBuffer[i + 0] = vertex.x;
  19714. vertexBuffer[i + 1] = vertex.y;
  19715. vertexBuffer[i + 2] = vertex.z;
  19716. }
  19717. }
  19718. function generateUVs() {
  19719. const vertex = new Vector3();
  19720. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19721. vertex.x = vertexBuffer[i + 0];
  19722. vertex.y = vertexBuffer[i + 1];
  19723. vertex.z = vertexBuffer[i + 2];
  19724. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  19725. const v = inclination(vertex) / Math.PI + 0.5;
  19726. uvBuffer.push(u, 1 - v);
  19727. }
  19728. correctUVs();
  19729. correctSeam();
  19730. }
  19731. function correctSeam() {
  19732. // handle case when face straddles the seam, see #3269
  19733. for (let i = 0; i < uvBuffer.length; i += 6) {
  19734. // uv data of a single face
  19735. const x0 = uvBuffer[i + 0];
  19736. const x1 = uvBuffer[i + 2];
  19737. const x2 = uvBuffer[i + 4];
  19738. const max = Math.max(x0, x1, x2);
  19739. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  19740. if (max > 0.9 && min < 0.1) {
  19741. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  19742. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  19743. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  19744. }
  19745. }
  19746. }
  19747. function pushVertex(vertex) {
  19748. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  19749. }
  19750. function getVertexByIndex(index, vertex) {
  19751. const stride = index * 3;
  19752. vertex.x = vertices[stride + 0];
  19753. vertex.y = vertices[stride + 1];
  19754. vertex.z = vertices[stride + 2];
  19755. }
  19756. function correctUVs() {
  19757. const a = new Vector3();
  19758. const b = new Vector3();
  19759. const c = new Vector3();
  19760. const centroid = new Vector3();
  19761. const uvA = new Vector2();
  19762. const uvB = new Vector2();
  19763. const uvC = new Vector2();
  19764. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  19765. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  19766. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  19767. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  19768. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  19769. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  19770. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  19771. centroid.copy(a).add(b).add(c).divideScalar(3);
  19772. const azi = azimuth(centroid);
  19773. correctUV(uvA, j + 0, a, azi);
  19774. correctUV(uvB, j + 2, b, azi);
  19775. correctUV(uvC, j + 4, c, azi);
  19776. }
  19777. }
  19778. function correctUV(uv, stride, vector, azimuth) {
  19779. if (azimuth < 0 && uv.x === 1) {
  19780. uvBuffer[stride] = uv.x - 1;
  19781. }
  19782. if (vector.x === 0 && vector.z === 0) {
  19783. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  19784. }
  19785. } // Angle around the Y axis, counter-clockwise when looking from above.
  19786. function azimuth(vector) {
  19787. return Math.atan2(vector.z, -vector.x);
  19788. } // Angle above the XZ plane.
  19789. function inclination(vector) {
  19790. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  19791. }
  19792. }
  19793. static fromJSON(data) {
  19794. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  19795. }
  19796. }
  19797. class DodecahedronGeometry extends PolyhedronGeometry {
  19798. constructor(radius = 1, detail = 0) {
  19799. const t = (1 + Math.sqrt(5)) / 2;
  19800. const r = 1 / t;
  19801. const vertices = [// (±1, ±1, ±1)
  19802. -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/φ, ±φ)
  19803. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  19804. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  19805. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  19806. 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];
  19807. super(vertices, indices, radius, detail);
  19808. this.type = 'DodecahedronGeometry';
  19809. this.parameters = {
  19810. radius: radius,
  19811. detail: detail
  19812. };
  19813. }
  19814. static fromJSON(data) {
  19815. return new DodecahedronGeometry(data.radius, data.detail);
  19816. }
  19817. }
  19818. const _v0 = /*@__PURE__*/new Vector3();
  19819. const _v1$1 = /*@__PURE__*/new Vector3();
  19820. const _normal = /*@__PURE__*/new Vector3();
  19821. const _triangle = /*@__PURE__*/new Triangle();
  19822. class EdgesGeometry extends BufferGeometry {
  19823. constructor(geometry = null, thresholdAngle = 1) {
  19824. super();
  19825. this.type = 'EdgesGeometry';
  19826. this.parameters = {
  19827. geometry: geometry,
  19828. thresholdAngle: thresholdAngle
  19829. };
  19830. if (geometry !== null) {
  19831. const precisionPoints = 4;
  19832. const precision = Math.pow(10, precisionPoints);
  19833. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  19834. const indexAttr = geometry.getIndex();
  19835. const positionAttr = geometry.getAttribute('position');
  19836. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  19837. const indexArr = [0, 0, 0];
  19838. const vertKeys = ['a', 'b', 'c'];
  19839. const hashes = new Array(3);
  19840. const edgeData = {};
  19841. const vertices = [];
  19842. for (let i = 0; i < indexCount; i += 3) {
  19843. if (indexAttr) {
  19844. indexArr[0] = indexAttr.getX(i);
  19845. indexArr[1] = indexAttr.getX(i + 1);
  19846. indexArr[2] = indexAttr.getX(i + 2);
  19847. } else {
  19848. indexArr[0] = i;
  19849. indexArr[1] = i + 1;
  19850. indexArr[2] = i + 2;
  19851. }
  19852. const {
  19853. a,
  19854. b,
  19855. c
  19856. } = _triangle;
  19857. a.fromBufferAttribute(positionAttr, indexArr[0]);
  19858. b.fromBufferAttribute(positionAttr, indexArr[1]);
  19859. c.fromBufferAttribute(positionAttr, indexArr[2]);
  19860. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  19861. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  19862. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  19863. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  19864. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  19865. continue;
  19866. } // iterate over every edge
  19867. for (let j = 0; j < 3; j++) {
  19868. // get the first and next vertex making up the edge
  19869. const jNext = (j + 1) % 3;
  19870. const vecHash0 = hashes[j];
  19871. const vecHash1 = hashes[jNext];
  19872. const v0 = _triangle[vertKeys[j]];
  19873. const v1 = _triangle[vertKeys[jNext]];
  19874. const hash = `${vecHash0}_${vecHash1}`;
  19875. const reverseHash = `${vecHash1}_${vecHash0}`;
  19876. if (reverseHash in edgeData && edgeData[reverseHash]) {
  19877. // if we found a sibling edge add it into the vertex array if
  19878. // it meets the angle threshold and delete the edge from the map.
  19879. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  19880. vertices.push(v0.x, v0.y, v0.z);
  19881. vertices.push(v1.x, v1.y, v1.z);
  19882. }
  19883. edgeData[reverseHash] = null;
  19884. } else if (!(hash in edgeData)) {
  19885. // if we've already got an edge here then skip adding a new one
  19886. edgeData[hash] = {
  19887. index0: indexArr[j],
  19888. index1: indexArr[jNext],
  19889. normal: _normal.clone()
  19890. };
  19891. }
  19892. }
  19893. } // iterate over all remaining, unmatched edges and add them to the vertex array
  19894. for (const key in edgeData) {
  19895. if (edgeData[key]) {
  19896. const {
  19897. index0,
  19898. index1
  19899. } = edgeData[key];
  19900. _v0.fromBufferAttribute(positionAttr, index0);
  19901. _v1$1.fromBufferAttribute(positionAttr, index1);
  19902. vertices.push(_v0.x, _v0.y, _v0.z);
  19903. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  19904. }
  19905. }
  19906. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19907. }
  19908. }
  19909. }
  19910. class Shape extends Path {
  19911. constructor(points) {
  19912. super(points);
  19913. this.uuid = generateUUID();
  19914. this.type = 'Shape';
  19915. this.holes = [];
  19916. }
  19917. getPointsHoles(divisions) {
  19918. const holesPts = [];
  19919. for (let i = 0, l = this.holes.length; i < l; i++) {
  19920. holesPts[i] = this.holes[i].getPoints(divisions);
  19921. }
  19922. return holesPts;
  19923. } // get points of shape and holes (keypoints based on segments parameter)
  19924. extractPoints(divisions) {
  19925. return {
  19926. shape: this.getPoints(divisions),
  19927. holes: this.getPointsHoles(divisions)
  19928. };
  19929. }
  19930. copy(source) {
  19931. super.copy(source);
  19932. this.holes = [];
  19933. for (let i = 0, l = source.holes.length; i < l; i++) {
  19934. const hole = source.holes[i];
  19935. this.holes.push(hole.clone());
  19936. }
  19937. return this;
  19938. }
  19939. toJSON() {
  19940. const data = super.toJSON();
  19941. data.uuid = this.uuid;
  19942. data.holes = [];
  19943. for (let i = 0, l = this.holes.length; i < l; i++) {
  19944. const hole = this.holes[i];
  19945. data.holes.push(hole.toJSON());
  19946. }
  19947. return data;
  19948. }
  19949. fromJSON(json) {
  19950. super.fromJSON(json);
  19951. this.uuid = json.uuid;
  19952. this.holes = [];
  19953. for (let i = 0, l = json.holes.length; i < l; i++) {
  19954. const hole = json.holes[i];
  19955. this.holes.push(new Path().fromJSON(hole));
  19956. }
  19957. return this;
  19958. }
  19959. }
  19960. /**
  19961. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19962. */
  19963. const Earcut = {
  19964. triangulate: function (data, holeIndices, dim = 2) {
  19965. const hasHoles = holeIndices && holeIndices.length;
  19966. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  19967. let outerNode = linkedList(data, 0, outerLen, dim, true);
  19968. const triangles = [];
  19969. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  19970. let minX, minY, maxX, maxY, x, y, invSize;
  19971. 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
  19972. if (data.length > 80 * dim) {
  19973. minX = maxX = data[0];
  19974. minY = maxY = data[1];
  19975. for (let i = dim; i < outerLen; i += dim) {
  19976. x = data[i];
  19977. y = data[i + 1];
  19978. if (x < minX) minX = x;
  19979. if (y < minY) minY = y;
  19980. if (x > maxX) maxX = x;
  19981. if (y > maxY) maxY = y;
  19982. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19983. invSize = Math.max(maxX - minX, maxY - minY);
  19984. invSize = invSize !== 0 ? 1 / invSize : 0;
  19985. }
  19986. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  19987. return triangles;
  19988. }
  19989. }; // create a circular doubly linked list from polygon points in the specified winding order
  19990. function linkedList(data, start, end, dim, clockwise) {
  19991. let i, last;
  19992. if (clockwise === signedArea(data, start, end, dim) > 0) {
  19993. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  19994. } else {
  19995. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  19996. }
  19997. if (last && equals(last, last.next)) {
  19998. removeNode(last);
  19999. last = last.next;
  20000. }
  20001. return last;
  20002. } // eliminate colinear or duplicate points
  20003. function filterPoints(start, end) {
  20004. if (!start) return start;
  20005. if (!end) end = start;
  20006. let p = start,
  20007. again;
  20008. do {
  20009. again = false;
  20010. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  20011. removeNode(p);
  20012. p = end = p.prev;
  20013. if (p === p.next) break;
  20014. again = true;
  20015. } else {
  20016. p = p.next;
  20017. }
  20018. } while (again || p !== end);
  20019. return end;
  20020. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  20021. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  20022. if (!ear) return; // interlink polygon nodes in z-order
  20023. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  20024. let stop = ear,
  20025. prev,
  20026. next; // iterate through ears, slicing them one by one
  20027. while (ear.prev !== ear.next) {
  20028. prev = ear.prev;
  20029. next = ear.next;
  20030. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  20031. // cut off the triangle
  20032. triangles.push(prev.i / dim);
  20033. triangles.push(ear.i / dim);
  20034. triangles.push(next.i / dim);
  20035. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  20036. ear = next.next;
  20037. stop = next.next;
  20038. continue;
  20039. }
  20040. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  20041. if (ear === stop) {
  20042. // try filtering points and slicing again
  20043. if (!pass) {
  20044. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  20045. } else if (pass === 1) {
  20046. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  20047. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  20048. } else if (pass === 2) {
  20049. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  20050. }
  20051. break;
  20052. }
  20053. }
  20054. } // check whether a polygon node forms a valid ear with adjacent nodes
  20055. function isEar(ear) {
  20056. const a = ear.prev,
  20057. b = ear,
  20058. c = ear.next;
  20059. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20060. // now make sure we don't have other points inside the potential ear
  20061. let p = ear.next.next;
  20062. while (p !== ear.prev) {
  20063. 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;
  20064. p = p.next;
  20065. }
  20066. return true;
  20067. }
  20068. function isEarHashed(ear, minX, minY, invSize) {
  20069. const a = ear.prev,
  20070. b = ear,
  20071. c = ear.next;
  20072. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20073. // triangle bbox; min & max are calculated like this for speed
  20074. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  20075. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  20076. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  20077. 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;
  20078. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  20079. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  20080. let p = ear.prevZ,
  20081. n = ear.nextZ; // look for points inside the triangle in both directions
  20082. while (p && p.z >= minZ && n && n.z <= maxZ) {
  20083. 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;
  20084. p = p.prevZ;
  20085. 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;
  20086. n = n.nextZ;
  20087. } // look for remaining points in decreasing z-order
  20088. while (p && p.z >= minZ) {
  20089. 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;
  20090. p = p.prevZ;
  20091. } // look for remaining points in increasing z-order
  20092. while (n && n.z <= maxZ) {
  20093. 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;
  20094. n = n.nextZ;
  20095. }
  20096. return true;
  20097. } // go through all polygon nodes and cure small local self-intersections
  20098. function cureLocalIntersections(start, triangles, dim) {
  20099. let p = start;
  20100. do {
  20101. const a = p.prev,
  20102. b = p.next.next;
  20103. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  20104. triangles.push(a.i / dim);
  20105. triangles.push(p.i / dim);
  20106. triangles.push(b.i / dim); // remove two nodes involved
  20107. removeNode(p);
  20108. removeNode(p.next);
  20109. p = start = b;
  20110. }
  20111. p = p.next;
  20112. } while (p !== start);
  20113. return filterPoints(p);
  20114. } // try splitting polygon into two and triangulate them independently
  20115. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  20116. // look for a valid diagonal that divides the polygon into two
  20117. let a = start;
  20118. do {
  20119. let b = a.next.next;
  20120. while (b !== a.prev) {
  20121. if (a.i !== b.i && isValidDiagonal(a, b)) {
  20122. // split the polygon in two by the diagonal
  20123. let c = splitPolygon(a, b); // filter colinear points around the cuts
  20124. a = filterPoints(a, a.next);
  20125. c = filterPoints(c, c.next); // run earcut on each half
  20126. earcutLinked(a, triangles, dim, minX, minY, invSize);
  20127. earcutLinked(c, triangles, dim, minX, minY, invSize);
  20128. return;
  20129. }
  20130. b = b.next;
  20131. }
  20132. a = a.next;
  20133. } while (a !== start);
  20134. } // link every hole into the outer loop, producing a single-ring polygon without holes
  20135. function eliminateHoles(data, holeIndices, outerNode, dim) {
  20136. const queue = [];
  20137. let i, len, start, end, list;
  20138. for (i = 0, len = holeIndices.length; i < len; i++) {
  20139. start = holeIndices[i] * dim;
  20140. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  20141. list = linkedList(data, start, end, dim, false);
  20142. if (list === list.next) list.steiner = true;
  20143. queue.push(getLeftmost(list));
  20144. }
  20145. queue.sort(compareX); // process holes from left to right
  20146. for (i = 0; i < queue.length; i++) {
  20147. eliminateHole(queue[i], outerNode);
  20148. outerNode = filterPoints(outerNode, outerNode.next);
  20149. }
  20150. return outerNode;
  20151. }
  20152. function compareX(a, b) {
  20153. return a.x - b.x;
  20154. } // find a bridge between vertices that connects hole with an outer ring and link it
  20155. function eliminateHole(hole, outerNode) {
  20156. outerNode = findHoleBridge(hole, outerNode);
  20157. if (outerNode) {
  20158. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  20159. filterPoints(outerNode, outerNode.next);
  20160. filterPoints(b, b.next);
  20161. }
  20162. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20163. function findHoleBridge(hole, outerNode) {
  20164. let p = outerNode;
  20165. const hx = hole.x;
  20166. const hy = hole.y;
  20167. let qx = -Infinity,
  20168. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  20169. // segment's endpoint with lesser x will be potential connection point
  20170. do {
  20171. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  20172. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  20173. if (x <= hx && x > qx) {
  20174. qx = x;
  20175. if (x === hx) {
  20176. if (hy === p.y) return p;
  20177. if (hy === p.next.y) return p.next;
  20178. }
  20179. m = p.x < p.next.x ? p : p.next;
  20180. }
  20181. }
  20182. p = p.next;
  20183. } while (p !== outerNode);
  20184. if (!m) return null;
  20185. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  20186. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20187. // if there are no points found, we have a valid connection;
  20188. // otherwise choose the point of the minimum angle with the ray as connection point
  20189. const stop = m,
  20190. mx = m.x,
  20191. my = m.y;
  20192. let tanMin = Infinity,
  20193. tan;
  20194. p = m;
  20195. do {
  20196. 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)) {
  20197. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  20198. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  20199. m = p;
  20200. tanMin = tan;
  20201. }
  20202. }
  20203. p = p.next;
  20204. } while (p !== stop);
  20205. return m;
  20206. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  20207. function sectorContainsSector(m, p) {
  20208. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  20209. } // interlink polygon nodes in z-order
  20210. function indexCurve(start, minX, minY, invSize) {
  20211. let p = start;
  20212. do {
  20213. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  20214. p.prevZ = p.prev;
  20215. p.nextZ = p.next;
  20216. p = p.next;
  20217. } while (p !== start);
  20218. p.prevZ.nextZ = null;
  20219. p.prevZ = null;
  20220. sortLinked(p);
  20221. } // Simon Tatham's linked list merge sort algorithm
  20222. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20223. function sortLinked(list) {
  20224. let i,
  20225. p,
  20226. q,
  20227. e,
  20228. tail,
  20229. numMerges,
  20230. pSize,
  20231. qSize,
  20232. inSize = 1;
  20233. do {
  20234. p = list;
  20235. list = null;
  20236. tail = null;
  20237. numMerges = 0;
  20238. while (p) {
  20239. numMerges++;
  20240. q = p;
  20241. pSize = 0;
  20242. for (i = 0; i < inSize; i++) {
  20243. pSize++;
  20244. q = q.nextZ;
  20245. if (!q) break;
  20246. }
  20247. qSize = inSize;
  20248. while (pSize > 0 || qSize > 0 && q) {
  20249. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  20250. e = p;
  20251. p = p.nextZ;
  20252. pSize--;
  20253. } else {
  20254. e = q;
  20255. q = q.nextZ;
  20256. qSize--;
  20257. }
  20258. if (tail) tail.nextZ = e;else list = e;
  20259. e.prevZ = tail;
  20260. tail = e;
  20261. }
  20262. p = q;
  20263. }
  20264. tail.nextZ = null;
  20265. inSize *= 2;
  20266. } while (numMerges > 1);
  20267. return list;
  20268. } // z-order of a point given coords and inverse of the longer side of data bbox
  20269. function zOrder(x, y, minX, minY, invSize) {
  20270. // coords are transformed into non-negative 15-bit integer range
  20271. x = 32767 * (x - minX) * invSize;
  20272. y = 32767 * (y - minY) * invSize;
  20273. x = (x | x << 8) & 0x00FF00FF;
  20274. x = (x | x << 4) & 0x0F0F0F0F;
  20275. x = (x | x << 2) & 0x33333333;
  20276. x = (x | x << 1) & 0x55555555;
  20277. y = (y | y << 8) & 0x00FF00FF;
  20278. y = (y | y << 4) & 0x0F0F0F0F;
  20279. y = (y | y << 2) & 0x33333333;
  20280. y = (y | y << 1) & 0x55555555;
  20281. return x | y << 1;
  20282. } // find the leftmost node of a polygon ring
  20283. function getLeftmost(start) {
  20284. let p = start,
  20285. leftmost = start;
  20286. do {
  20287. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  20288. p = p.next;
  20289. } while (p !== start);
  20290. return leftmost;
  20291. } // check if a point lies within a convex triangle
  20292. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  20293. 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;
  20294. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20295. function isValidDiagonal(a, b) {
  20296. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // doesn't intersect other edges
  20297. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  20298. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  20299. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  20300. } // signed area of a triangle
  20301. function area(p, q, r) {
  20302. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  20303. } // check if two points are equal
  20304. function equals(p1, p2) {
  20305. return p1.x === p2.x && p1.y === p2.y;
  20306. } // check if two segments intersect
  20307. function intersects(p1, q1, p2, q2) {
  20308. const o1 = sign(area(p1, q1, p2));
  20309. const o2 = sign(area(p1, q1, q2));
  20310. const o3 = sign(area(p2, q2, p1));
  20311. const o4 = sign(area(p2, q2, q1));
  20312. if (o1 !== o2 && o3 !== o4) return true; // general case
  20313. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20314. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20315. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20316. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20317. return false;
  20318. } // for collinear points p, q, r, check if point q lies on segment pr
  20319. function onSegment(p, q, r) {
  20320. 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);
  20321. }
  20322. function sign(num) {
  20323. return num > 0 ? 1 : num < 0 ? -1 : 0;
  20324. } // check if a polygon diagonal intersects any polygon segments
  20325. function intersectsPolygon(a, b) {
  20326. let p = a;
  20327. do {
  20328. 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;
  20329. p = p.next;
  20330. } while (p !== a);
  20331. return false;
  20332. } // check if a polygon diagonal is locally inside the polygon
  20333. function locallyInside(a, b) {
  20334. 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;
  20335. } // check if the middle point of a polygon diagonal is inside the polygon
  20336. function middleInside(a, b) {
  20337. let p = a,
  20338. inside = false;
  20339. const px = (a.x + b.x) / 2,
  20340. py = (a.y + b.y) / 2;
  20341. do {
  20342. 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;
  20343. p = p.next;
  20344. } while (p !== a);
  20345. return inside;
  20346. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20347. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20348. function splitPolygon(a, b) {
  20349. const a2 = new Node(a.i, a.x, a.y),
  20350. b2 = new Node(b.i, b.x, b.y),
  20351. an = a.next,
  20352. bp = b.prev;
  20353. a.next = b;
  20354. b.prev = a;
  20355. a2.next = an;
  20356. an.prev = a2;
  20357. b2.next = a2;
  20358. a2.prev = b2;
  20359. bp.next = b2;
  20360. b2.prev = bp;
  20361. return b2;
  20362. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  20363. function insertNode(i, x, y, last) {
  20364. const p = new Node(i, x, y);
  20365. if (!last) {
  20366. p.prev = p;
  20367. p.next = p;
  20368. } else {
  20369. p.next = last.next;
  20370. p.prev = last;
  20371. last.next.prev = p;
  20372. last.next = p;
  20373. }
  20374. return p;
  20375. }
  20376. function removeNode(p) {
  20377. p.next.prev = p.prev;
  20378. p.prev.next = p.next;
  20379. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  20380. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  20381. }
  20382. function Node(i, x, y) {
  20383. // vertex index in coordinates array
  20384. this.i = i; // vertex coordinates
  20385. this.x = x;
  20386. this.y = y; // previous and next vertex nodes in a polygon ring
  20387. this.prev = null;
  20388. this.next = null; // z-order curve value
  20389. this.z = null; // previous and next nodes in z-order
  20390. this.prevZ = null;
  20391. this.nextZ = null; // indicates whether this is a steiner point
  20392. this.steiner = false;
  20393. }
  20394. function signedArea(data, start, end, dim) {
  20395. let sum = 0;
  20396. for (let i = start, j = end - dim; i < end; i += dim) {
  20397. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  20398. j = i;
  20399. }
  20400. return sum;
  20401. }
  20402. class ShapeUtils {
  20403. // calculate area of the contour polygon
  20404. static area(contour) {
  20405. const n = contour.length;
  20406. let a = 0.0;
  20407. for (let p = n - 1, q = 0; q < n; p = q++) {
  20408. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  20409. }
  20410. return a * 0.5;
  20411. }
  20412. static isClockWise(pts) {
  20413. return ShapeUtils.area(pts) < 0;
  20414. }
  20415. static triangulateShape(contour, holes) {
  20416. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20417. const holeIndices = []; // array of hole indices
  20418. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20419. removeDupEndPts(contour);
  20420. addContour(vertices, contour); //
  20421. let holeIndex = contour.length;
  20422. holes.forEach(removeDupEndPts);
  20423. for (let i = 0; i < holes.length; i++) {
  20424. holeIndices.push(holeIndex);
  20425. holeIndex += holes[i].length;
  20426. addContour(vertices, holes[i]);
  20427. } //
  20428. const triangles = Earcut.triangulate(vertices, holeIndices); //
  20429. for (let i = 0; i < triangles.length; i += 3) {
  20430. faces.push(triangles.slice(i, i + 3));
  20431. }
  20432. return faces;
  20433. }
  20434. }
  20435. function removeDupEndPts(points) {
  20436. const l = points.length;
  20437. if (l > 2 && points[l - 1].equals(points[0])) {
  20438. points.pop();
  20439. }
  20440. }
  20441. function addContour(vertices, contour) {
  20442. for (let i = 0; i < contour.length; i++) {
  20443. vertices.push(contour[i].x);
  20444. vertices.push(contour[i].y);
  20445. }
  20446. }
  20447. /**
  20448. * Creates extruded geometry from a path shape.
  20449. *
  20450. * parameters = {
  20451. *
  20452. * curveSegments: <int>, // number of points on the curves
  20453. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20454. * depth: <float>, // Depth to extrude the shape
  20455. *
  20456. * bevelEnabled: <bool>, // turn on bevel
  20457. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20458. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20459. * bevelOffset: <float>, // how far from shape outline does bevel start
  20460. * bevelSegments: <int>, // number of bevel layers
  20461. *
  20462. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20463. *
  20464. * UVGenerator: <Object> // object that provides UV generator functions
  20465. *
  20466. * }
  20467. */
  20468. class ExtrudeGeometry extends BufferGeometry {
  20469. 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 = {}) {
  20470. super();
  20471. this.type = 'ExtrudeGeometry';
  20472. this.parameters = {
  20473. shapes: shapes,
  20474. options: options
  20475. };
  20476. shapes = Array.isArray(shapes) ? shapes : [shapes];
  20477. const scope = this;
  20478. const verticesArray = [];
  20479. const uvArray = [];
  20480. for (let i = 0, l = shapes.length; i < l; i++) {
  20481. const shape = shapes[i];
  20482. addShape(shape);
  20483. } // build geometry
  20484. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  20485. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  20486. this.computeVertexNormals(); // functions
  20487. function addShape(shape) {
  20488. const placeholder = []; // options
  20489. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20490. const steps = options.steps !== undefined ? options.steps : 1;
  20491. const depth = options.depth !== undefined ? options.depth : 1;
  20492. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20493. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20494. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20495. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20496. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20497. const extrudePath = options.extrudePath;
  20498. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; //
  20499. let extrudePts,
  20500. extrudeByPath = false;
  20501. let splineTube, binormal, normal, position2;
  20502. if (extrudePath) {
  20503. extrudePts = extrudePath.getSpacedPoints(steps);
  20504. extrudeByPath = true;
  20505. bevelEnabled = false; // bevels not supported for path extrusion
  20506. // SETUP TNB variables
  20507. // TODO1 - have a .isClosed in spline?
  20508. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20509. binormal = new Vector3();
  20510. normal = new Vector3();
  20511. position2 = new Vector3();
  20512. } // Safeguards if bevels are not enabled
  20513. if (!bevelEnabled) {
  20514. bevelSegments = 0;
  20515. bevelThickness = 0;
  20516. bevelSize = 0;
  20517. bevelOffset = 0;
  20518. } // Variables initialization
  20519. const shapePoints = shape.extractPoints(curveSegments);
  20520. let vertices = shapePoints.shape;
  20521. const holes = shapePoints.holes;
  20522. const reverse = !ShapeUtils.isClockWise(vertices);
  20523. if (reverse) {
  20524. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20525. for (let h = 0, hl = holes.length; h < hl; h++) {
  20526. const ahole = holes[h];
  20527. if (ShapeUtils.isClockWise(ahole)) {
  20528. holes[h] = ahole.reverse();
  20529. }
  20530. }
  20531. }
  20532. const faces = ShapeUtils.triangulateShape(vertices, holes);
  20533. /* Vertices */
  20534. const contour = vertices; // vertices has all points but contour has only points of circumference
  20535. for (let h = 0, hl = holes.length; h < hl; h++) {
  20536. const ahole = holes[h];
  20537. vertices = vertices.concat(ahole);
  20538. }
  20539. function scalePt2(pt, vec, size) {
  20540. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  20541. return vec.clone().multiplyScalar(size).add(pt);
  20542. }
  20543. const vlen = vertices.length,
  20544. flen = faces.length; // Find directions for point movement
  20545. function getBevelVec(inPt, inPrev, inNext) {
  20546. // computes for inPt the corresponding point inPt' on a new contour
  20547. // shifted by 1 unit (length of normalized vector) to the left
  20548. // if we walk along contour clockwise, this new contour is outside the old one
  20549. //
  20550. // inPt' is the intersection of the two lines parallel to the two
  20551. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20552. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20553. // good reading for geometry algorithms (here: line-line intersection)
  20554. // http://geomalgorithms.com/a05-_intersect-1.html
  20555. const v_prev_x = inPt.x - inPrev.x,
  20556. v_prev_y = inPt.y - inPrev.y;
  20557. const v_next_x = inNext.x - inPt.x,
  20558. v_next_y = inNext.y - inPt.y;
  20559. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  20560. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  20561. if (Math.abs(collinear0) > Number.EPSILON) {
  20562. // not collinear
  20563. // length of vectors for normalizing
  20564. const v_prev_len = Math.sqrt(v_prev_lensq);
  20565. 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
  20566. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  20567. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  20568. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  20569. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  20570. 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
  20571. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  20572. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  20573. // but prevent crazy spikes
  20574. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  20575. if (v_trans_lensq <= 2) {
  20576. return new Vector2(v_trans_x, v_trans_y);
  20577. } else {
  20578. shrink_by = Math.sqrt(v_trans_lensq / 2);
  20579. }
  20580. } else {
  20581. // handle special case of collinear edges
  20582. let direction_eq = false; // assumes: opposite
  20583. if (v_prev_x > Number.EPSILON) {
  20584. if (v_next_x > Number.EPSILON) {
  20585. direction_eq = true;
  20586. }
  20587. } else {
  20588. if (v_prev_x < -Number.EPSILON) {
  20589. if (v_next_x < -Number.EPSILON) {
  20590. direction_eq = true;
  20591. }
  20592. } else {
  20593. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  20594. direction_eq = true;
  20595. }
  20596. }
  20597. }
  20598. if (direction_eq) {
  20599. // console.log("Warning: lines are a straight sequence");
  20600. v_trans_x = -v_prev_y;
  20601. v_trans_y = v_prev_x;
  20602. shrink_by = Math.sqrt(v_prev_lensq);
  20603. } else {
  20604. // console.log("Warning: lines are a straight spike");
  20605. v_trans_x = v_prev_x;
  20606. v_trans_y = v_prev_y;
  20607. shrink_by = Math.sqrt(v_prev_lensq / 2);
  20608. }
  20609. }
  20610. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  20611. }
  20612. const contourMovements = [];
  20613. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20614. if (j === il) j = 0;
  20615. if (k === il) k = 0; // (j)---(i)---(k)
  20616. // console.log('i,j,k', i, j , k)
  20617. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  20618. }
  20619. const holesMovements = [];
  20620. let oneHoleMovements,
  20621. verticesMovements = contourMovements.concat();
  20622. for (let h = 0, hl = holes.length; h < hl; h++) {
  20623. const ahole = holes[h];
  20624. oneHoleMovements = [];
  20625. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20626. if (j === il) j = 0;
  20627. if (k === il) k = 0; // (j)---(i)---(k)
  20628. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  20629. }
  20630. holesMovements.push(oneHoleMovements);
  20631. verticesMovements = verticesMovements.concat(oneHoleMovements);
  20632. } // Loop bevelSegments, 1 for the front, 1 for the back
  20633. for (let b = 0; b < bevelSegments; b++) {
  20634. //for ( b = bevelSegments; b > 0; b -- ) {
  20635. const t = b / bevelSegments;
  20636. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20637. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20638. for (let i = 0, il = contour.length; i < il; i++) {
  20639. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20640. v(vert.x, vert.y, -z);
  20641. } // expand holes
  20642. for (let h = 0, hl = holes.length; h < hl; h++) {
  20643. const ahole = holes[h];
  20644. oneHoleMovements = holesMovements[h];
  20645. for (let i = 0, il = ahole.length; i < il; i++) {
  20646. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20647. v(vert.x, vert.y, -z);
  20648. }
  20649. }
  20650. }
  20651. const bs = bevelSize + bevelOffset; // Back facing vertices
  20652. for (let i = 0; i < vlen; i++) {
  20653. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20654. if (!extrudeByPath) {
  20655. v(vert.x, vert.y, 0);
  20656. } else {
  20657. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20658. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  20659. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  20660. position2.copy(extrudePts[0]).add(normal).add(binormal);
  20661. v(position2.x, position2.y, position2.z);
  20662. }
  20663. } // Add stepped vertices...
  20664. // Including front facing vertices
  20665. for (let s = 1; s <= steps; s++) {
  20666. for (let i = 0; i < vlen; i++) {
  20667. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20668. if (!extrudeByPath) {
  20669. v(vert.x, vert.y, depth / steps * s);
  20670. } else {
  20671. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20672. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  20673. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  20674. position2.copy(extrudePts[s]).add(normal).add(binormal);
  20675. v(position2.x, position2.y, position2.z);
  20676. }
  20677. }
  20678. } // Add bevel segments planes
  20679. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20680. for (let b = bevelSegments - 1; b >= 0; b--) {
  20681. const t = b / bevelSegments;
  20682. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20683. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20684. for (let i = 0, il = contour.length; i < il; i++) {
  20685. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20686. v(vert.x, vert.y, depth + z);
  20687. } // expand holes
  20688. for (let h = 0, hl = holes.length; h < hl; h++) {
  20689. const ahole = holes[h];
  20690. oneHoleMovements = holesMovements[h];
  20691. for (let i = 0, il = ahole.length; i < il; i++) {
  20692. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20693. if (!extrudeByPath) {
  20694. v(vert.x, vert.y, depth + z);
  20695. } else {
  20696. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  20697. }
  20698. }
  20699. }
  20700. }
  20701. /* Faces */
  20702. // Top and bottom faces
  20703. buildLidFaces(); // Sides faces
  20704. buildSideFaces(); ///// Internal functions
  20705. function buildLidFaces() {
  20706. const start = verticesArray.length / 3;
  20707. if (bevelEnabled) {
  20708. let layer = 0; // steps + 1
  20709. let offset = vlen * layer; // Bottom faces
  20710. for (let i = 0; i < flen; i++) {
  20711. const face = faces[i];
  20712. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  20713. }
  20714. layer = steps + bevelSegments * 2;
  20715. offset = vlen * layer; // Top faces
  20716. for (let i = 0; i < flen; i++) {
  20717. const face = faces[i];
  20718. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  20719. }
  20720. } else {
  20721. // Bottom faces
  20722. for (let i = 0; i < flen; i++) {
  20723. const face = faces[i];
  20724. f3(face[2], face[1], face[0]);
  20725. } // Top faces
  20726. for (let i = 0; i < flen; i++) {
  20727. const face = faces[i];
  20728. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  20729. }
  20730. }
  20731. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  20732. } // Create faces for the z-sides of the shape
  20733. function buildSideFaces() {
  20734. const start = verticesArray.length / 3;
  20735. let layeroffset = 0;
  20736. sidewalls(contour, layeroffset);
  20737. layeroffset += contour.length;
  20738. for (let h = 0, hl = holes.length; h < hl; h++) {
  20739. const ahole = holes[h];
  20740. sidewalls(ahole, layeroffset); //, true
  20741. layeroffset += ahole.length;
  20742. }
  20743. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  20744. }
  20745. function sidewalls(contour, layeroffset) {
  20746. let i = contour.length;
  20747. while (--i >= 0) {
  20748. const j = i;
  20749. let k = i - 1;
  20750. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  20751. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  20752. const slen1 = vlen * s;
  20753. const slen2 = vlen * (s + 1);
  20754. const a = layeroffset + j + slen1,
  20755. b = layeroffset + k + slen1,
  20756. c = layeroffset + k + slen2,
  20757. d = layeroffset + j + slen2;
  20758. f4(a, b, c, d);
  20759. }
  20760. }
  20761. }
  20762. function v(x, y, z) {
  20763. placeholder.push(x);
  20764. placeholder.push(y);
  20765. placeholder.push(z);
  20766. }
  20767. function f3(a, b, c) {
  20768. addVertex(a);
  20769. addVertex(b);
  20770. addVertex(c);
  20771. const nextIndex = verticesArray.length / 3;
  20772. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20773. addUV(uvs[0]);
  20774. addUV(uvs[1]);
  20775. addUV(uvs[2]);
  20776. }
  20777. function f4(a, b, c, d) {
  20778. addVertex(a);
  20779. addVertex(b);
  20780. addVertex(d);
  20781. addVertex(b);
  20782. addVertex(c);
  20783. addVertex(d);
  20784. const nextIndex = verticesArray.length / 3;
  20785. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20786. addUV(uvs[0]);
  20787. addUV(uvs[1]);
  20788. addUV(uvs[3]);
  20789. addUV(uvs[1]);
  20790. addUV(uvs[2]);
  20791. addUV(uvs[3]);
  20792. }
  20793. function addVertex(index) {
  20794. verticesArray.push(placeholder[index * 3 + 0]);
  20795. verticesArray.push(placeholder[index * 3 + 1]);
  20796. verticesArray.push(placeholder[index * 3 + 2]);
  20797. }
  20798. function addUV(vector2) {
  20799. uvArray.push(vector2.x);
  20800. uvArray.push(vector2.y);
  20801. }
  20802. }
  20803. }
  20804. toJSON() {
  20805. const data = super.toJSON();
  20806. const shapes = this.parameters.shapes;
  20807. const options = this.parameters.options;
  20808. return toJSON$1(shapes, options, data);
  20809. }
  20810. static fromJSON(data, shapes) {
  20811. const geometryShapes = [];
  20812. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20813. const shape = shapes[data.shapes[j]];
  20814. geometryShapes.push(shape);
  20815. }
  20816. const extrudePath = data.options.extrudePath;
  20817. if (extrudePath !== undefined) {
  20818. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  20819. }
  20820. return new ExtrudeGeometry(geometryShapes, data.options);
  20821. }
  20822. }
  20823. const WorldUVGenerator = {
  20824. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  20825. const a_x = vertices[indexA * 3];
  20826. const a_y = vertices[indexA * 3 + 1];
  20827. const b_x = vertices[indexB * 3];
  20828. const b_y = vertices[indexB * 3 + 1];
  20829. const c_x = vertices[indexC * 3];
  20830. const c_y = vertices[indexC * 3 + 1];
  20831. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  20832. },
  20833. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  20834. const a_x = vertices[indexA * 3];
  20835. const a_y = vertices[indexA * 3 + 1];
  20836. const a_z = vertices[indexA * 3 + 2];
  20837. const b_x = vertices[indexB * 3];
  20838. const b_y = vertices[indexB * 3 + 1];
  20839. const b_z = vertices[indexB * 3 + 2];
  20840. const c_x = vertices[indexC * 3];
  20841. const c_y = vertices[indexC * 3 + 1];
  20842. const c_z = vertices[indexC * 3 + 2];
  20843. const d_x = vertices[indexD * 3];
  20844. const d_y = vertices[indexD * 3 + 1];
  20845. const d_z = vertices[indexD * 3 + 2];
  20846. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  20847. 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)];
  20848. } else {
  20849. 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)];
  20850. }
  20851. }
  20852. };
  20853. function toJSON$1(shapes, options, data) {
  20854. data.shapes = [];
  20855. if (Array.isArray(shapes)) {
  20856. for (let i = 0, l = shapes.length; i < l; i++) {
  20857. const shape = shapes[i];
  20858. data.shapes.push(shape.uuid);
  20859. }
  20860. } else {
  20861. data.shapes.push(shapes.uuid);
  20862. }
  20863. data.options = Object.assign({}, options);
  20864. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  20865. return data;
  20866. }
  20867. class IcosahedronGeometry extends PolyhedronGeometry {
  20868. constructor(radius = 1, detail = 0) {
  20869. const t = (1 + Math.sqrt(5)) / 2;
  20870. 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];
  20871. 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];
  20872. super(vertices, indices, radius, detail);
  20873. this.type = 'IcosahedronGeometry';
  20874. this.parameters = {
  20875. radius: radius,
  20876. detail: detail
  20877. };
  20878. }
  20879. static fromJSON(data) {
  20880. return new IcosahedronGeometry(data.radius, data.detail);
  20881. }
  20882. }
  20883. class OctahedronGeometry extends PolyhedronGeometry {
  20884. constructor(radius = 1, detail = 0) {
  20885. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  20886. 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];
  20887. super(vertices, indices, radius, detail);
  20888. this.type = 'OctahedronGeometry';
  20889. this.parameters = {
  20890. radius: radius,
  20891. detail: detail
  20892. };
  20893. }
  20894. static fromJSON(data) {
  20895. return new OctahedronGeometry(data.radius, data.detail);
  20896. }
  20897. }
  20898. class RingGeometry extends BufferGeometry {
  20899. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  20900. super();
  20901. this.type = 'RingGeometry';
  20902. this.parameters = {
  20903. innerRadius: innerRadius,
  20904. outerRadius: outerRadius,
  20905. thetaSegments: thetaSegments,
  20906. phiSegments: phiSegments,
  20907. thetaStart: thetaStart,
  20908. thetaLength: thetaLength
  20909. };
  20910. thetaSegments = Math.max(3, thetaSegments);
  20911. phiSegments = Math.max(1, phiSegments); // buffers
  20912. const indices = [];
  20913. const vertices = [];
  20914. const normals = [];
  20915. const uvs = []; // some helper variables
  20916. let radius = innerRadius;
  20917. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  20918. const vertex = new Vector3();
  20919. const uv = new Vector2(); // generate vertices, normals and uvs
  20920. for (let j = 0; j <= phiSegments; j++) {
  20921. for (let i = 0; i <= thetaSegments; i++) {
  20922. // values are generate from the inside of the ring to the outside
  20923. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  20924. vertex.x = radius * Math.cos(segment);
  20925. vertex.y = radius * Math.sin(segment);
  20926. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20927. normals.push(0, 0, 1); // uv
  20928. uv.x = (vertex.x / outerRadius + 1) / 2;
  20929. uv.y = (vertex.y / outerRadius + 1) / 2;
  20930. uvs.push(uv.x, uv.y);
  20931. } // increase the radius for next row of vertices
  20932. radius += radiusStep;
  20933. } // indices
  20934. for (let j = 0; j < phiSegments; j++) {
  20935. const thetaSegmentLevel = j * (thetaSegments + 1);
  20936. for (let i = 0; i < thetaSegments; i++) {
  20937. const segment = i + thetaSegmentLevel;
  20938. const a = segment;
  20939. const b = segment + thetaSegments + 1;
  20940. const c = segment + thetaSegments + 2;
  20941. const d = segment + 1; // faces
  20942. indices.push(a, b, d);
  20943. indices.push(b, c, d);
  20944. }
  20945. } // build geometry
  20946. this.setIndex(indices);
  20947. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20948. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20949. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20950. }
  20951. static fromJSON(data) {
  20952. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  20953. }
  20954. }
  20955. class ShapeGeometry extends BufferGeometry {
  20956. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  20957. super();
  20958. this.type = 'ShapeGeometry';
  20959. this.parameters = {
  20960. shapes: shapes,
  20961. curveSegments: curveSegments
  20962. }; // buffers
  20963. const indices = [];
  20964. const vertices = [];
  20965. const normals = [];
  20966. const uvs = []; // helper variables
  20967. let groupStart = 0;
  20968. let groupCount = 0; // allow single and array values for "shapes" parameter
  20969. if (Array.isArray(shapes) === false) {
  20970. addShape(shapes);
  20971. } else {
  20972. for (let i = 0; i < shapes.length; i++) {
  20973. addShape(shapes[i]);
  20974. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20975. groupStart += groupCount;
  20976. groupCount = 0;
  20977. }
  20978. } // build geometry
  20979. this.setIndex(indices);
  20980. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20981. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20982. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20983. function addShape(shape) {
  20984. const indexOffset = vertices.length / 3;
  20985. const points = shape.extractPoints(curveSegments);
  20986. let shapeVertices = points.shape;
  20987. const shapeHoles = points.holes; // check direction of vertices
  20988. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20989. shapeVertices = shapeVertices.reverse();
  20990. }
  20991. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20992. const shapeHole = shapeHoles[i];
  20993. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20994. shapeHoles[i] = shapeHole.reverse();
  20995. }
  20996. }
  20997. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20998. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20999. const shapeHole = shapeHoles[i];
  21000. shapeVertices = shapeVertices.concat(shapeHole);
  21001. } // vertices, normals, uvs
  21002. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  21003. const vertex = shapeVertices[i];
  21004. vertices.push(vertex.x, vertex.y, 0);
  21005. normals.push(0, 0, 1);
  21006. uvs.push(vertex.x, vertex.y); // world uvs
  21007. } // incides
  21008. for (let i = 0, l = faces.length; i < l; i++) {
  21009. const face = faces[i];
  21010. const a = face[0] + indexOffset;
  21011. const b = face[1] + indexOffset;
  21012. const c = face[2] + indexOffset;
  21013. indices.push(a, b, c);
  21014. groupCount += 3;
  21015. }
  21016. }
  21017. }
  21018. toJSON() {
  21019. const data = super.toJSON();
  21020. const shapes = this.parameters.shapes;
  21021. return toJSON(shapes, data);
  21022. }
  21023. static fromJSON(data, shapes) {
  21024. const geometryShapes = [];
  21025. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  21026. const shape = shapes[data.shapes[j]];
  21027. geometryShapes.push(shape);
  21028. }
  21029. return new ShapeGeometry(geometryShapes, data.curveSegments);
  21030. }
  21031. }
  21032. function toJSON(shapes, data) {
  21033. data.shapes = [];
  21034. if (Array.isArray(shapes)) {
  21035. for (let i = 0, l = shapes.length; i < l; i++) {
  21036. const shape = shapes[i];
  21037. data.shapes.push(shape.uuid);
  21038. }
  21039. } else {
  21040. data.shapes.push(shapes.uuid);
  21041. }
  21042. return data;
  21043. }
  21044. class SphereGeometry extends BufferGeometry {
  21045. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  21046. super();
  21047. this.type = 'SphereGeometry';
  21048. this.parameters = {
  21049. radius: radius,
  21050. widthSegments: widthSegments,
  21051. heightSegments: heightSegments,
  21052. phiStart: phiStart,
  21053. phiLength: phiLength,
  21054. thetaStart: thetaStart,
  21055. thetaLength: thetaLength
  21056. };
  21057. widthSegments = Math.max(3, Math.floor(widthSegments));
  21058. heightSegments = Math.max(2, Math.floor(heightSegments));
  21059. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  21060. let index = 0;
  21061. const grid = [];
  21062. const vertex = new Vector3();
  21063. const normal = new Vector3(); // buffers
  21064. const indices = [];
  21065. const vertices = [];
  21066. const normals = [];
  21067. const uvs = []; // generate vertices, normals and uvs
  21068. for (let iy = 0; iy <= heightSegments; iy++) {
  21069. const verticesRow = [];
  21070. const v = iy / heightSegments; // special case for the poles
  21071. let uOffset = 0;
  21072. if (iy == 0 && thetaStart == 0) {
  21073. uOffset = 0.5 / widthSegments;
  21074. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  21075. uOffset = -0.5 / widthSegments;
  21076. }
  21077. for (let ix = 0; ix <= widthSegments; ix++) {
  21078. const u = ix / widthSegments; // vertex
  21079. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21080. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  21081. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21082. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  21083. normal.copy(vertex).normalize();
  21084. normals.push(normal.x, normal.y, normal.z); // uv
  21085. uvs.push(u + uOffset, 1 - v);
  21086. verticesRow.push(index++);
  21087. }
  21088. grid.push(verticesRow);
  21089. } // indices
  21090. for (let iy = 0; iy < heightSegments; iy++) {
  21091. for (let ix = 0; ix < widthSegments; ix++) {
  21092. const a = grid[iy][ix + 1];
  21093. const b = grid[iy][ix];
  21094. const c = grid[iy + 1][ix];
  21095. const d = grid[iy + 1][ix + 1];
  21096. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  21097. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  21098. }
  21099. } // build geometry
  21100. this.setIndex(indices);
  21101. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21102. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21103. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21104. }
  21105. static fromJSON(data) {
  21106. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  21107. }
  21108. }
  21109. class TetrahedronGeometry extends PolyhedronGeometry {
  21110. constructor(radius = 1, detail = 0) {
  21111. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  21112. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  21113. super(vertices, indices, radius, detail);
  21114. this.type = 'TetrahedronGeometry';
  21115. this.parameters = {
  21116. radius: radius,
  21117. detail: detail
  21118. };
  21119. }
  21120. static fromJSON(data) {
  21121. return new TetrahedronGeometry(data.radius, data.detail);
  21122. }
  21123. }
  21124. class TorusGeometry extends BufferGeometry {
  21125. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  21126. super();
  21127. this.type = 'TorusGeometry';
  21128. this.parameters = {
  21129. radius: radius,
  21130. tube: tube,
  21131. radialSegments: radialSegments,
  21132. tubularSegments: tubularSegments,
  21133. arc: arc
  21134. };
  21135. radialSegments = Math.floor(radialSegments);
  21136. tubularSegments = Math.floor(tubularSegments); // buffers
  21137. const indices = [];
  21138. const vertices = [];
  21139. const normals = [];
  21140. const uvs = []; // helper variables
  21141. const center = new Vector3();
  21142. const vertex = new Vector3();
  21143. const normal = new Vector3(); // generate vertices, normals and uvs
  21144. for (let j = 0; j <= radialSegments; j++) {
  21145. for (let i = 0; i <= tubularSegments; i++) {
  21146. const u = i / tubularSegments * arc;
  21147. const v = j / radialSegments * Math.PI * 2; // vertex
  21148. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  21149. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  21150. vertex.z = tube * Math.sin(v);
  21151. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  21152. center.x = radius * Math.cos(u);
  21153. center.y = radius * Math.sin(u);
  21154. normal.subVectors(vertex, center).normalize();
  21155. normals.push(normal.x, normal.y, normal.z); // uv
  21156. uvs.push(i / tubularSegments);
  21157. uvs.push(j / radialSegments);
  21158. }
  21159. } // generate indices
  21160. for (let j = 1; j <= radialSegments; j++) {
  21161. for (let i = 1; i <= tubularSegments; i++) {
  21162. // indices
  21163. const a = (tubularSegments + 1) * j + i - 1;
  21164. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  21165. const c = (tubularSegments + 1) * (j - 1) + i;
  21166. const d = (tubularSegments + 1) * j + i; // faces
  21167. indices.push(a, b, d);
  21168. indices.push(b, c, d);
  21169. }
  21170. } // build geometry
  21171. this.setIndex(indices);
  21172. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21173. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21174. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21175. }
  21176. static fromJSON(data) {
  21177. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  21178. }
  21179. }
  21180. class TorusKnotGeometry extends BufferGeometry {
  21181. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  21182. super();
  21183. this.type = 'TorusKnotGeometry';
  21184. this.parameters = {
  21185. radius: radius,
  21186. tube: tube,
  21187. tubularSegments: tubularSegments,
  21188. radialSegments: radialSegments,
  21189. p: p,
  21190. q: q
  21191. };
  21192. tubularSegments = Math.floor(tubularSegments);
  21193. radialSegments = Math.floor(radialSegments); // buffers
  21194. const indices = [];
  21195. const vertices = [];
  21196. const normals = [];
  21197. const uvs = []; // helper variables
  21198. const vertex = new Vector3();
  21199. const normal = new Vector3();
  21200. const P1 = new Vector3();
  21201. const P2 = new Vector3();
  21202. const B = new Vector3();
  21203. const T = new Vector3();
  21204. const N = new Vector3(); // generate vertices, normals and uvs
  21205. for (let i = 0; i <= tubularSegments; ++i) {
  21206. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21207. 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.
  21208. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21209. calculatePositionOnCurve(u, p, q, radius, P1);
  21210. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  21211. T.subVectors(P2, P1);
  21212. N.addVectors(P2, P1);
  21213. B.crossVectors(T, N);
  21214. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  21215. B.normalize();
  21216. N.normalize();
  21217. for (let j = 0; j <= radialSegments; ++j) {
  21218. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21219. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21220. const v = j / radialSegments * Math.PI * 2;
  21221. const cx = -tube * Math.cos(v);
  21222. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  21223. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21224. vertex.x = P1.x + (cx * N.x + cy * B.x);
  21225. vertex.y = P1.y + (cx * N.y + cy * B.y);
  21226. vertex.z = P1.z + (cx * N.z + cy * B.z);
  21227. 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)
  21228. normal.subVectors(vertex, P1).normalize();
  21229. normals.push(normal.x, normal.y, normal.z); // uv
  21230. uvs.push(i / tubularSegments);
  21231. uvs.push(j / radialSegments);
  21232. }
  21233. } // generate indices
  21234. for (let j = 1; j <= tubularSegments; j++) {
  21235. for (let i = 1; i <= radialSegments; i++) {
  21236. // indices
  21237. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  21238. const b = (radialSegments + 1) * j + (i - 1);
  21239. const c = (radialSegments + 1) * j + i;
  21240. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21241. indices.push(a, b, d);
  21242. indices.push(b, c, d);
  21243. }
  21244. } // build geometry
  21245. this.setIndex(indices);
  21246. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21247. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21248. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  21249. function calculatePositionOnCurve(u, p, q, radius, position) {
  21250. const cu = Math.cos(u);
  21251. const su = Math.sin(u);
  21252. const quOverP = q / p * u;
  21253. const cs = Math.cos(quOverP);
  21254. position.x = radius * (2 + cs) * 0.5 * cu;
  21255. position.y = radius * (2 + cs) * su * 0.5;
  21256. position.z = radius * Math.sin(quOverP) * 0.5;
  21257. }
  21258. }
  21259. static fromJSON(data) {
  21260. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  21261. }
  21262. }
  21263. class TubeGeometry extends BufferGeometry {
  21264. 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) {
  21265. super();
  21266. this.type = 'TubeGeometry';
  21267. this.parameters = {
  21268. path: path,
  21269. tubularSegments: tubularSegments,
  21270. radius: radius,
  21271. radialSegments: radialSegments,
  21272. closed: closed
  21273. };
  21274. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  21275. this.tangents = frames.tangents;
  21276. this.normals = frames.normals;
  21277. this.binormals = frames.binormals; // helper variables
  21278. const vertex = new Vector3();
  21279. const normal = new Vector3();
  21280. const uv = new Vector2();
  21281. let P = new Vector3(); // buffer
  21282. const vertices = [];
  21283. const normals = [];
  21284. const uvs = [];
  21285. const indices = []; // create buffer data
  21286. generateBufferData(); // build geometry
  21287. this.setIndex(indices);
  21288. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21289. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21290. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  21291. function generateBufferData() {
  21292. for (let i = 0; i < tubularSegments; i++) {
  21293. generateSegment(i);
  21294. } // if the geometry is not closed, generate the last row of vertices and normals
  21295. // at the regular position on the given path
  21296. //
  21297. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21298. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  21299. // this makes it easy compute correct values for closed geometries
  21300. generateUVs(); // finally create faces
  21301. generateIndices();
  21302. }
  21303. function generateSegment(i) {
  21304. // we use getPointAt to sample evenly distributed points from the given path
  21305. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  21306. const N = frames.normals[i];
  21307. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  21308. for (let j = 0; j <= radialSegments; j++) {
  21309. const v = j / radialSegments * Math.PI * 2;
  21310. const sin = Math.sin(v);
  21311. const cos = -Math.cos(v); // normal
  21312. normal.x = cos * N.x + sin * B.x;
  21313. normal.y = cos * N.y + sin * B.y;
  21314. normal.z = cos * N.z + sin * B.z;
  21315. normal.normalize();
  21316. normals.push(normal.x, normal.y, normal.z); // vertex
  21317. vertex.x = P.x + radius * normal.x;
  21318. vertex.y = P.y + radius * normal.y;
  21319. vertex.z = P.z + radius * normal.z;
  21320. vertices.push(vertex.x, vertex.y, vertex.z);
  21321. }
  21322. }
  21323. function generateIndices() {
  21324. for (let j = 1; j <= tubularSegments; j++) {
  21325. for (let i = 1; i <= radialSegments; i++) {
  21326. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  21327. const b = (radialSegments + 1) * j + (i - 1);
  21328. const c = (radialSegments + 1) * j + i;
  21329. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21330. indices.push(a, b, d);
  21331. indices.push(b, c, d);
  21332. }
  21333. }
  21334. }
  21335. function generateUVs() {
  21336. for (let i = 0; i <= tubularSegments; i++) {
  21337. for (let j = 0; j <= radialSegments; j++) {
  21338. uv.x = i / tubularSegments;
  21339. uv.y = j / radialSegments;
  21340. uvs.push(uv.x, uv.y);
  21341. }
  21342. }
  21343. }
  21344. }
  21345. toJSON() {
  21346. const data = super.toJSON();
  21347. data.path = this.parameters.path.toJSON();
  21348. return data;
  21349. }
  21350. static fromJSON(data) {
  21351. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21352. // User defined curves or instances of CurvePath will not be deserialized.
  21353. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  21354. }
  21355. }
  21356. class WireframeGeometry extends BufferGeometry {
  21357. constructor(geometry = null) {
  21358. super();
  21359. this.type = 'WireframeGeometry';
  21360. this.parameters = {
  21361. geometry: geometry
  21362. };
  21363. if (geometry !== null) {
  21364. // buffer
  21365. const vertices = [];
  21366. const edges = new Set(); // helper variables
  21367. const start = new Vector3();
  21368. const end = new Vector3();
  21369. if (geometry.index !== null) {
  21370. // indexed BufferGeometry
  21371. const position = geometry.attributes.position;
  21372. const indices = geometry.index;
  21373. let groups = geometry.groups;
  21374. if (groups.length === 0) {
  21375. groups = [{
  21376. start: 0,
  21377. count: indices.count,
  21378. materialIndex: 0
  21379. }];
  21380. } // create a data structure that contains all edges without duplicates
  21381. for (let o = 0, ol = groups.length; o < ol; ++o) {
  21382. const group = groups[o];
  21383. const groupStart = group.start;
  21384. const groupCount = group.count;
  21385. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  21386. for (let j = 0; j < 3; j++) {
  21387. const index1 = indices.getX(i + j);
  21388. const index2 = indices.getX(i + (j + 1) % 3);
  21389. start.fromBufferAttribute(position, index1);
  21390. end.fromBufferAttribute(position, index2);
  21391. if (isUniqueEdge(start, end, edges) === true) {
  21392. vertices.push(start.x, start.y, start.z);
  21393. vertices.push(end.x, end.y, end.z);
  21394. }
  21395. }
  21396. }
  21397. }
  21398. } else {
  21399. // non-indexed BufferGeometry
  21400. const position = geometry.attributes.position;
  21401. for (let i = 0, l = position.count / 3; i < l; i++) {
  21402. for (let j = 0; j < 3; j++) {
  21403. // three edges per triangle, an edge is represented as (index1, index2)
  21404. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21405. const index1 = 3 * i + j;
  21406. const index2 = 3 * i + (j + 1) % 3;
  21407. start.fromBufferAttribute(position, index1);
  21408. end.fromBufferAttribute(position, index2);
  21409. if (isUniqueEdge(start, end, edges) === true) {
  21410. vertices.push(start.x, start.y, start.z);
  21411. vertices.push(end.x, end.y, end.z);
  21412. }
  21413. }
  21414. }
  21415. } // build geometry
  21416. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21417. }
  21418. }
  21419. }
  21420. function isUniqueEdge(start, end, edges) {
  21421. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21422. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21423. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  21424. return false;
  21425. } else {
  21426. edges.add(hash1);
  21427. edges.add(hash2);
  21428. return true;
  21429. }
  21430. }
  21431. var Geometries = /*#__PURE__*/Object.freeze({
  21432. __proto__: null,
  21433. BoxGeometry: BoxGeometry,
  21434. BoxBufferGeometry: BoxGeometry,
  21435. CapsuleGeometry: CapsuleGeometry,
  21436. CapsuleBufferGeometry: CapsuleGeometry,
  21437. CircleGeometry: CircleGeometry,
  21438. CircleBufferGeometry: CircleGeometry,
  21439. ConeGeometry: ConeGeometry,
  21440. ConeBufferGeometry: ConeGeometry,
  21441. CylinderGeometry: CylinderGeometry,
  21442. CylinderBufferGeometry: CylinderGeometry,
  21443. DodecahedronGeometry: DodecahedronGeometry,
  21444. DodecahedronBufferGeometry: DodecahedronGeometry,
  21445. EdgesGeometry: EdgesGeometry,
  21446. ExtrudeGeometry: ExtrudeGeometry,
  21447. ExtrudeBufferGeometry: ExtrudeGeometry,
  21448. IcosahedronGeometry: IcosahedronGeometry,
  21449. IcosahedronBufferGeometry: IcosahedronGeometry,
  21450. LatheGeometry: LatheGeometry,
  21451. LatheBufferGeometry: LatheGeometry,
  21452. OctahedronGeometry: OctahedronGeometry,
  21453. OctahedronBufferGeometry: OctahedronGeometry,
  21454. PlaneGeometry: PlaneGeometry,
  21455. PlaneBufferGeometry: PlaneGeometry,
  21456. PolyhedronGeometry: PolyhedronGeometry,
  21457. PolyhedronBufferGeometry: PolyhedronGeometry,
  21458. RingGeometry: RingGeometry,
  21459. RingBufferGeometry: RingGeometry,
  21460. ShapeGeometry: ShapeGeometry,
  21461. ShapeBufferGeometry: ShapeGeometry,
  21462. SphereGeometry: SphereGeometry,
  21463. SphereBufferGeometry: SphereGeometry,
  21464. TetrahedronGeometry: TetrahedronGeometry,
  21465. TetrahedronBufferGeometry: TetrahedronGeometry,
  21466. TorusGeometry: TorusGeometry,
  21467. TorusBufferGeometry: TorusGeometry,
  21468. TorusKnotGeometry: TorusKnotGeometry,
  21469. TorusKnotBufferGeometry: TorusKnotGeometry,
  21470. TubeGeometry: TubeGeometry,
  21471. TubeBufferGeometry: TubeGeometry,
  21472. WireframeGeometry: WireframeGeometry
  21473. });
  21474. class ShadowMaterial extends Material {
  21475. constructor(parameters) {
  21476. super();
  21477. this.isShadowMaterial = true;
  21478. this.type = 'ShadowMaterial';
  21479. this.color = new Color(0x000000);
  21480. this.transparent = true;
  21481. this.fog = true;
  21482. this.setValues(parameters);
  21483. }
  21484. copy(source) {
  21485. super.copy(source);
  21486. this.color.copy(source.color);
  21487. this.fog = source.fog;
  21488. return this;
  21489. }
  21490. }
  21491. class RawShaderMaterial extends ShaderMaterial {
  21492. constructor(parameters) {
  21493. super(parameters);
  21494. this.isRawShaderMaterial = true;
  21495. this.type = 'RawShaderMaterial';
  21496. }
  21497. }
  21498. class MeshStandardMaterial extends Material {
  21499. constructor(parameters) {
  21500. super();
  21501. this.isMeshStandardMaterial = true;
  21502. this.defines = {
  21503. 'STANDARD': ''
  21504. };
  21505. this.type = 'MeshStandardMaterial';
  21506. this.color = new Color(0xffffff); // diffuse
  21507. this.roughness = 1.0;
  21508. this.metalness = 0.0;
  21509. this.map = null;
  21510. this.lightMap = null;
  21511. this.lightMapIntensity = 1.0;
  21512. this.aoMap = null;
  21513. this.aoMapIntensity = 1.0;
  21514. this.emissive = new Color(0x000000);
  21515. this.emissiveIntensity = 1.0;
  21516. this.emissiveMap = null;
  21517. this.bumpMap = null;
  21518. this.bumpScale = 1;
  21519. this.normalMap = null;
  21520. this.normalMapType = TangentSpaceNormalMap;
  21521. this.normalScale = new Vector2(1, 1);
  21522. this.displacementMap = null;
  21523. this.displacementScale = 1;
  21524. this.displacementBias = 0;
  21525. this.roughnessMap = null;
  21526. this.metalnessMap = null;
  21527. this.alphaMap = null;
  21528. this.envMap = null;
  21529. this.envMapIntensity = 1.0;
  21530. this.wireframe = false;
  21531. this.wireframeLinewidth = 1;
  21532. this.wireframeLinecap = 'round';
  21533. this.wireframeLinejoin = 'round';
  21534. this.flatShading = false;
  21535. this.fog = true;
  21536. this.setValues(parameters);
  21537. }
  21538. copy(source) {
  21539. super.copy(source);
  21540. this.defines = {
  21541. 'STANDARD': ''
  21542. };
  21543. this.color.copy(source.color);
  21544. this.roughness = source.roughness;
  21545. this.metalness = source.metalness;
  21546. this.map = source.map;
  21547. this.lightMap = source.lightMap;
  21548. this.lightMapIntensity = source.lightMapIntensity;
  21549. this.aoMap = source.aoMap;
  21550. this.aoMapIntensity = source.aoMapIntensity;
  21551. this.emissive.copy(source.emissive);
  21552. this.emissiveMap = source.emissiveMap;
  21553. this.emissiveIntensity = source.emissiveIntensity;
  21554. this.bumpMap = source.bumpMap;
  21555. this.bumpScale = source.bumpScale;
  21556. this.normalMap = source.normalMap;
  21557. this.normalMapType = source.normalMapType;
  21558. this.normalScale.copy(source.normalScale);
  21559. this.displacementMap = source.displacementMap;
  21560. this.displacementScale = source.displacementScale;
  21561. this.displacementBias = source.displacementBias;
  21562. this.roughnessMap = source.roughnessMap;
  21563. this.metalnessMap = source.metalnessMap;
  21564. this.alphaMap = source.alphaMap;
  21565. this.envMap = source.envMap;
  21566. this.envMapIntensity = source.envMapIntensity;
  21567. this.wireframe = source.wireframe;
  21568. this.wireframeLinewidth = source.wireframeLinewidth;
  21569. this.wireframeLinecap = source.wireframeLinecap;
  21570. this.wireframeLinejoin = source.wireframeLinejoin;
  21571. this.flatShading = source.flatShading;
  21572. this.fog = source.fog;
  21573. return this;
  21574. }
  21575. }
  21576. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21577. constructor(parameters) {
  21578. super();
  21579. this.isMeshPhysicalMaterial = true;
  21580. this.defines = {
  21581. 'STANDARD': '',
  21582. 'PHYSICAL': ''
  21583. };
  21584. this.type = 'MeshPhysicalMaterial';
  21585. this.clearcoatMap = null;
  21586. this.clearcoatRoughness = 0.0;
  21587. this.clearcoatRoughnessMap = null;
  21588. this.clearcoatNormalScale = new Vector2(1, 1);
  21589. this.clearcoatNormalMap = null;
  21590. this.ior = 1.5;
  21591. Object.defineProperty(this, 'reflectivity', {
  21592. get: function () {
  21593. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  21594. },
  21595. set: function (reflectivity) {
  21596. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  21597. }
  21598. });
  21599. this.iridescenceMap = null;
  21600. this.iridescenceIOR = 1.3;
  21601. this.iridescenceThicknessRange = [100, 400];
  21602. this.iridescenceThicknessMap = null;
  21603. this.sheenColor = new Color(0x000000);
  21604. this.sheenColorMap = null;
  21605. this.sheenRoughness = 1.0;
  21606. this.sheenRoughnessMap = null;
  21607. this.transmissionMap = null;
  21608. this.thickness = 0;
  21609. this.thicknessMap = null;
  21610. this.attenuationDistance = 0.0;
  21611. this.attenuationColor = new Color(1, 1, 1);
  21612. this.specularIntensity = 1.0;
  21613. this.specularIntensityMap = null;
  21614. this.specularColor = new Color(1, 1, 1);
  21615. this.specularColorMap = null;
  21616. this._sheen = 0.0;
  21617. this._clearcoat = 0;
  21618. this._iridescence = 0;
  21619. this._transmission = 0;
  21620. this.setValues(parameters);
  21621. }
  21622. get sheen() {
  21623. return this._sheen;
  21624. }
  21625. set sheen(value) {
  21626. if (this._sheen > 0 !== value > 0) {
  21627. this.version++;
  21628. }
  21629. this._sheen = value;
  21630. }
  21631. get clearcoat() {
  21632. return this._clearcoat;
  21633. }
  21634. set clearcoat(value) {
  21635. if (this._clearcoat > 0 !== value > 0) {
  21636. this.version++;
  21637. }
  21638. this._clearcoat = value;
  21639. }
  21640. get iridescence() {
  21641. return this._iridescence;
  21642. }
  21643. set iridescence(value) {
  21644. if (this._iridescence > 0 !== value > 0) {
  21645. this.version++;
  21646. }
  21647. this._iridescence = value;
  21648. }
  21649. get transmission() {
  21650. return this._transmission;
  21651. }
  21652. set transmission(value) {
  21653. if (this._transmission > 0 !== value > 0) {
  21654. this.version++;
  21655. }
  21656. this._transmission = value;
  21657. }
  21658. copy(source) {
  21659. super.copy(source);
  21660. this.defines = {
  21661. 'STANDARD': '',
  21662. 'PHYSICAL': ''
  21663. };
  21664. this.clearcoat = source.clearcoat;
  21665. this.clearcoatMap = source.clearcoatMap;
  21666. this.clearcoatRoughness = source.clearcoatRoughness;
  21667. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21668. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21669. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  21670. this.ior = source.ior;
  21671. this.iridescence = source.iridescence;
  21672. this.iridescenceMap = source.iridescenceMap;
  21673. this.iridescenceIOR = source.iridescenceIOR;
  21674. this.iridescenceThicknessRange = [...source.iridescenceThicknessRange];
  21675. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  21676. this.sheen = source.sheen;
  21677. this.sheenColor.copy(source.sheenColor);
  21678. this.sheenColorMap = source.sheenColorMap;
  21679. this.sheenRoughness = source.sheenRoughness;
  21680. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21681. this.transmission = source.transmission;
  21682. this.transmissionMap = source.transmissionMap;
  21683. this.thickness = source.thickness;
  21684. this.thicknessMap = source.thicknessMap;
  21685. this.attenuationDistance = source.attenuationDistance;
  21686. this.attenuationColor.copy(source.attenuationColor);
  21687. this.specularIntensity = source.specularIntensity;
  21688. this.specularIntensityMap = source.specularIntensityMap;
  21689. this.specularColor.copy(source.specularColor);
  21690. this.specularColorMap = source.specularColorMap;
  21691. return this;
  21692. }
  21693. }
  21694. class MeshPhongMaterial extends Material {
  21695. constructor(parameters) {
  21696. super();
  21697. this.isMeshPhongMaterial = true;
  21698. this.type = 'MeshPhongMaterial';
  21699. this.color = new Color(0xffffff); // diffuse
  21700. this.specular = new Color(0x111111);
  21701. this.shininess = 30;
  21702. this.map = null;
  21703. this.lightMap = null;
  21704. this.lightMapIntensity = 1.0;
  21705. this.aoMap = null;
  21706. this.aoMapIntensity = 1.0;
  21707. this.emissive = new Color(0x000000);
  21708. this.emissiveIntensity = 1.0;
  21709. this.emissiveMap = null;
  21710. this.bumpMap = null;
  21711. this.bumpScale = 1;
  21712. this.normalMap = null;
  21713. this.normalMapType = TangentSpaceNormalMap;
  21714. this.normalScale = new Vector2(1, 1);
  21715. this.displacementMap = null;
  21716. this.displacementScale = 1;
  21717. this.displacementBias = 0;
  21718. this.specularMap = null;
  21719. this.alphaMap = null;
  21720. this.envMap = null;
  21721. this.combine = MultiplyOperation;
  21722. this.reflectivity = 1;
  21723. this.refractionRatio = 0.98;
  21724. this.wireframe = false;
  21725. this.wireframeLinewidth = 1;
  21726. this.wireframeLinecap = 'round';
  21727. this.wireframeLinejoin = 'round';
  21728. this.flatShading = false;
  21729. this.fog = true;
  21730. this.setValues(parameters);
  21731. }
  21732. copy(source) {
  21733. super.copy(source);
  21734. this.color.copy(source.color);
  21735. this.specular.copy(source.specular);
  21736. this.shininess = source.shininess;
  21737. this.map = source.map;
  21738. this.lightMap = source.lightMap;
  21739. this.lightMapIntensity = source.lightMapIntensity;
  21740. this.aoMap = source.aoMap;
  21741. this.aoMapIntensity = source.aoMapIntensity;
  21742. this.emissive.copy(source.emissive);
  21743. this.emissiveMap = source.emissiveMap;
  21744. this.emissiveIntensity = source.emissiveIntensity;
  21745. this.bumpMap = source.bumpMap;
  21746. this.bumpScale = source.bumpScale;
  21747. this.normalMap = source.normalMap;
  21748. this.normalMapType = source.normalMapType;
  21749. this.normalScale.copy(source.normalScale);
  21750. this.displacementMap = source.displacementMap;
  21751. this.displacementScale = source.displacementScale;
  21752. this.displacementBias = source.displacementBias;
  21753. this.specularMap = source.specularMap;
  21754. this.alphaMap = source.alphaMap;
  21755. this.envMap = source.envMap;
  21756. this.combine = source.combine;
  21757. this.reflectivity = source.reflectivity;
  21758. this.refractionRatio = source.refractionRatio;
  21759. this.wireframe = source.wireframe;
  21760. this.wireframeLinewidth = source.wireframeLinewidth;
  21761. this.wireframeLinecap = source.wireframeLinecap;
  21762. this.wireframeLinejoin = source.wireframeLinejoin;
  21763. this.flatShading = source.flatShading;
  21764. this.fog = source.fog;
  21765. return this;
  21766. }
  21767. }
  21768. class MeshToonMaterial extends Material {
  21769. constructor(parameters) {
  21770. super();
  21771. this.isMeshToonMaterial = true;
  21772. this.defines = {
  21773. 'TOON': ''
  21774. };
  21775. this.type = 'MeshToonMaterial';
  21776. this.color = new Color(0xffffff);
  21777. this.map = null;
  21778. this.gradientMap = null;
  21779. this.lightMap = null;
  21780. this.lightMapIntensity = 1.0;
  21781. this.aoMap = null;
  21782. this.aoMapIntensity = 1.0;
  21783. this.emissive = new Color(0x000000);
  21784. this.emissiveIntensity = 1.0;
  21785. this.emissiveMap = null;
  21786. this.bumpMap = null;
  21787. this.bumpScale = 1;
  21788. this.normalMap = null;
  21789. this.normalMapType = TangentSpaceNormalMap;
  21790. this.normalScale = new Vector2(1, 1);
  21791. this.displacementMap = null;
  21792. this.displacementScale = 1;
  21793. this.displacementBias = 0;
  21794. this.alphaMap = null;
  21795. this.wireframe = false;
  21796. this.wireframeLinewidth = 1;
  21797. this.wireframeLinecap = 'round';
  21798. this.wireframeLinejoin = 'round';
  21799. this.fog = true;
  21800. this.setValues(parameters);
  21801. }
  21802. copy(source) {
  21803. super.copy(source);
  21804. this.color.copy(source.color);
  21805. this.map = source.map;
  21806. this.gradientMap = source.gradientMap;
  21807. this.lightMap = source.lightMap;
  21808. this.lightMapIntensity = source.lightMapIntensity;
  21809. this.aoMap = source.aoMap;
  21810. this.aoMapIntensity = source.aoMapIntensity;
  21811. this.emissive.copy(source.emissive);
  21812. this.emissiveMap = source.emissiveMap;
  21813. this.emissiveIntensity = source.emissiveIntensity;
  21814. this.bumpMap = source.bumpMap;
  21815. this.bumpScale = source.bumpScale;
  21816. this.normalMap = source.normalMap;
  21817. this.normalMapType = source.normalMapType;
  21818. this.normalScale.copy(source.normalScale);
  21819. this.displacementMap = source.displacementMap;
  21820. this.displacementScale = source.displacementScale;
  21821. this.displacementBias = source.displacementBias;
  21822. this.alphaMap = source.alphaMap;
  21823. this.wireframe = source.wireframe;
  21824. this.wireframeLinewidth = source.wireframeLinewidth;
  21825. this.wireframeLinecap = source.wireframeLinecap;
  21826. this.wireframeLinejoin = source.wireframeLinejoin;
  21827. this.fog = source.fog;
  21828. return this;
  21829. }
  21830. }
  21831. class MeshNormalMaterial extends Material {
  21832. constructor(parameters) {
  21833. super();
  21834. this.isMeshNormalMaterial = true;
  21835. this.type = 'MeshNormalMaterial';
  21836. this.bumpMap = null;
  21837. this.bumpScale = 1;
  21838. this.normalMap = null;
  21839. this.normalMapType = TangentSpaceNormalMap;
  21840. this.normalScale = new Vector2(1, 1);
  21841. this.displacementMap = null;
  21842. this.displacementScale = 1;
  21843. this.displacementBias = 0;
  21844. this.wireframe = false;
  21845. this.wireframeLinewidth = 1;
  21846. this.flatShading = false;
  21847. this.setValues(parameters);
  21848. }
  21849. copy(source) {
  21850. super.copy(source);
  21851. this.bumpMap = source.bumpMap;
  21852. this.bumpScale = source.bumpScale;
  21853. this.normalMap = source.normalMap;
  21854. this.normalMapType = source.normalMapType;
  21855. this.normalScale.copy(source.normalScale);
  21856. this.displacementMap = source.displacementMap;
  21857. this.displacementScale = source.displacementScale;
  21858. this.displacementBias = source.displacementBias;
  21859. this.wireframe = source.wireframe;
  21860. this.wireframeLinewidth = source.wireframeLinewidth;
  21861. this.flatShading = source.flatShading;
  21862. return this;
  21863. }
  21864. }
  21865. class MeshLambertMaterial extends Material {
  21866. constructor(parameters) {
  21867. super();
  21868. this.isMeshLambertMaterial = true;
  21869. this.type = 'MeshLambertMaterial';
  21870. this.color = new Color(0xffffff); // diffuse
  21871. this.map = null;
  21872. this.lightMap = null;
  21873. this.lightMapIntensity = 1.0;
  21874. this.aoMap = null;
  21875. this.aoMapIntensity = 1.0;
  21876. this.emissive = new Color(0x000000);
  21877. this.emissiveIntensity = 1.0;
  21878. this.emissiveMap = null;
  21879. this.specularMap = null;
  21880. this.alphaMap = null;
  21881. this.envMap = null;
  21882. this.combine = MultiplyOperation;
  21883. this.reflectivity = 1;
  21884. this.refractionRatio = 0.98;
  21885. this.wireframe = false;
  21886. this.wireframeLinewidth = 1;
  21887. this.wireframeLinecap = 'round';
  21888. this.wireframeLinejoin = 'round';
  21889. this.fog = true;
  21890. this.setValues(parameters);
  21891. }
  21892. copy(source) {
  21893. super.copy(source);
  21894. this.color.copy(source.color);
  21895. this.map = source.map;
  21896. this.lightMap = source.lightMap;
  21897. this.lightMapIntensity = source.lightMapIntensity;
  21898. this.aoMap = source.aoMap;
  21899. this.aoMapIntensity = source.aoMapIntensity;
  21900. this.emissive.copy(source.emissive);
  21901. this.emissiveMap = source.emissiveMap;
  21902. this.emissiveIntensity = source.emissiveIntensity;
  21903. this.specularMap = source.specularMap;
  21904. this.alphaMap = source.alphaMap;
  21905. this.envMap = source.envMap;
  21906. this.combine = source.combine;
  21907. this.reflectivity = source.reflectivity;
  21908. this.refractionRatio = source.refractionRatio;
  21909. this.wireframe = source.wireframe;
  21910. this.wireframeLinewidth = source.wireframeLinewidth;
  21911. this.wireframeLinecap = source.wireframeLinecap;
  21912. this.wireframeLinejoin = source.wireframeLinejoin;
  21913. this.fog = source.fog;
  21914. return this;
  21915. }
  21916. }
  21917. class MeshMatcapMaterial extends Material {
  21918. constructor(parameters) {
  21919. super();
  21920. this.isMeshMatcapMaterial = true;
  21921. this.defines = {
  21922. 'MATCAP': ''
  21923. };
  21924. this.type = 'MeshMatcapMaterial';
  21925. this.color = new Color(0xffffff); // diffuse
  21926. this.matcap = null;
  21927. this.map = null;
  21928. this.bumpMap = null;
  21929. this.bumpScale = 1;
  21930. this.normalMap = null;
  21931. this.normalMapType = TangentSpaceNormalMap;
  21932. this.normalScale = new Vector2(1, 1);
  21933. this.displacementMap = null;
  21934. this.displacementScale = 1;
  21935. this.displacementBias = 0;
  21936. this.alphaMap = null;
  21937. this.flatShading = false;
  21938. this.fog = true;
  21939. this.setValues(parameters);
  21940. }
  21941. copy(source) {
  21942. super.copy(source);
  21943. this.defines = {
  21944. 'MATCAP': ''
  21945. };
  21946. this.color.copy(source.color);
  21947. this.matcap = source.matcap;
  21948. this.map = source.map;
  21949. this.bumpMap = source.bumpMap;
  21950. this.bumpScale = source.bumpScale;
  21951. this.normalMap = source.normalMap;
  21952. this.normalMapType = source.normalMapType;
  21953. this.normalScale.copy(source.normalScale);
  21954. this.displacementMap = source.displacementMap;
  21955. this.displacementScale = source.displacementScale;
  21956. this.displacementBias = source.displacementBias;
  21957. this.alphaMap = source.alphaMap;
  21958. this.flatShading = source.flatShading;
  21959. this.fog = source.fog;
  21960. return this;
  21961. }
  21962. }
  21963. class LineDashedMaterial extends LineBasicMaterial {
  21964. constructor(parameters) {
  21965. super();
  21966. this.isLineDashedMaterial = true;
  21967. this.type = 'LineDashedMaterial';
  21968. this.scale = 1;
  21969. this.dashSize = 3;
  21970. this.gapSize = 1;
  21971. this.setValues(parameters);
  21972. }
  21973. copy(source) {
  21974. super.copy(source);
  21975. this.scale = source.scale;
  21976. this.dashSize = source.dashSize;
  21977. this.gapSize = source.gapSize;
  21978. return this;
  21979. }
  21980. }
  21981. function arraySlice(array, from, to) {
  21982. if (isTypedArray(array)) {
  21983. // in ios9 array.subarray(from, undefined) will return empty array
  21984. // but array.subarray(from) or array.subarray(from, len) is correct
  21985. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21986. }
  21987. return array.slice(from, to);
  21988. } // converts an array to a specific type
  21989. function convertArray(array, type, forceClone) {
  21990. if (!array || // let 'undefined' and 'null' pass
  21991. !forceClone && array.constructor === type) return array;
  21992. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21993. return new type(array); // create typed array
  21994. }
  21995. return Array.prototype.slice.call(array); // create Array
  21996. }
  21997. function isTypedArray(object) {
  21998. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21999. } // returns an array by which times and values can be sorted
  22000. function getKeyframeOrder(times) {
  22001. function compareTime(i, j) {
  22002. return times[i] - times[j];
  22003. }
  22004. const n = times.length;
  22005. const result = new Array(n);
  22006. for (let i = 0; i !== n; ++i) result[i] = i;
  22007. result.sort(compareTime);
  22008. return result;
  22009. } // uses the array previously returned by 'getKeyframeOrder' to sort data
  22010. function sortedArray(values, stride, order) {
  22011. const nValues = values.length;
  22012. const result = new values.constructor(nValues);
  22013. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  22014. const srcOffset = order[i] * stride;
  22015. for (let j = 0; j !== stride; ++j) {
  22016. result[dstOffset++] = values[srcOffset + j];
  22017. }
  22018. }
  22019. return result;
  22020. } // function for parsing AOS keyframe formats
  22021. function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  22022. let i = 1,
  22023. key = jsonKeys[0];
  22024. while (key !== undefined && key[valuePropertyName] === undefined) {
  22025. key = jsonKeys[i++];
  22026. }
  22027. if (key === undefined) return; // no data
  22028. let value = key[valuePropertyName];
  22029. if (value === undefined) return; // no data
  22030. if (Array.isArray(value)) {
  22031. do {
  22032. value = key[valuePropertyName];
  22033. if (value !== undefined) {
  22034. times.push(key.time);
  22035. values.push.apply(values, value); // push all elements
  22036. }
  22037. key = jsonKeys[i++];
  22038. } while (key !== undefined);
  22039. } else if (value.toArray !== undefined) {
  22040. // ...assume THREE.Math-ish
  22041. do {
  22042. value = key[valuePropertyName];
  22043. if (value !== undefined) {
  22044. times.push(key.time);
  22045. value.toArray(values, values.length);
  22046. }
  22047. key = jsonKeys[i++];
  22048. } while (key !== undefined);
  22049. } else {
  22050. // otherwise push as-is
  22051. do {
  22052. value = key[valuePropertyName];
  22053. if (value !== undefined) {
  22054. times.push(key.time);
  22055. values.push(value);
  22056. }
  22057. key = jsonKeys[i++];
  22058. } while (key !== undefined);
  22059. }
  22060. }
  22061. function subclip(sourceClip, name, startFrame, endFrame, fps = 30) {
  22062. const clip = sourceClip.clone();
  22063. clip.name = name;
  22064. const tracks = [];
  22065. for (let i = 0; i < clip.tracks.length; ++i) {
  22066. const track = clip.tracks[i];
  22067. const valueSize = track.getValueSize();
  22068. const times = [];
  22069. const values = [];
  22070. for (let j = 0; j < track.times.length; ++j) {
  22071. const frame = track.times[j] * fps;
  22072. if (frame < startFrame || frame >= endFrame) continue;
  22073. times.push(track.times[j]);
  22074. for (let k = 0; k < valueSize; ++k) {
  22075. values.push(track.values[j * valueSize + k]);
  22076. }
  22077. }
  22078. if (times.length === 0) continue;
  22079. track.times = convertArray(times, track.times.constructor);
  22080. track.values = convertArray(values, track.values.constructor);
  22081. tracks.push(track);
  22082. }
  22083. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  22084. let minStartTime = Infinity;
  22085. for (let i = 0; i < clip.tracks.length; ++i) {
  22086. if (minStartTime > clip.tracks[i].times[0]) {
  22087. minStartTime = clip.tracks[i].times[0];
  22088. }
  22089. } // shift all tracks such that clip begins at t=0
  22090. for (let i = 0; i < clip.tracks.length; ++i) {
  22091. clip.tracks[i].shift(-1 * minStartTime);
  22092. }
  22093. clip.resetDuration();
  22094. return clip;
  22095. }
  22096. function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  22097. if (fps <= 0) fps = 30;
  22098. const numTracks = referenceClip.tracks.length;
  22099. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  22100. for (let i = 0; i < numTracks; ++i) {
  22101. const referenceTrack = referenceClip.tracks[i];
  22102. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  22103. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  22104. const targetTrack = targetClip.tracks.find(function (track) {
  22105. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  22106. });
  22107. if (targetTrack === undefined) continue;
  22108. let referenceOffset = 0;
  22109. const referenceValueSize = referenceTrack.getValueSize();
  22110. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22111. referenceOffset = referenceValueSize / 3;
  22112. }
  22113. let targetOffset = 0;
  22114. const targetValueSize = targetTrack.getValueSize();
  22115. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22116. targetOffset = targetValueSize / 3;
  22117. }
  22118. const lastIndex = referenceTrack.times.length - 1;
  22119. let referenceValue; // Find the value to subtract out of the track
  22120. if (referenceTime <= referenceTrack.times[0]) {
  22121. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22122. const startIndex = referenceOffset;
  22123. const endIndex = referenceValueSize - referenceOffset;
  22124. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  22125. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  22126. // Reference frame is after the last keyframe, so just use the last keyframe
  22127. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22128. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22129. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  22130. } else {
  22131. // Interpolate to the reference value
  22132. const interpolant = referenceTrack.createInterpolant();
  22133. const startIndex = referenceOffset;
  22134. const endIndex = referenceValueSize - referenceOffset;
  22135. interpolant.evaluate(referenceTime);
  22136. referenceValue = arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  22137. } // Conjugate the quaternion
  22138. if (referenceTrackType === 'quaternion') {
  22139. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  22140. referenceQuat.toArray(referenceValue);
  22141. } // Subtract the reference value from all of the track values
  22142. const numTimes = targetTrack.times.length;
  22143. for (let j = 0; j < numTimes; ++j) {
  22144. const valueStart = j * targetValueSize + targetOffset;
  22145. if (referenceTrackType === 'quaternion') {
  22146. // Multiply the conjugate for quaternion track types
  22147. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  22148. } else {
  22149. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  22150. for (let k = 0; k < valueEnd; ++k) {
  22151. targetTrack.values[valueStart + k] -= referenceValue[k];
  22152. }
  22153. }
  22154. }
  22155. }
  22156. targetClip.blendMode = AdditiveAnimationBlendMode;
  22157. return targetClip;
  22158. }
  22159. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22160. __proto__: null,
  22161. arraySlice: arraySlice,
  22162. convertArray: convertArray,
  22163. isTypedArray: isTypedArray,
  22164. getKeyframeOrder: getKeyframeOrder,
  22165. sortedArray: sortedArray,
  22166. flattenJSON: flattenJSON,
  22167. subclip: subclip,
  22168. makeClipAdditive: makeClipAdditive
  22169. });
  22170. /**
  22171. * Abstract base class of interpolants over parametric samples.
  22172. *
  22173. * The parameter domain is one dimensional, typically the time or a path
  22174. * along a curve defined by the data.
  22175. *
  22176. * The sample values can have any dimensionality and derived classes may
  22177. * apply special interpretations to the data.
  22178. *
  22179. * This class provides the interval seek in a Template Method, deferring
  22180. * the actual interpolation to derived classes.
  22181. *
  22182. * Time complexity is O(1) for linear access crossing at most two points
  22183. * and O(log N) for random access, where N is the number of positions.
  22184. *
  22185. * References:
  22186. *
  22187. * http://www.oodesign.com/template-method-pattern.html
  22188. *
  22189. */
  22190. class Interpolant {
  22191. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22192. this.parameterPositions = parameterPositions;
  22193. this._cachedIndex = 0;
  22194. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  22195. this.sampleValues = sampleValues;
  22196. this.valueSize = sampleSize;
  22197. this.settings = null;
  22198. this.DefaultSettings_ = {};
  22199. }
  22200. evaluate(t) {
  22201. const pp = this.parameterPositions;
  22202. let i1 = this._cachedIndex,
  22203. t1 = pp[i1],
  22204. t0 = pp[i1 - 1];
  22205. validate_interval: {
  22206. seek: {
  22207. let right;
  22208. linear_scan: {
  22209. //- See http://jsperf.com/comparison-to-undefined/3
  22210. //- slower code:
  22211. //-
  22212. //- if ( t >= t1 || t1 === undefined ) {
  22213. forward_scan: if (!(t < t1)) {
  22214. for (let giveUpAt = i1 + 2;;) {
  22215. if (t1 === undefined) {
  22216. if (t < t0) break forward_scan; // after end
  22217. i1 = pp.length;
  22218. this._cachedIndex = i1;
  22219. return this.copySampleValue_(i1 - 1);
  22220. }
  22221. if (i1 === giveUpAt) break; // this loop
  22222. t0 = t1;
  22223. t1 = pp[++i1];
  22224. if (t < t1) {
  22225. // we have arrived at the sought interval
  22226. break seek;
  22227. }
  22228. } // prepare binary search on the right side of the index
  22229. right = pp.length;
  22230. break linear_scan;
  22231. } //- slower code:
  22232. //- if ( t < t0 || t0 === undefined ) {
  22233. if (!(t >= t0)) {
  22234. // looping?
  22235. const t1global = pp[1];
  22236. if (t < t1global) {
  22237. i1 = 2; // + 1, using the scan for the details
  22238. t0 = t1global;
  22239. } // linear reverse scan
  22240. for (let giveUpAt = i1 - 2;;) {
  22241. if (t0 === undefined) {
  22242. // before start
  22243. this._cachedIndex = 0;
  22244. return this.copySampleValue_(0);
  22245. }
  22246. if (i1 === giveUpAt) break; // this loop
  22247. t1 = t0;
  22248. t0 = pp[--i1 - 1];
  22249. if (t >= t0) {
  22250. // we have arrived at the sought interval
  22251. break seek;
  22252. }
  22253. } // prepare binary search on the left side of the index
  22254. right = i1;
  22255. i1 = 0;
  22256. break linear_scan;
  22257. } // the interval is valid
  22258. break validate_interval;
  22259. } // linear scan
  22260. // binary search
  22261. while (i1 < right) {
  22262. const mid = i1 + right >>> 1;
  22263. if (t < pp[mid]) {
  22264. right = mid;
  22265. } else {
  22266. i1 = mid + 1;
  22267. }
  22268. }
  22269. t1 = pp[i1];
  22270. t0 = pp[i1 - 1]; // check boundary cases, again
  22271. if (t0 === undefined) {
  22272. this._cachedIndex = 0;
  22273. return this.copySampleValue_(0);
  22274. }
  22275. if (t1 === undefined) {
  22276. i1 = pp.length;
  22277. this._cachedIndex = i1;
  22278. return this.copySampleValue_(i1 - 1);
  22279. }
  22280. } // seek
  22281. this._cachedIndex = i1;
  22282. this.intervalChanged_(i1, t0, t1);
  22283. } // validate_interval
  22284. return this.interpolate_(i1, t0, t, t1);
  22285. }
  22286. getSettings_() {
  22287. return this.settings || this.DefaultSettings_;
  22288. }
  22289. copySampleValue_(index) {
  22290. // copies a sample value to the result buffer
  22291. const result = this.resultBuffer,
  22292. values = this.sampleValues,
  22293. stride = this.valueSize,
  22294. offset = index * stride;
  22295. for (let i = 0; i !== stride; ++i) {
  22296. result[i] = values[offset + i];
  22297. }
  22298. return result;
  22299. } // Template methods for derived classes:
  22300. interpolate_() {
  22301. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  22302. }
  22303. intervalChanged_() {// empty
  22304. }
  22305. }
  22306. /**
  22307. * Fast and simple cubic spline interpolant.
  22308. *
  22309. * It was derived from a Hermitian construction setting the first derivative
  22310. * at each sample position to the linear slope between neighboring positions
  22311. * over their parameter interval.
  22312. */
  22313. class CubicInterpolant extends Interpolant {
  22314. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22315. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22316. this._weightPrev = -0;
  22317. this._offsetPrev = -0;
  22318. this._weightNext = -0;
  22319. this._offsetNext = -0;
  22320. this.DefaultSettings_ = {
  22321. endingStart: ZeroCurvatureEnding,
  22322. endingEnd: ZeroCurvatureEnding
  22323. };
  22324. }
  22325. intervalChanged_(i1, t0, t1) {
  22326. const pp = this.parameterPositions;
  22327. let iPrev = i1 - 2,
  22328. iNext = i1 + 1,
  22329. tPrev = pp[iPrev],
  22330. tNext = pp[iNext];
  22331. if (tPrev === undefined) {
  22332. switch (this.getSettings_().endingStart) {
  22333. case ZeroSlopeEnding:
  22334. // f'(t0) = 0
  22335. iPrev = i1;
  22336. tPrev = 2 * t0 - t1;
  22337. break;
  22338. case WrapAroundEnding:
  22339. // use the other end of the curve
  22340. iPrev = pp.length - 2;
  22341. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  22342. break;
  22343. default:
  22344. // ZeroCurvatureEnding
  22345. // f''(t0) = 0 a.k.a. Natural Spline
  22346. iPrev = i1;
  22347. tPrev = t1;
  22348. }
  22349. }
  22350. if (tNext === undefined) {
  22351. switch (this.getSettings_().endingEnd) {
  22352. case ZeroSlopeEnding:
  22353. // f'(tN) = 0
  22354. iNext = i1;
  22355. tNext = 2 * t1 - t0;
  22356. break;
  22357. case WrapAroundEnding:
  22358. // use the other end of the curve
  22359. iNext = 1;
  22360. tNext = t1 + pp[1] - pp[0];
  22361. break;
  22362. default:
  22363. // ZeroCurvatureEnding
  22364. // f''(tN) = 0, a.k.a. Natural Spline
  22365. iNext = i1 - 1;
  22366. tNext = t0;
  22367. }
  22368. }
  22369. const halfDt = (t1 - t0) * 0.5,
  22370. stride = this.valueSize;
  22371. this._weightPrev = halfDt / (t0 - tPrev);
  22372. this._weightNext = halfDt / (tNext - t1);
  22373. this._offsetPrev = iPrev * stride;
  22374. this._offsetNext = iNext * stride;
  22375. }
  22376. interpolate_(i1, t0, t, t1) {
  22377. const result = this.resultBuffer,
  22378. values = this.sampleValues,
  22379. stride = this.valueSize,
  22380. o1 = i1 * stride,
  22381. o0 = o1 - stride,
  22382. oP = this._offsetPrev,
  22383. oN = this._offsetNext,
  22384. wP = this._weightPrev,
  22385. wN = this._weightNext,
  22386. p = (t - t0) / (t1 - t0),
  22387. pp = p * p,
  22388. ppp = pp * p; // evaluate polynomials
  22389. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  22390. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  22391. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  22392. const sN = wN * ppp - wN * pp; // combine data linearly
  22393. for (let i = 0; i !== stride; ++i) {
  22394. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  22395. }
  22396. return result;
  22397. }
  22398. }
  22399. class LinearInterpolant extends Interpolant {
  22400. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22401. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22402. }
  22403. interpolate_(i1, t0, t, t1) {
  22404. const result = this.resultBuffer,
  22405. values = this.sampleValues,
  22406. stride = this.valueSize,
  22407. offset1 = i1 * stride,
  22408. offset0 = offset1 - stride,
  22409. weight1 = (t - t0) / (t1 - t0),
  22410. weight0 = 1 - weight1;
  22411. for (let i = 0; i !== stride; ++i) {
  22412. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  22413. }
  22414. return result;
  22415. }
  22416. }
  22417. /**
  22418. *
  22419. * Interpolant that evaluates to the sample value at the position preceding
  22420. * the parameter.
  22421. */
  22422. class DiscreteInterpolant extends Interpolant {
  22423. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22424. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22425. }
  22426. interpolate_(i1
  22427. /*, t0, t, t1 */
  22428. ) {
  22429. return this.copySampleValue_(i1 - 1);
  22430. }
  22431. }
  22432. class KeyframeTrack {
  22433. constructor(name, times, values, interpolation) {
  22434. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  22435. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  22436. this.name = name;
  22437. this.times = convertArray(times, this.TimeBufferType);
  22438. this.values = convertArray(values, this.ValueBufferType);
  22439. this.setInterpolation(interpolation || this.DefaultInterpolation);
  22440. } // Serialization (in static context, because of constructor invocation
  22441. // and automatic invocation of .toJSON):
  22442. static toJSON(track) {
  22443. const trackType = track.constructor;
  22444. let json; // derived classes can define a static toJSON method
  22445. if (trackType.toJSON !== this.toJSON) {
  22446. json = trackType.toJSON(track);
  22447. } else {
  22448. // by default, we assume the data can be serialized as-is
  22449. json = {
  22450. 'name': track.name,
  22451. 'times': convertArray(track.times, Array),
  22452. 'values': convertArray(track.values, Array)
  22453. };
  22454. const interpolation = track.getInterpolation();
  22455. if (interpolation !== track.DefaultInterpolation) {
  22456. json.interpolation = interpolation;
  22457. }
  22458. }
  22459. json.type = track.ValueTypeName; // mandatory
  22460. return json;
  22461. }
  22462. InterpolantFactoryMethodDiscrete(result) {
  22463. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  22464. }
  22465. InterpolantFactoryMethodLinear(result) {
  22466. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22467. }
  22468. InterpolantFactoryMethodSmooth(result) {
  22469. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  22470. }
  22471. setInterpolation(interpolation) {
  22472. let factoryMethod;
  22473. switch (interpolation) {
  22474. case InterpolateDiscrete:
  22475. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22476. break;
  22477. case InterpolateLinear:
  22478. factoryMethod = this.InterpolantFactoryMethodLinear;
  22479. break;
  22480. case InterpolateSmooth:
  22481. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22482. break;
  22483. }
  22484. if (factoryMethod === undefined) {
  22485. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  22486. if (this.createInterpolant === undefined) {
  22487. // fall back to default, unless the default itself is messed up
  22488. if (interpolation !== this.DefaultInterpolation) {
  22489. this.setInterpolation(this.DefaultInterpolation);
  22490. } else {
  22491. throw new Error(message); // fatal, in this case
  22492. }
  22493. }
  22494. console.warn('THREE.KeyframeTrack:', message);
  22495. return this;
  22496. }
  22497. this.createInterpolant = factoryMethod;
  22498. return this;
  22499. }
  22500. getInterpolation() {
  22501. switch (this.createInterpolant) {
  22502. case this.InterpolantFactoryMethodDiscrete:
  22503. return InterpolateDiscrete;
  22504. case this.InterpolantFactoryMethodLinear:
  22505. return InterpolateLinear;
  22506. case this.InterpolantFactoryMethodSmooth:
  22507. return InterpolateSmooth;
  22508. }
  22509. }
  22510. getValueSize() {
  22511. return this.values.length / this.times.length;
  22512. } // move all keyframes either forwards or backwards in time
  22513. shift(timeOffset) {
  22514. if (timeOffset !== 0.0) {
  22515. const times = this.times;
  22516. for (let i = 0, n = times.length; i !== n; ++i) {
  22517. times[i] += timeOffset;
  22518. }
  22519. }
  22520. return this;
  22521. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22522. scale(timeScale) {
  22523. if (timeScale !== 1.0) {
  22524. const times = this.times;
  22525. for (let i = 0, n = times.length; i !== n; ++i) {
  22526. times[i] *= timeScale;
  22527. }
  22528. }
  22529. return this;
  22530. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22531. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22532. trim(startTime, endTime) {
  22533. const times = this.times,
  22534. nKeys = times.length;
  22535. let from = 0,
  22536. to = nKeys - 1;
  22537. while (from !== nKeys && times[from] < startTime) {
  22538. ++from;
  22539. }
  22540. while (to !== -1 && times[to] > endTime) {
  22541. --to;
  22542. }
  22543. ++to; // inclusive -> exclusive bound
  22544. if (from !== 0 || to !== nKeys) {
  22545. // empty tracks are forbidden, so keep at least one keyframe
  22546. if (from >= to) {
  22547. to = Math.max(to, 1);
  22548. from = to - 1;
  22549. }
  22550. const stride = this.getValueSize();
  22551. this.times = arraySlice(times, from, to);
  22552. this.values = arraySlice(this.values, from * stride, to * stride);
  22553. }
  22554. return this;
  22555. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22556. validate() {
  22557. let valid = true;
  22558. const valueSize = this.getValueSize();
  22559. if (valueSize - Math.floor(valueSize) !== 0) {
  22560. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  22561. valid = false;
  22562. }
  22563. const times = this.times,
  22564. values = this.values,
  22565. nKeys = times.length;
  22566. if (nKeys === 0) {
  22567. console.error('THREE.KeyframeTrack: Track is empty.', this);
  22568. valid = false;
  22569. }
  22570. let prevTime = null;
  22571. for (let i = 0; i !== nKeys; i++) {
  22572. const currTime = times[i];
  22573. if (typeof currTime === 'number' && isNaN(currTime)) {
  22574. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  22575. valid = false;
  22576. break;
  22577. }
  22578. if (prevTime !== null && prevTime > currTime) {
  22579. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  22580. valid = false;
  22581. break;
  22582. }
  22583. prevTime = currTime;
  22584. }
  22585. if (values !== undefined) {
  22586. if (isTypedArray(values)) {
  22587. for (let i = 0, n = values.length; i !== n; ++i) {
  22588. const value = values[i];
  22589. if (isNaN(value)) {
  22590. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  22591. valid = false;
  22592. break;
  22593. }
  22594. }
  22595. }
  22596. }
  22597. return valid;
  22598. } // removes equivalent sequential keys as common in morph target sequences
  22599. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22600. optimize() {
  22601. // times or values may be shared with other tracks, so overwriting is unsafe
  22602. const times = arraySlice(this.times),
  22603. values = arraySlice(this.values),
  22604. stride = this.getValueSize(),
  22605. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22606. lastIndex = times.length - 1;
  22607. let writeIndex = 1;
  22608. for (let i = 1; i < lastIndex; ++i) {
  22609. let keep = false;
  22610. const time = times[i];
  22611. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  22612. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  22613. if (!smoothInterpolation) {
  22614. // remove unnecessary keyframes same as their neighbors
  22615. const offset = i * stride,
  22616. offsetP = offset - stride,
  22617. offsetN = offset + stride;
  22618. for (let j = 0; j !== stride; ++j) {
  22619. const value = values[offset + j];
  22620. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  22621. keep = true;
  22622. break;
  22623. }
  22624. }
  22625. } else {
  22626. keep = true;
  22627. }
  22628. } // in-place compaction
  22629. if (keep) {
  22630. if (i !== writeIndex) {
  22631. times[writeIndex] = times[i];
  22632. const readOffset = i * stride,
  22633. writeOffset = writeIndex * stride;
  22634. for (let j = 0; j !== stride; ++j) {
  22635. values[writeOffset + j] = values[readOffset + j];
  22636. }
  22637. }
  22638. ++writeIndex;
  22639. }
  22640. } // flush last keyframe (compaction looks ahead)
  22641. if (lastIndex > 0) {
  22642. times[writeIndex] = times[lastIndex];
  22643. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  22644. values[writeOffset + j] = values[readOffset + j];
  22645. }
  22646. ++writeIndex;
  22647. }
  22648. if (writeIndex !== times.length) {
  22649. this.times = arraySlice(times, 0, writeIndex);
  22650. this.values = arraySlice(values, 0, writeIndex * stride);
  22651. } else {
  22652. this.times = times;
  22653. this.values = values;
  22654. }
  22655. return this;
  22656. }
  22657. clone() {
  22658. const times = arraySlice(this.times, 0);
  22659. const values = arraySlice(this.values, 0);
  22660. const TypedKeyframeTrack = this.constructor;
  22661. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22662. track.createInterpolant = this.createInterpolant;
  22663. return track;
  22664. }
  22665. }
  22666. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22667. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22668. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22669. /**
  22670. * A Track of Boolean keyframe values.
  22671. */
  22672. class BooleanKeyframeTrack extends KeyframeTrack {}
  22673. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22674. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22675. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22676. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22677. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  22678. /**
  22679. * A Track of keyframe values that represent color.
  22680. */
  22681. class ColorKeyframeTrack extends KeyframeTrack {}
  22682. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  22683. /**
  22684. * A Track of numeric keyframe values.
  22685. */
  22686. class NumberKeyframeTrack extends KeyframeTrack {}
  22687. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  22688. /**
  22689. * Spherical linear unit quaternion interpolant.
  22690. */
  22691. class QuaternionLinearInterpolant extends Interpolant {
  22692. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22693. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22694. }
  22695. interpolate_(i1, t0, t, t1) {
  22696. const result = this.resultBuffer,
  22697. values = this.sampleValues,
  22698. stride = this.valueSize,
  22699. alpha = (t - t0) / (t1 - t0);
  22700. let offset = i1 * stride;
  22701. for (let end = offset + stride; offset !== end; offset += 4) {
  22702. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  22703. }
  22704. return result;
  22705. }
  22706. }
  22707. /**
  22708. * A Track of quaternion keyframe values.
  22709. */
  22710. class QuaternionKeyframeTrack extends KeyframeTrack {
  22711. InterpolantFactoryMethodLinear(result) {
  22712. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22713. }
  22714. }
  22715. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  22716. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22717. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22718. /**
  22719. * A Track that interpolates Strings
  22720. */
  22721. class StringKeyframeTrack extends KeyframeTrack {}
  22722. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22723. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22724. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22725. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22726. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22727. /**
  22728. * A Track of vectored keyframe values.
  22729. */
  22730. class VectorKeyframeTrack extends KeyframeTrack {}
  22731. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  22732. class AnimationClip {
  22733. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  22734. this.name = name;
  22735. this.tracks = tracks;
  22736. this.duration = duration;
  22737. this.blendMode = blendMode;
  22738. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  22739. if (this.duration < 0) {
  22740. this.resetDuration();
  22741. }
  22742. }
  22743. static parse(json) {
  22744. const tracks = [],
  22745. jsonTracks = json.tracks,
  22746. frameTime = 1.0 / (json.fps || 1.0);
  22747. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  22748. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22749. }
  22750. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22751. clip.uuid = json.uuid;
  22752. return clip;
  22753. }
  22754. static toJSON(clip) {
  22755. const tracks = [],
  22756. clipTracks = clip.tracks;
  22757. const json = {
  22758. 'name': clip.name,
  22759. 'duration': clip.duration,
  22760. 'tracks': tracks,
  22761. 'uuid': clip.uuid,
  22762. 'blendMode': clip.blendMode
  22763. };
  22764. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22765. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22766. }
  22767. return json;
  22768. }
  22769. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22770. const numMorphTargets = morphTargetSequence.length;
  22771. const tracks = [];
  22772. for (let i = 0; i < numMorphTargets; i++) {
  22773. let times = [];
  22774. let values = [];
  22775. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22776. values.push(0, 1, 0);
  22777. const order = getKeyframeOrder(times);
  22778. times = sortedArray(times, 1, order);
  22779. values = sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22780. // last frame as well for perfect loop.
  22781. if (!noLoop && times[0] === 0) {
  22782. times.push(numMorphTargets);
  22783. values.push(values[0]);
  22784. }
  22785. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22786. }
  22787. return new this(name, -1, tracks);
  22788. }
  22789. static findByName(objectOrClipArray, name) {
  22790. let clipArray = objectOrClipArray;
  22791. if (!Array.isArray(objectOrClipArray)) {
  22792. const o = objectOrClipArray;
  22793. clipArray = o.geometry && o.geometry.animations || o.animations;
  22794. }
  22795. for (let i = 0; i < clipArray.length; i++) {
  22796. if (clipArray[i].name === name) {
  22797. return clipArray[i];
  22798. }
  22799. }
  22800. return null;
  22801. }
  22802. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22803. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22804. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22805. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22806. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22807. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22808. const morphTarget = morphTargets[i];
  22809. const parts = morphTarget.name.match(pattern);
  22810. if (parts && parts.length > 1) {
  22811. const name = parts[1];
  22812. let animationMorphTargets = animationToMorphTargets[name];
  22813. if (!animationMorphTargets) {
  22814. animationToMorphTargets[name] = animationMorphTargets = [];
  22815. }
  22816. animationMorphTargets.push(morphTarget);
  22817. }
  22818. }
  22819. const clips = [];
  22820. for (const name in animationToMorphTargets) {
  22821. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22822. }
  22823. return clips;
  22824. } // parse the animation.hierarchy format
  22825. static parseAnimation(animation, bones) {
  22826. if (!animation) {
  22827. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22828. return null;
  22829. }
  22830. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22831. // only return track if there are actually keys.
  22832. if (animationKeys.length !== 0) {
  22833. const times = [];
  22834. const values = [];
  22835. flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22836. if (times.length !== 0) {
  22837. destTracks.push(new trackType(trackName, times, values));
  22838. }
  22839. }
  22840. };
  22841. const tracks = [];
  22842. const clipName = animation.name || 'default';
  22843. const fps = animation.fps || 30;
  22844. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22845. let duration = animation.length || -1;
  22846. const hierarchyTracks = animation.hierarchy || [];
  22847. for (let h = 0; h < hierarchyTracks.length; h++) {
  22848. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22849. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22850. if (animationKeys[0].morphTargets) {
  22851. // figure out all morph targets used in this track
  22852. const morphTargetNames = {};
  22853. let k;
  22854. for (k = 0; k < animationKeys.length; k++) {
  22855. if (animationKeys[k].morphTargets) {
  22856. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22857. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22858. }
  22859. }
  22860. } // create a track for each morph target with all zero
  22861. // morphTargetInfluences except for the keys in which
  22862. // the morphTarget is named.
  22863. for (const morphTargetName in morphTargetNames) {
  22864. const times = [];
  22865. const values = [];
  22866. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22867. const animationKey = animationKeys[k];
  22868. times.push(animationKey.time);
  22869. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22870. }
  22871. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22872. }
  22873. duration = morphTargetNames.length * fps;
  22874. } else {
  22875. // ...assume skeletal animation
  22876. const boneName = '.bones[' + bones[h].name + ']';
  22877. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22878. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22879. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22880. }
  22881. }
  22882. if (tracks.length === 0) {
  22883. return null;
  22884. }
  22885. const clip = new this(clipName, duration, tracks, blendMode);
  22886. return clip;
  22887. }
  22888. resetDuration() {
  22889. const tracks = this.tracks;
  22890. let duration = 0;
  22891. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22892. const track = this.tracks[i];
  22893. duration = Math.max(duration, track.times[track.times.length - 1]);
  22894. }
  22895. this.duration = duration;
  22896. return this;
  22897. }
  22898. trim() {
  22899. for (let i = 0; i < this.tracks.length; i++) {
  22900. this.tracks[i].trim(0, this.duration);
  22901. }
  22902. return this;
  22903. }
  22904. validate() {
  22905. let valid = true;
  22906. for (let i = 0; i < this.tracks.length; i++) {
  22907. valid = valid && this.tracks[i].validate();
  22908. }
  22909. return valid;
  22910. }
  22911. optimize() {
  22912. for (let i = 0; i < this.tracks.length; i++) {
  22913. this.tracks[i].optimize();
  22914. }
  22915. return this;
  22916. }
  22917. clone() {
  22918. const tracks = [];
  22919. for (let i = 0; i < this.tracks.length; i++) {
  22920. tracks.push(this.tracks[i].clone());
  22921. }
  22922. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22923. }
  22924. toJSON() {
  22925. return this.constructor.toJSON(this);
  22926. }
  22927. }
  22928. function getTrackTypeForValueTypeName(typeName) {
  22929. switch (typeName.toLowerCase()) {
  22930. case 'scalar':
  22931. case 'double':
  22932. case 'float':
  22933. case 'number':
  22934. case 'integer':
  22935. return NumberKeyframeTrack;
  22936. case 'vector':
  22937. case 'vector2':
  22938. case 'vector3':
  22939. case 'vector4':
  22940. return VectorKeyframeTrack;
  22941. case 'color':
  22942. return ColorKeyframeTrack;
  22943. case 'quaternion':
  22944. return QuaternionKeyframeTrack;
  22945. case 'bool':
  22946. case 'boolean':
  22947. return BooleanKeyframeTrack;
  22948. case 'string':
  22949. return StringKeyframeTrack;
  22950. }
  22951. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22952. }
  22953. function parseKeyframeTrack(json) {
  22954. if (json.type === undefined) {
  22955. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22956. }
  22957. const trackType = getTrackTypeForValueTypeName(json.type);
  22958. if (json.times === undefined) {
  22959. const times = [],
  22960. values = [];
  22961. flattenJSON(json.keys, times, values, 'value');
  22962. json.times = times;
  22963. json.values = values;
  22964. } // derived classes can define a static parse method
  22965. if (trackType.parse !== undefined) {
  22966. return trackType.parse(json);
  22967. } else {
  22968. // by default, we assume a constructor compatible with the base
  22969. return new trackType(json.name, json.times, json.values, json.interpolation);
  22970. }
  22971. }
  22972. const Cache = {
  22973. enabled: false,
  22974. files: {},
  22975. add: function (key, file) {
  22976. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22977. this.files[key] = file;
  22978. },
  22979. get: function (key) {
  22980. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22981. return this.files[key];
  22982. },
  22983. remove: function (key) {
  22984. delete this.files[key];
  22985. },
  22986. clear: function () {
  22987. this.files = {};
  22988. }
  22989. };
  22990. class LoadingManager {
  22991. constructor(onLoad, onProgress, onError) {
  22992. const scope = this;
  22993. let isLoading = false;
  22994. let itemsLoaded = 0;
  22995. let itemsTotal = 0;
  22996. let urlModifier = undefined;
  22997. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22998. // in the constructor
  22999. this.onStart = undefined;
  23000. this.onLoad = onLoad;
  23001. this.onProgress = onProgress;
  23002. this.onError = onError;
  23003. this.itemStart = function (url) {
  23004. itemsTotal++;
  23005. if (isLoading === false) {
  23006. if (scope.onStart !== undefined) {
  23007. scope.onStart(url, itemsLoaded, itemsTotal);
  23008. }
  23009. }
  23010. isLoading = true;
  23011. };
  23012. this.itemEnd = function (url) {
  23013. itemsLoaded++;
  23014. if (scope.onProgress !== undefined) {
  23015. scope.onProgress(url, itemsLoaded, itemsTotal);
  23016. }
  23017. if (itemsLoaded === itemsTotal) {
  23018. isLoading = false;
  23019. if (scope.onLoad !== undefined) {
  23020. scope.onLoad();
  23021. }
  23022. }
  23023. };
  23024. this.itemError = function (url) {
  23025. if (scope.onError !== undefined) {
  23026. scope.onError(url);
  23027. }
  23028. };
  23029. this.resolveURL = function (url) {
  23030. if (urlModifier) {
  23031. return urlModifier(url);
  23032. }
  23033. return url;
  23034. };
  23035. this.setURLModifier = function (transform) {
  23036. urlModifier = transform;
  23037. return this;
  23038. };
  23039. this.addHandler = function (regex, loader) {
  23040. handlers.push(regex, loader);
  23041. return this;
  23042. };
  23043. this.removeHandler = function (regex) {
  23044. const index = handlers.indexOf(regex);
  23045. if (index !== -1) {
  23046. handlers.splice(index, 2);
  23047. }
  23048. return this;
  23049. };
  23050. this.getHandler = function (file) {
  23051. for (let i = 0, l = handlers.length; i < l; i += 2) {
  23052. const regex = handlers[i];
  23053. const loader = handlers[i + 1];
  23054. if (regex.global) regex.lastIndex = 0; // see #17920
  23055. if (regex.test(file)) {
  23056. return loader;
  23057. }
  23058. }
  23059. return null;
  23060. };
  23061. }
  23062. }
  23063. const DefaultLoadingManager = /*@__PURE__*/new LoadingManager();
  23064. class Loader {
  23065. constructor(manager) {
  23066. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  23067. this.crossOrigin = 'anonymous';
  23068. this.withCredentials = false;
  23069. this.path = '';
  23070. this.resourcePath = '';
  23071. this.requestHeader = {};
  23072. }
  23073. load() {}
  23074. loadAsync(url, onProgress) {
  23075. const scope = this;
  23076. return new Promise(function (resolve, reject) {
  23077. scope.load(url, resolve, onProgress, reject);
  23078. });
  23079. }
  23080. parse() {}
  23081. setCrossOrigin(crossOrigin) {
  23082. this.crossOrigin = crossOrigin;
  23083. return this;
  23084. }
  23085. setWithCredentials(value) {
  23086. this.withCredentials = value;
  23087. return this;
  23088. }
  23089. setPath(path) {
  23090. this.path = path;
  23091. return this;
  23092. }
  23093. setResourcePath(resourcePath) {
  23094. this.resourcePath = resourcePath;
  23095. return this;
  23096. }
  23097. setRequestHeader(requestHeader) {
  23098. this.requestHeader = requestHeader;
  23099. return this;
  23100. }
  23101. }
  23102. const loading = {};
  23103. class HttpError extends Error {
  23104. constructor(message, response) {
  23105. super(message);
  23106. this.response = response;
  23107. }
  23108. }
  23109. class FileLoader extends Loader {
  23110. constructor(manager) {
  23111. super(manager);
  23112. }
  23113. load(url, onLoad, onProgress, onError) {
  23114. if (url === undefined) url = '';
  23115. if (this.path !== undefined) url = this.path + url;
  23116. url = this.manager.resolveURL(url);
  23117. const cached = Cache.get(url);
  23118. if (cached !== undefined) {
  23119. this.manager.itemStart(url);
  23120. setTimeout(() => {
  23121. if (onLoad) onLoad(cached);
  23122. this.manager.itemEnd(url);
  23123. }, 0);
  23124. return cached;
  23125. } // Check if request is duplicate
  23126. if (loading[url] !== undefined) {
  23127. loading[url].push({
  23128. onLoad: onLoad,
  23129. onProgress: onProgress,
  23130. onError: onError
  23131. });
  23132. return;
  23133. } // Initialise array for duplicate requests
  23134. loading[url] = [];
  23135. loading[url].push({
  23136. onLoad: onLoad,
  23137. onProgress: onProgress,
  23138. onError: onError
  23139. }); // create request
  23140. const req = new Request(url, {
  23141. headers: new Headers(this.requestHeader),
  23142. credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
  23143. }); // record states ( avoid data race )
  23144. const mimeType = this.mimeType;
  23145. const responseType = this.responseType; // start the fetch
  23146. fetch(req).then(response => {
  23147. if (response.status === 200 || response.status === 0) {
  23148. // Some browsers return HTTP Status 0 when using non-http protocol
  23149. // e.g. 'file://' or 'data://'. Handle as success.
  23150. if (response.status === 0) {
  23151. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  23152. } // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23153. if (typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined) {
  23154. return response;
  23155. }
  23156. const callbacks = loading[url];
  23157. const reader = response.body.getReader();
  23158. const contentLength = response.headers.get('Content-Length');
  23159. const total = contentLength ? parseInt(contentLength) : 0;
  23160. const lengthComputable = total !== 0;
  23161. let loaded = 0; // periodically read data into the new stream tracking while download progress
  23162. const stream = new ReadableStream({
  23163. start(controller) {
  23164. readData();
  23165. function readData() {
  23166. reader.read().then(({
  23167. done,
  23168. value
  23169. }) => {
  23170. if (done) {
  23171. controller.close();
  23172. } else {
  23173. loaded += value.byteLength;
  23174. const event = new ProgressEvent('progress', {
  23175. lengthComputable,
  23176. loaded,
  23177. total
  23178. });
  23179. for (let i = 0, il = callbacks.length; i < il; i++) {
  23180. const callback = callbacks[i];
  23181. if (callback.onProgress) callback.onProgress(event);
  23182. }
  23183. controller.enqueue(value);
  23184. readData();
  23185. }
  23186. });
  23187. }
  23188. }
  23189. });
  23190. return new Response(stream);
  23191. } else {
  23192. throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response);
  23193. }
  23194. }).then(response => {
  23195. switch (responseType) {
  23196. case 'arraybuffer':
  23197. return response.arrayBuffer();
  23198. case 'blob':
  23199. return response.blob();
  23200. case 'document':
  23201. return response.text().then(text => {
  23202. const parser = new DOMParser();
  23203. return parser.parseFromString(text, mimeType);
  23204. });
  23205. case 'json':
  23206. return response.json();
  23207. default:
  23208. if (mimeType === undefined) {
  23209. return response.text();
  23210. } else {
  23211. // sniff encoding
  23212. const re = /charset="?([^;"\s]*)"?/i;
  23213. const exec = re.exec(mimeType);
  23214. const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
  23215. const decoder = new TextDecoder(label);
  23216. return response.arrayBuffer().then(ab => decoder.decode(ab));
  23217. }
  23218. }
  23219. }).then(data => {
  23220. // Add to cache only on HTTP success, so that we do not cache
  23221. // error response bodies as proper responses to requests.
  23222. Cache.add(url, data);
  23223. const callbacks = loading[url];
  23224. delete loading[url];
  23225. for (let i = 0, il = callbacks.length; i < il; i++) {
  23226. const callback = callbacks[i];
  23227. if (callback.onLoad) callback.onLoad(data);
  23228. }
  23229. }).catch(err => {
  23230. // Abort errors and other errors are handled the same
  23231. const callbacks = loading[url];
  23232. if (callbacks === undefined) {
  23233. // When onLoad was called and url was deleted in `loading`
  23234. this.manager.itemError(url);
  23235. throw err;
  23236. }
  23237. delete loading[url];
  23238. for (let i = 0, il = callbacks.length; i < il; i++) {
  23239. const callback = callbacks[i];
  23240. if (callback.onError) callback.onError(err);
  23241. }
  23242. this.manager.itemError(url);
  23243. }).finally(() => {
  23244. this.manager.itemEnd(url);
  23245. });
  23246. this.manager.itemStart(url);
  23247. }
  23248. setResponseType(value) {
  23249. this.responseType = value;
  23250. return this;
  23251. }
  23252. setMimeType(value) {
  23253. this.mimeType = value;
  23254. return this;
  23255. }
  23256. }
  23257. class AnimationLoader extends Loader {
  23258. constructor(manager) {
  23259. super(manager);
  23260. }
  23261. load(url, onLoad, onProgress, onError) {
  23262. const scope = this;
  23263. const loader = new FileLoader(this.manager);
  23264. loader.setPath(this.path);
  23265. loader.setRequestHeader(this.requestHeader);
  23266. loader.setWithCredentials(this.withCredentials);
  23267. loader.load(url, function (text) {
  23268. try {
  23269. onLoad(scope.parse(JSON.parse(text)));
  23270. } catch (e) {
  23271. if (onError) {
  23272. onError(e);
  23273. } else {
  23274. console.error(e);
  23275. }
  23276. scope.manager.itemError(url);
  23277. }
  23278. }, onProgress, onError);
  23279. }
  23280. parse(json) {
  23281. const animations = [];
  23282. for (let i = 0; i < json.length; i++) {
  23283. const clip = AnimationClip.parse(json[i]);
  23284. animations.push(clip);
  23285. }
  23286. return animations;
  23287. }
  23288. }
  23289. /**
  23290. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23291. *
  23292. * Sub classes have to implement the parse() method which will be used in load().
  23293. */
  23294. class CompressedTextureLoader extends Loader {
  23295. constructor(manager) {
  23296. super(manager);
  23297. }
  23298. load(url, onLoad, onProgress, onError) {
  23299. const scope = this;
  23300. const images = [];
  23301. const texture = new CompressedTexture();
  23302. const loader = new FileLoader(this.manager);
  23303. loader.setPath(this.path);
  23304. loader.setResponseType('arraybuffer');
  23305. loader.setRequestHeader(this.requestHeader);
  23306. loader.setWithCredentials(scope.withCredentials);
  23307. let loaded = 0;
  23308. function loadTexture(i) {
  23309. loader.load(url[i], function (buffer) {
  23310. const texDatas = scope.parse(buffer, true);
  23311. images[i] = {
  23312. width: texDatas.width,
  23313. height: texDatas.height,
  23314. format: texDatas.format,
  23315. mipmaps: texDatas.mipmaps
  23316. };
  23317. loaded += 1;
  23318. if (loaded === 6) {
  23319. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  23320. texture.image = images;
  23321. texture.format = texDatas.format;
  23322. texture.needsUpdate = true;
  23323. if (onLoad) onLoad(texture);
  23324. }
  23325. }, onProgress, onError);
  23326. }
  23327. if (Array.isArray(url)) {
  23328. for (let i = 0, il = url.length; i < il; ++i) {
  23329. loadTexture(i);
  23330. }
  23331. } else {
  23332. // compressed cubemap texture stored in a single DDS file
  23333. loader.load(url, function (buffer) {
  23334. const texDatas = scope.parse(buffer, true);
  23335. if (texDatas.isCubemap) {
  23336. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23337. for (let f = 0; f < faces; f++) {
  23338. images[f] = {
  23339. mipmaps: []
  23340. };
  23341. for (let i = 0; i < texDatas.mipmapCount; i++) {
  23342. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  23343. images[f].format = texDatas.format;
  23344. images[f].width = texDatas.width;
  23345. images[f].height = texDatas.height;
  23346. }
  23347. }
  23348. texture.image = images;
  23349. } else {
  23350. texture.image.width = texDatas.width;
  23351. texture.image.height = texDatas.height;
  23352. texture.mipmaps = texDatas.mipmaps;
  23353. }
  23354. if (texDatas.mipmapCount === 1) {
  23355. texture.minFilter = LinearFilter;
  23356. }
  23357. texture.format = texDatas.format;
  23358. texture.needsUpdate = true;
  23359. if (onLoad) onLoad(texture);
  23360. }, onProgress, onError);
  23361. }
  23362. return texture;
  23363. }
  23364. }
  23365. class ImageLoader extends Loader {
  23366. constructor(manager) {
  23367. super(manager);
  23368. }
  23369. load(url, onLoad, onProgress, onError) {
  23370. if (this.path !== undefined) url = this.path + url;
  23371. url = this.manager.resolveURL(url);
  23372. const scope = this;
  23373. const cached = Cache.get(url);
  23374. if (cached !== undefined) {
  23375. scope.manager.itemStart(url);
  23376. setTimeout(function () {
  23377. if (onLoad) onLoad(cached);
  23378. scope.manager.itemEnd(url);
  23379. }, 0);
  23380. return cached;
  23381. }
  23382. const image = createElementNS('img');
  23383. function onImageLoad() {
  23384. removeEventListeners();
  23385. Cache.add(url, this);
  23386. if (onLoad) onLoad(this);
  23387. scope.manager.itemEnd(url);
  23388. }
  23389. function onImageError(event) {
  23390. removeEventListeners();
  23391. if (onError) onError(event);
  23392. scope.manager.itemError(url);
  23393. scope.manager.itemEnd(url);
  23394. }
  23395. function removeEventListeners() {
  23396. image.removeEventListener('load', onImageLoad, false);
  23397. image.removeEventListener('error', onImageError, false);
  23398. }
  23399. image.addEventListener('load', onImageLoad, false);
  23400. image.addEventListener('error', onImageError, false);
  23401. if (url.slice(0, 5) !== 'data:') {
  23402. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  23403. }
  23404. scope.manager.itemStart(url);
  23405. image.src = url;
  23406. return image;
  23407. }
  23408. }
  23409. class CubeTextureLoader extends Loader {
  23410. constructor(manager) {
  23411. super(manager);
  23412. }
  23413. load(urls, onLoad, onProgress, onError) {
  23414. const texture = new CubeTexture();
  23415. const loader = new ImageLoader(this.manager);
  23416. loader.setCrossOrigin(this.crossOrigin);
  23417. loader.setPath(this.path);
  23418. let loaded = 0;
  23419. function loadTexture(i) {
  23420. loader.load(urls[i], function (image) {
  23421. texture.images[i] = image;
  23422. loaded++;
  23423. if (loaded === 6) {
  23424. texture.needsUpdate = true;
  23425. if (onLoad) onLoad(texture);
  23426. }
  23427. }, undefined, onError);
  23428. }
  23429. for (let i = 0; i < urls.length; ++i) {
  23430. loadTexture(i);
  23431. }
  23432. return texture;
  23433. }
  23434. }
  23435. /**
  23436. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23437. *
  23438. * Sub classes have to implement the parse() method which will be used in load().
  23439. */
  23440. class DataTextureLoader extends Loader {
  23441. constructor(manager) {
  23442. super(manager);
  23443. }
  23444. load(url, onLoad, onProgress, onError) {
  23445. const scope = this;
  23446. const texture = new DataTexture();
  23447. const loader = new FileLoader(this.manager);
  23448. loader.setResponseType('arraybuffer');
  23449. loader.setRequestHeader(this.requestHeader);
  23450. loader.setPath(this.path);
  23451. loader.setWithCredentials(scope.withCredentials);
  23452. loader.load(url, function (buffer) {
  23453. const texData = scope.parse(buffer);
  23454. if (!texData) return;
  23455. if (texData.image !== undefined) {
  23456. texture.image = texData.image;
  23457. } else if (texData.data !== undefined) {
  23458. texture.image.width = texData.width;
  23459. texture.image.height = texData.height;
  23460. texture.image.data = texData.data;
  23461. }
  23462. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23463. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23464. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23465. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23466. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23467. if (texData.encoding !== undefined) {
  23468. texture.encoding = texData.encoding;
  23469. }
  23470. if (texData.flipY !== undefined) {
  23471. texture.flipY = texData.flipY;
  23472. }
  23473. if (texData.format !== undefined) {
  23474. texture.format = texData.format;
  23475. }
  23476. if (texData.type !== undefined) {
  23477. texture.type = texData.type;
  23478. }
  23479. if (texData.mipmaps !== undefined) {
  23480. texture.mipmaps = texData.mipmaps;
  23481. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23482. }
  23483. if (texData.mipmapCount === 1) {
  23484. texture.minFilter = LinearFilter;
  23485. }
  23486. if (texData.generateMipmaps !== undefined) {
  23487. texture.generateMipmaps = texData.generateMipmaps;
  23488. }
  23489. texture.needsUpdate = true;
  23490. if (onLoad) onLoad(texture, texData);
  23491. }, onProgress, onError);
  23492. return texture;
  23493. }
  23494. }
  23495. class TextureLoader extends Loader {
  23496. constructor(manager) {
  23497. super(manager);
  23498. }
  23499. load(url, onLoad, onProgress, onError) {
  23500. const texture = new Texture();
  23501. const loader = new ImageLoader(this.manager);
  23502. loader.setCrossOrigin(this.crossOrigin);
  23503. loader.setPath(this.path);
  23504. loader.load(url, function (image) {
  23505. texture.image = image;
  23506. texture.needsUpdate = true;
  23507. if (onLoad !== undefined) {
  23508. onLoad(texture);
  23509. }
  23510. }, onProgress, onError);
  23511. return texture;
  23512. }
  23513. }
  23514. class Light extends Object3D {
  23515. constructor(color, intensity = 1) {
  23516. super();
  23517. this.isLight = true;
  23518. this.type = 'Light';
  23519. this.color = new Color(color);
  23520. this.intensity = intensity;
  23521. }
  23522. dispose() {// Empty here in base class; some subclasses override.
  23523. }
  23524. copy(source, recursive) {
  23525. super.copy(source, recursive);
  23526. this.color.copy(source.color);
  23527. this.intensity = source.intensity;
  23528. return this;
  23529. }
  23530. toJSON(meta) {
  23531. const data = super.toJSON(meta);
  23532. data.object.color = this.color.getHex();
  23533. data.object.intensity = this.intensity;
  23534. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23535. if (this.distance !== undefined) data.object.distance = this.distance;
  23536. if (this.angle !== undefined) data.object.angle = this.angle;
  23537. if (this.decay !== undefined) data.object.decay = this.decay;
  23538. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23539. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23540. return data;
  23541. }
  23542. }
  23543. class HemisphereLight extends Light {
  23544. constructor(skyColor, groundColor, intensity) {
  23545. super(skyColor, intensity);
  23546. this.isHemisphereLight = true;
  23547. this.type = 'HemisphereLight';
  23548. this.position.copy(Object3D.DefaultUp);
  23549. this.updateMatrix();
  23550. this.groundColor = new Color(groundColor);
  23551. }
  23552. copy(source, recursive) {
  23553. super.copy(source, recursive);
  23554. this.groundColor.copy(source.groundColor);
  23555. return this;
  23556. }
  23557. }
  23558. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23559. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23560. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23561. class LightShadow {
  23562. constructor(camera) {
  23563. this.camera = camera;
  23564. this.bias = 0;
  23565. this.normalBias = 0;
  23566. this.radius = 1;
  23567. this.blurSamples = 8;
  23568. this.mapSize = new Vector2(512, 512);
  23569. this.map = null;
  23570. this.mapPass = null;
  23571. this.matrix = new Matrix4();
  23572. this.autoUpdate = true;
  23573. this.needsUpdate = false;
  23574. this._frustum = new Frustum();
  23575. this._frameExtents = new Vector2(1, 1);
  23576. this._viewportCount = 1;
  23577. this._viewports = [new Vector4(0, 0, 1, 1)];
  23578. }
  23579. getViewportCount() {
  23580. return this._viewportCount;
  23581. }
  23582. getFrustum() {
  23583. return this._frustum;
  23584. }
  23585. updateMatrices(light) {
  23586. const shadowCamera = this.camera;
  23587. const shadowMatrix = this.matrix;
  23588. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23589. shadowCamera.position.copy(_lightPositionWorld$1);
  23590. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23591. shadowCamera.lookAt(_lookTarget$1);
  23592. shadowCamera.updateMatrixWorld();
  23593. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23594. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23595. 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);
  23596. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23597. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23598. }
  23599. getViewport(viewportIndex) {
  23600. return this._viewports[viewportIndex];
  23601. }
  23602. getFrameExtents() {
  23603. return this._frameExtents;
  23604. }
  23605. dispose() {
  23606. if (this.map) {
  23607. this.map.dispose();
  23608. }
  23609. if (this.mapPass) {
  23610. this.mapPass.dispose();
  23611. }
  23612. }
  23613. copy(source) {
  23614. this.camera = source.camera.clone();
  23615. this.bias = source.bias;
  23616. this.radius = source.radius;
  23617. this.mapSize.copy(source.mapSize);
  23618. return this;
  23619. }
  23620. clone() {
  23621. return new this.constructor().copy(this);
  23622. }
  23623. toJSON() {
  23624. const object = {};
  23625. if (this.bias !== 0) object.bias = this.bias;
  23626. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23627. if (this.radius !== 1) object.radius = this.radius;
  23628. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23629. object.camera = this.camera.toJSON(false).object;
  23630. delete object.camera.matrix;
  23631. return object;
  23632. }
  23633. }
  23634. class SpotLightShadow extends LightShadow {
  23635. constructor() {
  23636. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23637. this.isSpotLightShadow = true;
  23638. this.focus = 1;
  23639. }
  23640. updateMatrices(light) {
  23641. const camera = this.camera;
  23642. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23643. const aspect = this.mapSize.width / this.mapSize.height;
  23644. const far = light.distance || camera.far;
  23645. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23646. camera.fov = fov;
  23647. camera.aspect = aspect;
  23648. camera.far = far;
  23649. camera.updateProjectionMatrix();
  23650. }
  23651. super.updateMatrices(light);
  23652. }
  23653. copy(source) {
  23654. super.copy(source);
  23655. this.focus = source.focus;
  23656. return this;
  23657. }
  23658. }
  23659. class SpotLight extends Light {
  23660. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23661. super(color, intensity);
  23662. this.isSpotLight = true;
  23663. this.type = 'SpotLight';
  23664. this.position.copy(Object3D.DefaultUp);
  23665. this.updateMatrix();
  23666. this.target = new Object3D();
  23667. this.distance = distance;
  23668. this.angle = angle;
  23669. this.penumbra = penumbra;
  23670. this.decay = decay; // for physically correct lights, should be 2.
  23671. this.shadow = new SpotLightShadow();
  23672. }
  23673. get power() {
  23674. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23675. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23676. return this.intensity * Math.PI;
  23677. }
  23678. set power(power) {
  23679. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23680. this.intensity = power / Math.PI;
  23681. }
  23682. dispose() {
  23683. this.shadow.dispose();
  23684. }
  23685. copy(source, recursive) {
  23686. super.copy(source, recursive);
  23687. this.distance = source.distance;
  23688. this.angle = source.angle;
  23689. this.penumbra = source.penumbra;
  23690. this.decay = source.decay;
  23691. this.target = source.target.clone();
  23692. this.shadow = source.shadow.clone();
  23693. return this;
  23694. }
  23695. }
  23696. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23697. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23698. const _lookTarget = /*@__PURE__*/new Vector3();
  23699. class PointLightShadow extends LightShadow {
  23700. constructor() {
  23701. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23702. this.isPointLightShadow = true;
  23703. this._frameExtents = new Vector2(4, 2);
  23704. this._viewportCount = 6;
  23705. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23706. // following orientation:
  23707. //
  23708. // xzXZ
  23709. // y Y
  23710. //
  23711. // X - Positive x direction
  23712. // x - Negative x direction
  23713. // Y - Positive y direction
  23714. // y - Negative y direction
  23715. // Z - Positive z direction
  23716. // z - Negative z direction
  23717. // positive X
  23718. new Vector4(2, 1, 1, 1), // negative X
  23719. new Vector4(0, 1, 1, 1), // positive Z
  23720. new Vector4(3, 1, 1, 1), // negative Z
  23721. new Vector4(1, 1, 1, 1), // positive Y
  23722. new Vector4(3, 0, 1, 1), // negative Y
  23723. new Vector4(1, 0, 1, 1)];
  23724. 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)];
  23725. 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)];
  23726. }
  23727. updateMatrices(light, viewportIndex = 0) {
  23728. const camera = this.camera;
  23729. const shadowMatrix = this.matrix;
  23730. const far = light.distance || camera.far;
  23731. if (far !== camera.far) {
  23732. camera.far = far;
  23733. camera.updateProjectionMatrix();
  23734. }
  23735. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23736. camera.position.copy(_lightPositionWorld);
  23737. _lookTarget.copy(camera.position);
  23738. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23739. camera.up.copy(this._cubeUps[viewportIndex]);
  23740. camera.lookAt(_lookTarget);
  23741. camera.updateMatrixWorld();
  23742. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23743. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23744. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23745. }
  23746. }
  23747. class PointLight extends Light {
  23748. constructor(color, intensity, distance = 0, decay = 1) {
  23749. super(color, intensity);
  23750. this.isPointLight = true;
  23751. this.type = 'PointLight';
  23752. this.distance = distance;
  23753. this.decay = decay; // for physically correct lights, should be 2.
  23754. this.shadow = new PointLightShadow();
  23755. }
  23756. get power() {
  23757. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23758. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23759. return this.intensity * 4 * Math.PI;
  23760. }
  23761. set power(power) {
  23762. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23763. this.intensity = power / (4 * Math.PI);
  23764. }
  23765. dispose() {
  23766. this.shadow.dispose();
  23767. }
  23768. copy(source, recursive) {
  23769. super.copy(source, recursive);
  23770. this.distance = source.distance;
  23771. this.decay = source.decay;
  23772. this.shadow = source.shadow.clone();
  23773. return this;
  23774. }
  23775. }
  23776. class DirectionalLightShadow extends LightShadow {
  23777. constructor() {
  23778. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23779. this.isDirectionalLightShadow = true;
  23780. }
  23781. }
  23782. class DirectionalLight extends Light {
  23783. constructor(color, intensity) {
  23784. super(color, intensity);
  23785. this.isDirectionalLight = true;
  23786. this.type = 'DirectionalLight';
  23787. this.position.copy(Object3D.DefaultUp);
  23788. this.updateMatrix();
  23789. this.target = new Object3D();
  23790. this.shadow = new DirectionalLightShadow();
  23791. }
  23792. dispose() {
  23793. this.shadow.dispose();
  23794. }
  23795. copy(source) {
  23796. super.copy(source);
  23797. this.target = source.target.clone();
  23798. this.shadow = source.shadow.clone();
  23799. return this;
  23800. }
  23801. }
  23802. class AmbientLight extends Light {
  23803. constructor(color, intensity) {
  23804. super(color, intensity);
  23805. this.isAmbientLight = true;
  23806. this.type = 'AmbientLight';
  23807. }
  23808. }
  23809. class RectAreaLight extends Light {
  23810. constructor(color, intensity, width = 10, height = 10) {
  23811. super(color, intensity);
  23812. this.isRectAreaLight = true;
  23813. this.type = 'RectAreaLight';
  23814. this.width = width;
  23815. this.height = height;
  23816. }
  23817. get power() {
  23818. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23819. return this.intensity * this.width * this.height * Math.PI;
  23820. }
  23821. set power(power) {
  23822. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23823. this.intensity = power / (this.width * this.height * Math.PI);
  23824. }
  23825. copy(source) {
  23826. super.copy(source);
  23827. this.width = source.width;
  23828. this.height = source.height;
  23829. return this;
  23830. }
  23831. toJSON(meta) {
  23832. const data = super.toJSON(meta);
  23833. data.object.width = this.width;
  23834. data.object.height = this.height;
  23835. return data;
  23836. }
  23837. }
  23838. /**
  23839. * Primary reference:
  23840. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23841. *
  23842. * Secondary reference:
  23843. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23844. */
  23845. // 3-band SH defined by 9 coefficients
  23846. class SphericalHarmonics3 {
  23847. constructor() {
  23848. this.isSphericalHarmonics3 = true;
  23849. this.coefficients = [];
  23850. for (let i = 0; i < 9; i++) {
  23851. this.coefficients.push(new Vector3());
  23852. }
  23853. }
  23854. set(coefficients) {
  23855. for (let i = 0; i < 9; i++) {
  23856. this.coefficients[i].copy(coefficients[i]);
  23857. }
  23858. return this;
  23859. }
  23860. zero() {
  23861. for (let i = 0; i < 9; i++) {
  23862. this.coefficients[i].set(0, 0, 0);
  23863. }
  23864. return this;
  23865. } // get the radiance in the direction of the normal
  23866. // target is a Vector3
  23867. getAt(normal, target) {
  23868. // normal is assumed to be unit length
  23869. const x = normal.x,
  23870. y = normal.y,
  23871. z = normal.z;
  23872. const coeff = this.coefficients; // band 0
  23873. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23874. target.addScaledVector(coeff[1], 0.488603 * y);
  23875. target.addScaledVector(coeff[2], 0.488603 * z);
  23876. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23877. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23878. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23879. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23880. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23881. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23882. return target;
  23883. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23884. // target is a Vector3
  23885. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23886. getIrradianceAt(normal, target) {
  23887. // normal is assumed to be unit length
  23888. const x = normal.x,
  23889. y = normal.y,
  23890. z = normal.z;
  23891. const coeff = this.coefficients; // band 0
  23892. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23893. // band 1
  23894. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23895. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23896. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23897. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23898. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23899. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23900. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23901. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23902. return target;
  23903. }
  23904. add(sh) {
  23905. for (let i = 0; i < 9; i++) {
  23906. this.coefficients[i].add(sh.coefficients[i]);
  23907. }
  23908. return this;
  23909. }
  23910. addScaledSH(sh, s) {
  23911. for (let i = 0; i < 9; i++) {
  23912. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23913. }
  23914. return this;
  23915. }
  23916. scale(s) {
  23917. for (let i = 0; i < 9; i++) {
  23918. this.coefficients[i].multiplyScalar(s);
  23919. }
  23920. return this;
  23921. }
  23922. lerp(sh, alpha) {
  23923. for (let i = 0; i < 9; i++) {
  23924. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23925. }
  23926. return this;
  23927. }
  23928. equals(sh) {
  23929. for (let i = 0; i < 9; i++) {
  23930. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23931. return false;
  23932. }
  23933. }
  23934. return true;
  23935. }
  23936. copy(sh) {
  23937. return this.set(sh.coefficients);
  23938. }
  23939. clone() {
  23940. return new this.constructor().copy(this);
  23941. }
  23942. fromArray(array, offset = 0) {
  23943. const coefficients = this.coefficients;
  23944. for (let i = 0; i < 9; i++) {
  23945. coefficients[i].fromArray(array, offset + i * 3);
  23946. }
  23947. return this;
  23948. }
  23949. toArray(array = [], offset = 0) {
  23950. const coefficients = this.coefficients;
  23951. for (let i = 0; i < 9; i++) {
  23952. coefficients[i].toArray(array, offset + i * 3);
  23953. }
  23954. return array;
  23955. } // evaluate the basis functions
  23956. // shBasis is an Array[ 9 ]
  23957. static getBasisAt(normal, shBasis) {
  23958. // normal is assumed to be unit length
  23959. const x = normal.x,
  23960. y = normal.y,
  23961. z = normal.z; // band 0
  23962. shBasis[0] = 0.282095; // band 1
  23963. shBasis[1] = 0.488603 * y;
  23964. shBasis[2] = 0.488603 * z;
  23965. shBasis[3] = 0.488603 * x; // band 2
  23966. shBasis[4] = 1.092548 * x * y;
  23967. shBasis[5] = 1.092548 * y * z;
  23968. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23969. shBasis[7] = 1.092548 * x * z;
  23970. shBasis[8] = 0.546274 * (x * x - y * y);
  23971. }
  23972. }
  23973. class LightProbe extends Light {
  23974. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23975. super(undefined, intensity);
  23976. this.isLightProbe = true;
  23977. this.sh = sh;
  23978. }
  23979. copy(source) {
  23980. super.copy(source);
  23981. this.sh.copy(source.sh);
  23982. return this;
  23983. }
  23984. fromJSON(json) {
  23985. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23986. this.sh.fromArray(json.sh);
  23987. return this;
  23988. }
  23989. toJSON(meta) {
  23990. const data = super.toJSON(meta);
  23991. data.object.sh = this.sh.toArray();
  23992. return data;
  23993. }
  23994. }
  23995. class MaterialLoader extends Loader {
  23996. constructor(manager) {
  23997. super(manager);
  23998. this.textures = {};
  23999. }
  24000. load(url, onLoad, onProgress, onError) {
  24001. const scope = this;
  24002. const loader = new FileLoader(scope.manager);
  24003. loader.setPath(scope.path);
  24004. loader.setRequestHeader(scope.requestHeader);
  24005. loader.setWithCredentials(scope.withCredentials);
  24006. loader.load(url, function (text) {
  24007. try {
  24008. onLoad(scope.parse(JSON.parse(text)));
  24009. } catch (e) {
  24010. if (onError) {
  24011. onError(e);
  24012. } else {
  24013. console.error(e);
  24014. }
  24015. scope.manager.itemError(url);
  24016. }
  24017. }, onProgress, onError);
  24018. }
  24019. parse(json) {
  24020. const textures = this.textures;
  24021. function getTexture(name) {
  24022. if (textures[name] === undefined) {
  24023. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24024. }
  24025. return textures[name];
  24026. }
  24027. const material = MaterialLoader.createMaterialFromType(json.type);
  24028. if (json.uuid !== undefined) material.uuid = json.uuid;
  24029. if (json.name !== undefined) material.name = json.name;
  24030. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  24031. if (json.roughness !== undefined) material.roughness = json.roughness;
  24032. if (json.metalness !== undefined) material.metalness = json.metalness;
  24033. if (json.sheen !== undefined) material.sheen = json.sheen;
  24034. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  24035. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  24036. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  24037. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  24038. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  24039. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  24040. if (json.shininess !== undefined) material.shininess = json.shininess;
  24041. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24042. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24043. if (json.iridescence !== undefined) material.iridescence = json.iridescence;
  24044. if (json.iridescenceIOR !== undefined) material.iridescenceIOR = json.iridescenceIOR;
  24045. if (json.iridescenceThicknessRange !== undefined) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24046. if (json.transmission !== undefined) material.transmission = json.transmission;
  24047. if (json.thickness !== undefined) material.thickness = json.thickness;
  24048. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  24049. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  24050. if (json.fog !== undefined) material.fog = json.fog;
  24051. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24052. if (json.blending !== undefined) material.blending = json.blending;
  24053. if (json.combine !== undefined) material.combine = json.combine;
  24054. if (json.side !== undefined) material.side = json.side;
  24055. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  24056. if (json.opacity !== undefined) material.opacity = json.opacity;
  24057. if (json.transparent !== undefined) material.transparent = json.transparent;
  24058. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24059. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24060. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24061. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24062. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24063. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24064. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24065. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24066. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24067. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24068. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24069. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24070. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24071. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24072. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24073. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24074. if (json.rotation !== undefined) material.rotation = json.rotation;
  24075. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24076. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24077. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24078. if (json.scale !== undefined) material.scale = json.scale;
  24079. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24080. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24081. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24082. if (json.dithering !== undefined) material.dithering = json.dithering;
  24083. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  24084. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  24085. if (json.visible !== undefined) material.visible = json.visible;
  24086. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24087. if (json.userData !== undefined) material.userData = json.userData;
  24088. if (json.vertexColors !== undefined) {
  24089. if (typeof json.vertexColors === 'number') {
  24090. material.vertexColors = json.vertexColors > 0 ? true : false;
  24091. } else {
  24092. material.vertexColors = json.vertexColors;
  24093. }
  24094. } // Shader Material
  24095. if (json.uniforms !== undefined) {
  24096. for (const name in json.uniforms) {
  24097. const uniform = json.uniforms[name];
  24098. material.uniforms[name] = {};
  24099. switch (uniform.type) {
  24100. case 't':
  24101. material.uniforms[name].value = getTexture(uniform.value);
  24102. break;
  24103. case 'c':
  24104. material.uniforms[name].value = new Color().setHex(uniform.value);
  24105. break;
  24106. case 'v2':
  24107. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24108. break;
  24109. case 'v3':
  24110. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24111. break;
  24112. case 'v4':
  24113. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24114. break;
  24115. case 'm3':
  24116. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24117. break;
  24118. case 'm4':
  24119. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24120. break;
  24121. default:
  24122. material.uniforms[name].value = uniform.value;
  24123. }
  24124. }
  24125. }
  24126. if (json.defines !== undefined) material.defines = json.defines;
  24127. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24128. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24129. if (json.extensions !== undefined) {
  24130. for (const key in json.extensions) {
  24131. material.extensions[key] = json.extensions[key];
  24132. }
  24133. } // Deprecated
  24134. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24135. // for PointsMaterial
  24136. if (json.size !== undefined) material.size = json.size;
  24137. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24138. if (json.map !== undefined) material.map = getTexture(json.map);
  24139. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24140. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  24141. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24142. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24143. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24144. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24145. if (json.normalScale !== undefined) {
  24146. let normalScale = json.normalScale;
  24147. if (Array.isArray(normalScale) === false) {
  24148. // Blender exporter used to export a scalar. See #7459
  24149. normalScale = [normalScale, normalScale];
  24150. }
  24151. material.normalScale = new Vector2().fromArray(normalScale);
  24152. }
  24153. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24154. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24155. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24156. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24157. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24158. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24159. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24160. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24161. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  24162. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  24163. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24164. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24165. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24166. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24167. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24168. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24169. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24170. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24171. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24172. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  24173. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  24174. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24175. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24176. if (json.iridescenceMap !== undefined) material.iridescenceMap = getTexture(json.iridescenceMap);
  24177. if (json.iridescenceThicknessMap !== undefined) material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap);
  24178. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  24179. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  24180. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  24181. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  24182. return material;
  24183. }
  24184. setTextures(value) {
  24185. this.textures = value;
  24186. return this;
  24187. }
  24188. static createMaterialFromType(type) {
  24189. const materialLib = {
  24190. ShadowMaterial,
  24191. SpriteMaterial,
  24192. RawShaderMaterial,
  24193. ShaderMaterial,
  24194. PointsMaterial,
  24195. MeshPhysicalMaterial,
  24196. MeshStandardMaterial,
  24197. MeshPhongMaterial,
  24198. MeshToonMaterial,
  24199. MeshNormalMaterial,
  24200. MeshLambertMaterial,
  24201. MeshDepthMaterial,
  24202. MeshDistanceMaterial,
  24203. MeshBasicMaterial,
  24204. MeshMatcapMaterial,
  24205. LineDashedMaterial,
  24206. LineBasicMaterial,
  24207. Material
  24208. };
  24209. return new materialLib[type]();
  24210. }
  24211. }
  24212. class LoaderUtils {
  24213. static decodeText(array) {
  24214. if (typeof TextDecoder !== 'undefined') {
  24215. return new TextDecoder().decode(array);
  24216. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24217. // throws a "maximum call stack size exceeded" error for large arrays.
  24218. let s = '';
  24219. for (let i = 0, il = array.length; i < il; i++) {
  24220. // Implicitly assumes little-endian.
  24221. s += String.fromCharCode(array[i]);
  24222. }
  24223. try {
  24224. // merges multi-byte utf-8 characters.
  24225. return decodeURIComponent(escape(s));
  24226. } catch (e) {
  24227. // see #16358
  24228. return s;
  24229. }
  24230. }
  24231. static extractUrlBase(url) {
  24232. const index = url.lastIndexOf('/');
  24233. if (index === -1) return './';
  24234. return url.slice(0, index + 1);
  24235. }
  24236. static resolveURL(url, path) {
  24237. // Invalid URL
  24238. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  24239. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  24240. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  24241. } // Absolute URL http://,https://,//
  24242. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  24243. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  24244. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  24245. return path + url;
  24246. }
  24247. }
  24248. class InstancedBufferGeometry extends BufferGeometry {
  24249. constructor() {
  24250. super();
  24251. this.isInstancedBufferGeometry = true;
  24252. this.type = 'InstancedBufferGeometry';
  24253. this.instanceCount = Infinity;
  24254. }
  24255. copy(source) {
  24256. super.copy(source);
  24257. this.instanceCount = source.instanceCount;
  24258. return this;
  24259. }
  24260. clone() {
  24261. return new this.constructor().copy(this);
  24262. }
  24263. toJSON() {
  24264. const data = super.toJSON(this);
  24265. data.instanceCount = this.instanceCount;
  24266. data.isInstancedBufferGeometry = true;
  24267. return data;
  24268. }
  24269. }
  24270. class BufferGeometryLoader extends Loader {
  24271. constructor(manager) {
  24272. super(manager);
  24273. }
  24274. load(url, onLoad, onProgress, onError) {
  24275. const scope = this;
  24276. const loader = new FileLoader(scope.manager);
  24277. loader.setPath(scope.path);
  24278. loader.setRequestHeader(scope.requestHeader);
  24279. loader.setWithCredentials(scope.withCredentials);
  24280. loader.load(url, function (text) {
  24281. try {
  24282. onLoad(scope.parse(JSON.parse(text)));
  24283. } catch (e) {
  24284. if (onError) {
  24285. onError(e);
  24286. } else {
  24287. console.error(e);
  24288. }
  24289. scope.manager.itemError(url);
  24290. }
  24291. }, onProgress, onError);
  24292. }
  24293. parse(json) {
  24294. const interleavedBufferMap = {};
  24295. const arrayBufferMap = {};
  24296. function getInterleavedBuffer(json, uuid) {
  24297. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24298. const interleavedBuffers = json.interleavedBuffers;
  24299. const interleavedBuffer = interleavedBuffers[uuid];
  24300. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24301. const array = getTypedArray(interleavedBuffer.type, buffer);
  24302. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24303. ib.uuid = interleavedBuffer.uuid;
  24304. interleavedBufferMap[uuid] = ib;
  24305. return ib;
  24306. }
  24307. function getArrayBuffer(json, uuid) {
  24308. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24309. const arrayBuffers = json.arrayBuffers;
  24310. const arrayBuffer = arrayBuffers[uuid];
  24311. const ab = new Uint32Array(arrayBuffer).buffer;
  24312. arrayBufferMap[uuid] = ab;
  24313. return ab;
  24314. }
  24315. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24316. const index = json.data.index;
  24317. if (index !== undefined) {
  24318. const typedArray = getTypedArray(index.type, index.array);
  24319. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24320. }
  24321. const attributes = json.data.attributes;
  24322. for (const key in attributes) {
  24323. const attribute = attributes[key];
  24324. let bufferAttribute;
  24325. if (attribute.isInterleavedBufferAttribute) {
  24326. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24327. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24328. } else {
  24329. const typedArray = getTypedArray(attribute.type, attribute.array);
  24330. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24331. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24332. }
  24333. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24334. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  24335. if (attribute.updateRange !== undefined) {
  24336. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24337. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24338. }
  24339. geometry.setAttribute(key, bufferAttribute);
  24340. }
  24341. const morphAttributes = json.data.morphAttributes;
  24342. if (morphAttributes) {
  24343. for (const key in morphAttributes) {
  24344. const attributeArray = morphAttributes[key];
  24345. const array = [];
  24346. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24347. const attribute = attributeArray[i];
  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. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24355. }
  24356. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24357. array.push(bufferAttribute);
  24358. }
  24359. geometry.morphAttributes[key] = array;
  24360. }
  24361. }
  24362. const morphTargetsRelative = json.data.morphTargetsRelative;
  24363. if (morphTargetsRelative) {
  24364. geometry.morphTargetsRelative = true;
  24365. }
  24366. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24367. if (groups !== undefined) {
  24368. for (let i = 0, n = groups.length; i !== n; ++i) {
  24369. const group = groups[i];
  24370. geometry.addGroup(group.start, group.count, group.materialIndex);
  24371. }
  24372. }
  24373. const boundingSphere = json.data.boundingSphere;
  24374. if (boundingSphere !== undefined) {
  24375. const center = new Vector3();
  24376. if (boundingSphere.center !== undefined) {
  24377. center.fromArray(boundingSphere.center);
  24378. }
  24379. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24380. }
  24381. if (json.name) geometry.name = json.name;
  24382. if (json.userData) geometry.userData = json.userData;
  24383. return geometry;
  24384. }
  24385. }
  24386. class ObjectLoader extends Loader {
  24387. constructor(manager) {
  24388. super(manager);
  24389. }
  24390. load(url, onLoad, onProgress, onError) {
  24391. const scope = this;
  24392. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24393. this.resourcePath = this.resourcePath || path;
  24394. const loader = new FileLoader(this.manager);
  24395. loader.setPath(this.path);
  24396. loader.setRequestHeader(this.requestHeader);
  24397. loader.setWithCredentials(this.withCredentials);
  24398. loader.load(url, function (text) {
  24399. let json = null;
  24400. try {
  24401. json = JSON.parse(text);
  24402. } catch (error) {
  24403. if (onError !== undefined) onError(error);
  24404. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24405. return;
  24406. }
  24407. const metadata = json.metadata;
  24408. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24409. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24410. return;
  24411. }
  24412. scope.parse(json, onLoad);
  24413. }, onProgress, onError);
  24414. }
  24415. async loadAsync(url, onProgress) {
  24416. const scope = this;
  24417. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24418. this.resourcePath = this.resourcePath || path;
  24419. const loader = new FileLoader(this.manager);
  24420. loader.setPath(this.path);
  24421. loader.setRequestHeader(this.requestHeader);
  24422. loader.setWithCredentials(this.withCredentials);
  24423. const text = await loader.loadAsync(url, onProgress);
  24424. const json = JSON.parse(text);
  24425. const metadata = json.metadata;
  24426. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24427. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  24428. }
  24429. return await scope.parseAsync(json);
  24430. }
  24431. parse(json, onLoad) {
  24432. const animations = this.parseAnimations(json.animations);
  24433. const shapes = this.parseShapes(json.shapes);
  24434. const geometries = this.parseGeometries(json.geometries, shapes);
  24435. const images = this.parseImages(json.images, function () {
  24436. if (onLoad !== undefined) onLoad(object);
  24437. });
  24438. const textures = this.parseTextures(json.textures, images);
  24439. const materials = this.parseMaterials(json.materials, textures);
  24440. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24441. const skeletons = this.parseSkeletons(json.skeletons, object);
  24442. this.bindSkeletons(object, skeletons); //
  24443. if (onLoad !== undefined) {
  24444. let hasImages = false;
  24445. for (const uuid in images) {
  24446. if (images[uuid].data instanceof HTMLImageElement) {
  24447. hasImages = true;
  24448. break;
  24449. }
  24450. }
  24451. if (hasImages === false) onLoad(object);
  24452. }
  24453. return object;
  24454. }
  24455. async parseAsync(json) {
  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 = await this.parseImagesAsync(json.images);
  24460. const textures = this.parseTextures(json.textures, images);
  24461. const materials = this.parseMaterials(json.materials, textures);
  24462. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24463. const skeletons = this.parseSkeletons(json.skeletons, object);
  24464. this.bindSkeletons(object, skeletons);
  24465. return object;
  24466. }
  24467. parseShapes(json) {
  24468. const shapes = {};
  24469. if (json !== undefined) {
  24470. for (let i = 0, l = json.length; i < l; i++) {
  24471. const shape = new Shape().fromJSON(json[i]);
  24472. shapes[shape.uuid] = shape;
  24473. }
  24474. }
  24475. return shapes;
  24476. }
  24477. parseSkeletons(json, object) {
  24478. const skeletons = {};
  24479. const bones = {}; // generate bone lookup table
  24480. object.traverse(function (child) {
  24481. if (child.isBone) bones[child.uuid] = child;
  24482. }); // create skeletons
  24483. if (json !== undefined) {
  24484. for (let i = 0, l = json.length; i < l; i++) {
  24485. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24486. skeletons[skeleton.uuid] = skeleton;
  24487. }
  24488. }
  24489. return skeletons;
  24490. }
  24491. parseGeometries(json, shapes) {
  24492. const geometries = {};
  24493. if (json !== undefined) {
  24494. const bufferGeometryLoader = new BufferGeometryLoader();
  24495. for (let i = 0, l = json.length; i < l; i++) {
  24496. let geometry;
  24497. const data = json[i];
  24498. switch (data.type) {
  24499. case 'BufferGeometry':
  24500. case 'InstancedBufferGeometry':
  24501. geometry = bufferGeometryLoader.parse(data);
  24502. break;
  24503. case 'Geometry':
  24504. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  24505. break;
  24506. default:
  24507. if (data.type in Geometries) {
  24508. geometry = Geometries[data.type].fromJSON(data, shapes);
  24509. } else {
  24510. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  24511. }
  24512. }
  24513. geometry.uuid = data.uuid;
  24514. if (data.name !== undefined) geometry.name = data.name;
  24515. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24516. geometries[data.uuid] = geometry;
  24517. }
  24518. }
  24519. return geometries;
  24520. }
  24521. parseMaterials(json, textures) {
  24522. const cache = {}; // MultiMaterial
  24523. const materials = {};
  24524. if (json !== undefined) {
  24525. const loader = new MaterialLoader();
  24526. loader.setTextures(textures);
  24527. for (let i = 0, l = json.length; i < l; i++) {
  24528. const data = json[i];
  24529. if (data.type === 'MultiMaterial') {
  24530. // Deprecated
  24531. const array = [];
  24532. for (let j = 0; j < data.materials.length; j++) {
  24533. const material = data.materials[j];
  24534. if (cache[material.uuid] === undefined) {
  24535. cache[material.uuid] = loader.parse(material);
  24536. }
  24537. array.push(cache[material.uuid]);
  24538. }
  24539. materials[data.uuid] = array;
  24540. } else {
  24541. if (cache[data.uuid] === undefined) {
  24542. cache[data.uuid] = loader.parse(data);
  24543. }
  24544. materials[data.uuid] = cache[data.uuid];
  24545. }
  24546. }
  24547. }
  24548. return materials;
  24549. }
  24550. parseAnimations(json) {
  24551. const animations = {};
  24552. if (json !== undefined) {
  24553. for (let i = 0; i < json.length; i++) {
  24554. const data = json[i];
  24555. const clip = AnimationClip.parse(data);
  24556. animations[clip.uuid] = clip;
  24557. }
  24558. }
  24559. return animations;
  24560. }
  24561. parseImages(json, onLoad) {
  24562. const scope = this;
  24563. const images = {};
  24564. let loader;
  24565. function loadImage(url) {
  24566. scope.manager.itemStart(url);
  24567. return loader.load(url, function () {
  24568. scope.manager.itemEnd(url);
  24569. }, undefined, function () {
  24570. scope.manager.itemError(url);
  24571. scope.manager.itemEnd(url);
  24572. });
  24573. }
  24574. function deserializeImage(image) {
  24575. if (typeof image === 'string') {
  24576. const url = image;
  24577. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24578. return loadImage(path);
  24579. } else {
  24580. if (image.data) {
  24581. return {
  24582. data: getTypedArray(image.type, image.data),
  24583. width: image.width,
  24584. height: image.height
  24585. };
  24586. } else {
  24587. return null;
  24588. }
  24589. }
  24590. }
  24591. if (json !== undefined && json.length > 0) {
  24592. const manager = new LoadingManager(onLoad);
  24593. loader = new ImageLoader(manager);
  24594. loader.setCrossOrigin(this.crossOrigin);
  24595. for (let i = 0, il = json.length; i < il; i++) {
  24596. const image = json[i];
  24597. const url = image.url;
  24598. if (Array.isArray(url)) {
  24599. // load array of images e.g CubeTexture
  24600. const imageArray = [];
  24601. for (let j = 0, jl = url.length; j < jl; j++) {
  24602. const currentUrl = url[j];
  24603. const deserializedImage = deserializeImage(currentUrl);
  24604. if (deserializedImage !== null) {
  24605. if (deserializedImage instanceof HTMLImageElement) {
  24606. imageArray.push(deserializedImage);
  24607. } else {
  24608. // special case: handle array of data textures for cube textures
  24609. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24610. }
  24611. }
  24612. }
  24613. images[image.uuid] = new Source(imageArray);
  24614. } else {
  24615. // load single image
  24616. const deserializedImage = deserializeImage(image.url);
  24617. images[image.uuid] = new Source(deserializedImage);
  24618. }
  24619. }
  24620. }
  24621. return images;
  24622. }
  24623. async parseImagesAsync(json) {
  24624. const scope = this;
  24625. const images = {};
  24626. let loader;
  24627. async function deserializeImage(image) {
  24628. if (typeof image === 'string') {
  24629. const url = image;
  24630. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24631. return await loader.loadAsync(path);
  24632. } else {
  24633. if (image.data) {
  24634. return {
  24635. data: getTypedArray(image.type, image.data),
  24636. width: image.width,
  24637. height: image.height
  24638. };
  24639. } else {
  24640. return null;
  24641. }
  24642. }
  24643. }
  24644. if (json !== undefined && json.length > 0) {
  24645. loader = new ImageLoader(this.manager);
  24646. loader.setCrossOrigin(this.crossOrigin);
  24647. for (let i = 0, il = json.length; i < il; i++) {
  24648. const image = json[i];
  24649. const url = image.url;
  24650. if (Array.isArray(url)) {
  24651. // load array of images e.g CubeTexture
  24652. const imageArray = [];
  24653. for (let j = 0, jl = url.length; j < jl; j++) {
  24654. const currentUrl = url[j];
  24655. const deserializedImage = await deserializeImage(currentUrl);
  24656. if (deserializedImage !== null) {
  24657. if (deserializedImage instanceof HTMLImageElement) {
  24658. imageArray.push(deserializedImage);
  24659. } else {
  24660. // special case: handle array of data textures for cube textures
  24661. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24662. }
  24663. }
  24664. }
  24665. images[image.uuid] = new Source(imageArray);
  24666. } else {
  24667. // load single image
  24668. const deserializedImage = await deserializeImage(image.url);
  24669. images[image.uuid] = new Source(deserializedImage);
  24670. }
  24671. }
  24672. }
  24673. return images;
  24674. }
  24675. parseTextures(json, images) {
  24676. function parseConstant(value, type) {
  24677. if (typeof value === 'number') return value;
  24678. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24679. return type[value];
  24680. }
  24681. const textures = {};
  24682. if (json !== undefined) {
  24683. for (let i = 0, l = json.length; i < l; i++) {
  24684. const data = json[i];
  24685. if (data.image === undefined) {
  24686. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24687. }
  24688. if (images[data.image] === undefined) {
  24689. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24690. }
  24691. const source = images[data.image];
  24692. const image = source.data;
  24693. let texture;
  24694. if (Array.isArray(image)) {
  24695. texture = new CubeTexture();
  24696. if (image.length === 6) texture.needsUpdate = true;
  24697. } else {
  24698. if (image && image.data) {
  24699. texture = new DataTexture();
  24700. } else {
  24701. texture = new Texture();
  24702. }
  24703. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24704. }
  24705. texture.source = source;
  24706. texture.uuid = data.uuid;
  24707. if (data.name !== undefined) texture.name = data.name;
  24708. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24709. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24710. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24711. if (data.center !== undefined) texture.center.fromArray(data.center);
  24712. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24713. if (data.wrap !== undefined) {
  24714. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24715. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24716. }
  24717. if (data.format !== undefined) texture.format = data.format;
  24718. if (data.type !== undefined) texture.type = data.type;
  24719. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24720. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24721. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24722. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24723. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24724. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24725. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24726. if (data.userData !== undefined) texture.userData = data.userData;
  24727. textures[data.uuid] = texture;
  24728. }
  24729. }
  24730. return textures;
  24731. }
  24732. parseObject(data, geometries, materials, textures, animations) {
  24733. let object;
  24734. function getGeometry(name) {
  24735. if (geometries[name] === undefined) {
  24736. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24737. }
  24738. return geometries[name];
  24739. }
  24740. function getMaterial(name) {
  24741. if (name === undefined) return undefined;
  24742. if (Array.isArray(name)) {
  24743. const array = [];
  24744. for (let i = 0, l = name.length; i < l; i++) {
  24745. const uuid = name[i];
  24746. if (materials[uuid] === undefined) {
  24747. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24748. }
  24749. array.push(materials[uuid]);
  24750. }
  24751. return array;
  24752. }
  24753. if (materials[name] === undefined) {
  24754. console.warn('THREE.ObjectLoader: Undefined material', name);
  24755. }
  24756. return materials[name];
  24757. }
  24758. function getTexture(uuid) {
  24759. if (textures[uuid] === undefined) {
  24760. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24761. }
  24762. return textures[uuid];
  24763. }
  24764. let geometry, material;
  24765. switch (data.type) {
  24766. case 'Scene':
  24767. object = new Scene();
  24768. if (data.background !== undefined) {
  24769. if (Number.isInteger(data.background)) {
  24770. object.background = new Color(data.background);
  24771. } else {
  24772. object.background = getTexture(data.background);
  24773. }
  24774. }
  24775. if (data.environment !== undefined) {
  24776. object.environment = getTexture(data.environment);
  24777. }
  24778. if (data.fog !== undefined) {
  24779. if (data.fog.type === 'Fog') {
  24780. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24781. } else if (data.fog.type === 'FogExp2') {
  24782. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24783. }
  24784. }
  24785. break;
  24786. case 'PerspectiveCamera':
  24787. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24788. if (data.focus !== undefined) object.focus = data.focus;
  24789. if (data.zoom !== undefined) object.zoom = data.zoom;
  24790. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24791. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24792. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24793. break;
  24794. case 'OrthographicCamera':
  24795. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24796. if (data.zoom !== undefined) object.zoom = data.zoom;
  24797. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24798. break;
  24799. case 'AmbientLight':
  24800. object = new AmbientLight(data.color, data.intensity);
  24801. break;
  24802. case 'DirectionalLight':
  24803. object = new DirectionalLight(data.color, data.intensity);
  24804. break;
  24805. case 'PointLight':
  24806. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24807. break;
  24808. case 'RectAreaLight':
  24809. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24810. break;
  24811. case 'SpotLight':
  24812. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24813. break;
  24814. case 'HemisphereLight':
  24815. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24816. break;
  24817. case 'LightProbe':
  24818. object = new LightProbe().fromJSON(data);
  24819. break;
  24820. case 'SkinnedMesh':
  24821. geometry = getGeometry(data.geometry);
  24822. material = getMaterial(data.material);
  24823. object = new SkinnedMesh(geometry, material);
  24824. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24825. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24826. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24827. break;
  24828. case 'Mesh':
  24829. geometry = getGeometry(data.geometry);
  24830. material = getMaterial(data.material);
  24831. object = new Mesh(geometry, material);
  24832. break;
  24833. case 'InstancedMesh':
  24834. geometry = getGeometry(data.geometry);
  24835. material = getMaterial(data.material);
  24836. const count = data.count;
  24837. const instanceMatrix = data.instanceMatrix;
  24838. const instanceColor = data.instanceColor;
  24839. object = new InstancedMesh(geometry, material, count);
  24840. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24841. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24842. break;
  24843. case 'LOD':
  24844. object = new LOD();
  24845. break;
  24846. case 'Line':
  24847. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24848. break;
  24849. case 'LineLoop':
  24850. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24851. break;
  24852. case 'LineSegments':
  24853. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24854. break;
  24855. case 'PointCloud':
  24856. case 'Points':
  24857. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24858. break;
  24859. case 'Sprite':
  24860. object = new Sprite(getMaterial(data.material));
  24861. break;
  24862. case 'Group':
  24863. object = new Group();
  24864. break;
  24865. case 'Bone':
  24866. object = new Bone();
  24867. break;
  24868. default:
  24869. object = new Object3D();
  24870. }
  24871. object.uuid = data.uuid;
  24872. if (data.name !== undefined) object.name = data.name;
  24873. if (data.matrix !== undefined) {
  24874. object.matrix.fromArray(data.matrix);
  24875. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24876. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24877. } else {
  24878. if (data.position !== undefined) object.position.fromArray(data.position);
  24879. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24880. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24881. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24882. }
  24883. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24884. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24885. if (data.shadow) {
  24886. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24887. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24888. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24889. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24890. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24891. }
  24892. if (data.visible !== undefined) object.visible = data.visible;
  24893. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24894. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24895. if (data.userData !== undefined) object.userData = data.userData;
  24896. if (data.layers !== undefined) object.layers.mask = data.layers;
  24897. if (data.children !== undefined) {
  24898. const children = data.children;
  24899. for (let i = 0; i < children.length; i++) {
  24900. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24901. }
  24902. }
  24903. if (data.animations !== undefined) {
  24904. const objectAnimations = data.animations;
  24905. for (let i = 0; i < objectAnimations.length; i++) {
  24906. const uuid = objectAnimations[i];
  24907. object.animations.push(animations[uuid]);
  24908. }
  24909. }
  24910. if (data.type === 'LOD') {
  24911. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24912. const levels = data.levels;
  24913. for (let l = 0; l < levels.length; l++) {
  24914. const level = levels[l];
  24915. const child = object.getObjectByProperty('uuid', level.object);
  24916. if (child !== undefined) {
  24917. object.addLevel(child, level.distance);
  24918. }
  24919. }
  24920. }
  24921. return object;
  24922. }
  24923. bindSkeletons(object, skeletons) {
  24924. if (Object.keys(skeletons).length === 0) return;
  24925. object.traverse(function (child) {
  24926. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24927. const skeleton = skeletons[child.skeleton];
  24928. if (skeleton === undefined) {
  24929. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24930. } else {
  24931. child.bind(skeleton, child.bindMatrix);
  24932. }
  24933. }
  24934. });
  24935. }
  24936. }
  24937. const TEXTURE_MAPPING = {
  24938. UVMapping: UVMapping,
  24939. CubeReflectionMapping: CubeReflectionMapping,
  24940. CubeRefractionMapping: CubeRefractionMapping,
  24941. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24942. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24943. CubeUVReflectionMapping: CubeUVReflectionMapping
  24944. };
  24945. const TEXTURE_WRAPPING = {
  24946. RepeatWrapping: RepeatWrapping,
  24947. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24948. MirroredRepeatWrapping: MirroredRepeatWrapping
  24949. };
  24950. const TEXTURE_FILTER = {
  24951. NearestFilter: NearestFilter,
  24952. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24953. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24954. LinearFilter: LinearFilter,
  24955. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24956. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24957. };
  24958. class ImageBitmapLoader extends Loader {
  24959. constructor(manager) {
  24960. super(manager);
  24961. this.isImageBitmapLoader = true;
  24962. if (typeof createImageBitmap === 'undefined') {
  24963. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24964. }
  24965. if (typeof fetch === 'undefined') {
  24966. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24967. }
  24968. this.options = {
  24969. premultiplyAlpha: 'none'
  24970. };
  24971. }
  24972. setOptions(options) {
  24973. this.options = options;
  24974. return this;
  24975. }
  24976. load(url, onLoad, onProgress, onError) {
  24977. if (url === undefined) url = '';
  24978. if (this.path !== undefined) url = this.path + url;
  24979. url = this.manager.resolveURL(url);
  24980. const scope = this;
  24981. const cached = Cache.get(url);
  24982. if (cached !== undefined) {
  24983. scope.manager.itemStart(url);
  24984. setTimeout(function () {
  24985. if (onLoad) onLoad(cached);
  24986. scope.manager.itemEnd(url);
  24987. }, 0);
  24988. return cached;
  24989. }
  24990. const fetchOptions = {};
  24991. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24992. fetchOptions.headers = this.requestHeader;
  24993. fetch(url, fetchOptions).then(function (res) {
  24994. return res.blob();
  24995. }).then(function (blob) {
  24996. return createImageBitmap(blob, Object.assign(scope.options, {
  24997. colorSpaceConversion: 'none'
  24998. }));
  24999. }).then(function (imageBitmap) {
  25000. Cache.add(url, imageBitmap);
  25001. if (onLoad) onLoad(imageBitmap);
  25002. scope.manager.itemEnd(url);
  25003. }).catch(function (e) {
  25004. if (onError) onError(e);
  25005. scope.manager.itemError(url);
  25006. scope.manager.itemEnd(url);
  25007. });
  25008. scope.manager.itemStart(url);
  25009. }
  25010. }
  25011. let _context;
  25012. const AudioContext = {
  25013. getContext: function () {
  25014. if (_context === undefined) {
  25015. _context = new (window.AudioContext || window.webkitAudioContext)();
  25016. }
  25017. return _context;
  25018. },
  25019. setContext: function (value) {
  25020. _context = value;
  25021. }
  25022. };
  25023. class AudioLoader extends Loader {
  25024. constructor(manager) {
  25025. super(manager);
  25026. }
  25027. load(url, onLoad, onProgress, onError) {
  25028. const scope = this;
  25029. const loader = new FileLoader(this.manager);
  25030. loader.setResponseType('arraybuffer');
  25031. loader.setPath(this.path);
  25032. loader.setRequestHeader(this.requestHeader);
  25033. loader.setWithCredentials(this.withCredentials);
  25034. loader.load(url, function (buffer) {
  25035. try {
  25036. // Create a copy of the buffer. The `decodeAudioData` method
  25037. // detaches the buffer when complete, preventing reuse.
  25038. const bufferCopy = buffer.slice(0);
  25039. const context = AudioContext.getContext();
  25040. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25041. onLoad(audioBuffer);
  25042. });
  25043. } catch (e) {
  25044. if (onError) {
  25045. onError(e);
  25046. } else {
  25047. console.error(e);
  25048. }
  25049. scope.manager.itemError(url);
  25050. }
  25051. }, onProgress, onError);
  25052. }
  25053. }
  25054. class HemisphereLightProbe extends LightProbe {
  25055. constructor(skyColor, groundColor, intensity = 1) {
  25056. super(undefined, intensity);
  25057. this.isHemisphereLightProbe = true;
  25058. const color1 = new Color().set(skyColor);
  25059. const color2 = new Color().set(groundColor);
  25060. const sky = new Vector3(color1.r, color1.g, color1.b);
  25061. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25062. const c0 = Math.sqrt(Math.PI);
  25063. const c1 = c0 * Math.sqrt(0.75);
  25064. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25065. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25066. }
  25067. }
  25068. class AmbientLightProbe extends LightProbe {
  25069. constructor(color, intensity = 1) {
  25070. super(undefined, intensity);
  25071. this.isAmbientLightProbe = true;
  25072. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25073. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25074. }
  25075. }
  25076. const _eyeRight = /*@__PURE__*/new Matrix4();
  25077. const _eyeLeft = /*@__PURE__*/new Matrix4();
  25078. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  25079. class StereoCamera {
  25080. constructor() {
  25081. this.type = 'StereoCamera';
  25082. this.aspect = 1;
  25083. this.eyeSep = 0.064;
  25084. this.cameraL = new PerspectiveCamera();
  25085. this.cameraL.layers.enable(1);
  25086. this.cameraL.matrixAutoUpdate = false;
  25087. this.cameraR = new PerspectiveCamera();
  25088. this.cameraR.layers.enable(2);
  25089. this.cameraR.matrixAutoUpdate = false;
  25090. this._cache = {
  25091. focus: null,
  25092. fov: null,
  25093. aspect: null,
  25094. near: null,
  25095. far: null,
  25096. zoom: null,
  25097. eyeSep: null
  25098. };
  25099. }
  25100. update(camera) {
  25101. const cache = this._cache;
  25102. 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;
  25103. if (needsUpdate) {
  25104. cache.focus = camera.focus;
  25105. cache.fov = camera.fov;
  25106. cache.aspect = camera.aspect * this.aspect;
  25107. cache.near = camera.near;
  25108. cache.far = camera.far;
  25109. cache.zoom = camera.zoom;
  25110. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25111. // http://paulbourke.net/stereographics/stereorender/
  25112. _projectionMatrix.copy(camera.projectionMatrix);
  25113. const eyeSepHalf = cache.eyeSep / 2;
  25114. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25115. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25116. let xmin, xmax; // translate xOffset
  25117. _eyeLeft.elements[12] = -eyeSepHalf;
  25118. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25119. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25120. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25121. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25122. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25123. this.cameraL.projectionMatrix.copy(_projectionMatrix); // for right eye
  25124. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25125. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25126. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25127. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25128. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  25129. }
  25130. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25131. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25132. }
  25133. }
  25134. class Clock {
  25135. constructor(autoStart = true) {
  25136. this.autoStart = autoStart;
  25137. this.startTime = 0;
  25138. this.oldTime = 0;
  25139. this.elapsedTime = 0;
  25140. this.running = false;
  25141. }
  25142. start() {
  25143. this.startTime = now();
  25144. this.oldTime = this.startTime;
  25145. this.elapsedTime = 0;
  25146. this.running = true;
  25147. }
  25148. stop() {
  25149. this.getElapsedTime();
  25150. this.running = false;
  25151. this.autoStart = false;
  25152. }
  25153. getElapsedTime() {
  25154. this.getDelta();
  25155. return this.elapsedTime;
  25156. }
  25157. getDelta() {
  25158. let diff = 0;
  25159. if (this.autoStart && !this.running) {
  25160. this.start();
  25161. return 0;
  25162. }
  25163. if (this.running) {
  25164. const newTime = now();
  25165. diff = (newTime - this.oldTime) / 1000;
  25166. this.oldTime = newTime;
  25167. this.elapsedTime += diff;
  25168. }
  25169. return diff;
  25170. }
  25171. }
  25172. function now() {
  25173. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25174. }
  25175. const _position$1 = /*@__PURE__*/new Vector3();
  25176. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  25177. const _scale$1 = /*@__PURE__*/new Vector3();
  25178. const _orientation$1 = /*@__PURE__*/new Vector3();
  25179. class AudioListener extends Object3D {
  25180. constructor() {
  25181. super();
  25182. this.type = 'AudioListener';
  25183. this.context = AudioContext.getContext();
  25184. this.gain = this.context.createGain();
  25185. this.gain.connect(this.context.destination);
  25186. this.filter = null;
  25187. this.timeDelta = 0; // private
  25188. this._clock = new Clock();
  25189. }
  25190. getInput() {
  25191. return this.gain;
  25192. }
  25193. removeFilter() {
  25194. if (this.filter !== null) {
  25195. this.gain.disconnect(this.filter);
  25196. this.filter.disconnect(this.context.destination);
  25197. this.gain.connect(this.context.destination);
  25198. this.filter = null;
  25199. }
  25200. return this;
  25201. }
  25202. getFilter() {
  25203. return this.filter;
  25204. }
  25205. setFilter(value) {
  25206. if (this.filter !== null) {
  25207. this.gain.disconnect(this.filter);
  25208. this.filter.disconnect(this.context.destination);
  25209. } else {
  25210. this.gain.disconnect(this.context.destination);
  25211. }
  25212. this.filter = value;
  25213. this.gain.connect(this.filter);
  25214. this.filter.connect(this.context.destination);
  25215. return this;
  25216. }
  25217. getMasterVolume() {
  25218. return this.gain.gain.value;
  25219. }
  25220. setMasterVolume(value) {
  25221. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25222. return this;
  25223. }
  25224. updateMatrixWorld(force) {
  25225. super.updateMatrixWorld(force);
  25226. const listener = this.context.listener;
  25227. const up = this.up;
  25228. this.timeDelta = this._clock.getDelta();
  25229. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  25230. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  25231. if (listener.positionX) {
  25232. // code path for Chrome (see #14393)
  25233. const endTime = this.context.currentTime + this.timeDelta;
  25234. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  25235. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  25236. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  25237. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25238. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25239. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25240. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25241. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25242. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25243. } else {
  25244. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  25245. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  25246. }
  25247. }
  25248. }
  25249. class Audio extends Object3D {
  25250. constructor(listener) {
  25251. super();
  25252. this.type = 'Audio';
  25253. this.listener = listener;
  25254. this.context = listener.context;
  25255. this.gain = this.context.createGain();
  25256. this.gain.connect(listener.getInput());
  25257. this.autoplay = false;
  25258. this.buffer = null;
  25259. this.detune = 0;
  25260. this.loop = false;
  25261. this.loopStart = 0;
  25262. this.loopEnd = 0;
  25263. this.offset = 0;
  25264. this.duration = undefined;
  25265. this.playbackRate = 1;
  25266. this.isPlaying = false;
  25267. this.hasPlaybackControl = true;
  25268. this.source = null;
  25269. this.sourceType = 'empty';
  25270. this._startedAt = 0;
  25271. this._progress = 0;
  25272. this._connected = false;
  25273. this.filters = [];
  25274. }
  25275. getOutput() {
  25276. return this.gain;
  25277. }
  25278. setNodeSource(audioNode) {
  25279. this.hasPlaybackControl = false;
  25280. this.sourceType = 'audioNode';
  25281. this.source = audioNode;
  25282. this.connect();
  25283. return this;
  25284. }
  25285. setMediaElementSource(mediaElement) {
  25286. this.hasPlaybackControl = false;
  25287. this.sourceType = 'mediaNode';
  25288. this.source = this.context.createMediaElementSource(mediaElement);
  25289. this.connect();
  25290. return this;
  25291. }
  25292. setMediaStreamSource(mediaStream) {
  25293. this.hasPlaybackControl = false;
  25294. this.sourceType = 'mediaStreamNode';
  25295. this.source = this.context.createMediaStreamSource(mediaStream);
  25296. this.connect();
  25297. return this;
  25298. }
  25299. setBuffer(audioBuffer) {
  25300. this.buffer = audioBuffer;
  25301. this.sourceType = 'buffer';
  25302. if (this.autoplay) this.play();
  25303. return this;
  25304. }
  25305. play(delay = 0) {
  25306. if (this.isPlaying === true) {
  25307. console.warn('THREE.Audio: Audio is already playing.');
  25308. return;
  25309. }
  25310. if (this.hasPlaybackControl === false) {
  25311. console.warn('THREE.Audio: this Audio has no playback control.');
  25312. return;
  25313. }
  25314. this._startedAt = this.context.currentTime + delay;
  25315. const source = this.context.createBufferSource();
  25316. source.buffer = this.buffer;
  25317. source.loop = this.loop;
  25318. source.loopStart = this.loopStart;
  25319. source.loopEnd = this.loopEnd;
  25320. source.onended = this.onEnded.bind(this);
  25321. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25322. this.isPlaying = true;
  25323. this.source = source;
  25324. this.setDetune(this.detune);
  25325. this.setPlaybackRate(this.playbackRate);
  25326. return this.connect();
  25327. }
  25328. pause() {
  25329. if (this.hasPlaybackControl === false) {
  25330. console.warn('THREE.Audio: this Audio has no playback control.');
  25331. return;
  25332. }
  25333. if (this.isPlaying === true) {
  25334. // update current progress
  25335. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25336. if (this.loop === true) {
  25337. // ensure _progress does not exceed duration with looped audios
  25338. this._progress = this._progress % (this.duration || this.buffer.duration);
  25339. }
  25340. this.source.stop();
  25341. this.source.onended = null;
  25342. this.isPlaying = false;
  25343. }
  25344. return this;
  25345. }
  25346. stop() {
  25347. if (this.hasPlaybackControl === false) {
  25348. console.warn('THREE.Audio: this Audio has no playback control.');
  25349. return;
  25350. }
  25351. this._progress = 0;
  25352. this.source.stop();
  25353. this.source.onended = null;
  25354. this.isPlaying = false;
  25355. return this;
  25356. }
  25357. connect() {
  25358. if (this.filters.length > 0) {
  25359. this.source.connect(this.filters[0]);
  25360. for (let i = 1, l = this.filters.length; i < l; i++) {
  25361. this.filters[i - 1].connect(this.filters[i]);
  25362. }
  25363. this.filters[this.filters.length - 1].connect(this.getOutput());
  25364. } else {
  25365. this.source.connect(this.getOutput());
  25366. }
  25367. this._connected = true;
  25368. return this;
  25369. }
  25370. disconnect() {
  25371. if (this.filters.length > 0) {
  25372. this.source.disconnect(this.filters[0]);
  25373. for (let i = 1, l = this.filters.length; i < l; i++) {
  25374. this.filters[i - 1].disconnect(this.filters[i]);
  25375. }
  25376. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25377. } else {
  25378. this.source.disconnect(this.getOutput());
  25379. }
  25380. this._connected = false;
  25381. return this;
  25382. }
  25383. getFilters() {
  25384. return this.filters;
  25385. }
  25386. setFilters(value) {
  25387. if (!value) value = [];
  25388. if (this._connected === true) {
  25389. this.disconnect();
  25390. this.filters = value.slice();
  25391. this.connect();
  25392. } else {
  25393. this.filters = value.slice();
  25394. }
  25395. return this;
  25396. }
  25397. setDetune(value) {
  25398. this.detune = value;
  25399. if (this.source.detune === undefined) return; // only set detune when available
  25400. if (this.isPlaying === true) {
  25401. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25402. }
  25403. return this;
  25404. }
  25405. getDetune() {
  25406. return this.detune;
  25407. }
  25408. getFilter() {
  25409. return this.getFilters()[0];
  25410. }
  25411. setFilter(filter) {
  25412. return this.setFilters(filter ? [filter] : []);
  25413. }
  25414. setPlaybackRate(value) {
  25415. if (this.hasPlaybackControl === false) {
  25416. console.warn('THREE.Audio: this Audio has no playback control.');
  25417. return;
  25418. }
  25419. this.playbackRate = value;
  25420. if (this.isPlaying === true) {
  25421. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25422. }
  25423. return this;
  25424. }
  25425. getPlaybackRate() {
  25426. return this.playbackRate;
  25427. }
  25428. onEnded() {
  25429. this.isPlaying = false;
  25430. }
  25431. getLoop() {
  25432. if (this.hasPlaybackControl === false) {
  25433. console.warn('THREE.Audio: this Audio has no playback control.');
  25434. return false;
  25435. }
  25436. return this.loop;
  25437. }
  25438. setLoop(value) {
  25439. if (this.hasPlaybackControl === false) {
  25440. console.warn('THREE.Audio: this Audio has no playback control.');
  25441. return;
  25442. }
  25443. this.loop = value;
  25444. if (this.isPlaying === true) {
  25445. this.source.loop = this.loop;
  25446. }
  25447. return this;
  25448. }
  25449. setLoopStart(value) {
  25450. this.loopStart = value;
  25451. return this;
  25452. }
  25453. setLoopEnd(value) {
  25454. this.loopEnd = value;
  25455. return this;
  25456. }
  25457. getVolume() {
  25458. return this.gain.gain.value;
  25459. }
  25460. setVolume(value) {
  25461. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25462. return this;
  25463. }
  25464. }
  25465. const _position = /*@__PURE__*/new Vector3();
  25466. const _quaternion = /*@__PURE__*/new Quaternion();
  25467. const _scale = /*@__PURE__*/new Vector3();
  25468. const _orientation = /*@__PURE__*/new Vector3();
  25469. class PositionalAudio extends Audio {
  25470. constructor(listener) {
  25471. super(listener);
  25472. this.panner = this.context.createPanner();
  25473. this.panner.panningModel = 'HRTF';
  25474. this.panner.connect(this.gain);
  25475. }
  25476. disconnect() {
  25477. super.disconnect();
  25478. this.panner.disconnect(this.gain);
  25479. }
  25480. getOutput() {
  25481. return this.panner;
  25482. }
  25483. getRefDistance() {
  25484. return this.panner.refDistance;
  25485. }
  25486. setRefDistance(value) {
  25487. this.panner.refDistance = value;
  25488. return this;
  25489. }
  25490. getRolloffFactor() {
  25491. return this.panner.rolloffFactor;
  25492. }
  25493. setRolloffFactor(value) {
  25494. this.panner.rolloffFactor = value;
  25495. return this;
  25496. }
  25497. getDistanceModel() {
  25498. return this.panner.distanceModel;
  25499. }
  25500. setDistanceModel(value) {
  25501. this.panner.distanceModel = value;
  25502. return this;
  25503. }
  25504. getMaxDistance() {
  25505. return this.panner.maxDistance;
  25506. }
  25507. setMaxDistance(value) {
  25508. this.panner.maxDistance = value;
  25509. return this;
  25510. }
  25511. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25512. this.panner.coneInnerAngle = coneInnerAngle;
  25513. this.panner.coneOuterAngle = coneOuterAngle;
  25514. this.panner.coneOuterGain = coneOuterGain;
  25515. return this;
  25516. }
  25517. updateMatrixWorld(force) {
  25518. super.updateMatrixWorld(force);
  25519. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25520. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25521. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25522. const panner = this.panner;
  25523. if (panner.positionX) {
  25524. // code path for Chrome and Firefox (see #14393)
  25525. const endTime = this.context.currentTime + this.listener.timeDelta;
  25526. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25527. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25528. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25529. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25530. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25531. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25532. } else {
  25533. panner.setPosition(_position.x, _position.y, _position.z);
  25534. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25535. }
  25536. }
  25537. }
  25538. class AudioAnalyser {
  25539. constructor(audio, fftSize = 2048) {
  25540. this.analyser = audio.context.createAnalyser();
  25541. this.analyser.fftSize = fftSize;
  25542. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25543. audio.getOutput().connect(this.analyser);
  25544. }
  25545. getFrequencyData() {
  25546. this.analyser.getByteFrequencyData(this.data);
  25547. return this.data;
  25548. }
  25549. getAverageFrequency() {
  25550. let value = 0;
  25551. const data = this.getFrequencyData();
  25552. for (let i = 0; i < data.length; i++) {
  25553. value += data[i];
  25554. }
  25555. return value / data.length;
  25556. }
  25557. }
  25558. class PropertyMixer {
  25559. constructor(binding, typeName, valueSize) {
  25560. this.binding = binding;
  25561. this.valueSize = valueSize;
  25562. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25563. //
  25564. // interpolators can use .buffer as their .result
  25565. // the data then goes to 'incoming'
  25566. //
  25567. // 'accu0' and 'accu1' are used frame-interleaved for
  25568. // the cumulative result and are compared to detect
  25569. // changes
  25570. //
  25571. // 'orig' stores the original state of the property
  25572. //
  25573. // 'add' is used for additive cumulative results
  25574. //
  25575. // 'work' is optional and is only present for quaternion types. It is used
  25576. // to store intermediate quaternion multiplication results
  25577. switch (typeName) {
  25578. case 'quaternion':
  25579. mixFunction = this._slerp;
  25580. mixFunctionAdditive = this._slerpAdditive;
  25581. setIdentity = this._setAdditiveIdentityQuaternion;
  25582. this.buffer = new Float64Array(valueSize * 6);
  25583. this._workIndex = 5;
  25584. break;
  25585. case 'string':
  25586. case 'bool':
  25587. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25588. // additive is not relevant for non-numeric types
  25589. mixFunctionAdditive = this._select;
  25590. setIdentity = this._setAdditiveIdentityOther;
  25591. this.buffer = new Array(valueSize * 5);
  25592. break;
  25593. default:
  25594. mixFunction = this._lerp;
  25595. mixFunctionAdditive = this._lerpAdditive;
  25596. setIdentity = this._setAdditiveIdentityNumeric;
  25597. this.buffer = new Float64Array(valueSize * 5);
  25598. }
  25599. this._mixBufferRegion = mixFunction;
  25600. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25601. this._setIdentity = setIdentity;
  25602. this._origIndex = 3;
  25603. this._addIndex = 4;
  25604. this.cumulativeWeight = 0;
  25605. this.cumulativeWeightAdditive = 0;
  25606. this.useCount = 0;
  25607. this.referenceCount = 0;
  25608. } // accumulate data in the 'incoming' region into 'accu<i>'
  25609. accumulate(accuIndex, weight) {
  25610. // note: happily accumulating nothing when weight = 0, the caller knows
  25611. // the weight and shouldn't have made the call in the first place
  25612. const buffer = this.buffer,
  25613. stride = this.valueSize,
  25614. offset = accuIndex * stride + stride;
  25615. let currentWeight = this.cumulativeWeight;
  25616. if (currentWeight === 0) {
  25617. // accuN := incoming * weight
  25618. for (let i = 0; i !== stride; ++i) {
  25619. buffer[offset + i] = buffer[i];
  25620. }
  25621. currentWeight = weight;
  25622. } else {
  25623. // accuN := accuN + incoming * weight
  25624. currentWeight += weight;
  25625. const mix = weight / currentWeight;
  25626. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25627. }
  25628. this.cumulativeWeight = currentWeight;
  25629. } // accumulate data in the 'incoming' region into 'add'
  25630. accumulateAdditive(weight) {
  25631. const buffer = this.buffer,
  25632. stride = this.valueSize,
  25633. offset = stride * this._addIndex;
  25634. if (this.cumulativeWeightAdditive === 0) {
  25635. // add = identity
  25636. this._setIdentity();
  25637. } // add := add + incoming * weight
  25638. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25639. this.cumulativeWeightAdditive += weight;
  25640. } // apply the state of 'accu<i>' to the binding when accus differ
  25641. apply(accuIndex) {
  25642. const stride = this.valueSize,
  25643. buffer = this.buffer,
  25644. offset = accuIndex * stride + stride,
  25645. weight = this.cumulativeWeight,
  25646. weightAdditive = this.cumulativeWeightAdditive,
  25647. binding = this.binding;
  25648. this.cumulativeWeight = 0;
  25649. this.cumulativeWeightAdditive = 0;
  25650. if (weight < 1) {
  25651. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25652. const originalValueOffset = stride * this._origIndex;
  25653. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25654. }
  25655. if (weightAdditive > 0) {
  25656. // accuN := accuN + additive accuN
  25657. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25658. }
  25659. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25660. if (buffer[i] !== buffer[i + stride]) {
  25661. // value has changed -> update scene graph
  25662. binding.setValue(buffer, offset);
  25663. break;
  25664. }
  25665. }
  25666. } // remember the state of the bound property and copy it to both accus
  25667. saveOriginalState() {
  25668. const binding = this.binding;
  25669. const buffer = this.buffer,
  25670. stride = this.valueSize,
  25671. originalValueOffset = stride * this._origIndex;
  25672. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25673. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25674. buffer[i] = buffer[originalValueOffset + i % stride];
  25675. } // Add to identity for additive
  25676. this._setIdentity();
  25677. this.cumulativeWeight = 0;
  25678. this.cumulativeWeightAdditive = 0;
  25679. } // apply the state previously taken via 'saveOriginalState' to the binding
  25680. restoreOriginalState() {
  25681. const originalValueOffset = this.valueSize * 3;
  25682. this.binding.setValue(this.buffer, originalValueOffset);
  25683. }
  25684. _setAdditiveIdentityNumeric() {
  25685. const startIndex = this._addIndex * this.valueSize;
  25686. const endIndex = startIndex + this.valueSize;
  25687. for (let i = startIndex; i < endIndex; i++) {
  25688. this.buffer[i] = 0;
  25689. }
  25690. }
  25691. _setAdditiveIdentityQuaternion() {
  25692. this._setAdditiveIdentityNumeric();
  25693. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25694. }
  25695. _setAdditiveIdentityOther() {
  25696. const startIndex = this._origIndex * this.valueSize;
  25697. const targetIndex = this._addIndex * this.valueSize;
  25698. for (let i = 0; i < this.valueSize; i++) {
  25699. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25700. }
  25701. } // mix functions
  25702. _select(buffer, dstOffset, srcOffset, t, stride) {
  25703. if (t >= 0.5) {
  25704. for (let i = 0; i !== stride; ++i) {
  25705. buffer[dstOffset + i] = buffer[srcOffset + i];
  25706. }
  25707. }
  25708. }
  25709. _slerp(buffer, dstOffset, srcOffset, t) {
  25710. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25711. }
  25712. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25713. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25714. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25715. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25716. }
  25717. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25718. const s = 1 - t;
  25719. for (let i = 0; i !== stride; ++i) {
  25720. const j = dstOffset + i;
  25721. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25722. }
  25723. }
  25724. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25725. for (let i = 0; i !== stride; ++i) {
  25726. const j = dstOffset + i;
  25727. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25728. }
  25729. }
  25730. }
  25731. // Characters [].:/ are reserved for track binding syntax.
  25732. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25733. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25734. // only latin characters, and the unicode \p{L} is not yet supported. So
  25735. // instead, we exclude reserved characters and match everything else.
  25736. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25737. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25738. // be matched to parse the rest of the track name.
  25739. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25740. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25741. // characters. Accessor may contain any character except closing bracket.
  25742. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25743. // contain any non-bracket characters.
  25744. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25745. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25746. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25747. class Composite {
  25748. constructor(targetGroup, path, optionalParsedPath) {
  25749. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25750. this._targetGroup = targetGroup;
  25751. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25752. }
  25753. getValue(array, offset) {
  25754. this.bind(); // bind all binding
  25755. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25756. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25757. if (binding !== undefined) binding.getValue(array, offset);
  25758. }
  25759. setValue(array, offset) {
  25760. const bindings = this._bindings;
  25761. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25762. bindings[i].setValue(array, offset);
  25763. }
  25764. }
  25765. bind() {
  25766. const bindings = this._bindings;
  25767. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25768. bindings[i].bind();
  25769. }
  25770. }
  25771. unbind() {
  25772. const bindings = this._bindings;
  25773. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25774. bindings[i].unbind();
  25775. }
  25776. }
  25777. } // Note: This class uses a State pattern on a per-method basis:
  25778. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25779. // prototype version of these methods with one that represents
  25780. // the bound state. When the property is not found, the methods
  25781. // become no-ops.
  25782. class PropertyBinding {
  25783. constructor(rootNode, path, parsedPath) {
  25784. this.path = path;
  25785. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25786. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25787. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25788. this.getValue = this._getValue_unbound;
  25789. this.setValue = this._setValue_unbound;
  25790. }
  25791. static create(root, path, parsedPath) {
  25792. if (!(root && root.isAnimationObjectGroup)) {
  25793. return new PropertyBinding(root, path, parsedPath);
  25794. } else {
  25795. return new PropertyBinding.Composite(root, path, parsedPath);
  25796. }
  25797. }
  25798. /**
  25799. * Replaces spaces with underscores and removes unsupported characters from
  25800. * node names, to ensure compatibility with parseTrackName().
  25801. *
  25802. * @param {string} name Node name to be sanitized.
  25803. * @return {string}
  25804. */
  25805. static sanitizeNodeName(name) {
  25806. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25807. }
  25808. static parseTrackName(trackName) {
  25809. const matches = _trackRe.exec(trackName);
  25810. if (matches === null) {
  25811. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25812. }
  25813. const results = {
  25814. // directoryName: matches[ 1 ], // (tschw) currently unused
  25815. nodeName: matches[2],
  25816. objectName: matches[3],
  25817. objectIndex: matches[4],
  25818. propertyName: matches[5],
  25819. // required
  25820. propertyIndex: matches[6]
  25821. };
  25822. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25823. if (lastDot !== undefined && lastDot !== -1) {
  25824. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25825. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25826. // 'bar' could be the objectName, or part of a nodeName (which can
  25827. // include '.' characters).
  25828. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25829. results.nodeName = results.nodeName.substring(0, lastDot);
  25830. results.objectName = objectName;
  25831. }
  25832. }
  25833. if (results.propertyName === null || results.propertyName.length === 0) {
  25834. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25835. }
  25836. return results;
  25837. }
  25838. static findNode(root, nodeName) {
  25839. if (nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25840. return root;
  25841. } // search into skeleton bones.
  25842. if (root.skeleton) {
  25843. const bone = root.skeleton.getBoneByName(nodeName);
  25844. if (bone !== undefined) {
  25845. return bone;
  25846. }
  25847. } // search into node subtree.
  25848. if (root.children) {
  25849. const searchNodeSubtree = function (children) {
  25850. for (let i = 0; i < children.length; i++) {
  25851. const childNode = children[i];
  25852. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25853. return childNode;
  25854. }
  25855. const result = searchNodeSubtree(childNode.children);
  25856. if (result) return result;
  25857. }
  25858. return null;
  25859. };
  25860. const subTreeNode = searchNodeSubtree(root.children);
  25861. if (subTreeNode) {
  25862. return subTreeNode;
  25863. }
  25864. }
  25865. return null;
  25866. } // these are used to "bind" a nonexistent property
  25867. _getValue_unavailable() {}
  25868. _setValue_unavailable() {} // Getters
  25869. _getValue_direct(buffer, offset) {
  25870. buffer[offset] = this.targetObject[this.propertyName];
  25871. }
  25872. _getValue_array(buffer, offset) {
  25873. const source = this.resolvedProperty;
  25874. for (let i = 0, n = source.length; i !== n; ++i) {
  25875. buffer[offset++] = source[i];
  25876. }
  25877. }
  25878. _getValue_arrayElement(buffer, offset) {
  25879. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25880. }
  25881. _getValue_toArray(buffer, offset) {
  25882. this.resolvedProperty.toArray(buffer, offset);
  25883. } // Direct
  25884. _setValue_direct(buffer, offset) {
  25885. this.targetObject[this.propertyName] = buffer[offset];
  25886. }
  25887. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25888. this.targetObject[this.propertyName] = buffer[offset];
  25889. this.targetObject.needsUpdate = true;
  25890. }
  25891. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25892. this.targetObject[this.propertyName] = buffer[offset];
  25893. this.targetObject.matrixWorldNeedsUpdate = true;
  25894. } // EntireArray
  25895. _setValue_array(buffer, offset) {
  25896. const dest = this.resolvedProperty;
  25897. for (let i = 0, n = dest.length; i !== n; ++i) {
  25898. dest[i] = buffer[offset++];
  25899. }
  25900. }
  25901. _setValue_array_setNeedsUpdate(buffer, offset) {
  25902. const dest = this.resolvedProperty;
  25903. for (let i = 0, n = dest.length; i !== n; ++i) {
  25904. dest[i] = buffer[offset++];
  25905. }
  25906. this.targetObject.needsUpdate = true;
  25907. }
  25908. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25909. const dest = this.resolvedProperty;
  25910. for (let i = 0, n = dest.length; i !== n; ++i) {
  25911. dest[i] = buffer[offset++];
  25912. }
  25913. this.targetObject.matrixWorldNeedsUpdate = true;
  25914. } // ArrayElement
  25915. _setValue_arrayElement(buffer, offset) {
  25916. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25917. }
  25918. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25919. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25920. this.targetObject.needsUpdate = true;
  25921. }
  25922. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25923. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25924. this.targetObject.matrixWorldNeedsUpdate = true;
  25925. } // HasToFromArray
  25926. _setValue_fromArray(buffer, offset) {
  25927. this.resolvedProperty.fromArray(buffer, offset);
  25928. }
  25929. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25930. this.resolvedProperty.fromArray(buffer, offset);
  25931. this.targetObject.needsUpdate = true;
  25932. }
  25933. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25934. this.resolvedProperty.fromArray(buffer, offset);
  25935. this.targetObject.matrixWorldNeedsUpdate = true;
  25936. }
  25937. _getValue_unbound(targetArray, offset) {
  25938. this.bind();
  25939. this.getValue(targetArray, offset);
  25940. }
  25941. _setValue_unbound(sourceArray, offset) {
  25942. this.bind();
  25943. this.setValue(sourceArray, offset);
  25944. } // create getter / setter pair for a property in the scene graph
  25945. bind() {
  25946. let targetObject = this.node;
  25947. const parsedPath = this.parsedPath;
  25948. const objectName = parsedPath.objectName;
  25949. const propertyName = parsedPath.propertyName;
  25950. let propertyIndex = parsedPath.propertyIndex;
  25951. if (!targetObject) {
  25952. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25953. this.node = targetObject;
  25954. } // set fail state so we can just 'return' on error
  25955. this.getValue = this._getValue_unavailable;
  25956. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25957. if (!targetObject) {
  25958. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25959. return;
  25960. }
  25961. if (objectName) {
  25962. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25963. switch (objectName) {
  25964. case 'materials':
  25965. if (!targetObject.material) {
  25966. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25967. return;
  25968. }
  25969. if (!targetObject.material.materials) {
  25970. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25971. return;
  25972. }
  25973. targetObject = targetObject.material.materials;
  25974. break;
  25975. case 'bones':
  25976. if (!targetObject.skeleton) {
  25977. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25978. return;
  25979. } // potential future optimization: skip this if propertyIndex is already an integer
  25980. // and convert the integer string to a true integer.
  25981. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25982. for (let i = 0; i < targetObject.length; i++) {
  25983. if (targetObject[i].name === objectIndex) {
  25984. objectIndex = i;
  25985. break;
  25986. }
  25987. }
  25988. break;
  25989. default:
  25990. if (targetObject[objectName] === undefined) {
  25991. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25992. return;
  25993. }
  25994. targetObject = targetObject[objectName];
  25995. }
  25996. if (objectIndex !== undefined) {
  25997. if (targetObject[objectIndex] === undefined) {
  25998. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25999. return;
  26000. }
  26001. targetObject = targetObject[objectIndex];
  26002. }
  26003. } // resolve property
  26004. const nodeProperty = targetObject[propertyName];
  26005. if (nodeProperty === undefined) {
  26006. const nodeName = parsedPath.nodeName;
  26007. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26008. return;
  26009. } // determine versioning scheme
  26010. let versioning = this.Versioning.None;
  26011. this.targetObject = targetObject;
  26012. if (targetObject.needsUpdate !== undefined) {
  26013. // material
  26014. versioning = this.Versioning.NeedsUpdate;
  26015. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26016. // node transform
  26017. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26018. } // determine how the property gets bound
  26019. let bindingType = this.BindingType.Direct;
  26020. if (propertyIndex !== undefined) {
  26021. // access a sub element of the property array (only primitives are supported right now)
  26022. if (propertyName === 'morphTargetInfluences') {
  26023. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26024. // support resolving morphTarget names into indices.
  26025. if (!targetObject.geometry) {
  26026. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26027. return;
  26028. }
  26029. if (!targetObject.geometry.morphAttributes) {
  26030. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26031. return;
  26032. }
  26033. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  26034. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  26035. }
  26036. }
  26037. bindingType = this.BindingType.ArrayElement;
  26038. this.resolvedProperty = nodeProperty;
  26039. this.propertyIndex = propertyIndex;
  26040. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26041. // must use copy for Object3D.Euler/Quaternion
  26042. bindingType = this.BindingType.HasFromToArray;
  26043. this.resolvedProperty = nodeProperty;
  26044. } else if (Array.isArray(nodeProperty)) {
  26045. bindingType = this.BindingType.EntireArray;
  26046. this.resolvedProperty = nodeProperty;
  26047. } else {
  26048. this.propertyName = propertyName;
  26049. } // select getter / setter
  26050. this.getValue = this.GetterByBindingType[bindingType];
  26051. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26052. }
  26053. unbind() {
  26054. this.node = null; // back to the prototype version of getValue / setValue
  26055. // note: avoiding to mutate the shape of 'this' via 'delete'
  26056. this.getValue = this._getValue_unbound;
  26057. this.setValue = this._setValue_unbound;
  26058. }
  26059. }
  26060. PropertyBinding.Composite = Composite;
  26061. PropertyBinding.prototype.BindingType = {
  26062. Direct: 0,
  26063. EntireArray: 1,
  26064. ArrayElement: 2,
  26065. HasFromToArray: 3
  26066. };
  26067. PropertyBinding.prototype.Versioning = {
  26068. None: 0,
  26069. NeedsUpdate: 1,
  26070. MatrixWorldNeedsUpdate: 2
  26071. };
  26072. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  26073. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  26074. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  26075. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  26076. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  26077. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  26078. /**
  26079. *
  26080. * A group of objects that receives a shared animation state.
  26081. *
  26082. * Usage:
  26083. *
  26084. * - Add objects you would otherwise pass as 'root' to the
  26085. * constructor or the .clipAction method of AnimationMixer.
  26086. *
  26087. * - Instead pass this object as 'root'.
  26088. *
  26089. * - You can also add and remove objects later when the mixer
  26090. * is running.
  26091. *
  26092. * Note:
  26093. *
  26094. * Objects of this class appear as one object to the mixer,
  26095. * so cache control of the individual objects must be done
  26096. * on the group.
  26097. *
  26098. * Limitation:
  26099. *
  26100. * - The animated properties must be compatible among the
  26101. * all objects in the group.
  26102. *
  26103. * - A single property can either be controlled through a
  26104. * target group or directly, but not both.
  26105. */
  26106. class AnimationObjectGroup {
  26107. constructor() {
  26108. this.isAnimationObjectGroup = true;
  26109. this.uuid = generateUUID(); // cached objects followed by the active ones
  26110. this._objects = Array.prototype.slice.call(arguments);
  26111. this.nCachedObjects_ = 0; // threshold
  26112. // note: read by PropertyBinding.Composite
  26113. const indices = {};
  26114. this._indicesByUUID = indices; // for bookkeeping
  26115. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26116. indices[arguments[i].uuid] = i;
  26117. }
  26118. this._paths = []; // inside: string
  26119. this._parsedPaths = []; // inside: { we don't care, here }
  26120. this._bindings = []; // inside: Array< PropertyBinding >
  26121. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26122. const scope = this;
  26123. this.stats = {
  26124. objects: {
  26125. get total() {
  26126. return scope._objects.length;
  26127. },
  26128. get inUse() {
  26129. return this.total - scope.nCachedObjects_;
  26130. }
  26131. },
  26132. get bindingsPerObject() {
  26133. return scope._bindings.length;
  26134. }
  26135. };
  26136. }
  26137. add() {
  26138. const objects = this._objects,
  26139. indicesByUUID = this._indicesByUUID,
  26140. paths = this._paths,
  26141. parsedPaths = this._parsedPaths,
  26142. bindings = this._bindings,
  26143. nBindings = bindings.length;
  26144. let knownObject = undefined,
  26145. nObjects = objects.length,
  26146. nCachedObjects = this.nCachedObjects_;
  26147. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26148. const object = arguments[i],
  26149. uuid = object.uuid;
  26150. let index = indicesByUUID[uuid];
  26151. if (index === undefined) {
  26152. // unknown object -> add it to the ACTIVE region
  26153. index = nObjects++;
  26154. indicesByUUID[uuid] = index;
  26155. objects.push(object); // accounting is done, now do the same for all bindings
  26156. for (let j = 0, m = nBindings; j !== m; ++j) {
  26157. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26158. }
  26159. } else if (index < nCachedObjects) {
  26160. knownObject = objects[index]; // move existing object to the ACTIVE region
  26161. const firstActiveIndex = --nCachedObjects,
  26162. lastCachedObject = objects[firstActiveIndex];
  26163. indicesByUUID[lastCachedObject.uuid] = index;
  26164. objects[index] = lastCachedObject;
  26165. indicesByUUID[uuid] = firstActiveIndex;
  26166. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26167. for (let j = 0, m = nBindings; j !== m; ++j) {
  26168. const bindingsForPath = bindings[j],
  26169. lastCached = bindingsForPath[firstActiveIndex];
  26170. let binding = bindingsForPath[index];
  26171. bindingsForPath[index] = lastCached;
  26172. if (binding === undefined) {
  26173. // since we do not bother to create new bindings
  26174. // for objects that are cached, the binding may
  26175. // or may not exist
  26176. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26177. }
  26178. bindingsForPath[firstActiveIndex] = binding;
  26179. }
  26180. } else if (objects[index] !== knownObject) {
  26181. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26182. } // else the object is already where we want it to be
  26183. } // for arguments
  26184. this.nCachedObjects_ = nCachedObjects;
  26185. }
  26186. remove() {
  26187. const objects = this._objects,
  26188. indicesByUUID = this._indicesByUUID,
  26189. bindings = this._bindings,
  26190. nBindings = bindings.length;
  26191. let nCachedObjects = this.nCachedObjects_;
  26192. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26193. const object = arguments[i],
  26194. uuid = object.uuid,
  26195. index = indicesByUUID[uuid];
  26196. if (index !== undefined && index >= nCachedObjects) {
  26197. // move existing object into the CACHED region
  26198. const lastCachedIndex = nCachedObjects++,
  26199. firstActiveObject = objects[lastCachedIndex];
  26200. indicesByUUID[firstActiveObject.uuid] = index;
  26201. objects[index] = firstActiveObject;
  26202. indicesByUUID[uuid] = lastCachedIndex;
  26203. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26204. for (let j = 0, m = nBindings; j !== m; ++j) {
  26205. const bindingsForPath = bindings[j],
  26206. firstActive = bindingsForPath[lastCachedIndex],
  26207. binding = bindingsForPath[index];
  26208. bindingsForPath[index] = firstActive;
  26209. bindingsForPath[lastCachedIndex] = binding;
  26210. }
  26211. }
  26212. } // for arguments
  26213. this.nCachedObjects_ = nCachedObjects;
  26214. } // remove & forget
  26215. uncache() {
  26216. const objects = this._objects,
  26217. indicesByUUID = this._indicesByUUID,
  26218. bindings = this._bindings,
  26219. nBindings = bindings.length;
  26220. let nCachedObjects = this.nCachedObjects_,
  26221. nObjects = objects.length;
  26222. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26223. const object = arguments[i],
  26224. uuid = object.uuid,
  26225. index = indicesByUUID[uuid];
  26226. if (index !== undefined) {
  26227. delete indicesByUUID[uuid];
  26228. if (index < nCachedObjects) {
  26229. // object is cached, shrink the CACHED region
  26230. const firstActiveIndex = --nCachedObjects,
  26231. lastCachedObject = objects[firstActiveIndex],
  26232. lastIndex = --nObjects,
  26233. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26234. indicesByUUID[lastCachedObject.uuid] = index;
  26235. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26236. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26237. objects[firstActiveIndex] = lastObject;
  26238. objects.pop(); // accounting is done, now do the same for all bindings
  26239. for (let j = 0, m = nBindings; j !== m; ++j) {
  26240. const bindingsForPath = bindings[j],
  26241. lastCached = bindingsForPath[firstActiveIndex],
  26242. last = bindingsForPath[lastIndex];
  26243. bindingsForPath[index] = lastCached;
  26244. bindingsForPath[firstActiveIndex] = last;
  26245. bindingsForPath.pop();
  26246. }
  26247. } else {
  26248. // object is active, just swap with the last and pop
  26249. const lastIndex = --nObjects,
  26250. lastObject = objects[lastIndex];
  26251. if (lastIndex > 0) {
  26252. indicesByUUID[lastObject.uuid] = index;
  26253. }
  26254. objects[index] = lastObject;
  26255. objects.pop(); // accounting is done, now do the same for all bindings
  26256. for (let j = 0, m = nBindings; j !== m; ++j) {
  26257. const bindingsForPath = bindings[j];
  26258. bindingsForPath[index] = bindingsForPath[lastIndex];
  26259. bindingsForPath.pop();
  26260. }
  26261. } // cached or active
  26262. } // if object is known
  26263. } // for arguments
  26264. this.nCachedObjects_ = nCachedObjects;
  26265. } // Internal interface used by befriended PropertyBinding.Composite:
  26266. subscribe_(path, parsedPath) {
  26267. // returns an array of bindings for the given path that is changed
  26268. // according to the contained objects in the group
  26269. const indicesByPath = this._bindingsIndicesByPath;
  26270. let index = indicesByPath[path];
  26271. const bindings = this._bindings;
  26272. if (index !== undefined) return bindings[index];
  26273. const paths = this._paths,
  26274. parsedPaths = this._parsedPaths,
  26275. objects = this._objects,
  26276. nObjects = objects.length,
  26277. nCachedObjects = this.nCachedObjects_,
  26278. bindingsForPath = new Array(nObjects);
  26279. index = bindings.length;
  26280. indicesByPath[path] = index;
  26281. paths.push(path);
  26282. parsedPaths.push(parsedPath);
  26283. bindings.push(bindingsForPath);
  26284. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26285. const object = objects[i];
  26286. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26287. }
  26288. return bindingsForPath;
  26289. }
  26290. unsubscribe_(path) {
  26291. // tells the group to forget about a property path and no longer
  26292. // update the array previously obtained with 'subscribe_'
  26293. const indicesByPath = this._bindingsIndicesByPath,
  26294. index = indicesByPath[path];
  26295. if (index !== undefined) {
  26296. const paths = this._paths,
  26297. parsedPaths = this._parsedPaths,
  26298. bindings = this._bindings,
  26299. lastBindingsIndex = bindings.length - 1,
  26300. lastBindings = bindings[lastBindingsIndex],
  26301. lastBindingsPath = path[lastBindingsIndex];
  26302. indicesByPath[lastBindingsPath] = index;
  26303. bindings[index] = lastBindings;
  26304. bindings.pop();
  26305. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26306. parsedPaths.pop();
  26307. paths[index] = paths[lastBindingsIndex];
  26308. paths.pop();
  26309. }
  26310. }
  26311. }
  26312. class AnimationAction {
  26313. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26314. this._mixer = mixer;
  26315. this._clip = clip;
  26316. this._localRoot = localRoot;
  26317. this.blendMode = blendMode;
  26318. const tracks = clip.tracks,
  26319. nTracks = tracks.length,
  26320. interpolants = new Array(nTracks);
  26321. const interpolantSettings = {
  26322. endingStart: ZeroCurvatureEnding,
  26323. endingEnd: ZeroCurvatureEnding
  26324. };
  26325. for (let i = 0; i !== nTracks; ++i) {
  26326. const interpolant = tracks[i].createInterpolant(null);
  26327. interpolants[i] = interpolant;
  26328. interpolant.settings = interpolantSettings;
  26329. }
  26330. this._interpolantSettings = interpolantSettings;
  26331. this._interpolants = interpolants; // bound by the mixer
  26332. // inside: PropertyMixer (managed by the mixer)
  26333. this._propertyBindings = new Array(nTracks);
  26334. this._cacheIndex = null; // for the memory manager
  26335. this._byClipCacheIndex = null; // for the memory manager
  26336. this._timeScaleInterpolant = null;
  26337. this._weightInterpolant = null;
  26338. this.loop = LoopRepeat;
  26339. this._loopCount = -1; // global mixer time when the action is to be started
  26340. // it's set back to 'null' upon start of the action
  26341. this._startTime = null; // scaled local time of the action
  26342. // gets clamped or wrapped to 0..clip.duration according to loop
  26343. this.time = 0;
  26344. this.timeScale = 1;
  26345. this._effectiveTimeScale = 1;
  26346. this.weight = 1;
  26347. this._effectiveWeight = 1;
  26348. this.repetitions = Infinity; // no. of repetitions when looping
  26349. this.paused = false; // true -> zero effective time scale
  26350. this.enabled = true; // false -> zero effective weight
  26351. this.clampWhenFinished = false; // keep feeding the last frame?
  26352. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26353. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26354. } // State & Scheduling
  26355. play() {
  26356. this._mixer._activateAction(this);
  26357. return this;
  26358. }
  26359. stop() {
  26360. this._mixer._deactivateAction(this);
  26361. return this.reset();
  26362. }
  26363. reset() {
  26364. this.paused = false;
  26365. this.enabled = true;
  26366. this.time = 0; // restart clip
  26367. this._loopCount = -1; // forget previous loops
  26368. this._startTime = null; // forget scheduling
  26369. return this.stopFading().stopWarping();
  26370. }
  26371. isRunning() {
  26372. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26373. } // return true when play has been called
  26374. isScheduled() {
  26375. return this._mixer._isActiveAction(this);
  26376. }
  26377. startAt(time) {
  26378. this._startTime = time;
  26379. return this;
  26380. }
  26381. setLoop(mode, repetitions) {
  26382. this.loop = mode;
  26383. this.repetitions = repetitions;
  26384. return this;
  26385. } // Weight
  26386. // set the weight stopping any scheduled fading
  26387. // although .enabled = false yields an effective weight of zero, this
  26388. // method does *not* change .enabled, because it would be confusing
  26389. setEffectiveWeight(weight) {
  26390. this.weight = weight; // note: same logic as when updated at runtime
  26391. this._effectiveWeight = this.enabled ? weight : 0;
  26392. return this.stopFading();
  26393. } // return the weight considering fading and .enabled
  26394. getEffectiveWeight() {
  26395. return this._effectiveWeight;
  26396. }
  26397. fadeIn(duration) {
  26398. return this._scheduleFading(duration, 0, 1);
  26399. }
  26400. fadeOut(duration) {
  26401. return this._scheduleFading(duration, 1, 0);
  26402. }
  26403. crossFadeFrom(fadeOutAction, duration, warp) {
  26404. fadeOutAction.fadeOut(duration);
  26405. this.fadeIn(duration);
  26406. if (warp) {
  26407. const fadeInDuration = this._clip.duration,
  26408. fadeOutDuration = fadeOutAction._clip.duration,
  26409. startEndRatio = fadeOutDuration / fadeInDuration,
  26410. endStartRatio = fadeInDuration / fadeOutDuration;
  26411. fadeOutAction.warp(1.0, startEndRatio, duration);
  26412. this.warp(endStartRatio, 1.0, duration);
  26413. }
  26414. return this;
  26415. }
  26416. crossFadeTo(fadeInAction, duration, warp) {
  26417. return fadeInAction.crossFadeFrom(this, duration, warp);
  26418. }
  26419. stopFading() {
  26420. const weightInterpolant = this._weightInterpolant;
  26421. if (weightInterpolant !== null) {
  26422. this._weightInterpolant = null;
  26423. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26424. }
  26425. return this;
  26426. } // Time Scale Control
  26427. // set the time scale stopping any scheduled warping
  26428. // although .paused = true yields an effective time scale of zero, this
  26429. // method does *not* change .paused, because it would be confusing
  26430. setEffectiveTimeScale(timeScale) {
  26431. this.timeScale = timeScale;
  26432. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26433. return this.stopWarping();
  26434. } // return the time scale considering warping and .paused
  26435. getEffectiveTimeScale() {
  26436. return this._effectiveTimeScale;
  26437. }
  26438. setDuration(duration) {
  26439. this.timeScale = this._clip.duration / duration;
  26440. return this.stopWarping();
  26441. }
  26442. syncWith(action) {
  26443. this.time = action.time;
  26444. this.timeScale = action.timeScale;
  26445. return this.stopWarping();
  26446. }
  26447. halt(duration) {
  26448. return this.warp(this._effectiveTimeScale, 0, duration);
  26449. }
  26450. warp(startTimeScale, endTimeScale, duration) {
  26451. const mixer = this._mixer,
  26452. now = mixer.time,
  26453. timeScale = this.timeScale;
  26454. let interpolant = this._timeScaleInterpolant;
  26455. if (interpolant === null) {
  26456. interpolant = mixer._lendControlInterpolant();
  26457. this._timeScaleInterpolant = interpolant;
  26458. }
  26459. const times = interpolant.parameterPositions,
  26460. values = interpolant.sampleValues;
  26461. times[0] = now;
  26462. times[1] = now + duration;
  26463. values[0] = startTimeScale / timeScale;
  26464. values[1] = endTimeScale / timeScale;
  26465. return this;
  26466. }
  26467. stopWarping() {
  26468. const timeScaleInterpolant = this._timeScaleInterpolant;
  26469. if (timeScaleInterpolant !== null) {
  26470. this._timeScaleInterpolant = null;
  26471. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26472. }
  26473. return this;
  26474. } // Object Accessors
  26475. getMixer() {
  26476. return this._mixer;
  26477. }
  26478. getClip() {
  26479. return this._clip;
  26480. }
  26481. getRoot() {
  26482. return this._localRoot || this._mixer._root;
  26483. } // Interna
  26484. _update(time, deltaTime, timeDirection, accuIndex) {
  26485. // called by the mixer
  26486. if (!this.enabled) {
  26487. // call ._updateWeight() to update ._effectiveWeight
  26488. this._updateWeight(time);
  26489. return;
  26490. }
  26491. const startTime = this._startTime;
  26492. if (startTime !== null) {
  26493. // check for scheduled start of action
  26494. const timeRunning = (time - startTime) * timeDirection;
  26495. if (timeRunning < 0 || timeDirection === 0) {
  26496. return; // yet to come / don't decide when delta = 0
  26497. } // start
  26498. this._startTime = null; // unschedule
  26499. deltaTime = timeDirection * timeRunning;
  26500. } // apply time scale and advance time
  26501. deltaTime *= this._updateTimeScale(time);
  26502. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26503. // an effective weight of 0
  26504. const weight = this._updateWeight(time);
  26505. if (weight > 0) {
  26506. const interpolants = this._interpolants;
  26507. const propertyMixers = this._propertyBindings;
  26508. switch (this.blendMode) {
  26509. case AdditiveAnimationBlendMode:
  26510. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26511. interpolants[j].evaluate(clipTime);
  26512. propertyMixers[j].accumulateAdditive(weight);
  26513. }
  26514. break;
  26515. case NormalAnimationBlendMode:
  26516. default:
  26517. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26518. interpolants[j].evaluate(clipTime);
  26519. propertyMixers[j].accumulate(accuIndex, weight);
  26520. }
  26521. }
  26522. }
  26523. }
  26524. _updateWeight(time) {
  26525. let weight = 0;
  26526. if (this.enabled) {
  26527. weight = this.weight;
  26528. const interpolant = this._weightInterpolant;
  26529. if (interpolant !== null) {
  26530. const interpolantValue = interpolant.evaluate(time)[0];
  26531. weight *= interpolantValue;
  26532. if (time > interpolant.parameterPositions[1]) {
  26533. this.stopFading();
  26534. if (interpolantValue === 0) {
  26535. // faded out, disable
  26536. this.enabled = false;
  26537. }
  26538. }
  26539. }
  26540. }
  26541. this._effectiveWeight = weight;
  26542. return weight;
  26543. }
  26544. _updateTimeScale(time) {
  26545. let timeScale = 0;
  26546. if (!this.paused) {
  26547. timeScale = this.timeScale;
  26548. const interpolant = this._timeScaleInterpolant;
  26549. if (interpolant !== null) {
  26550. const interpolantValue = interpolant.evaluate(time)[0];
  26551. timeScale *= interpolantValue;
  26552. if (time > interpolant.parameterPositions[1]) {
  26553. this.stopWarping();
  26554. if (timeScale === 0) {
  26555. // motion has halted, pause
  26556. this.paused = true;
  26557. } else {
  26558. // warp done - apply final time scale
  26559. this.timeScale = timeScale;
  26560. }
  26561. }
  26562. }
  26563. }
  26564. this._effectiveTimeScale = timeScale;
  26565. return timeScale;
  26566. }
  26567. _updateTime(deltaTime) {
  26568. const duration = this._clip.duration;
  26569. const loop = this.loop;
  26570. let time = this.time + deltaTime;
  26571. let loopCount = this._loopCount;
  26572. const pingPong = loop === LoopPingPong;
  26573. if (deltaTime === 0) {
  26574. if (loopCount === -1) return time;
  26575. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26576. }
  26577. if (loop === LoopOnce) {
  26578. if (loopCount === -1) {
  26579. // just started
  26580. this._loopCount = 0;
  26581. this._setEndings(true, true, false);
  26582. }
  26583. handle_stop: {
  26584. if (time >= duration) {
  26585. time = duration;
  26586. } else if (time < 0) {
  26587. time = 0;
  26588. } else {
  26589. this.time = time;
  26590. break handle_stop;
  26591. }
  26592. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26593. this.time = time;
  26594. this._mixer.dispatchEvent({
  26595. type: 'finished',
  26596. action: this,
  26597. direction: deltaTime < 0 ? -1 : 1
  26598. });
  26599. }
  26600. } else {
  26601. // repetitive Repeat or PingPong
  26602. if (loopCount === -1) {
  26603. // just started
  26604. if (deltaTime >= 0) {
  26605. loopCount = 0;
  26606. this._setEndings(true, this.repetitions === 0, pingPong);
  26607. } else {
  26608. // when looping in reverse direction, the initial
  26609. // transition through zero counts as a repetition,
  26610. // so leave loopCount at -1
  26611. this._setEndings(this.repetitions === 0, true, pingPong);
  26612. }
  26613. }
  26614. if (time >= duration || time < 0) {
  26615. // wrap around
  26616. const loopDelta = Math.floor(time / duration); // signed
  26617. time -= duration * loopDelta;
  26618. loopCount += Math.abs(loopDelta);
  26619. const pending = this.repetitions - loopCount;
  26620. if (pending <= 0) {
  26621. // have to stop (switch state, clamp time, fire event)
  26622. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26623. time = deltaTime > 0 ? duration : 0;
  26624. this.time = time;
  26625. this._mixer.dispatchEvent({
  26626. type: 'finished',
  26627. action: this,
  26628. direction: deltaTime > 0 ? 1 : -1
  26629. });
  26630. } else {
  26631. // keep running
  26632. if (pending === 1) {
  26633. // entering the last round
  26634. const atStart = deltaTime < 0;
  26635. this._setEndings(atStart, !atStart, pingPong);
  26636. } else {
  26637. this._setEndings(false, false, pingPong);
  26638. }
  26639. this._loopCount = loopCount;
  26640. this.time = time;
  26641. this._mixer.dispatchEvent({
  26642. type: 'loop',
  26643. action: this,
  26644. loopDelta: loopDelta
  26645. });
  26646. }
  26647. } else {
  26648. this.time = time;
  26649. }
  26650. if (pingPong && (loopCount & 1) === 1) {
  26651. // invert time for the "pong round"
  26652. return duration - time;
  26653. }
  26654. }
  26655. return time;
  26656. }
  26657. _setEndings(atStart, atEnd, pingPong) {
  26658. const settings = this._interpolantSettings;
  26659. if (pingPong) {
  26660. settings.endingStart = ZeroSlopeEnding;
  26661. settings.endingEnd = ZeroSlopeEnding;
  26662. } else {
  26663. // assuming for LoopOnce atStart == atEnd == true
  26664. if (atStart) {
  26665. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26666. } else {
  26667. settings.endingStart = WrapAroundEnding;
  26668. }
  26669. if (atEnd) {
  26670. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26671. } else {
  26672. settings.endingEnd = WrapAroundEnding;
  26673. }
  26674. }
  26675. }
  26676. _scheduleFading(duration, weightNow, weightThen) {
  26677. const mixer = this._mixer,
  26678. now = mixer.time;
  26679. let interpolant = this._weightInterpolant;
  26680. if (interpolant === null) {
  26681. interpolant = mixer._lendControlInterpolant();
  26682. this._weightInterpolant = interpolant;
  26683. }
  26684. const times = interpolant.parameterPositions,
  26685. values = interpolant.sampleValues;
  26686. times[0] = now;
  26687. values[0] = weightNow;
  26688. times[1] = now + duration;
  26689. values[1] = weightThen;
  26690. return this;
  26691. }
  26692. }
  26693. const _controlInterpolantsResultBuffer = new Float32Array(1);
  26694. class AnimationMixer extends EventDispatcher {
  26695. constructor(root) {
  26696. super();
  26697. this._root = root;
  26698. this._initMemoryManager();
  26699. this._accuIndex = 0;
  26700. this.time = 0;
  26701. this.timeScale = 1.0;
  26702. }
  26703. _bindAction(action, prototypeAction) {
  26704. const root = action._localRoot || this._root,
  26705. tracks = action._clip.tracks,
  26706. nTracks = tracks.length,
  26707. bindings = action._propertyBindings,
  26708. interpolants = action._interpolants,
  26709. rootUuid = root.uuid,
  26710. bindingsByRoot = this._bindingsByRootAndName;
  26711. let bindingsByName = bindingsByRoot[rootUuid];
  26712. if (bindingsByName === undefined) {
  26713. bindingsByName = {};
  26714. bindingsByRoot[rootUuid] = bindingsByName;
  26715. }
  26716. for (let i = 0; i !== nTracks; ++i) {
  26717. const track = tracks[i],
  26718. trackName = track.name;
  26719. let binding = bindingsByName[trackName];
  26720. if (binding !== undefined) {
  26721. ++binding.referenceCount;
  26722. bindings[i] = binding;
  26723. } else {
  26724. binding = bindings[i];
  26725. if (binding !== undefined) {
  26726. // existing binding, make sure the cache knows
  26727. if (binding._cacheIndex === null) {
  26728. ++binding.referenceCount;
  26729. this._addInactiveBinding(binding, rootUuid, trackName);
  26730. }
  26731. continue;
  26732. }
  26733. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26734. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26735. ++binding.referenceCount;
  26736. this._addInactiveBinding(binding, rootUuid, trackName);
  26737. bindings[i] = binding;
  26738. }
  26739. interpolants[i].resultBuffer = binding.buffer;
  26740. }
  26741. }
  26742. _activateAction(action) {
  26743. if (!this._isActiveAction(action)) {
  26744. if (action._cacheIndex === null) {
  26745. // this action has been forgotten by the cache, but the user
  26746. // appears to be still using it -> rebind
  26747. const rootUuid = (action._localRoot || this._root).uuid,
  26748. clipUuid = action._clip.uuid,
  26749. actionsForClip = this._actionsByClip[clipUuid];
  26750. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26751. this._addInactiveAction(action, clipUuid, rootUuid);
  26752. }
  26753. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26754. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26755. const binding = bindings[i];
  26756. if (binding.useCount++ === 0) {
  26757. this._lendBinding(binding);
  26758. binding.saveOriginalState();
  26759. }
  26760. }
  26761. this._lendAction(action);
  26762. }
  26763. }
  26764. _deactivateAction(action) {
  26765. if (this._isActiveAction(action)) {
  26766. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26767. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26768. const binding = bindings[i];
  26769. if (--binding.useCount === 0) {
  26770. binding.restoreOriginalState();
  26771. this._takeBackBinding(binding);
  26772. }
  26773. }
  26774. this._takeBackAction(action);
  26775. }
  26776. } // Memory manager
  26777. _initMemoryManager() {
  26778. this._actions = []; // 'nActiveActions' followed by inactive ones
  26779. this._nActiveActions = 0;
  26780. this._actionsByClip = {}; // inside:
  26781. // {
  26782. // knownActions: Array< AnimationAction > - used as prototypes
  26783. // actionByRoot: AnimationAction - lookup
  26784. // }
  26785. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26786. this._nActiveBindings = 0;
  26787. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26788. this._controlInterpolants = []; // same game as above
  26789. this._nActiveControlInterpolants = 0;
  26790. const scope = this;
  26791. this.stats = {
  26792. actions: {
  26793. get total() {
  26794. return scope._actions.length;
  26795. },
  26796. get inUse() {
  26797. return scope._nActiveActions;
  26798. }
  26799. },
  26800. bindings: {
  26801. get total() {
  26802. return scope._bindings.length;
  26803. },
  26804. get inUse() {
  26805. return scope._nActiveBindings;
  26806. }
  26807. },
  26808. controlInterpolants: {
  26809. get total() {
  26810. return scope._controlInterpolants.length;
  26811. },
  26812. get inUse() {
  26813. return scope._nActiveControlInterpolants;
  26814. }
  26815. }
  26816. };
  26817. } // Memory management for AnimationAction objects
  26818. _isActiveAction(action) {
  26819. const index = action._cacheIndex;
  26820. return index !== null && index < this._nActiveActions;
  26821. }
  26822. _addInactiveAction(action, clipUuid, rootUuid) {
  26823. const actions = this._actions,
  26824. actionsByClip = this._actionsByClip;
  26825. let actionsForClip = actionsByClip[clipUuid];
  26826. if (actionsForClip === undefined) {
  26827. actionsForClip = {
  26828. knownActions: [action],
  26829. actionByRoot: {}
  26830. };
  26831. action._byClipCacheIndex = 0;
  26832. actionsByClip[clipUuid] = actionsForClip;
  26833. } else {
  26834. const knownActions = actionsForClip.knownActions;
  26835. action._byClipCacheIndex = knownActions.length;
  26836. knownActions.push(action);
  26837. }
  26838. action._cacheIndex = actions.length;
  26839. actions.push(action);
  26840. actionsForClip.actionByRoot[rootUuid] = action;
  26841. }
  26842. _removeInactiveAction(action) {
  26843. const actions = this._actions,
  26844. lastInactiveAction = actions[actions.length - 1],
  26845. cacheIndex = action._cacheIndex;
  26846. lastInactiveAction._cacheIndex = cacheIndex;
  26847. actions[cacheIndex] = lastInactiveAction;
  26848. actions.pop();
  26849. action._cacheIndex = null;
  26850. const clipUuid = action._clip.uuid,
  26851. actionsByClip = this._actionsByClip,
  26852. actionsForClip = actionsByClip[clipUuid],
  26853. knownActionsForClip = actionsForClip.knownActions,
  26854. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26855. byClipCacheIndex = action._byClipCacheIndex;
  26856. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26857. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26858. knownActionsForClip.pop();
  26859. action._byClipCacheIndex = null;
  26860. const actionByRoot = actionsForClip.actionByRoot,
  26861. rootUuid = (action._localRoot || this._root).uuid;
  26862. delete actionByRoot[rootUuid];
  26863. if (knownActionsForClip.length === 0) {
  26864. delete actionsByClip[clipUuid];
  26865. }
  26866. this._removeInactiveBindingsForAction(action);
  26867. }
  26868. _removeInactiveBindingsForAction(action) {
  26869. const bindings = action._propertyBindings;
  26870. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26871. const binding = bindings[i];
  26872. if (--binding.referenceCount === 0) {
  26873. this._removeInactiveBinding(binding);
  26874. }
  26875. }
  26876. }
  26877. _lendAction(action) {
  26878. // [ active actions | inactive actions ]
  26879. // [ active actions >| inactive actions ]
  26880. // s a
  26881. // <-swap->
  26882. // a s
  26883. const actions = this._actions,
  26884. prevIndex = action._cacheIndex,
  26885. lastActiveIndex = this._nActiveActions++,
  26886. firstInactiveAction = actions[lastActiveIndex];
  26887. action._cacheIndex = lastActiveIndex;
  26888. actions[lastActiveIndex] = action;
  26889. firstInactiveAction._cacheIndex = prevIndex;
  26890. actions[prevIndex] = firstInactiveAction;
  26891. }
  26892. _takeBackAction(action) {
  26893. // [ active actions | inactive actions ]
  26894. // [ active actions |< inactive actions ]
  26895. // a s
  26896. // <-swap->
  26897. // s a
  26898. const actions = this._actions,
  26899. prevIndex = action._cacheIndex,
  26900. firstInactiveIndex = --this._nActiveActions,
  26901. lastActiveAction = actions[firstInactiveIndex];
  26902. action._cacheIndex = firstInactiveIndex;
  26903. actions[firstInactiveIndex] = action;
  26904. lastActiveAction._cacheIndex = prevIndex;
  26905. actions[prevIndex] = lastActiveAction;
  26906. } // Memory management for PropertyMixer objects
  26907. _addInactiveBinding(binding, rootUuid, trackName) {
  26908. const bindingsByRoot = this._bindingsByRootAndName,
  26909. bindings = this._bindings;
  26910. let bindingByName = bindingsByRoot[rootUuid];
  26911. if (bindingByName === undefined) {
  26912. bindingByName = {};
  26913. bindingsByRoot[rootUuid] = bindingByName;
  26914. }
  26915. bindingByName[trackName] = binding;
  26916. binding._cacheIndex = bindings.length;
  26917. bindings.push(binding);
  26918. }
  26919. _removeInactiveBinding(binding) {
  26920. const bindings = this._bindings,
  26921. propBinding = binding.binding,
  26922. rootUuid = propBinding.rootNode.uuid,
  26923. trackName = propBinding.path,
  26924. bindingsByRoot = this._bindingsByRootAndName,
  26925. bindingByName = bindingsByRoot[rootUuid],
  26926. lastInactiveBinding = bindings[bindings.length - 1],
  26927. cacheIndex = binding._cacheIndex;
  26928. lastInactiveBinding._cacheIndex = cacheIndex;
  26929. bindings[cacheIndex] = lastInactiveBinding;
  26930. bindings.pop();
  26931. delete bindingByName[trackName];
  26932. if (Object.keys(bindingByName).length === 0) {
  26933. delete bindingsByRoot[rootUuid];
  26934. }
  26935. }
  26936. _lendBinding(binding) {
  26937. const bindings = this._bindings,
  26938. prevIndex = binding._cacheIndex,
  26939. lastActiveIndex = this._nActiveBindings++,
  26940. firstInactiveBinding = bindings[lastActiveIndex];
  26941. binding._cacheIndex = lastActiveIndex;
  26942. bindings[lastActiveIndex] = binding;
  26943. firstInactiveBinding._cacheIndex = prevIndex;
  26944. bindings[prevIndex] = firstInactiveBinding;
  26945. }
  26946. _takeBackBinding(binding) {
  26947. const bindings = this._bindings,
  26948. prevIndex = binding._cacheIndex,
  26949. firstInactiveIndex = --this._nActiveBindings,
  26950. lastActiveBinding = bindings[firstInactiveIndex];
  26951. binding._cacheIndex = firstInactiveIndex;
  26952. bindings[firstInactiveIndex] = binding;
  26953. lastActiveBinding._cacheIndex = prevIndex;
  26954. bindings[prevIndex] = lastActiveBinding;
  26955. } // Memory management of Interpolants for weight and time scale
  26956. _lendControlInterpolant() {
  26957. const interpolants = this._controlInterpolants,
  26958. lastActiveIndex = this._nActiveControlInterpolants++;
  26959. let interpolant = interpolants[lastActiveIndex];
  26960. if (interpolant === undefined) {
  26961. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer);
  26962. interpolant.__cacheIndex = lastActiveIndex;
  26963. interpolants[lastActiveIndex] = interpolant;
  26964. }
  26965. return interpolant;
  26966. }
  26967. _takeBackControlInterpolant(interpolant) {
  26968. const interpolants = this._controlInterpolants,
  26969. prevIndex = interpolant.__cacheIndex,
  26970. firstInactiveIndex = --this._nActiveControlInterpolants,
  26971. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26972. interpolant.__cacheIndex = firstInactiveIndex;
  26973. interpolants[firstInactiveIndex] = interpolant;
  26974. lastActiveInterpolant.__cacheIndex = prevIndex;
  26975. interpolants[prevIndex] = lastActiveInterpolant;
  26976. } // return an action for a clip optionally using a custom root target
  26977. // object (this method allocates a lot of dynamic memory in case a
  26978. // previously unknown clip/root combination is specified)
  26979. clipAction(clip, optionalRoot, blendMode) {
  26980. const root = optionalRoot || this._root,
  26981. rootUuid = root.uuid;
  26982. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26983. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26984. const actionsForClip = this._actionsByClip[clipUuid];
  26985. let prototypeAction = null;
  26986. if (blendMode === undefined) {
  26987. if (clipObject !== null) {
  26988. blendMode = clipObject.blendMode;
  26989. } else {
  26990. blendMode = NormalAnimationBlendMode;
  26991. }
  26992. }
  26993. if (actionsForClip !== undefined) {
  26994. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26995. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26996. return existingAction;
  26997. } // we know the clip, so we don't have to parse all
  26998. // the bindings again but can just copy
  26999. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27000. if (clipObject === null) clipObject = prototypeAction._clip;
  27001. } // clip must be known when specified via string
  27002. if (clipObject === null) return null; // allocate all resources required to run it
  27003. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  27004. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27005. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27006. return newAction;
  27007. } // get an existing action
  27008. existingAction(clip, optionalRoot) {
  27009. const root = optionalRoot || this._root,
  27010. rootUuid = root.uuid,
  27011. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27012. clipUuid = clipObject ? clipObject.uuid : clip,
  27013. actionsForClip = this._actionsByClip[clipUuid];
  27014. if (actionsForClip !== undefined) {
  27015. return actionsForClip.actionByRoot[rootUuid] || null;
  27016. }
  27017. return null;
  27018. } // deactivates all previously scheduled actions
  27019. stopAllAction() {
  27020. const actions = this._actions,
  27021. nActions = this._nActiveActions;
  27022. for (let i = nActions - 1; i >= 0; --i) {
  27023. actions[i].stop();
  27024. }
  27025. return this;
  27026. } // advance the time and update apply the animation
  27027. update(deltaTime) {
  27028. deltaTime *= this.timeScale;
  27029. const actions = this._actions,
  27030. nActions = this._nActiveActions,
  27031. time = this.time += deltaTime,
  27032. timeDirection = Math.sign(deltaTime),
  27033. accuIndex = this._accuIndex ^= 1; // run active actions
  27034. for (let i = 0; i !== nActions; ++i) {
  27035. const action = actions[i];
  27036. action._update(time, deltaTime, timeDirection, accuIndex);
  27037. } // update scene graph
  27038. const bindings = this._bindings,
  27039. nBindings = this._nActiveBindings;
  27040. for (let i = 0; i !== nBindings; ++i) {
  27041. bindings[i].apply(accuIndex);
  27042. }
  27043. return this;
  27044. } // Allows you to seek to a specific time in an animation.
  27045. setTime(timeInSeconds) {
  27046. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27047. for (let i = 0; i < this._actions.length; i++) {
  27048. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27049. }
  27050. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27051. } // return this mixer's root target object
  27052. getRoot() {
  27053. return this._root;
  27054. } // free all resources specific to a particular clip
  27055. uncacheClip(clip) {
  27056. const actions = this._actions,
  27057. clipUuid = clip.uuid,
  27058. actionsByClip = this._actionsByClip,
  27059. actionsForClip = actionsByClip[clipUuid];
  27060. if (actionsForClip !== undefined) {
  27061. // note: just calling _removeInactiveAction would mess up the
  27062. // iteration state and also require updating the state we can
  27063. // just throw away
  27064. const actionsToRemove = actionsForClip.knownActions;
  27065. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27066. const action = actionsToRemove[i];
  27067. this._deactivateAction(action);
  27068. const cacheIndex = action._cacheIndex,
  27069. lastInactiveAction = actions[actions.length - 1];
  27070. action._cacheIndex = null;
  27071. action._byClipCacheIndex = null;
  27072. lastInactiveAction._cacheIndex = cacheIndex;
  27073. actions[cacheIndex] = lastInactiveAction;
  27074. actions.pop();
  27075. this._removeInactiveBindingsForAction(action);
  27076. }
  27077. delete actionsByClip[clipUuid];
  27078. }
  27079. } // free all resources specific to a particular root target object
  27080. uncacheRoot(root) {
  27081. const rootUuid = root.uuid,
  27082. actionsByClip = this._actionsByClip;
  27083. for (const clipUuid in actionsByClip) {
  27084. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27085. action = actionByRoot[rootUuid];
  27086. if (action !== undefined) {
  27087. this._deactivateAction(action);
  27088. this._removeInactiveAction(action);
  27089. }
  27090. }
  27091. const bindingsByRoot = this._bindingsByRootAndName,
  27092. bindingByName = bindingsByRoot[rootUuid];
  27093. if (bindingByName !== undefined) {
  27094. for (const trackName in bindingByName) {
  27095. const binding = bindingByName[trackName];
  27096. binding.restoreOriginalState();
  27097. this._removeInactiveBinding(binding);
  27098. }
  27099. }
  27100. } // remove a targeted clip from the cache
  27101. uncacheAction(clip, optionalRoot) {
  27102. const action = this.existingAction(clip, optionalRoot);
  27103. if (action !== null) {
  27104. this._deactivateAction(action);
  27105. this._removeInactiveAction(action);
  27106. }
  27107. }
  27108. }
  27109. class Uniform {
  27110. constructor(value) {
  27111. if (typeof value === 'string') {
  27112. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27113. value = arguments[1];
  27114. }
  27115. this.value = value;
  27116. }
  27117. clone() {
  27118. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27119. }
  27120. }
  27121. let id = 0;
  27122. class UniformsGroup extends EventDispatcher {
  27123. constructor() {
  27124. super();
  27125. this.isUniformsGroup = true;
  27126. Object.defineProperty(this, 'id', {
  27127. value: id++
  27128. });
  27129. this.name = '';
  27130. this.usage = StaticDrawUsage;
  27131. this.uniforms = [];
  27132. }
  27133. add(uniform) {
  27134. this.uniforms.push(uniform);
  27135. return this;
  27136. }
  27137. remove(uniform) {
  27138. const index = this.uniforms.indexOf(uniform);
  27139. if (index !== -1) this.uniforms.splice(index, 1);
  27140. return this;
  27141. }
  27142. setName(name) {
  27143. this.name = name;
  27144. return this;
  27145. }
  27146. setUsage(value) {
  27147. this.usage = value;
  27148. return this;
  27149. }
  27150. dispose() {
  27151. this.dispatchEvent({
  27152. type: 'dispose'
  27153. });
  27154. return this;
  27155. }
  27156. copy(source) {
  27157. this.name = source.name;
  27158. this.usage = source.usage;
  27159. const uniformsSource = source.uniforms;
  27160. this.uniforms.length = 0;
  27161. for (let i = 0, l = uniformsSource.length; i < l; i++) {
  27162. this.uniforms.push(uniformsSource[i].clone());
  27163. }
  27164. return this;
  27165. }
  27166. clone() {
  27167. return new this.constructor().copy(this);
  27168. }
  27169. }
  27170. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27171. constructor(array, stride, meshPerAttribute = 1) {
  27172. super(array, stride);
  27173. this.isInstancedInterleavedBuffer = true;
  27174. this.meshPerAttribute = meshPerAttribute;
  27175. }
  27176. copy(source) {
  27177. super.copy(source);
  27178. this.meshPerAttribute = source.meshPerAttribute;
  27179. return this;
  27180. }
  27181. clone(data) {
  27182. const ib = super.clone(data);
  27183. ib.meshPerAttribute = this.meshPerAttribute;
  27184. return ib;
  27185. }
  27186. toJSON(data) {
  27187. const json = super.toJSON(data);
  27188. json.isInstancedInterleavedBuffer = true;
  27189. json.meshPerAttribute = this.meshPerAttribute;
  27190. return json;
  27191. }
  27192. }
  27193. class GLBufferAttribute {
  27194. constructor(buffer, type, itemSize, elementSize, count) {
  27195. this.isGLBufferAttribute = true;
  27196. this.buffer = buffer;
  27197. this.type = type;
  27198. this.itemSize = itemSize;
  27199. this.elementSize = elementSize;
  27200. this.count = count;
  27201. this.version = 0;
  27202. }
  27203. set needsUpdate(value) {
  27204. if (value === true) this.version++;
  27205. }
  27206. setBuffer(buffer) {
  27207. this.buffer = buffer;
  27208. return this;
  27209. }
  27210. setType(type, elementSize) {
  27211. this.type = type;
  27212. this.elementSize = elementSize;
  27213. return this;
  27214. }
  27215. setItemSize(itemSize) {
  27216. this.itemSize = itemSize;
  27217. return this;
  27218. }
  27219. setCount(count) {
  27220. this.count = count;
  27221. return this;
  27222. }
  27223. }
  27224. class Raycaster {
  27225. constructor(origin, direction, near = 0, far = Infinity) {
  27226. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27227. this.near = near;
  27228. this.far = far;
  27229. this.camera = null;
  27230. this.layers = new Layers();
  27231. this.params = {
  27232. Mesh: {},
  27233. Line: {
  27234. threshold: 1
  27235. },
  27236. LOD: {},
  27237. Points: {
  27238. threshold: 1
  27239. },
  27240. Sprite: {}
  27241. };
  27242. }
  27243. set(origin, direction) {
  27244. // direction is assumed to be normalized (for accurate distance calculations)
  27245. this.ray.set(origin, direction);
  27246. }
  27247. setFromCamera(coords, camera) {
  27248. if (camera.isPerspectiveCamera) {
  27249. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27250. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27251. this.camera = camera;
  27252. } else if (camera.isOrthographicCamera) {
  27253. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27254. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27255. this.camera = camera;
  27256. } else {
  27257. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  27258. }
  27259. }
  27260. intersectObject(object, recursive = true, intersects = []) {
  27261. intersectObject(object, this, intersects, recursive);
  27262. intersects.sort(ascSort);
  27263. return intersects;
  27264. }
  27265. intersectObjects(objects, recursive = true, intersects = []) {
  27266. for (let i = 0, l = objects.length; i < l; i++) {
  27267. intersectObject(objects[i], this, intersects, recursive);
  27268. }
  27269. intersects.sort(ascSort);
  27270. return intersects;
  27271. }
  27272. }
  27273. function ascSort(a, b) {
  27274. return a.distance - b.distance;
  27275. }
  27276. function intersectObject(object, raycaster, intersects, recursive) {
  27277. if (object.layers.test(raycaster.layers)) {
  27278. object.raycast(raycaster, intersects);
  27279. }
  27280. if (recursive === true) {
  27281. const children = object.children;
  27282. for (let i = 0, l = children.length; i < l; i++) {
  27283. intersectObject(children[i], raycaster, intersects, true);
  27284. }
  27285. }
  27286. }
  27287. /**
  27288. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27289. *
  27290. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27291. * The azimuthal angle (theta) is measured from the positive z-axis.
  27292. */
  27293. class Spherical {
  27294. constructor(radius = 1, phi = 0, theta = 0) {
  27295. this.radius = radius;
  27296. this.phi = phi; // polar angle
  27297. this.theta = theta; // azimuthal angle
  27298. return this;
  27299. }
  27300. set(radius, phi, theta) {
  27301. this.radius = radius;
  27302. this.phi = phi;
  27303. this.theta = theta;
  27304. return this;
  27305. }
  27306. copy(other) {
  27307. this.radius = other.radius;
  27308. this.phi = other.phi;
  27309. this.theta = other.theta;
  27310. return this;
  27311. } // restrict phi to be between EPS and PI-EPS
  27312. makeSafe() {
  27313. const EPS = 0.000001;
  27314. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27315. return this;
  27316. }
  27317. setFromVector3(v) {
  27318. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27319. }
  27320. setFromCartesianCoords(x, y, z) {
  27321. this.radius = Math.sqrt(x * x + y * y + z * z);
  27322. if (this.radius === 0) {
  27323. this.theta = 0;
  27324. this.phi = 0;
  27325. } else {
  27326. this.theta = Math.atan2(x, z);
  27327. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27328. }
  27329. return this;
  27330. }
  27331. clone() {
  27332. return new this.constructor().copy(this);
  27333. }
  27334. }
  27335. /**
  27336. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27337. */
  27338. class Cylindrical {
  27339. constructor(radius = 1, theta = 0, y = 0) {
  27340. this.radius = radius; // distance from the origin to a point in the x-z plane
  27341. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27342. this.y = y; // height above the x-z plane
  27343. return this;
  27344. }
  27345. set(radius, theta, y) {
  27346. this.radius = radius;
  27347. this.theta = theta;
  27348. this.y = y;
  27349. return this;
  27350. }
  27351. copy(other) {
  27352. this.radius = other.radius;
  27353. this.theta = other.theta;
  27354. this.y = other.y;
  27355. return this;
  27356. }
  27357. setFromVector3(v) {
  27358. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27359. }
  27360. setFromCartesianCoords(x, y, z) {
  27361. this.radius = Math.sqrt(x * x + z * z);
  27362. this.theta = Math.atan2(x, z);
  27363. this.y = y;
  27364. return this;
  27365. }
  27366. clone() {
  27367. return new this.constructor().copy(this);
  27368. }
  27369. }
  27370. const _vector$4 = /*@__PURE__*/new Vector2();
  27371. class Box2 {
  27372. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27373. this.isBox2 = true;
  27374. this.min = min;
  27375. this.max = max;
  27376. }
  27377. set(min, max) {
  27378. this.min.copy(min);
  27379. this.max.copy(max);
  27380. return this;
  27381. }
  27382. setFromPoints(points) {
  27383. this.makeEmpty();
  27384. for (let i = 0, il = points.length; i < il; i++) {
  27385. this.expandByPoint(points[i]);
  27386. }
  27387. return this;
  27388. }
  27389. setFromCenterAndSize(center, size) {
  27390. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27391. this.min.copy(center).sub(halfSize);
  27392. this.max.copy(center).add(halfSize);
  27393. return this;
  27394. }
  27395. clone() {
  27396. return new this.constructor().copy(this);
  27397. }
  27398. copy(box) {
  27399. this.min.copy(box.min);
  27400. this.max.copy(box.max);
  27401. return this;
  27402. }
  27403. makeEmpty() {
  27404. this.min.x = this.min.y = +Infinity;
  27405. this.max.x = this.max.y = -Infinity;
  27406. return this;
  27407. }
  27408. isEmpty() {
  27409. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27410. return this.max.x < this.min.x || this.max.y < this.min.y;
  27411. }
  27412. getCenter(target) {
  27413. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27414. }
  27415. getSize(target) {
  27416. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27417. }
  27418. expandByPoint(point) {
  27419. this.min.min(point);
  27420. this.max.max(point);
  27421. return this;
  27422. }
  27423. expandByVector(vector) {
  27424. this.min.sub(vector);
  27425. this.max.add(vector);
  27426. return this;
  27427. }
  27428. expandByScalar(scalar) {
  27429. this.min.addScalar(-scalar);
  27430. this.max.addScalar(scalar);
  27431. return this;
  27432. }
  27433. containsPoint(point) {
  27434. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27435. }
  27436. containsBox(box) {
  27437. 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;
  27438. }
  27439. getParameter(point, target) {
  27440. // This can potentially have a divide by zero if the box
  27441. // has a size dimension of 0.
  27442. 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));
  27443. }
  27444. intersectsBox(box) {
  27445. // using 4 splitting planes to rule out intersections
  27446. 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;
  27447. }
  27448. clampPoint(point, target) {
  27449. return target.copy(point).clamp(this.min, this.max);
  27450. }
  27451. distanceToPoint(point) {
  27452. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27453. return clampedPoint.sub(point).length();
  27454. }
  27455. intersect(box) {
  27456. this.min.max(box.min);
  27457. this.max.min(box.max);
  27458. return this;
  27459. }
  27460. union(box) {
  27461. this.min.min(box.min);
  27462. this.max.max(box.max);
  27463. return this;
  27464. }
  27465. translate(offset) {
  27466. this.min.add(offset);
  27467. this.max.add(offset);
  27468. return this;
  27469. }
  27470. equals(box) {
  27471. return box.min.equals(this.min) && box.max.equals(this.max);
  27472. }
  27473. }
  27474. const _startP = /*@__PURE__*/new Vector3();
  27475. const _startEnd = /*@__PURE__*/new Vector3();
  27476. class Line3 {
  27477. constructor(start = new Vector3(), end = new Vector3()) {
  27478. this.start = start;
  27479. this.end = end;
  27480. }
  27481. set(start, end) {
  27482. this.start.copy(start);
  27483. this.end.copy(end);
  27484. return this;
  27485. }
  27486. copy(line) {
  27487. this.start.copy(line.start);
  27488. this.end.copy(line.end);
  27489. return this;
  27490. }
  27491. getCenter(target) {
  27492. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27493. }
  27494. delta(target) {
  27495. return target.subVectors(this.end, this.start);
  27496. }
  27497. distanceSq() {
  27498. return this.start.distanceToSquared(this.end);
  27499. }
  27500. distance() {
  27501. return this.start.distanceTo(this.end);
  27502. }
  27503. at(t, target) {
  27504. return this.delta(target).multiplyScalar(t).add(this.start);
  27505. }
  27506. closestPointToPointParameter(point, clampToLine) {
  27507. _startP.subVectors(point, this.start);
  27508. _startEnd.subVectors(this.end, this.start);
  27509. const startEnd2 = _startEnd.dot(_startEnd);
  27510. const startEnd_startP = _startEnd.dot(_startP);
  27511. let t = startEnd_startP / startEnd2;
  27512. if (clampToLine) {
  27513. t = clamp(t, 0, 1);
  27514. }
  27515. return t;
  27516. }
  27517. closestPointToPoint(point, clampToLine, target) {
  27518. const t = this.closestPointToPointParameter(point, clampToLine);
  27519. return this.delta(target).multiplyScalar(t).add(this.start);
  27520. }
  27521. applyMatrix4(matrix) {
  27522. this.start.applyMatrix4(matrix);
  27523. this.end.applyMatrix4(matrix);
  27524. return this;
  27525. }
  27526. equals(line) {
  27527. return line.start.equals(this.start) && line.end.equals(this.end);
  27528. }
  27529. clone() {
  27530. return new this.constructor().copy(this);
  27531. }
  27532. }
  27533. const _vector$3 = /*@__PURE__*/new Vector3();
  27534. class SpotLightHelper extends Object3D {
  27535. constructor(light, color) {
  27536. super();
  27537. this.light = light;
  27538. this.light.updateMatrixWorld();
  27539. this.matrix = light.matrixWorld;
  27540. this.matrixAutoUpdate = false;
  27541. this.color = color;
  27542. const geometry = new BufferGeometry();
  27543. 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];
  27544. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27545. const p1 = i / l * Math.PI * 2;
  27546. const p2 = j / l * Math.PI * 2;
  27547. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27548. }
  27549. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27550. const material = new LineBasicMaterial({
  27551. fog: false,
  27552. toneMapped: false
  27553. });
  27554. this.cone = new LineSegments(geometry, material);
  27555. this.add(this.cone);
  27556. this.update();
  27557. }
  27558. dispose() {
  27559. this.cone.geometry.dispose();
  27560. this.cone.material.dispose();
  27561. }
  27562. update() {
  27563. this.light.updateMatrixWorld();
  27564. const coneLength = this.light.distance ? this.light.distance : 1000;
  27565. const coneWidth = coneLength * Math.tan(this.light.angle);
  27566. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27567. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27568. this.cone.lookAt(_vector$3);
  27569. if (this.color !== undefined) {
  27570. this.cone.material.color.set(this.color);
  27571. } else {
  27572. this.cone.material.color.copy(this.light.color);
  27573. }
  27574. }
  27575. }
  27576. const _vector$2 = /*@__PURE__*/new Vector3();
  27577. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27578. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27579. class SkeletonHelper extends LineSegments {
  27580. constructor(object) {
  27581. const bones = getBoneList(object);
  27582. const geometry = new BufferGeometry();
  27583. const vertices = [];
  27584. const colors = [];
  27585. const color1 = new Color(0, 0, 1);
  27586. const color2 = new Color(0, 1, 0);
  27587. for (let i = 0; i < bones.length; i++) {
  27588. const bone = bones[i];
  27589. if (bone.parent && bone.parent.isBone) {
  27590. vertices.push(0, 0, 0);
  27591. vertices.push(0, 0, 0);
  27592. colors.push(color1.r, color1.g, color1.b);
  27593. colors.push(color2.r, color2.g, color2.b);
  27594. }
  27595. }
  27596. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27597. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27598. const material = new LineBasicMaterial({
  27599. vertexColors: true,
  27600. depthTest: false,
  27601. depthWrite: false,
  27602. toneMapped: false,
  27603. transparent: true
  27604. });
  27605. super(geometry, material);
  27606. this.isSkeletonHelper = true;
  27607. this.type = 'SkeletonHelper';
  27608. this.root = object;
  27609. this.bones = bones;
  27610. this.matrix = object.matrixWorld;
  27611. this.matrixAutoUpdate = false;
  27612. }
  27613. updateMatrixWorld(force) {
  27614. const bones = this.bones;
  27615. const geometry = this.geometry;
  27616. const position = geometry.getAttribute('position');
  27617. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27618. for (let i = 0, j = 0; i < bones.length; i++) {
  27619. const bone = bones[i];
  27620. if (bone.parent && bone.parent.isBone) {
  27621. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27622. _vector$2.setFromMatrixPosition(_boneMatrix);
  27623. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27624. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27625. _vector$2.setFromMatrixPosition(_boneMatrix);
  27626. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27627. j += 2;
  27628. }
  27629. }
  27630. geometry.getAttribute('position').needsUpdate = true;
  27631. super.updateMatrixWorld(force);
  27632. }
  27633. }
  27634. function getBoneList(object) {
  27635. const boneList = [];
  27636. if (object.isBone === true) {
  27637. boneList.push(object);
  27638. }
  27639. for (let i = 0; i < object.children.length; i++) {
  27640. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27641. }
  27642. return boneList;
  27643. }
  27644. class PointLightHelper extends Mesh {
  27645. constructor(light, sphereSize, color) {
  27646. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27647. const material = new MeshBasicMaterial({
  27648. wireframe: true,
  27649. fog: false,
  27650. toneMapped: false
  27651. });
  27652. super(geometry, material);
  27653. this.light = light;
  27654. this.light.updateMatrixWorld();
  27655. this.color = color;
  27656. this.type = 'PointLightHelper';
  27657. this.matrix = this.light.matrixWorld;
  27658. this.matrixAutoUpdate = false;
  27659. this.update();
  27660. /*
  27661. // TODO: delete this comment?
  27662. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  27663. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27664. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27665. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27666. const d = light.distance;
  27667. if ( d === 0.0 ) {
  27668. this.lightDistance.visible = false;
  27669. } else {
  27670. this.lightDistance.scale.set( d, d, d );
  27671. }
  27672. this.add( this.lightDistance );
  27673. */
  27674. }
  27675. dispose() {
  27676. this.geometry.dispose();
  27677. this.material.dispose();
  27678. }
  27679. update() {
  27680. if (this.color !== undefined) {
  27681. this.material.color.set(this.color);
  27682. } else {
  27683. this.material.color.copy(this.light.color);
  27684. }
  27685. /*
  27686. const d = this.light.distance;
  27687. if ( d === 0.0 ) {
  27688. this.lightDistance.visible = false;
  27689. } else {
  27690. this.lightDistance.visible = true;
  27691. this.lightDistance.scale.set( d, d, d );
  27692. }
  27693. */
  27694. }
  27695. }
  27696. const _vector$1 = /*@__PURE__*/new Vector3();
  27697. const _color1 = /*@__PURE__*/new Color();
  27698. const _color2 = /*@__PURE__*/new Color();
  27699. class HemisphereLightHelper extends Object3D {
  27700. constructor(light, size, color) {
  27701. super();
  27702. this.light = light;
  27703. this.light.updateMatrixWorld();
  27704. this.matrix = light.matrixWorld;
  27705. this.matrixAutoUpdate = false;
  27706. this.color = color;
  27707. const geometry = new OctahedronGeometry(size);
  27708. geometry.rotateY(Math.PI * 0.5);
  27709. this.material = new MeshBasicMaterial({
  27710. wireframe: true,
  27711. fog: false,
  27712. toneMapped: false
  27713. });
  27714. if (this.color === undefined) this.material.vertexColors = true;
  27715. const position = geometry.getAttribute('position');
  27716. const colors = new Float32Array(position.count * 3);
  27717. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27718. this.add(new Mesh(geometry, this.material));
  27719. this.update();
  27720. }
  27721. dispose() {
  27722. this.children[0].geometry.dispose();
  27723. this.children[0].material.dispose();
  27724. }
  27725. update() {
  27726. const mesh = this.children[0];
  27727. if (this.color !== undefined) {
  27728. this.material.color.set(this.color);
  27729. } else {
  27730. const colors = mesh.geometry.getAttribute('color');
  27731. _color1.copy(this.light.color);
  27732. _color2.copy(this.light.groundColor);
  27733. for (let i = 0, l = colors.count; i < l; i++) {
  27734. const color = i < l / 2 ? _color1 : _color2;
  27735. colors.setXYZ(i, color.r, color.g, color.b);
  27736. }
  27737. colors.needsUpdate = true;
  27738. }
  27739. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27740. }
  27741. }
  27742. class GridHelper extends LineSegments {
  27743. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27744. color1 = new Color(color1);
  27745. color2 = new Color(color2);
  27746. const center = divisions / 2;
  27747. const step = size / divisions;
  27748. const halfSize = size / 2;
  27749. const vertices = [],
  27750. colors = [];
  27751. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27752. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27753. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27754. const color = i === center ? color1 : color2;
  27755. color.toArray(colors, j);
  27756. j += 3;
  27757. color.toArray(colors, j);
  27758. j += 3;
  27759. color.toArray(colors, j);
  27760. j += 3;
  27761. color.toArray(colors, j);
  27762. j += 3;
  27763. }
  27764. const geometry = new BufferGeometry();
  27765. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27766. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27767. const material = new LineBasicMaterial({
  27768. vertexColors: true,
  27769. toneMapped: false
  27770. });
  27771. super(geometry, material);
  27772. this.type = 'GridHelper';
  27773. }
  27774. }
  27775. class PolarGridHelper extends LineSegments {
  27776. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27777. color1 = new Color(color1);
  27778. color2 = new Color(color2);
  27779. const vertices = [];
  27780. const colors = []; // create the radials
  27781. for (let i = 0; i <= radials; i++) {
  27782. const v = i / radials * (Math.PI * 2);
  27783. const x = Math.sin(v) * radius;
  27784. const z = Math.cos(v) * radius;
  27785. vertices.push(0, 0, 0);
  27786. vertices.push(x, 0, z);
  27787. const color = i & 1 ? color1 : color2;
  27788. colors.push(color.r, color.g, color.b);
  27789. colors.push(color.r, color.g, color.b);
  27790. } // create the circles
  27791. for (let i = 0; i <= circles; i++) {
  27792. const color = i & 1 ? color1 : color2;
  27793. const r = radius - radius / circles * i;
  27794. for (let j = 0; j < divisions; j++) {
  27795. // first vertex
  27796. let v = j / divisions * (Math.PI * 2);
  27797. let x = Math.sin(v) * r;
  27798. let z = Math.cos(v) * r;
  27799. vertices.push(x, 0, z);
  27800. colors.push(color.r, color.g, color.b); // second vertex
  27801. v = (j + 1) / divisions * (Math.PI * 2);
  27802. x = Math.sin(v) * r;
  27803. z = Math.cos(v) * r;
  27804. vertices.push(x, 0, z);
  27805. colors.push(color.r, color.g, color.b);
  27806. }
  27807. }
  27808. const geometry = new BufferGeometry();
  27809. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27810. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27811. const material = new LineBasicMaterial({
  27812. vertexColors: true,
  27813. toneMapped: false
  27814. });
  27815. super(geometry, material);
  27816. this.type = 'PolarGridHelper';
  27817. }
  27818. }
  27819. const _v1 = /*@__PURE__*/new Vector3();
  27820. const _v2 = /*@__PURE__*/new Vector3();
  27821. const _v3 = /*@__PURE__*/new Vector3();
  27822. class DirectionalLightHelper extends Object3D {
  27823. constructor(light, size, color) {
  27824. super();
  27825. this.light = light;
  27826. this.light.updateMatrixWorld();
  27827. this.matrix = light.matrixWorld;
  27828. this.matrixAutoUpdate = false;
  27829. this.color = color;
  27830. if (size === undefined) size = 1;
  27831. let geometry = new BufferGeometry();
  27832. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27833. const material = new LineBasicMaterial({
  27834. fog: false,
  27835. toneMapped: false
  27836. });
  27837. this.lightPlane = new Line(geometry, material);
  27838. this.add(this.lightPlane);
  27839. geometry = new BufferGeometry();
  27840. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27841. this.targetLine = new Line(geometry, material);
  27842. this.add(this.targetLine);
  27843. this.update();
  27844. }
  27845. dispose() {
  27846. this.lightPlane.geometry.dispose();
  27847. this.lightPlane.material.dispose();
  27848. this.targetLine.geometry.dispose();
  27849. this.targetLine.material.dispose();
  27850. }
  27851. update() {
  27852. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27853. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27854. _v3.subVectors(_v2, _v1);
  27855. this.lightPlane.lookAt(_v2);
  27856. if (this.color !== undefined) {
  27857. this.lightPlane.material.color.set(this.color);
  27858. this.targetLine.material.color.set(this.color);
  27859. } else {
  27860. this.lightPlane.material.color.copy(this.light.color);
  27861. this.targetLine.material.color.copy(this.light.color);
  27862. }
  27863. this.targetLine.lookAt(_v2);
  27864. this.targetLine.scale.z = _v3.length();
  27865. }
  27866. }
  27867. const _vector = /*@__PURE__*/new Vector3();
  27868. const _camera = /*@__PURE__*/new Camera();
  27869. /**
  27870. * - shows frustum, line of sight and up of the camera
  27871. * - suitable for fast updates
  27872. * - based on frustum visualization in lightgl.js shadowmap example
  27873. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  27874. */
  27875. class CameraHelper extends LineSegments {
  27876. constructor(camera) {
  27877. const geometry = new BufferGeometry();
  27878. const material = new LineBasicMaterial({
  27879. color: 0xffffff,
  27880. vertexColors: true,
  27881. toneMapped: false
  27882. });
  27883. const vertices = [];
  27884. const colors = [];
  27885. const pointMap = {}; // near
  27886. addLine('n1', 'n2');
  27887. addLine('n2', 'n4');
  27888. addLine('n4', 'n3');
  27889. addLine('n3', 'n1'); // far
  27890. addLine('f1', 'f2');
  27891. addLine('f2', 'f4');
  27892. addLine('f4', 'f3');
  27893. addLine('f3', 'f1'); // sides
  27894. addLine('n1', 'f1');
  27895. addLine('n2', 'f2');
  27896. addLine('n3', 'f3');
  27897. addLine('n4', 'f4'); // cone
  27898. addLine('p', 'n1');
  27899. addLine('p', 'n2');
  27900. addLine('p', 'n3');
  27901. addLine('p', 'n4'); // up
  27902. addLine('u1', 'u2');
  27903. addLine('u2', 'u3');
  27904. addLine('u3', 'u1'); // target
  27905. addLine('c', 't');
  27906. addLine('p', 'c'); // cross
  27907. addLine('cn1', 'cn2');
  27908. addLine('cn3', 'cn4');
  27909. addLine('cf1', 'cf2');
  27910. addLine('cf3', 'cf4');
  27911. function addLine(a, b) {
  27912. addPoint(a);
  27913. addPoint(b);
  27914. }
  27915. function addPoint(id) {
  27916. vertices.push(0, 0, 0);
  27917. colors.push(0, 0, 0);
  27918. if (pointMap[id] === undefined) {
  27919. pointMap[id] = [];
  27920. }
  27921. pointMap[id].push(vertices.length / 3 - 1);
  27922. }
  27923. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27924. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27925. super(geometry, material);
  27926. this.type = 'CameraHelper';
  27927. this.camera = camera;
  27928. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27929. this.matrix = camera.matrixWorld;
  27930. this.matrixAutoUpdate = false;
  27931. this.pointMap = pointMap;
  27932. this.update(); // colors
  27933. const colorFrustum = new Color(0xffaa00);
  27934. const colorCone = new Color(0xff0000);
  27935. const colorUp = new Color(0x00aaff);
  27936. const colorTarget = new Color(0xffffff);
  27937. const colorCross = new Color(0x333333);
  27938. this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross);
  27939. }
  27940. setColors(frustum, cone, up, target, cross) {
  27941. const geometry = this.geometry;
  27942. const colorAttribute = geometry.getAttribute('color'); // near
  27943. colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b);
  27944. colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); // n1, n2
  27945. colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b);
  27946. colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); // n2, n4
  27947. colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b);
  27948. colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); // n4, n3
  27949. colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b);
  27950. colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); // n3, n1
  27951. // far
  27952. colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b);
  27953. colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); // f1, f2
  27954. colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b);
  27955. colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); // f2, f4
  27956. colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b);
  27957. colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); // f4, f3
  27958. colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b);
  27959. colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); // f3, f1
  27960. // sides
  27961. colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b);
  27962. colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); // n1, f1
  27963. colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b);
  27964. colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); // n2, f2
  27965. colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b);
  27966. colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); // n3, f3
  27967. colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b);
  27968. colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); // n4, f4
  27969. // cone
  27970. colorAttribute.setXYZ(24, cone.r, cone.g, cone.b);
  27971. colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); // p, n1
  27972. colorAttribute.setXYZ(26, cone.r, cone.g, cone.b);
  27973. colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); // p, n2
  27974. colorAttribute.setXYZ(28, cone.r, cone.g, cone.b);
  27975. colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); // p, n3
  27976. colorAttribute.setXYZ(30, cone.r, cone.g, cone.b);
  27977. colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); // p, n4
  27978. // up
  27979. colorAttribute.setXYZ(32, up.r, up.g, up.b);
  27980. colorAttribute.setXYZ(33, up.r, up.g, up.b); // u1, u2
  27981. colorAttribute.setXYZ(34, up.r, up.g, up.b);
  27982. colorAttribute.setXYZ(35, up.r, up.g, up.b); // u2, u3
  27983. colorAttribute.setXYZ(36, up.r, up.g, up.b);
  27984. colorAttribute.setXYZ(37, up.r, up.g, up.b); // u3, u1
  27985. // target
  27986. colorAttribute.setXYZ(38, target.r, target.g, target.b);
  27987. colorAttribute.setXYZ(39, target.r, target.g, target.b); // c, t
  27988. colorAttribute.setXYZ(40, cross.r, cross.g, cross.b);
  27989. colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); // p, c
  27990. // cross
  27991. colorAttribute.setXYZ(42, cross.r, cross.g, cross.b);
  27992. colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); // cn1, cn2
  27993. colorAttribute.setXYZ(44, cross.r, cross.g, cross.b);
  27994. colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); // cn3, cn4
  27995. colorAttribute.setXYZ(46, cross.r, cross.g, cross.b);
  27996. colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); // cf1, cf2
  27997. colorAttribute.setXYZ(48, cross.r, cross.g, cross.b);
  27998. colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); // cf3, cf4
  27999. colorAttribute.needsUpdate = true;
  28000. }
  28001. update() {
  28002. const geometry = this.geometry;
  28003. const pointMap = this.pointMap;
  28004. const w = 1,
  28005. h = 1; // we need just camera projection matrix inverse
  28006. // world matrix must be identity
  28007. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28008. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28009. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28010. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28011. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28012. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28013. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28014. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28015. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28016. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28017. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28018. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28019. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28020. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28021. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28022. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28023. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28024. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28025. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28026. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28027. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28028. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28029. geometry.getAttribute('position').needsUpdate = true;
  28030. }
  28031. dispose() {
  28032. this.geometry.dispose();
  28033. this.material.dispose();
  28034. }
  28035. }
  28036. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28037. _vector.set(x, y, z).unproject(camera);
  28038. const points = pointMap[point];
  28039. if (points !== undefined) {
  28040. const position = geometry.getAttribute('position');
  28041. for (let i = 0, l = points.length; i < l; i++) {
  28042. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  28043. }
  28044. }
  28045. }
  28046. const _box = /*@__PURE__*/new Box3();
  28047. class BoxHelper extends LineSegments {
  28048. constructor(object, color = 0xffff00) {
  28049. 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]);
  28050. const positions = new Float32Array(8 * 3);
  28051. const geometry = new BufferGeometry();
  28052. geometry.setIndex(new BufferAttribute(indices, 1));
  28053. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  28054. super(geometry, new LineBasicMaterial({
  28055. color: color,
  28056. toneMapped: false
  28057. }));
  28058. this.object = object;
  28059. this.type = 'BoxHelper';
  28060. this.matrixAutoUpdate = false;
  28061. this.update();
  28062. }
  28063. update(object) {
  28064. if (object !== undefined) {
  28065. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28066. }
  28067. if (this.object !== undefined) {
  28068. _box.setFromObject(this.object);
  28069. }
  28070. if (_box.isEmpty()) return;
  28071. const min = _box.min;
  28072. const max = _box.max;
  28073. /*
  28074. 5____4
  28075. 1/___0/|
  28076. | 6__|_7
  28077. 2/___3/
  28078. 0: max.x, max.y, max.z
  28079. 1: min.x, max.y, max.z
  28080. 2: min.x, min.y, max.z
  28081. 3: max.x, min.y, max.z
  28082. 4: max.x, max.y, min.z
  28083. 5: min.x, max.y, min.z
  28084. 6: min.x, min.y, min.z
  28085. 7: max.x, min.y, min.z
  28086. */
  28087. const position = this.geometry.attributes.position;
  28088. const array = position.array;
  28089. array[0] = max.x;
  28090. array[1] = max.y;
  28091. array[2] = max.z;
  28092. array[3] = min.x;
  28093. array[4] = max.y;
  28094. array[5] = max.z;
  28095. array[6] = min.x;
  28096. array[7] = min.y;
  28097. array[8] = max.z;
  28098. array[9] = max.x;
  28099. array[10] = min.y;
  28100. array[11] = max.z;
  28101. array[12] = max.x;
  28102. array[13] = max.y;
  28103. array[14] = min.z;
  28104. array[15] = min.x;
  28105. array[16] = max.y;
  28106. array[17] = min.z;
  28107. array[18] = min.x;
  28108. array[19] = min.y;
  28109. array[20] = min.z;
  28110. array[21] = max.x;
  28111. array[22] = min.y;
  28112. array[23] = min.z;
  28113. position.needsUpdate = true;
  28114. this.geometry.computeBoundingSphere();
  28115. }
  28116. setFromObject(object) {
  28117. this.object = object;
  28118. this.update();
  28119. return this;
  28120. }
  28121. copy(source, recursive) {
  28122. super.copy(source, recursive);
  28123. this.object = source.object;
  28124. return this;
  28125. }
  28126. }
  28127. class Box3Helper extends LineSegments {
  28128. constructor(box, color = 0xffff00) {
  28129. 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]);
  28130. 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];
  28131. const geometry = new BufferGeometry();
  28132. geometry.setIndex(new BufferAttribute(indices, 1));
  28133. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28134. super(geometry, new LineBasicMaterial({
  28135. color: color,
  28136. toneMapped: false
  28137. }));
  28138. this.box = box;
  28139. this.type = 'Box3Helper';
  28140. this.geometry.computeBoundingSphere();
  28141. }
  28142. updateMatrixWorld(force) {
  28143. const box = this.box;
  28144. if (box.isEmpty()) return;
  28145. box.getCenter(this.position);
  28146. box.getSize(this.scale);
  28147. this.scale.multiplyScalar(0.5);
  28148. super.updateMatrixWorld(force);
  28149. }
  28150. }
  28151. class PlaneHelper extends Line {
  28152. constructor(plane, size = 1, hex = 0xffff00) {
  28153. const color = hex;
  28154. 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];
  28155. const geometry = new BufferGeometry();
  28156. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28157. geometry.computeBoundingSphere();
  28158. super(geometry, new LineBasicMaterial({
  28159. color: color,
  28160. toneMapped: false
  28161. }));
  28162. this.type = 'PlaneHelper';
  28163. this.plane = plane;
  28164. this.size = size;
  28165. const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28166. const geometry2 = new BufferGeometry();
  28167. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28168. geometry2.computeBoundingSphere();
  28169. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28170. color: color,
  28171. opacity: 0.2,
  28172. transparent: true,
  28173. depthWrite: false,
  28174. toneMapped: false
  28175. })));
  28176. }
  28177. updateMatrixWorld(force) {
  28178. this.position.set(0, 0, 0);
  28179. this.scale.set(0.5 * this.size, 0.5 * this.size, 1);
  28180. this.lookAt(this.plane.normal);
  28181. this.translateZ(-this.plane.constant);
  28182. super.updateMatrixWorld(force);
  28183. }
  28184. }
  28185. const _axis = /*@__PURE__*/new Vector3();
  28186. let _lineGeometry, _coneGeometry;
  28187. class ArrowHelper extends Object3D {
  28188. // dir is assumed to be normalized
  28189. 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) {
  28190. super();
  28191. this.type = 'ArrowHelper';
  28192. if (_lineGeometry === undefined) {
  28193. _lineGeometry = new BufferGeometry();
  28194. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28195. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  28196. _coneGeometry.translate(0, -0.5, 0);
  28197. }
  28198. this.position.copy(origin);
  28199. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28200. color: color,
  28201. toneMapped: false
  28202. }));
  28203. this.line.matrixAutoUpdate = false;
  28204. this.add(this.line);
  28205. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28206. color: color,
  28207. toneMapped: false
  28208. }));
  28209. this.cone.matrixAutoUpdate = false;
  28210. this.add(this.cone);
  28211. this.setDirection(dir);
  28212. this.setLength(length, headLength, headWidth);
  28213. }
  28214. setDirection(dir) {
  28215. // dir is assumed to be normalized
  28216. if (dir.y > 0.99999) {
  28217. this.quaternion.set(0, 0, 0, 1);
  28218. } else if (dir.y < -0.99999) {
  28219. this.quaternion.set(1, 0, 0, 0);
  28220. } else {
  28221. _axis.set(dir.z, 0, -dir.x).normalize();
  28222. const radians = Math.acos(dir.y);
  28223. this.quaternion.setFromAxisAngle(_axis, radians);
  28224. }
  28225. }
  28226. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  28227. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28228. this.line.updateMatrix();
  28229. this.cone.scale.set(headWidth, headLength, headWidth);
  28230. this.cone.position.y = length;
  28231. this.cone.updateMatrix();
  28232. }
  28233. setColor(color) {
  28234. this.line.material.color.set(color);
  28235. this.cone.material.color.set(color);
  28236. }
  28237. copy(source) {
  28238. super.copy(source, false);
  28239. this.line.copy(source.line);
  28240. this.cone.copy(source.cone);
  28241. return this;
  28242. }
  28243. }
  28244. class AxesHelper extends LineSegments {
  28245. constructor(size = 1) {
  28246. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28247. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28248. const geometry = new BufferGeometry();
  28249. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28250. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28251. const material = new LineBasicMaterial({
  28252. vertexColors: true,
  28253. toneMapped: false
  28254. });
  28255. super(geometry, material);
  28256. this.type = 'AxesHelper';
  28257. }
  28258. setColors(xAxisColor, yAxisColor, zAxisColor) {
  28259. const color = new Color();
  28260. const array = this.geometry.attributes.color.array;
  28261. color.set(xAxisColor);
  28262. color.toArray(array, 0);
  28263. color.toArray(array, 3);
  28264. color.set(yAxisColor);
  28265. color.toArray(array, 6);
  28266. color.toArray(array, 9);
  28267. color.set(zAxisColor);
  28268. color.toArray(array, 12);
  28269. color.toArray(array, 15);
  28270. this.geometry.attributes.color.needsUpdate = true;
  28271. return this;
  28272. }
  28273. dispose() {
  28274. this.geometry.dispose();
  28275. this.material.dispose();
  28276. }
  28277. }
  28278. class ShapePath {
  28279. constructor() {
  28280. this.type = 'ShapePath';
  28281. this.color = new Color();
  28282. this.subPaths = [];
  28283. this.currentPath = null;
  28284. }
  28285. moveTo(x, y) {
  28286. this.currentPath = new Path();
  28287. this.subPaths.push(this.currentPath);
  28288. this.currentPath.moveTo(x, y);
  28289. return this;
  28290. }
  28291. lineTo(x, y) {
  28292. this.currentPath.lineTo(x, y);
  28293. return this;
  28294. }
  28295. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  28296. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  28297. return this;
  28298. }
  28299. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  28300. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  28301. return this;
  28302. }
  28303. splineThru(pts) {
  28304. this.currentPath.splineThru(pts);
  28305. return this;
  28306. }
  28307. toShapes(isCCW, noHoles) {
  28308. function toShapesNoHoles(inSubpaths) {
  28309. const shapes = [];
  28310. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  28311. const tmpPath = inSubpaths[i];
  28312. const tmpShape = new Shape();
  28313. tmpShape.curves = tmpPath.curves;
  28314. shapes.push(tmpShape);
  28315. }
  28316. return shapes;
  28317. }
  28318. function isPointInsidePolygon(inPt, inPolygon) {
  28319. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  28320. // toggling of inside/outside at every single! intersection point of an edge
  28321. // with the horizontal line through inPt, left of inPt
  28322. // not counting lowerY endpoints of edges and whole edges on that line
  28323. let inside = false;
  28324. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  28325. let edgeLowPt = inPolygon[p];
  28326. let edgeHighPt = inPolygon[q];
  28327. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28328. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28329. if (Math.abs(edgeDy) > Number.EPSILON) {
  28330. // not parallel
  28331. if (edgeDy < 0) {
  28332. edgeLowPt = inPolygon[q];
  28333. edgeDx = -edgeDx;
  28334. edgeHighPt = inPolygon[p];
  28335. edgeDy = -edgeDy;
  28336. }
  28337. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  28338. if (inPt.y === edgeLowPt.y) {
  28339. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  28340. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28341. } else {
  28342. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  28343. if (perpEdge === 0) return true; // inPt is on contour ?
  28344. if (perpEdge < 0) continue;
  28345. inside = !inside; // true intersection left of inPt
  28346. }
  28347. } else {
  28348. // parallel or collinear
  28349. if (inPt.y !== edgeLowPt.y) continue; // parallel
  28350. // edge lies on the same horizontal line as inPt
  28351. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  28352. // continue;
  28353. }
  28354. }
  28355. return inside;
  28356. }
  28357. const isClockWise = ShapeUtils.isClockWise;
  28358. const subPaths = this.subPaths;
  28359. if (subPaths.length === 0) return [];
  28360. if (noHoles === true) return toShapesNoHoles(subPaths);
  28361. let solid, tmpPath, tmpShape;
  28362. const shapes = [];
  28363. if (subPaths.length === 1) {
  28364. tmpPath = subPaths[0];
  28365. tmpShape = new Shape();
  28366. tmpShape.curves = tmpPath.curves;
  28367. shapes.push(tmpShape);
  28368. return shapes;
  28369. }
  28370. let holesFirst = !isClockWise(subPaths[0].getPoints());
  28371. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  28372. const betterShapeHoles = [];
  28373. const newShapes = [];
  28374. let newShapeHoles = [];
  28375. let mainIdx = 0;
  28376. let tmpPoints;
  28377. newShapes[mainIdx] = undefined;
  28378. newShapeHoles[mainIdx] = [];
  28379. for (let i = 0, l = subPaths.length; i < l; i++) {
  28380. tmpPath = subPaths[i];
  28381. tmpPoints = tmpPath.getPoints();
  28382. solid = isClockWise(tmpPoints);
  28383. solid = isCCW ? !solid : solid;
  28384. if (solid) {
  28385. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  28386. newShapes[mainIdx] = {
  28387. s: new Shape(),
  28388. p: tmpPoints
  28389. };
  28390. newShapes[mainIdx].s.curves = tmpPath.curves;
  28391. if (holesFirst) mainIdx++;
  28392. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  28393. } else {
  28394. newShapeHoles[mainIdx].push({
  28395. h: tmpPath,
  28396. p: tmpPoints[0]
  28397. }); //console.log('ccw', i);
  28398. }
  28399. } // only Holes? -> probably all Shapes with wrong orientation
  28400. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  28401. if (newShapes.length > 1) {
  28402. let ambiguous = false;
  28403. let toChange = 0;
  28404. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28405. betterShapeHoles[sIdx] = [];
  28406. }
  28407. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28408. const sho = newShapeHoles[sIdx];
  28409. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  28410. const ho = sho[hIdx];
  28411. let hole_unassigned = true;
  28412. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  28413. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  28414. if (sIdx !== s2Idx) toChange++;
  28415. if (hole_unassigned) {
  28416. hole_unassigned = false;
  28417. betterShapeHoles[s2Idx].push(ho);
  28418. } else {
  28419. ambiguous = true;
  28420. }
  28421. }
  28422. }
  28423. if (hole_unassigned) {
  28424. betterShapeHoles[sIdx].push(ho);
  28425. }
  28426. }
  28427. }
  28428. if (toChange > 0 && ambiguous === false) {
  28429. newShapeHoles = betterShapeHoles;
  28430. }
  28431. }
  28432. let tmpHoles;
  28433. for (let i = 0, il = newShapes.length; i < il; i++) {
  28434. tmpShape = newShapes[i].s;
  28435. shapes.push(tmpShape);
  28436. tmpHoles = newShapeHoles[i];
  28437. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  28438. tmpShape.holes.push(tmpHoles[j].h);
  28439. }
  28440. } //console.log("shape", shapes);
  28441. return shapes;
  28442. }
  28443. }
  28444. const _tables = /*@__PURE__*/_generateTables();
  28445. function _generateTables() {
  28446. // float32 to float16 helpers
  28447. const buffer = new ArrayBuffer(4);
  28448. const floatView = new Float32Array(buffer);
  28449. const uint32View = new Uint32Array(buffer);
  28450. const baseTable = new Uint32Array(512);
  28451. const shiftTable = new Uint32Array(512);
  28452. for (let i = 0; i < 256; ++i) {
  28453. const e = i - 127; // very small number (0, -0)
  28454. if (e < -27) {
  28455. baseTable[i] = 0x0000;
  28456. baseTable[i | 0x100] = 0x8000;
  28457. shiftTable[i] = 24;
  28458. shiftTable[i | 0x100] = 24; // small number (denorm)
  28459. } else if (e < -14) {
  28460. baseTable[i] = 0x0400 >> -e - 14;
  28461. baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
  28462. shiftTable[i] = -e - 1;
  28463. shiftTable[i | 0x100] = -e - 1; // normal number
  28464. } else if (e <= 15) {
  28465. baseTable[i] = e + 15 << 10;
  28466. baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
  28467. shiftTable[i] = 13;
  28468. shiftTable[i | 0x100] = 13; // large number (Infinity, -Infinity)
  28469. } else if (e < 128) {
  28470. baseTable[i] = 0x7c00;
  28471. baseTable[i | 0x100] = 0xfc00;
  28472. shiftTable[i] = 24;
  28473. shiftTable[i | 0x100] = 24; // stay (NaN, Infinity, -Infinity)
  28474. } else {
  28475. baseTable[i] = 0x7c00;
  28476. baseTable[i | 0x100] = 0xfc00;
  28477. shiftTable[i] = 13;
  28478. shiftTable[i | 0x100] = 13;
  28479. }
  28480. } // float16 to float32 helpers
  28481. const mantissaTable = new Uint32Array(2048);
  28482. const exponentTable = new Uint32Array(64);
  28483. const offsetTable = new Uint32Array(64);
  28484. for (let i = 1; i < 1024; ++i) {
  28485. let m = i << 13; // zero pad mantissa bits
  28486. let e = 0; // zero exponent
  28487. // normalized
  28488. while ((m & 0x00800000) === 0) {
  28489. m <<= 1;
  28490. e -= 0x00800000; // decrement exponent
  28491. }
  28492. m &= ~0x00800000; // clear leading 1 bit
  28493. e += 0x38800000; // adjust bias
  28494. mantissaTable[i] = m | e;
  28495. }
  28496. for (let i = 1024; i < 2048; ++i) {
  28497. mantissaTable[i] = 0x38000000 + (i - 1024 << 13);
  28498. }
  28499. for (let i = 1; i < 31; ++i) {
  28500. exponentTable[i] = i << 23;
  28501. }
  28502. exponentTable[31] = 0x47800000;
  28503. exponentTable[32] = 0x80000000;
  28504. for (let i = 33; i < 63; ++i) {
  28505. exponentTable[i] = 0x80000000 + (i - 32 << 23);
  28506. }
  28507. exponentTable[63] = 0xc7800000;
  28508. for (let i = 1; i < 64; ++i) {
  28509. if (i !== 32) {
  28510. offsetTable[i] = 1024;
  28511. }
  28512. }
  28513. return {
  28514. floatView: floatView,
  28515. uint32View: uint32View,
  28516. baseTable: baseTable,
  28517. shiftTable: shiftTable,
  28518. mantissaTable: mantissaTable,
  28519. exponentTable: exponentTable,
  28520. offsetTable: offsetTable
  28521. };
  28522. } // float32 to float16
  28523. function toHalfFloat(val) {
  28524. if (Math.abs(val) > 65504) console.warn('THREE.DataUtils.toHalfFloat(): Value out of range.');
  28525. val = clamp(val, -65504, 65504);
  28526. _tables.floatView[0] = val;
  28527. const f = _tables.uint32View[0];
  28528. const e = f >> 23 & 0x1ff;
  28529. return _tables.baseTable[e] + ((f & 0x007fffff) >> _tables.shiftTable[e]);
  28530. } // float16 to float32
  28531. function fromHalfFloat(val) {
  28532. const m = val >> 10;
  28533. _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 0x3ff)] + _tables.exponentTable[m];
  28534. return _tables.floatView[0];
  28535. }
  28536. var DataUtils = /*#__PURE__*/Object.freeze({
  28537. __proto__: null,
  28538. toHalfFloat: toHalfFloat,
  28539. fromHalfFloat: fromHalfFloat
  28540. });
  28541. class ParametricGeometry extends BufferGeometry {
  28542. constructor() {
  28543. console.error('THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js');
  28544. super();
  28545. }
  28546. } // r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92
  28547. class TextGeometry extends BufferGeometry {
  28548. constructor() {
  28549. console.error('THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js');
  28550. super();
  28551. }
  28552. } // r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92
  28553. function FontLoader() {
  28554. console.error('THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js');
  28555. } // r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92
  28556. function Font() {
  28557. console.error('THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js');
  28558. } // r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0
  28559. function ImmediateRenderObject() {
  28560. console.error('THREE.ImmediateRenderObject has been removed.');
  28561. } // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  28562. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  28563. constructor(width, height, options) {
  28564. console.error('THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.');
  28565. super(width, height, options);
  28566. this.samples = 4;
  28567. }
  28568. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28569. class DataTexture2DArray extends DataArrayTexture {
  28570. constructor(data, width, height, depth) {
  28571. console.warn('THREE.DataTexture2DArray has been renamed to DataArrayTexture.');
  28572. super(data, width, height, depth);
  28573. }
  28574. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28575. class DataTexture3D extends Data3DTexture {
  28576. constructor(data, width, height, depth) {
  28577. console.warn('THREE.DataTexture3D has been renamed to Data3DTexture.');
  28578. super(data, width, height, depth);
  28579. }
  28580. }
  28581. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28582. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28583. detail: {
  28584. revision: REVISION
  28585. }
  28586. }));
  28587. }
  28588. if (typeof window !== 'undefined') {
  28589. if (window.__THREE__) {
  28590. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28591. } else {
  28592. window.__THREE__ = REVISION;
  28593. }
  28594. }
  28595. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28596. exports.AddEquation = AddEquation;
  28597. exports.AddOperation = AddOperation;
  28598. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28599. exports.AdditiveBlending = AdditiveBlending;
  28600. exports.AlphaFormat = AlphaFormat;
  28601. exports.AlwaysDepth = AlwaysDepth;
  28602. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28603. exports.AmbientLight = AmbientLight;
  28604. exports.AmbientLightProbe = AmbientLightProbe;
  28605. exports.AnimationClip = AnimationClip;
  28606. exports.AnimationLoader = AnimationLoader;
  28607. exports.AnimationMixer = AnimationMixer;
  28608. exports.AnimationObjectGroup = AnimationObjectGroup;
  28609. exports.AnimationUtils = AnimationUtils;
  28610. exports.ArcCurve = ArcCurve;
  28611. exports.ArrayCamera = ArrayCamera;
  28612. exports.ArrowHelper = ArrowHelper;
  28613. exports.Audio = Audio;
  28614. exports.AudioAnalyser = AudioAnalyser;
  28615. exports.AudioContext = AudioContext;
  28616. exports.AudioListener = AudioListener;
  28617. exports.AudioLoader = AudioLoader;
  28618. exports.AxesHelper = AxesHelper;
  28619. exports.BackSide = BackSide;
  28620. exports.BasicDepthPacking = BasicDepthPacking;
  28621. exports.BasicShadowMap = BasicShadowMap;
  28622. exports.Bone = Bone;
  28623. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28624. exports.Box2 = Box2;
  28625. exports.Box3 = Box3;
  28626. exports.Box3Helper = Box3Helper;
  28627. exports.BoxBufferGeometry = BoxGeometry;
  28628. exports.BoxGeometry = BoxGeometry;
  28629. exports.BoxHelper = BoxHelper;
  28630. exports.BufferAttribute = BufferAttribute;
  28631. exports.BufferGeometry = BufferGeometry;
  28632. exports.BufferGeometryLoader = BufferGeometryLoader;
  28633. exports.ByteType = ByteType;
  28634. exports.Cache = Cache;
  28635. exports.Camera = Camera;
  28636. exports.CameraHelper = CameraHelper;
  28637. exports.CanvasTexture = CanvasTexture;
  28638. exports.CapsuleBufferGeometry = CapsuleGeometry;
  28639. exports.CapsuleGeometry = CapsuleGeometry;
  28640. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28641. exports.CineonToneMapping = CineonToneMapping;
  28642. exports.CircleBufferGeometry = CircleGeometry;
  28643. exports.CircleGeometry = CircleGeometry;
  28644. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28645. exports.Clock = Clock;
  28646. exports.Color = Color;
  28647. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28648. exports.ColorManagement = ColorManagement;
  28649. exports.CompressedTexture = CompressedTexture;
  28650. exports.CompressedTextureLoader = CompressedTextureLoader;
  28651. exports.ConeBufferGeometry = ConeGeometry;
  28652. exports.ConeGeometry = ConeGeometry;
  28653. exports.CubeCamera = CubeCamera;
  28654. exports.CubeReflectionMapping = CubeReflectionMapping;
  28655. exports.CubeRefractionMapping = CubeRefractionMapping;
  28656. exports.CubeTexture = CubeTexture;
  28657. exports.CubeTextureLoader = CubeTextureLoader;
  28658. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28659. exports.CubicBezierCurve = CubicBezierCurve;
  28660. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28661. exports.CubicInterpolant = CubicInterpolant;
  28662. exports.CullFaceBack = CullFaceBack;
  28663. exports.CullFaceFront = CullFaceFront;
  28664. exports.CullFaceFrontBack = CullFaceFrontBack;
  28665. exports.CullFaceNone = CullFaceNone;
  28666. exports.Curve = Curve;
  28667. exports.CurvePath = CurvePath;
  28668. exports.CustomBlending = CustomBlending;
  28669. exports.CustomToneMapping = CustomToneMapping;
  28670. exports.CylinderBufferGeometry = CylinderGeometry;
  28671. exports.CylinderGeometry = CylinderGeometry;
  28672. exports.Cylindrical = Cylindrical;
  28673. exports.Data3DTexture = Data3DTexture;
  28674. exports.DataArrayTexture = DataArrayTexture;
  28675. exports.DataTexture = DataTexture;
  28676. exports.DataTexture2DArray = DataTexture2DArray;
  28677. exports.DataTexture3D = DataTexture3D;
  28678. exports.DataTextureLoader = DataTextureLoader;
  28679. exports.DataUtils = DataUtils;
  28680. exports.DecrementStencilOp = DecrementStencilOp;
  28681. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28682. exports.DefaultLoadingManager = DefaultLoadingManager;
  28683. exports.DepthFormat = DepthFormat;
  28684. exports.DepthStencilFormat = DepthStencilFormat;
  28685. exports.DepthTexture = DepthTexture;
  28686. exports.DirectionalLight = DirectionalLight;
  28687. exports.DirectionalLightHelper = DirectionalLightHelper;
  28688. exports.DiscreteInterpolant = DiscreteInterpolant;
  28689. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  28690. exports.DodecahedronGeometry = DodecahedronGeometry;
  28691. exports.DoubleSide = DoubleSide;
  28692. exports.DstAlphaFactor = DstAlphaFactor;
  28693. exports.DstColorFactor = DstColorFactor;
  28694. exports.DynamicCopyUsage = DynamicCopyUsage;
  28695. exports.DynamicDrawUsage = DynamicDrawUsage;
  28696. exports.DynamicReadUsage = DynamicReadUsage;
  28697. exports.EdgesGeometry = EdgesGeometry;
  28698. exports.EllipseCurve = EllipseCurve;
  28699. exports.EqualDepth = EqualDepth;
  28700. exports.EqualStencilFunc = EqualStencilFunc;
  28701. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28702. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28703. exports.Euler = Euler;
  28704. exports.EventDispatcher = EventDispatcher;
  28705. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  28706. exports.ExtrudeGeometry = ExtrudeGeometry;
  28707. exports.FileLoader = FileLoader;
  28708. exports.FlatShading = FlatShading;
  28709. exports.Float16BufferAttribute = Float16BufferAttribute;
  28710. exports.Float32BufferAttribute = Float32BufferAttribute;
  28711. exports.Float64BufferAttribute = Float64BufferAttribute;
  28712. exports.FloatType = FloatType;
  28713. exports.Fog = Fog;
  28714. exports.FogExp2 = FogExp2;
  28715. exports.Font = Font;
  28716. exports.FontLoader = FontLoader;
  28717. exports.FramebufferTexture = FramebufferTexture;
  28718. exports.FrontSide = FrontSide;
  28719. exports.Frustum = Frustum;
  28720. exports.GLBufferAttribute = GLBufferAttribute;
  28721. exports.GLSL1 = GLSL1;
  28722. exports.GLSL3 = GLSL3;
  28723. exports.GreaterDepth = GreaterDepth;
  28724. exports.GreaterEqualDepth = GreaterEqualDepth;
  28725. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28726. exports.GreaterStencilFunc = GreaterStencilFunc;
  28727. exports.GridHelper = GridHelper;
  28728. exports.Group = Group;
  28729. exports.HalfFloatType = HalfFloatType;
  28730. exports.HemisphereLight = HemisphereLight;
  28731. exports.HemisphereLightHelper = HemisphereLightHelper;
  28732. exports.HemisphereLightProbe = HemisphereLightProbe;
  28733. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  28734. exports.IcosahedronGeometry = IcosahedronGeometry;
  28735. exports.ImageBitmapLoader = ImageBitmapLoader;
  28736. exports.ImageLoader = ImageLoader;
  28737. exports.ImageUtils = ImageUtils;
  28738. exports.ImmediateRenderObject = ImmediateRenderObject;
  28739. exports.IncrementStencilOp = IncrementStencilOp;
  28740. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  28741. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  28742. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  28743. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  28744. exports.InstancedMesh = InstancedMesh;
  28745. exports.Int16BufferAttribute = Int16BufferAttribute;
  28746. exports.Int32BufferAttribute = Int32BufferAttribute;
  28747. exports.Int8BufferAttribute = Int8BufferAttribute;
  28748. exports.IntType = IntType;
  28749. exports.InterleavedBuffer = InterleavedBuffer;
  28750. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  28751. exports.Interpolant = Interpolant;
  28752. exports.InterpolateDiscrete = InterpolateDiscrete;
  28753. exports.InterpolateLinear = InterpolateLinear;
  28754. exports.InterpolateSmooth = InterpolateSmooth;
  28755. exports.InvertStencilOp = InvertStencilOp;
  28756. exports.KeepStencilOp = KeepStencilOp;
  28757. exports.KeyframeTrack = KeyframeTrack;
  28758. exports.LOD = LOD;
  28759. exports.LatheBufferGeometry = LatheGeometry;
  28760. exports.LatheGeometry = LatheGeometry;
  28761. exports.Layers = Layers;
  28762. exports.LessDepth = LessDepth;
  28763. exports.LessEqualDepth = LessEqualDepth;
  28764. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  28765. exports.LessStencilFunc = LessStencilFunc;
  28766. exports.Light = Light;
  28767. exports.LightProbe = LightProbe;
  28768. exports.Line = Line;
  28769. exports.Line3 = Line3;
  28770. exports.LineBasicMaterial = LineBasicMaterial;
  28771. exports.LineCurve = LineCurve;
  28772. exports.LineCurve3 = LineCurve3;
  28773. exports.LineDashedMaterial = LineDashedMaterial;
  28774. exports.LineLoop = LineLoop;
  28775. exports.LineSegments = LineSegments;
  28776. exports.LinearEncoding = LinearEncoding;
  28777. exports.LinearFilter = LinearFilter;
  28778. exports.LinearInterpolant = LinearInterpolant;
  28779. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  28780. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  28781. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  28782. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  28783. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  28784. exports.LinearToneMapping = LinearToneMapping;
  28785. exports.Loader = Loader;
  28786. exports.LoaderUtils = LoaderUtils;
  28787. exports.LoadingManager = LoadingManager;
  28788. exports.LoopOnce = LoopOnce;
  28789. exports.LoopPingPong = LoopPingPong;
  28790. exports.LoopRepeat = LoopRepeat;
  28791. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  28792. exports.LuminanceFormat = LuminanceFormat;
  28793. exports.MOUSE = MOUSE;
  28794. exports.Material = Material;
  28795. exports.MaterialLoader = MaterialLoader;
  28796. exports.MathUtils = MathUtils;
  28797. exports.Matrix3 = Matrix3;
  28798. exports.Matrix4 = Matrix4;
  28799. exports.MaxEquation = MaxEquation;
  28800. exports.Mesh = Mesh;
  28801. exports.MeshBasicMaterial = MeshBasicMaterial;
  28802. exports.MeshDepthMaterial = MeshDepthMaterial;
  28803. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  28804. exports.MeshLambertMaterial = MeshLambertMaterial;
  28805. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  28806. exports.MeshNormalMaterial = MeshNormalMaterial;
  28807. exports.MeshPhongMaterial = MeshPhongMaterial;
  28808. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  28809. exports.MeshStandardMaterial = MeshStandardMaterial;
  28810. exports.MeshToonMaterial = MeshToonMaterial;
  28811. exports.MinEquation = MinEquation;
  28812. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  28813. exports.MixOperation = MixOperation;
  28814. exports.MultiplyBlending = MultiplyBlending;
  28815. exports.MultiplyOperation = MultiplyOperation;
  28816. exports.NearestFilter = NearestFilter;
  28817. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  28818. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  28819. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  28820. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  28821. exports.NeverDepth = NeverDepth;
  28822. exports.NeverStencilFunc = NeverStencilFunc;
  28823. exports.NoBlending = NoBlending;
  28824. exports.NoColorSpace = NoColorSpace;
  28825. exports.NoToneMapping = NoToneMapping;
  28826. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  28827. exports.NormalBlending = NormalBlending;
  28828. exports.NotEqualDepth = NotEqualDepth;
  28829. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  28830. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  28831. exports.Object3D = Object3D;
  28832. exports.ObjectLoader = ObjectLoader;
  28833. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  28834. exports.OctahedronBufferGeometry = OctahedronGeometry;
  28835. exports.OctahedronGeometry = OctahedronGeometry;
  28836. exports.OneFactor = OneFactor;
  28837. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  28838. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  28839. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  28840. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  28841. exports.OrthographicCamera = OrthographicCamera;
  28842. exports.PCFShadowMap = PCFShadowMap;
  28843. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  28844. exports.PMREMGenerator = PMREMGenerator;
  28845. exports.ParametricGeometry = ParametricGeometry;
  28846. exports.Path = Path;
  28847. exports.PerspectiveCamera = PerspectiveCamera;
  28848. exports.Plane = Plane;
  28849. exports.PlaneBufferGeometry = PlaneGeometry;
  28850. exports.PlaneGeometry = PlaneGeometry;
  28851. exports.PlaneHelper = PlaneHelper;
  28852. exports.PointLight = PointLight;
  28853. exports.PointLightHelper = PointLightHelper;
  28854. exports.Points = Points;
  28855. exports.PointsMaterial = PointsMaterial;
  28856. exports.PolarGridHelper = PolarGridHelper;
  28857. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  28858. exports.PolyhedronGeometry = PolyhedronGeometry;
  28859. exports.PositionalAudio = PositionalAudio;
  28860. exports.PropertyBinding = PropertyBinding;
  28861. exports.PropertyMixer = PropertyMixer;
  28862. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  28863. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  28864. exports.Quaternion = Quaternion;
  28865. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  28866. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  28867. exports.REVISION = REVISION;
  28868. exports.RGBADepthPacking = RGBADepthPacking;
  28869. exports.RGBAFormat = RGBAFormat;
  28870. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  28871. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  28872. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  28873. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  28874. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  28875. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  28876. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  28877. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  28878. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  28879. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  28880. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  28881. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  28882. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  28883. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  28884. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  28885. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  28886. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  28887. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  28888. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  28889. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  28890. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  28891. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  28892. exports.RGBFormat = RGBFormat;
  28893. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  28894. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  28895. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  28896. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  28897. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  28898. exports.RGFormat = RGFormat;
  28899. exports.RGIntegerFormat = RGIntegerFormat;
  28900. exports.RawShaderMaterial = RawShaderMaterial;
  28901. exports.Ray = Ray;
  28902. exports.Raycaster = Raycaster;
  28903. exports.RectAreaLight = RectAreaLight;
  28904. exports.RedFormat = RedFormat;
  28905. exports.RedIntegerFormat = RedIntegerFormat;
  28906. exports.ReinhardToneMapping = ReinhardToneMapping;
  28907. exports.RepeatWrapping = RepeatWrapping;
  28908. exports.ReplaceStencilOp = ReplaceStencilOp;
  28909. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  28910. exports.RingBufferGeometry = RingGeometry;
  28911. exports.RingGeometry = RingGeometry;
  28912. exports.SRGBColorSpace = SRGBColorSpace;
  28913. exports.Scene = Scene;
  28914. exports.ShaderChunk = ShaderChunk;
  28915. exports.ShaderLib = ShaderLib;
  28916. exports.ShaderMaterial = ShaderMaterial;
  28917. exports.ShadowMaterial = ShadowMaterial;
  28918. exports.Shape = Shape;
  28919. exports.ShapeBufferGeometry = ShapeGeometry;
  28920. exports.ShapeGeometry = ShapeGeometry;
  28921. exports.ShapePath = ShapePath;
  28922. exports.ShapeUtils = ShapeUtils;
  28923. exports.ShortType = ShortType;
  28924. exports.Skeleton = Skeleton;
  28925. exports.SkeletonHelper = SkeletonHelper;
  28926. exports.SkinnedMesh = SkinnedMesh;
  28927. exports.SmoothShading = SmoothShading;
  28928. exports.Source = Source;
  28929. exports.Sphere = Sphere;
  28930. exports.SphereBufferGeometry = SphereGeometry;
  28931. exports.SphereGeometry = SphereGeometry;
  28932. exports.Spherical = Spherical;
  28933. exports.SphericalHarmonics3 = SphericalHarmonics3;
  28934. exports.SplineCurve = SplineCurve;
  28935. exports.SpotLight = SpotLight;
  28936. exports.SpotLightHelper = SpotLightHelper;
  28937. exports.Sprite = Sprite;
  28938. exports.SpriteMaterial = SpriteMaterial;
  28939. exports.SrcAlphaFactor = SrcAlphaFactor;
  28940. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  28941. exports.SrcColorFactor = SrcColorFactor;
  28942. exports.StaticCopyUsage = StaticCopyUsage;
  28943. exports.StaticDrawUsage = StaticDrawUsage;
  28944. exports.StaticReadUsage = StaticReadUsage;
  28945. exports.StereoCamera = StereoCamera;
  28946. exports.StreamCopyUsage = StreamCopyUsage;
  28947. exports.StreamDrawUsage = StreamDrawUsage;
  28948. exports.StreamReadUsage = StreamReadUsage;
  28949. exports.StringKeyframeTrack = StringKeyframeTrack;
  28950. exports.SubtractEquation = SubtractEquation;
  28951. exports.SubtractiveBlending = SubtractiveBlending;
  28952. exports.TOUCH = TOUCH;
  28953. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  28954. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  28955. exports.TetrahedronGeometry = TetrahedronGeometry;
  28956. exports.TextGeometry = TextGeometry;
  28957. exports.Texture = Texture;
  28958. exports.TextureLoader = TextureLoader;
  28959. exports.TorusBufferGeometry = TorusGeometry;
  28960. exports.TorusGeometry = TorusGeometry;
  28961. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  28962. exports.TorusKnotGeometry = TorusKnotGeometry;
  28963. exports.Triangle = Triangle;
  28964. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  28965. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  28966. exports.TrianglesDrawMode = TrianglesDrawMode;
  28967. exports.TubeBufferGeometry = TubeGeometry;
  28968. exports.TubeGeometry = TubeGeometry;
  28969. exports.UVMapping = UVMapping;
  28970. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  28971. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  28972. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  28973. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  28974. exports.Uniform = Uniform;
  28975. exports.UniformsGroup = UniformsGroup;
  28976. exports.UniformsLib = UniformsLib;
  28977. exports.UniformsUtils = UniformsUtils;
  28978. exports.UnsignedByteType = UnsignedByteType;
  28979. exports.UnsignedInt248Type = UnsignedInt248Type;
  28980. exports.UnsignedIntType = UnsignedIntType;
  28981. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  28982. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  28983. exports.UnsignedShortType = UnsignedShortType;
  28984. exports.VSMShadowMap = VSMShadowMap;
  28985. exports.Vector2 = Vector2;
  28986. exports.Vector3 = Vector3;
  28987. exports.Vector4 = Vector4;
  28988. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  28989. exports.VideoTexture = VideoTexture;
  28990. exports.WebGL1Renderer = WebGL1Renderer;
  28991. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  28992. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  28993. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  28994. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  28995. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  28996. exports.WebGLRenderTarget = WebGLRenderTarget;
  28997. exports.WebGLRenderer = WebGLRenderer;
  28998. exports.WebGLUtils = WebGLUtils;
  28999. exports.WireframeGeometry = WireframeGeometry;
  29000. exports.WrapAroundEnding = WrapAroundEnding;
  29001. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29002. exports.ZeroFactor = ZeroFactor;
  29003. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29004. exports.ZeroStencilOp = ZeroStencilOp;
  29005. exports._SRGBAFormat = _SRGBAFormat;
  29006. exports.sRGBEncoding = sRGBEncoding;