three.cjs 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '164dev';
  8. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  9. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  10. const CullFaceNone = 0;
  11. const CullFaceBack = 1;
  12. const CullFaceFront = 2;
  13. const CullFaceFrontBack = 3;
  14. const BasicShadowMap = 0;
  15. const PCFShadowMap = 1;
  16. const PCFSoftShadowMap = 2;
  17. const VSMShadowMap = 3;
  18. const FrontSide = 0;
  19. const BackSide = 1;
  20. const DoubleSide = 2;
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const ConstantColorFactor = 211;
  44. const OneMinusConstantColorFactor = 212;
  45. const ConstantAlphaFactor = 213;
  46. const OneMinusConstantAlphaFactor = 214;
  47. const NeverDepth = 0;
  48. const AlwaysDepth = 1;
  49. const LessDepth = 2;
  50. const LessEqualDepth = 3;
  51. const EqualDepth = 4;
  52. const GreaterEqualDepth = 5;
  53. const GreaterDepth = 6;
  54. const NotEqualDepth = 7;
  55. const MultiplyOperation = 0;
  56. const MixOperation = 1;
  57. const AddOperation = 2;
  58. const NoToneMapping = 0;
  59. const LinearToneMapping = 1;
  60. const ReinhardToneMapping = 2;
  61. const CineonToneMapping = 3;
  62. const ACESFilmicToneMapping = 4;
  63. const CustomToneMapping = 5;
  64. const AgXToneMapping = 6;
  65. const NeutralToneMapping = 7;
  66. const AttachedBindMode = 'attached';
  67. const DetachedBindMode = 'detached';
  68. const UVMapping = 300;
  69. const CubeReflectionMapping = 301;
  70. const CubeRefractionMapping = 302;
  71. const EquirectangularReflectionMapping = 303;
  72. const EquirectangularRefractionMapping = 304;
  73. const CubeUVReflectionMapping = 306;
  74. const RepeatWrapping = 1000;
  75. const ClampToEdgeWrapping = 1001;
  76. const MirroredRepeatWrapping = 1002;
  77. const NearestFilter = 1003;
  78. const NearestMipmapNearestFilter = 1004;
  79. const NearestMipMapNearestFilter = 1004;
  80. const NearestMipmapLinearFilter = 1005;
  81. const NearestMipMapLinearFilter = 1005;
  82. const LinearFilter = 1006;
  83. const LinearMipmapNearestFilter = 1007;
  84. const LinearMipMapNearestFilter = 1007;
  85. const LinearMipmapLinearFilter = 1008;
  86. const LinearMipMapLinearFilter = 1008;
  87. const UnsignedByteType = 1009;
  88. const ByteType = 1010;
  89. const ShortType = 1011;
  90. const UnsignedShortType = 1012;
  91. const IntType = 1013;
  92. const UnsignedIntType = 1014;
  93. const FloatType = 1015;
  94. const HalfFloatType = 1016;
  95. const UnsignedShort4444Type = 1017;
  96. const UnsignedShort5551Type = 1018;
  97. const UnsignedInt248Type = 1020;
  98. const UnsignedInt5999Type = 35902;
  99. const AlphaFormat = 1021;
  100. const RGBFormat = 1022;
  101. const RGBAFormat = 1023;
  102. const LuminanceFormat = 1024;
  103. const LuminanceAlphaFormat = 1025;
  104. const DepthFormat = 1026;
  105. const DepthStencilFormat = 1027;
  106. const RedFormat = 1028;
  107. const RedIntegerFormat = 1029;
  108. const RGFormat = 1030;
  109. const RGIntegerFormat = 1031;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  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 BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const TangentSpaceNormalMap = 0;
  160. const ObjectSpaceNormalMap = 1;
  161. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  162. const NoColorSpace = '';
  163. const SRGBColorSpace = 'srgb';
  164. const LinearSRGBColorSpace = 'srgb-linear';
  165. const DisplayP3ColorSpace = 'display-p3';
  166. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  167. const LinearTransfer = 'linear';
  168. const SRGBTransfer = 'srgb';
  169. const Rec709Primaries = 'rec709';
  170. const P3Primaries = 'p3';
  171. const ZeroStencilOp = 0;
  172. const KeepStencilOp = 7680;
  173. const ReplaceStencilOp = 7681;
  174. const IncrementStencilOp = 7682;
  175. const DecrementStencilOp = 7683;
  176. const IncrementWrapStencilOp = 34055;
  177. const DecrementWrapStencilOp = 34056;
  178. const InvertStencilOp = 5386;
  179. const NeverStencilFunc = 512;
  180. const LessStencilFunc = 513;
  181. const EqualStencilFunc = 514;
  182. const LessEqualStencilFunc = 515;
  183. const GreaterStencilFunc = 516;
  184. const NotEqualStencilFunc = 517;
  185. const GreaterEqualStencilFunc = 518;
  186. const AlwaysStencilFunc = 519;
  187. const NeverCompare = 512;
  188. const LessCompare = 513;
  189. const EqualCompare = 514;
  190. const LessEqualCompare = 515;
  191. const GreaterCompare = 516;
  192. const NotEqualCompare = 517;
  193. const GreaterEqualCompare = 518;
  194. const AlwaysCompare = 519;
  195. const StaticDrawUsage = 35044;
  196. const DynamicDrawUsage = 35048;
  197. const StreamDrawUsage = 35040;
  198. const StaticReadUsage = 35045;
  199. const DynamicReadUsage = 35049;
  200. const StreamReadUsage = 35041;
  201. const StaticCopyUsage = 35046;
  202. const DynamicCopyUsage = 35050;
  203. const StreamCopyUsage = 35042;
  204. const GLSL1 = '100';
  205. const GLSL3 = '300 es';
  206. const WebGLCoordinateSystem = 2000;
  207. const WebGPUCoordinateSystem = 2001;
  208. /**
  209. * https://github.com/mrdoob/eventdispatcher.js/
  210. */
  211. class EventDispatcher {
  212. addEventListener( type, listener ) {
  213. if ( this._listeners === undefined ) this._listeners = {};
  214. const listeners = this._listeners;
  215. if ( listeners[ type ] === undefined ) {
  216. listeners[ type ] = [];
  217. }
  218. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  219. listeners[ type ].push( listener );
  220. }
  221. }
  222. hasEventListener( type, listener ) {
  223. if ( this._listeners === undefined ) return false;
  224. const listeners = this._listeners;
  225. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  226. }
  227. removeEventListener( type, listener ) {
  228. if ( this._listeners === undefined ) return;
  229. const listeners = this._listeners;
  230. const listenerArray = listeners[ type ];
  231. if ( listenerArray !== undefined ) {
  232. const index = listenerArray.indexOf( listener );
  233. if ( index !== - 1 ) {
  234. listenerArray.splice( index, 1 );
  235. }
  236. }
  237. }
  238. dispatchEvent( event ) {
  239. if ( this._listeners === undefined ) return;
  240. const listeners = this._listeners;
  241. const listenerArray = listeners[ event.type ];
  242. if ( listenerArray !== undefined ) {
  243. event.target = this;
  244. // Make a copy, in case listeners are removed while iterating.
  245. const array = listenerArray.slice( 0 );
  246. for ( let i = 0, l = array.length; i < l; i ++ ) {
  247. array[ i ].call( this, event );
  248. }
  249. event.target = null;
  250. }
  251. }
  252. }
  253. 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' ];
  254. let _seed = 1234567;
  255. const DEG2RAD = Math.PI / 180;
  256. const RAD2DEG = 180 / Math.PI;
  257. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  258. function generateUUID() {
  259. const d0 = Math.random() * 0xffffffff | 0;
  260. const d1 = Math.random() * 0xffffffff | 0;
  261. const d2 = Math.random() * 0xffffffff | 0;
  262. const d3 = Math.random() * 0xffffffff | 0;
  263. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  264. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  265. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  266. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  267. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  268. return uuid.toLowerCase();
  269. }
  270. function clamp( value, min, max ) {
  271. return Math.max( min, Math.min( max, value ) );
  272. }
  273. // compute euclidean modulo of m % n
  274. // https://en.wikipedia.org/wiki/Modulo_operation
  275. function euclideanModulo( n, m ) {
  276. return ( ( n % m ) + m ) % m;
  277. }
  278. // Linear mapping from range <a1, a2> to range <b1, b2>
  279. function mapLinear( x, a1, a2, b1, b2 ) {
  280. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  281. }
  282. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  283. function inverseLerp( x, y, value ) {
  284. if ( x !== y ) {
  285. return ( value - x ) / ( y - x );
  286. } else {
  287. return 0;
  288. }
  289. }
  290. // https://en.wikipedia.org/wiki/Linear_interpolation
  291. function lerp( x, y, t ) {
  292. return ( 1 - t ) * x + t * y;
  293. }
  294. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  295. function damp( x, y, lambda, dt ) {
  296. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  297. }
  298. // https://www.desmos.com/calculator/vcsjnyz7x4
  299. function pingpong( x, length = 1 ) {
  300. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  301. }
  302. // http://en.wikipedia.org/wiki/Smoothstep
  303. function smoothstep( x, min, max ) {
  304. if ( x <= min ) return 0;
  305. if ( x >= max ) return 1;
  306. x = ( x - min ) / ( max - min );
  307. return x * x * ( 3 - 2 * x );
  308. }
  309. function smootherstep( x, min, max ) {
  310. if ( x <= min ) return 0;
  311. if ( x >= max ) return 1;
  312. x = ( x - min ) / ( max - min );
  313. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  314. }
  315. // Random integer from <low, high> interval
  316. function randInt( low, high ) {
  317. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  318. }
  319. // Random float from <low, high> interval
  320. function randFloat( low, high ) {
  321. return low + Math.random() * ( high - low );
  322. }
  323. // Random float from <-range/2, range/2> interval
  324. function randFloatSpread( range ) {
  325. return range * ( 0.5 - Math.random() );
  326. }
  327. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  328. function seededRandom( s ) {
  329. if ( s !== undefined ) _seed = s;
  330. // Mulberry32 generator
  331. let t = _seed += 0x6D2B79F5;
  332. t = Math.imul( t ^ t >>> 15, t | 1 );
  333. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  334. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  335. }
  336. function degToRad( degrees ) {
  337. return degrees * DEG2RAD;
  338. }
  339. function radToDeg( radians ) {
  340. return radians * RAD2DEG;
  341. }
  342. function isPowerOfTwo( value ) {
  343. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  344. }
  345. function ceilPowerOfTwo( value ) {
  346. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  347. }
  348. function floorPowerOfTwo( value ) {
  349. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  350. }
  351. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  352. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  353. // rotations are applied to the axes in the order specified by 'order'
  354. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  355. // angles are in radians
  356. const cos = Math.cos;
  357. const sin = Math.sin;
  358. const c2 = cos( b / 2 );
  359. const s2 = sin( b / 2 );
  360. const c13 = cos( ( a + c ) / 2 );
  361. const s13 = sin( ( a + c ) / 2 );
  362. const c1_3 = cos( ( a - c ) / 2 );
  363. const s1_3 = sin( ( a - c ) / 2 );
  364. const c3_1 = cos( ( c - a ) / 2 );
  365. const s3_1 = sin( ( c - a ) / 2 );
  366. switch ( order ) {
  367. case 'XYX':
  368. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  369. break;
  370. case 'YZY':
  371. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  372. break;
  373. case 'ZXZ':
  374. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  375. break;
  376. case 'XZX':
  377. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  378. break;
  379. case 'YXY':
  380. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  381. break;
  382. case 'ZYZ':
  383. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  384. break;
  385. default:
  386. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  387. }
  388. }
  389. function denormalize( value, array ) {
  390. switch ( array.constructor ) {
  391. case Float32Array:
  392. return value;
  393. case Uint32Array:
  394. return value / 4294967295.0;
  395. case Uint16Array:
  396. return value / 65535.0;
  397. case Uint8Array:
  398. return value / 255.0;
  399. case Int32Array:
  400. return Math.max( value / 2147483647.0, - 1.0 );
  401. case Int16Array:
  402. return Math.max( value / 32767.0, - 1.0 );
  403. case Int8Array:
  404. return Math.max( value / 127.0, - 1.0 );
  405. default:
  406. throw new Error( 'Invalid component type.' );
  407. }
  408. }
  409. function normalize( value, array ) {
  410. switch ( array.constructor ) {
  411. case Float32Array:
  412. return value;
  413. case Uint32Array:
  414. return Math.round( value * 4294967295.0 );
  415. case Uint16Array:
  416. return Math.round( value * 65535.0 );
  417. case Uint8Array:
  418. return Math.round( value * 255.0 );
  419. case Int32Array:
  420. return Math.round( value * 2147483647.0 );
  421. case Int16Array:
  422. return Math.round( value * 32767.0 );
  423. case Int8Array:
  424. return Math.round( value * 127.0 );
  425. default:
  426. throw new Error( 'Invalid component type.' );
  427. }
  428. }
  429. const MathUtils = {
  430. DEG2RAD: DEG2RAD,
  431. RAD2DEG: RAD2DEG,
  432. generateUUID: generateUUID,
  433. clamp: clamp,
  434. euclideanModulo: euclideanModulo,
  435. mapLinear: mapLinear,
  436. inverseLerp: inverseLerp,
  437. lerp: lerp,
  438. damp: damp,
  439. pingpong: pingpong,
  440. smoothstep: smoothstep,
  441. smootherstep: smootherstep,
  442. randInt: randInt,
  443. randFloat: randFloat,
  444. randFloatSpread: randFloatSpread,
  445. seededRandom: seededRandom,
  446. degToRad: degToRad,
  447. radToDeg: radToDeg,
  448. isPowerOfTwo: isPowerOfTwo,
  449. ceilPowerOfTwo: ceilPowerOfTwo,
  450. floorPowerOfTwo: floorPowerOfTwo,
  451. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  452. normalize: normalize,
  453. denormalize: denormalize
  454. };
  455. class Vector2 {
  456. constructor( x = 0, y = 0 ) {
  457. Vector2.prototype.isVector2 = true;
  458. this.x = x;
  459. this.y = y;
  460. }
  461. get width() {
  462. return this.x;
  463. }
  464. set width( value ) {
  465. this.x = value;
  466. }
  467. get height() {
  468. return this.y;
  469. }
  470. set height( value ) {
  471. this.y = value;
  472. }
  473. set( x, y ) {
  474. this.x = x;
  475. this.y = y;
  476. return this;
  477. }
  478. setScalar( scalar ) {
  479. this.x = scalar;
  480. this.y = scalar;
  481. return this;
  482. }
  483. setX( x ) {
  484. this.x = x;
  485. return this;
  486. }
  487. setY( y ) {
  488. this.y = y;
  489. return this;
  490. }
  491. setComponent( index, value ) {
  492. switch ( index ) {
  493. case 0: this.x = value; break;
  494. case 1: this.y = value; break;
  495. default: throw new Error( 'index is out of range: ' + index );
  496. }
  497. return this;
  498. }
  499. getComponent( index ) {
  500. switch ( index ) {
  501. case 0: return this.x;
  502. case 1: return this.y;
  503. default: throw new Error( 'index is out of range: ' + index );
  504. }
  505. }
  506. clone() {
  507. return new this.constructor( this.x, this.y );
  508. }
  509. copy( v ) {
  510. this.x = v.x;
  511. this.y = v.y;
  512. return this;
  513. }
  514. add( v ) {
  515. this.x += v.x;
  516. this.y += v.y;
  517. return this;
  518. }
  519. addScalar( s ) {
  520. this.x += s;
  521. this.y += s;
  522. return this;
  523. }
  524. addVectors( a, b ) {
  525. this.x = a.x + b.x;
  526. this.y = a.y + b.y;
  527. return this;
  528. }
  529. addScaledVector( v, s ) {
  530. this.x += v.x * s;
  531. this.y += v.y * s;
  532. return this;
  533. }
  534. sub( v ) {
  535. this.x -= v.x;
  536. this.y -= v.y;
  537. return this;
  538. }
  539. subScalar( s ) {
  540. this.x -= s;
  541. this.y -= s;
  542. return this;
  543. }
  544. subVectors( a, b ) {
  545. this.x = a.x - b.x;
  546. this.y = a.y - b.y;
  547. return this;
  548. }
  549. multiply( v ) {
  550. this.x *= v.x;
  551. this.y *= v.y;
  552. return this;
  553. }
  554. multiplyScalar( scalar ) {
  555. this.x *= scalar;
  556. this.y *= scalar;
  557. return this;
  558. }
  559. divide( v ) {
  560. this.x /= v.x;
  561. this.y /= v.y;
  562. return this;
  563. }
  564. divideScalar( scalar ) {
  565. return this.multiplyScalar( 1 / scalar );
  566. }
  567. applyMatrix3( m ) {
  568. const x = this.x, y = this.y;
  569. const e = m.elements;
  570. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  571. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  572. return this;
  573. }
  574. min( v ) {
  575. this.x = Math.min( this.x, v.x );
  576. this.y = Math.min( this.y, v.y );
  577. return this;
  578. }
  579. max( v ) {
  580. this.x = Math.max( this.x, v.x );
  581. this.y = Math.max( this.y, v.y );
  582. return this;
  583. }
  584. clamp( min, max ) {
  585. // assumes min < max, componentwise
  586. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  587. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  588. return this;
  589. }
  590. clampScalar( minVal, maxVal ) {
  591. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  592. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  593. return this;
  594. }
  595. clampLength( min, max ) {
  596. const length = this.length();
  597. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  598. }
  599. floor() {
  600. this.x = Math.floor( this.x );
  601. this.y = Math.floor( this.y );
  602. return this;
  603. }
  604. ceil() {
  605. this.x = Math.ceil( this.x );
  606. this.y = Math.ceil( this.y );
  607. return this;
  608. }
  609. round() {
  610. this.x = Math.round( this.x );
  611. this.y = Math.round( this.y );
  612. return this;
  613. }
  614. roundToZero() {
  615. this.x = Math.trunc( this.x );
  616. this.y = Math.trunc( this.y );
  617. return this;
  618. }
  619. negate() {
  620. this.x = - this.x;
  621. this.y = - this.y;
  622. return this;
  623. }
  624. dot( v ) {
  625. return this.x * v.x + this.y * v.y;
  626. }
  627. cross( v ) {
  628. return this.x * v.y - this.y * v.x;
  629. }
  630. lengthSq() {
  631. return this.x * this.x + this.y * this.y;
  632. }
  633. length() {
  634. return Math.sqrt( this.x * this.x + this.y * this.y );
  635. }
  636. manhattanLength() {
  637. return Math.abs( this.x ) + Math.abs( this.y );
  638. }
  639. normalize() {
  640. return this.divideScalar( this.length() || 1 );
  641. }
  642. angle() {
  643. // computes the angle in radians with respect to the positive x-axis
  644. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  645. return angle;
  646. }
  647. angleTo( v ) {
  648. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  649. if ( denominator === 0 ) return Math.PI / 2;
  650. const theta = this.dot( v ) / denominator;
  651. // clamp, to handle numerical problems
  652. return Math.acos( clamp( theta, - 1, 1 ) );
  653. }
  654. distanceTo( v ) {
  655. return Math.sqrt( this.distanceToSquared( v ) );
  656. }
  657. distanceToSquared( v ) {
  658. const dx = this.x - v.x, dy = this.y - v.y;
  659. return dx * dx + dy * dy;
  660. }
  661. manhattanDistanceTo( v ) {
  662. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  663. }
  664. setLength( length ) {
  665. return this.normalize().multiplyScalar( length );
  666. }
  667. lerp( v, alpha ) {
  668. this.x += ( v.x - this.x ) * alpha;
  669. this.y += ( v.y - this.y ) * alpha;
  670. return this;
  671. }
  672. lerpVectors( v1, v2, alpha ) {
  673. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  674. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  675. return this;
  676. }
  677. equals( v ) {
  678. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  679. }
  680. fromArray( array, offset = 0 ) {
  681. this.x = array[ offset ];
  682. this.y = array[ offset + 1 ];
  683. return this;
  684. }
  685. toArray( array = [], offset = 0 ) {
  686. array[ offset ] = this.x;
  687. array[ offset + 1 ] = this.y;
  688. return array;
  689. }
  690. fromBufferAttribute( attribute, index ) {
  691. this.x = attribute.getX( index );
  692. this.y = attribute.getY( index );
  693. return this;
  694. }
  695. rotateAround( center, angle ) {
  696. const c = Math.cos( angle ), s = Math.sin( angle );
  697. const x = this.x - center.x;
  698. const y = this.y - center.y;
  699. this.x = x * c - y * s + center.x;
  700. this.y = x * s + y * c + center.y;
  701. return this;
  702. }
  703. random() {
  704. this.x = Math.random();
  705. this.y = Math.random();
  706. return this;
  707. }
  708. *[ Symbol.iterator ]() {
  709. yield this.x;
  710. yield this.y;
  711. }
  712. }
  713. class Matrix3 {
  714. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  715. Matrix3.prototype.isMatrix3 = true;
  716. this.elements = [
  717. 1, 0, 0,
  718. 0, 1, 0,
  719. 0, 0, 1
  720. ];
  721. if ( n11 !== undefined ) {
  722. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  723. }
  724. }
  725. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  726. const te = this.elements;
  727. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  728. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  729. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  730. return this;
  731. }
  732. identity() {
  733. this.set(
  734. 1, 0, 0,
  735. 0, 1, 0,
  736. 0, 0, 1
  737. );
  738. return this;
  739. }
  740. copy( m ) {
  741. const te = this.elements;
  742. const me = m.elements;
  743. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  744. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  745. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  746. return this;
  747. }
  748. extractBasis( xAxis, yAxis, zAxis ) {
  749. xAxis.setFromMatrix3Column( this, 0 );
  750. yAxis.setFromMatrix3Column( this, 1 );
  751. zAxis.setFromMatrix3Column( this, 2 );
  752. return this;
  753. }
  754. setFromMatrix4( m ) {
  755. const me = m.elements;
  756. this.set(
  757. me[ 0 ], me[ 4 ], me[ 8 ],
  758. me[ 1 ], me[ 5 ], me[ 9 ],
  759. me[ 2 ], me[ 6 ], me[ 10 ]
  760. );
  761. return this;
  762. }
  763. multiply( m ) {
  764. return this.multiplyMatrices( this, m );
  765. }
  766. premultiply( m ) {
  767. return this.multiplyMatrices( m, this );
  768. }
  769. multiplyMatrices( a, b ) {
  770. const ae = a.elements;
  771. const be = b.elements;
  772. const te = this.elements;
  773. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  774. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  775. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  776. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  777. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  778. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  779. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  780. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  781. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  782. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  783. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  784. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  785. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  786. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  787. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  788. return this;
  789. }
  790. multiplyScalar( s ) {
  791. const te = this.elements;
  792. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  793. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  794. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  795. return this;
  796. }
  797. determinant() {
  798. const te = this.elements;
  799. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  800. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  801. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  802. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  803. }
  804. invert() {
  805. const te = this.elements,
  806. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  807. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  808. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  809. t11 = n33 * n22 - n32 * n23,
  810. t12 = n32 * n13 - n33 * n12,
  811. t13 = n23 * n12 - n22 * n13,
  812. det = n11 * t11 + n21 * t12 + n31 * t13;
  813. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  814. const detInv = 1 / det;
  815. te[ 0 ] = t11 * detInv;
  816. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  817. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  818. te[ 3 ] = t12 * detInv;
  819. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  820. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  821. te[ 6 ] = t13 * detInv;
  822. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  823. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  824. return this;
  825. }
  826. transpose() {
  827. let tmp;
  828. const m = this.elements;
  829. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  830. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  831. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  832. return this;
  833. }
  834. getNormalMatrix( matrix4 ) {
  835. return this.setFromMatrix4( matrix4 ).invert().transpose();
  836. }
  837. transposeIntoArray( r ) {
  838. const m = this.elements;
  839. r[ 0 ] = m[ 0 ];
  840. r[ 1 ] = m[ 3 ];
  841. r[ 2 ] = m[ 6 ];
  842. r[ 3 ] = m[ 1 ];
  843. r[ 4 ] = m[ 4 ];
  844. r[ 5 ] = m[ 7 ];
  845. r[ 6 ] = m[ 2 ];
  846. r[ 7 ] = m[ 5 ];
  847. r[ 8 ] = m[ 8 ];
  848. return this;
  849. }
  850. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  851. const c = Math.cos( rotation );
  852. const s = Math.sin( rotation );
  853. this.set(
  854. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  855. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  856. 0, 0, 1
  857. );
  858. return this;
  859. }
  860. //
  861. scale( sx, sy ) {
  862. this.premultiply( _m3.makeScale( sx, sy ) );
  863. return this;
  864. }
  865. rotate( theta ) {
  866. this.premultiply( _m3.makeRotation( - theta ) );
  867. return this;
  868. }
  869. translate( tx, ty ) {
  870. this.premultiply( _m3.makeTranslation( tx, ty ) );
  871. return this;
  872. }
  873. // for 2D Transforms
  874. makeTranslation( x, y ) {
  875. if ( x.isVector2 ) {
  876. this.set(
  877. 1, 0, x.x,
  878. 0, 1, x.y,
  879. 0, 0, 1
  880. );
  881. } else {
  882. this.set(
  883. 1, 0, x,
  884. 0, 1, y,
  885. 0, 0, 1
  886. );
  887. }
  888. return this;
  889. }
  890. makeRotation( theta ) {
  891. // counterclockwise
  892. const c = Math.cos( theta );
  893. const s = Math.sin( theta );
  894. this.set(
  895. c, - s, 0,
  896. s, c, 0,
  897. 0, 0, 1
  898. );
  899. return this;
  900. }
  901. makeScale( x, y ) {
  902. this.set(
  903. x, 0, 0,
  904. 0, y, 0,
  905. 0, 0, 1
  906. );
  907. return this;
  908. }
  909. //
  910. equals( matrix ) {
  911. const te = this.elements;
  912. const me = matrix.elements;
  913. for ( let i = 0; i < 9; i ++ ) {
  914. if ( te[ i ] !== me[ i ] ) return false;
  915. }
  916. return true;
  917. }
  918. fromArray( array, offset = 0 ) {
  919. for ( let i = 0; i < 9; i ++ ) {
  920. this.elements[ i ] = array[ i + offset ];
  921. }
  922. return this;
  923. }
  924. toArray( array = [], offset = 0 ) {
  925. const te = this.elements;
  926. array[ offset ] = te[ 0 ];
  927. array[ offset + 1 ] = te[ 1 ];
  928. array[ offset + 2 ] = te[ 2 ];
  929. array[ offset + 3 ] = te[ 3 ];
  930. array[ offset + 4 ] = te[ 4 ];
  931. array[ offset + 5 ] = te[ 5 ];
  932. array[ offset + 6 ] = te[ 6 ];
  933. array[ offset + 7 ] = te[ 7 ];
  934. array[ offset + 8 ] = te[ 8 ];
  935. return array;
  936. }
  937. clone() {
  938. return new this.constructor().fromArray( this.elements );
  939. }
  940. }
  941. const _m3 = /*@__PURE__*/ new Matrix3();
  942. function arrayNeedsUint32( array ) {
  943. // assumes larger values usually on last
  944. for ( let i = array.length - 1; i >= 0; -- i ) {
  945. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  946. }
  947. return false;
  948. }
  949. const TYPED_ARRAYS = {
  950. Int8Array: Int8Array,
  951. Uint8Array: Uint8Array,
  952. Uint8ClampedArray: Uint8ClampedArray,
  953. Int16Array: Int16Array,
  954. Uint16Array: Uint16Array,
  955. Int32Array: Int32Array,
  956. Uint32Array: Uint32Array,
  957. Float32Array: Float32Array,
  958. Float64Array: Float64Array
  959. };
  960. function getTypedArray( type, buffer ) {
  961. return new TYPED_ARRAYS[ type ]( buffer );
  962. }
  963. function createElementNS( name ) {
  964. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  965. }
  966. function createCanvasElement() {
  967. const canvas = createElementNS( 'canvas' );
  968. canvas.style.display = 'block';
  969. return canvas;
  970. }
  971. const _cache = {};
  972. function warnOnce( message ) {
  973. if ( message in _cache ) return;
  974. _cache[ message ] = true;
  975. console.warn( message );
  976. }
  977. /**
  978. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  979. * or clipping. Based on W3C specifications for sRGB and Display P3,
  980. * and ICC specifications for the D50 connection space. Values in/out
  981. * are _linear_ sRGB and _linear_ Display P3.
  982. *
  983. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  984. *
  985. * Reference:
  986. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  987. */
  988. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  989. 0.8224621, 0.177538, 0.0,
  990. 0.0331941, 0.9668058, 0.0,
  991. 0.0170827, 0.0723974, 0.9105199,
  992. );
  993. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  994. 1.2249401, - 0.2249404, 0.0,
  995. - 0.0420569, 1.0420571, 0.0,
  996. - 0.0196376, - 0.0786361, 1.0982735
  997. );
  998. /**
  999. * Defines supported color spaces by transfer function and primaries,
  1000. * and provides conversions to/from the Linear-sRGB reference space.
  1001. */
  1002. const COLOR_SPACES = {
  1003. [ LinearSRGBColorSpace ]: {
  1004. transfer: LinearTransfer,
  1005. primaries: Rec709Primaries,
  1006. toReference: ( color ) => color,
  1007. fromReference: ( color ) => color,
  1008. },
  1009. [ SRGBColorSpace ]: {
  1010. transfer: SRGBTransfer,
  1011. primaries: Rec709Primaries,
  1012. toReference: ( color ) => color.convertSRGBToLinear(),
  1013. fromReference: ( color ) => color.convertLinearToSRGB(),
  1014. },
  1015. [ LinearDisplayP3ColorSpace ]: {
  1016. transfer: LinearTransfer,
  1017. primaries: P3Primaries,
  1018. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1019. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1020. },
  1021. [ DisplayP3ColorSpace ]: {
  1022. transfer: SRGBTransfer,
  1023. primaries: P3Primaries,
  1024. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1025. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1026. },
  1027. };
  1028. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1029. const ColorManagement = {
  1030. enabled: true,
  1031. _workingColorSpace: LinearSRGBColorSpace,
  1032. get workingColorSpace() {
  1033. return this._workingColorSpace;
  1034. },
  1035. set workingColorSpace( colorSpace ) {
  1036. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1037. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1038. }
  1039. this._workingColorSpace = colorSpace;
  1040. },
  1041. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1042. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1043. return color;
  1044. }
  1045. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1046. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1047. return targetFromReference( sourceToReference( color ) );
  1048. },
  1049. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1050. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1051. },
  1052. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1053. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1054. },
  1055. getPrimaries: function ( colorSpace ) {
  1056. return COLOR_SPACES[ colorSpace ].primaries;
  1057. },
  1058. getTransfer: function ( colorSpace ) {
  1059. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1060. return COLOR_SPACES[ colorSpace ].transfer;
  1061. },
  1062. };
  1063. function SRGBToLinear( c ) {
  1064. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1065. }
  1066. function LinearToSRGB( c ) {
  1067. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1068. }
  1069. let _canvas;
  1070. class ImageUtils {
  1071. static getDataURL( image ) {
  1072. if ( /^data:/i.test( image.src ) ) {
  1073. return image.src;
  1074. }
  1075. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1076. return image.src;
  1077. }
  1078. let canvas;
  1079. if ( image instanceof HTMLCanvasElement ) {
  1080. canvas = image;
  1081. } else {
  1082. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1083. _canvas.width = image.width;
  1084. _canvas.height = image.height;
  1085. const context = _canvas.getContext( '2d' );
  1086. if ( image instanceof ImageData ) {
  1087. context.putImageData( image, 0, 0 );
  1088. } else {
  1089. context.drawImage( image, 0, 0, image.width, image.height );
  1090. }
  1091. canvas = _canvas;
  1092. }
  1093. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1094. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1095. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1096. } else {
  1097. return canvas.toDataURL( 'image/png' );
  1098. }
  1099. }
  1100. static sRGBToLinear( image ) {
  1101. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1102. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1103. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1104. const canvas = createElementNS( 'canvas' );
  1105. canvas.width = image.width;
  1106. canvas.height = image.height;
  1107. const context = canvas.getContext( '2d' );
  1108. context.drawImage( image, 0, 0, image.width, image.height );
  1109. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1110. const data = imageData.data;
  1111. for ( let i = 0; i < data.length; i ++ ) {
  1112. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1113. }
  1114. context.putImageData( imageData, 0, 0 );
  1115. return canvas;
  1116. } else if ( image.data ) {
  1117. const data = image.data.slice( 0 );
  1118. for ( let i = 0; i < data.length; i ++ ) {
  1119. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1120. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1121. } else {
  1122. // assuming float
  1123. data[ i ] = SRGBToLinear( data[ i ] );
  1124. }
  1125. }
  1126. return {
  1127. data: data,
  1128. width: image.width,
  1129. height: image.height
  1130. };
  1131. } else {
  1132. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1133. return image;
  1134. }
  1135. }
  1136. }
  1137. let _sourceId = 0;
  1138. class Source {
  1139. constructor( data = null ) {
  1140. this.isSource = true;
  1141. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1142. this.uuid = generateUUID();
  1143. this.data = data;
  1144. this.dataReady = true;
  1145. this.version = 0;
  1146. }
  1147. set needsUpdate( value ) {
  1148. if ( value === true ) this.version ++;
  1149. }
  1150. toJSON( meta ) {
  1151. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1152. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1153. return meta.images[ this.uuid ];
  1154. }
  1155. const output = {
  1156. uuid: this.uuid,
  1157. url: ''
  1158. };
  1159. const data = this.data;
  1160. if ( data !== null ) {
  1161. let url;
  1162. if ( Array.isArray( data ) ) {
  1163. // cube texture
  1164. url = [];
  1165. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1166. if ( data[ i ].isDataTexture ) {
  1167. url.push( serializeImage( data[ i ].image ) );
  1168. } else {
  1169. url.push( serializeImage( data[ i ] ) );
  1170. }
  1171. }
  1172. } else {
  1173. // texture
  1174. url = serializeImage( data );
  1175. }
  1176. output.url = url;
  1177. }
  1178. if ( ! isRootObject ) {
  1179. meta.images[ this.uuid ] = output;
  1180. }
  1181. return output;
  1182. }
  1183. }
  1184. function serializeImage( image ) {
  1185. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1186. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1187. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1188. // default images
  1189. return ImageUtils.getDataURL( image );
  1190. } else {
  1191. if ( image.data ) {
  1192. // images of DataTexture
  1193. return {
  1194. data: Array.from( image.data ),
  1195. width: image.width,
  1196. height: image.height,
  1197. type: image.data.constructor.name
  1198. };
  1199. } else {
  1200. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1201. return {};
  1202. }
  1203. }
  1204. }
  1205. let _textureId = 0;
  1206. class Texture extends EventDispatcher {
  1207. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1208. super();
  1209. this.isTexture = true;
  1210. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1211. this.uuid = generateUUID();
  1212. this.name = '';
  1213. this.source = new Source( image );
  1214. this.mipmaps = [];
  1215. this.mapping = mapping;
  1216. this.channel = 0;
  1217. this.wrapS = wrapS;
  1218. this.wrapT = wrapT;
  1219. this.magFilter = magFilter;
  1220. this.minFilter = minFilter;
  1221. this.anisotropy = anisotropy;
  1222. this.format = format;
  1223. this.internalFormat = null;
  1224. this.type = type;
  1225. this.offset = new Vector2( 0, 0 );
  1226. this.repeat = new Vector2( 1, 1 );
  1227. this.center = new Vector2( 0, 0 );
  1228. this.rotation = 0;
  1229. this.matrixAutoUpdate = true;
  1230. this.matrix = new Matrix3();
  1231. this.generateMipmaps = true;
  1232. this.premultiplyAlpha = false;
  1233. this.flipY = true;
  1234. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1235. this.colorSpace = colorSpace;
  1236. this.userData = {};
  1237. this.version = 0;
  1238. this.onUpdate = null;
  1239. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1240. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1241. }
  1242. get image() {
  1243. return this.source.data;
  1244. }
  1245. set image( value = null ) {
  1246. this.source.data = value;
  1247. }
  1248. updateMatrix() {
  1249. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1250. }
  1251. clone() {
  1252. return new this.constructor().copy( this );
  1253. }
  1254. copy( source ) {
  1255. this.name = source.name;
  1256. this.source = source.source;
  1257. this.mipmaps = source.mipmaps.slice( 0 );
  1258. this.mapping = source.mapping;
  1259. this.channel = source.channel;
  1260. this.wrapS = source.wrapS;
  1261. this.wrapT = source.wrapT;
  1262. this.magFilter = source.magFilter;
  1263. this.minFilter = source.minFilter;
  1264. this.anisotropy = source.anisotropy;
  1265. this.format = source.format;
  1266. this.internalFormat = source.internalFormat;
  1267. this.type = source.type;
  1268. this.offset.copy( source.offset );
  1269. this.repeat.copy( source.repeat );
  1270. this.center.copy( source.center );
  1271. this.rotation = source.rotation;
  1272. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1273. this.matrix.copy( source.matrix );
  1274. this.generateMipmaps = source.generateMipmaps;
  1275. this.premultiplyAlpha = source.premultiplyAlpha;
  1276. this.flipY = source.flipY;
  1277. this.unpackAlignment = source.unpackAlignment;
  1278. this.colorSpace = source.colorSpace;
  1279. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1280. this.needsUpdate = true;
  1281. return this;
  1282. }
  1283. toJSON( meta ) {
  1284. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1285. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1286. return meta.textures[ this.uuid ];
  1287. }
  1288. const output = {
  1289. metadata: {
  1290. version: 4.6,
  1291. type: 'Texture',
  1292. generator: 'Texture.toJSON'
  1293. },
  1294. uuid: this.uuid,
  1295. name: this.name,
  1296. image: this.source.toJSON( meta ).uuid,
  1297. mapping: this.mapping,
  1298. channel: this.channel,
  1299. repeat: [ this.repeat.x, this.repeat.y ],
  1300. offset: [ this.offset.x, this.offset.y ],
  1301. center: [ this.center.x, this.center.y ],
  1302. rotation: this.rotation,
  1303. wrap: [ this.wrapS, this.wrapT ],
  1304. format: this.format,
  1305. internalFormat: this.internalFormat,
  1306. type: this.type,
  1307. colorSpace: this.colorSpace,
  1308. minFilter: this.minFilter,
  1309. magFilter: this.magFilter,
  1310. anisotropy: this.anisotropy,
  1311. flipY: this.flipY,
  1312. generateMipmaps: this.generateMipmaps,
  1313. premultiplyAlpha: this.premultiplyAlpha,
  1314. unpackAlignment: this.unpackAlignment
  1315. };
  1316. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1317. if ( ! isRootObject ) {
  1318. meta.textures[ this.uuid ] = output;
  1319. }
  1320. return output;
  1321. }
  1322. dispose() {
  1323. this.dispatchEvent( { type: 'dispose' } );
  1324. }
  1325. transformUv( uv ) {
  1326. if ( this.mapping !== UVMapping ) return uv;
  1327. uv.applyMatrix3( this.matrix );
  1328. if ( uv.x < 0 || uv.x > 1 ) {
  1329. switch ( this.wrapS ) {
  1330. case RepeatWrapping:
  1331. uv.x = uv.x - Math.floor( uv.x );
  1332. break;
  1333. case ClampToEdgeWrapping:
  1334. uv.x = uv.x < 0 ? 0 : 1;
  1335. break;
  1336. case MirroredRepeatWrapping:
  1337. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1338. uv.x = Math.ceil( uv.x ) - uv.x;
  1339. } else {
  1340. uv.x = uv.x - Math.floor( uv.x );
  1341. }
  1342. break;
  1343. }
  1344. }
  1345. if ( uv.y < 0 || uv.y > 1 ) {
  1346. switch ( this.wrapT ) {
  1347. case RepeatWrapping:
  1348. uv.y = uv.y - Math.floor( uv.y );
  1349. break;
  1350. case ClampToEdgeWrapping:
  1351. uv.y = uv.y < 0 ? 0 : 1;
  1352. break;
  1353. case MirroredRepeatWrapping:
  1354. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1355. uv.y = Math.ceil( uv.y ) - uv.y;
  1356. } else {
  1357. uv.y = uv.y - Math.floor( uv.y );
  1358. }
  1359. break;
  1360. }
  1361. }
  1362. if ( this.flipY ) {
  1363. uv.y = 1 - uv.y;
  1364. }
  1365. return uv;
  1366. }
  1367. set needsUpdate( value ) {
  1368. if ( value === true ) {
  1369. this.version ++;
  1370. this.source.needsUpdate = true;
  1371. }
  1372. }
  1373. set needsPMREMUpdate( value ) {
  1374. if ( value === true ) {
  1375. this.pmremVersion ++;
  1376. }
  1377. }
  1378. }
  1379. Texture.DEFAULT_IMAGE = null;
  1380. Texture.DEFAULT_MAPPING = UVMapping;
  1381. Texture.DEFAULT_ANISOTROPY = 1;
  1382. class Vector4 {
  1383. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1384. Vector4.prototype.isVector4 = true;
  1385. this.x = x;
  1386. this.y = y;
  1387. this.z = z;
  1388. this.w = w;
  1389. }
  1390. get width() {
  1391. return this.z;
  1392. }
  1393. set width( value ) {
  1394. this.z = value;
  1395. }
  1396. get height() {
  1397. return this.w;
  1398. }
  1399. set height( value ) {
  1400. this.w = value;
  1401. }
  1402. set( x, y, z, w ) {
  1403. this.x = x;
  1404. this.y = y;
  1405. this.z = z;
  1406. this.w = w;
  1407. return this;
  1408. }
  1409. setScalar( scalar ) {
  1410. this.x = scalar;
  1411. this.y = scalar;
  1412. this.z = scalar;
  1413. this.w = scalar;
  1414. return this;
  1415. }
  1416. setX( x ) {
  1417. this.x = x;
  1418. return this;
  1419. }
  1420. setY( y ) {
  1421. this.y = y;
  1422. return this;
  1423. }
  1424. setZ( z ) {
  1425. this.z = z;
  1426. return this;
  1427. }
  1428. setW( w ) {
  1429. this.w = w;
  1430. return this;
  1431. }
  1432. setComponent( index, value ) {
  1433. switch ( index ) {
  1434. case 0: this.x = value; break;
  1435. case 1: this.y = value; break;
  1436. case 2: this.z = value; break;
  1437. case 3: this.w = value; break;
  1438. default: throw new Error( 'index is out of range: ' + index );
  1439. }
  1440. return this;
  1441. }
  1442. getComponent( index ) {
  1443. switch ( index ) {
  1444. case 0: return this.x;
  1445. case 1: return this.y;
  1446. case 2: return this.z;
  1447. case 3: return this.w;
  1448. default: throw new Error( 'index is out of range: ' + index );
  1449. }
  1450. }
  1451. clone() {
  1452. return new this.constructor( this.x, this.y, this.z, this.w );
  1453. }
  1454. copy( v ) {
  1455. this.x = v.x;
  1456. this.y = v.y;
  1457. this.z = v.z;
  1458. this.w = ( v.w !== undefined ) ? v.w : 1;
  1459. return this;
  1460. }
  1461. add( v ) {
  1462. this.x += v.x;
  1463. this.y += v.y;
  1464. this.z += v.z;
  1465. this.w += v.w;
  1466. return this;
  1467. }
  1468. addScalar( s ) {
  1469. this.x += s;
  1470. this.y += s;
  1471. this.z += s;
  1472. this.w += s;
  1473. return this;
  1474. }
  1475. addVectors( a, b ) {
  1476. this.x = a.x + b.x;
  1477. this.y = a.y + b.y;
  1478. this.z = a.z + b.z;
  1479. this.w = a.w + b.w;
  1480. return this;
  1481. }
  1482. addScaledVector( v, s ) {
  1483. this.x += v.x * s;
  1484. this.y += v.y * s;
  1485. this.z += v.z * s;
  1486. this.w += v.w * s;
  1487. return this;
  1488. }
  1489. sub( v ) {
  1490. this.x -= v.x;
  1491. this.y -= v.y;
  1492. this.z -= v.z;
  1493. this.w -= v.w;
  1494. return this;
  1495. }
  1496. subScalar( s ) {
  1497. this.x -= s;
  1498. this.y -= s;
  1499. this.z -= s;
  1500. this.w -= s;
  1501. return this;
  1502. }
  1503. subVectors( a, b ) {
  1504. this.x = a.x - b.x;
  1505. this.y = a.y - b.y;
  1506. this.z = a.z - b.z;
  1507. this.w = a.w - b.w;
  1508. return this;
  1509. }
  1510. multiply( v ) {
  1511. this.x *= v.x;
  1512. this.y *= v.y;
  1513. this.z *= v.z;
  1514. this.w *= v.w;
  1515. return this;
  1516. }
  1517. multiplyScalar( scalar ) {
  1518. this.x *= scalar;
  1519. this.y *= scalar;
  1520. this.z *= scalar;
  1521. this.w *= scalar;
  1522. return this;
  1523. }
  1524. applyMatrix4( m ) {
  1525. const x = this.x, y = this.y, z = this.z, w = this.w;
  1526. const e = m.elements;
  1527. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1528. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1529. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1530. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1531. return this;
  1532. }
  1533. divideScalar( scalar ) {
  1534. return this.multiplyScalar( 1 / scalar );
  1535. }
  1536. setAxisAngleFromQuaternion( q ) {
  1537. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1538. // q is assumed to be normalized
  1539. this.w = 2 * Math.acos( q.w );
  1540. const s = Math.sqrt( 1 - q.w * q.w );
  1541. if ( s < 0.0001 ) {
  1542. this.x = 1;
  1543. this.y = 0;
  1544. this.z = 0;
  1545. } else {
  1546. this.x = q.x / s;
  1547. this.y = q.y / s;
  1548. this.z = q.z / s;
  1549. }
  1550. return this;
  1551. }
  1552. setAxisAngleFromRotationMatrix( m ) {
  1553. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1554. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1555. let angle, x, y, z; // variables for result
  1556. const epsilon = 0.01, // margin to allow for rounding errors
  1557. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1558. te = m.elements,
  1559. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1560. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1561. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1562. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1563. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1564. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1565. // singularity found
  1566. // first check for identity matrix which must have +1 for all terms
  1567. // in leading diagonal and zero in other terms
  1568. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1569. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1570. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1571. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1572. // this singularity is identity matrix so angle = 0
  1573. this.set( 1, 0, 0, 0 );
  1574. return this; // zero angle, arbitrary axis
  1575. }
  1576. // otherwise this singularity is angle = 180
  1577. angle = Math.PI;
  1578. const xx = ( m11 + 1 ) / 2;
  1579. const yy = ( m22 + 1 ) / 2;
  1580. const zz = ( m33 + 1 ) / 2;
  1581. const xy = ( m12 + m21 ) / 4;
  1582. const xz = ( m13 + m31 ) / 4;
  1583. const yz = ( m23 + m32 ) / 4;
  1584. if ( ( xx > yy ) && ( xx > zz ) ) {
  1585. // m11 is the largest diagonal term
  1586. if ( xx < epsilon ) {
  1587. x = 0;
  1588. y = 0.707106781;
  1589. z = 0.707106781;
  1590. } else {
  1591. x = Math.sqrt( xx );
  1592. y = xy / x;
  1593. z = xz / x;
  1594. }
  1595. } else if ( yy > zz ) {
  1596. // m22 is the largest diagonal term
  1597. if ( yy < epsilon ) {
  1598. x = 0.707106781;
  1599. y = 0;
  1600. z = 0.707106781;
  1601. } else {
  1602. y = Math.sqrt( yy );
  1603. x = xy / y;
  1604. z = yz / y;
  1605. }
  1606. } else {
  1607. // m33 is the largest diagonal term so base result on this
  1608. if ( zz < epsilon ) {
  1609. x = 0.707106781;
  1610. y = 0.707106781;
  1611. z = 0;
  1612. } else {
  1613. z = Math.sqrt( zz );
  1614. x = xz / z;
  1615. y = yz / z;
  1616. }
  1617. }
  1618. this.set( x, y, z, angle );
  1619. return this; // return 180 deg rotation
  1620. }
  1621. // as we have reached here there are no singularities so we can handle normally
  1622. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1623. ( m13 - m31 ) * ( m13 - m31 ) +
  1624. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1625. if ( Math.abs( s ) < 0.001 ) s = 1;
  1626. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1627. // caught by singularity test above, but I've left it in just in case
  1628. this.x = ( m32 - m23 ) / s;
  1629. this.y = ( m13 - m31 ) / s;
  1630. this.z = ( m21 - m12 ) / s;
  1631. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1632. return this;
  1633. }
  1634. min( v ) {
  1635. this.x = Math.min( this.x, v.x );
  1636. this.y = Math.min( this.y, v.y );
  1637. this.z = Math.min( this.z, v.z );
  1638. this.w = Math.min( this.w, v.w );
  1639. return this;
  1640. }
  1641. max( v ) {
  1642. this.x = Math.max( this.x, v.x );
  1643. this.y = Math.max( this.y, v.y );
  1644. this.z = Math.max( this.z, v.z );
  1645. this.w = Math.max( this.w, v.w );
  1646. return this;
  1647. }
  1648. clamp( min, max ) {
  1649. // assumes min < max, componentwise
  1650. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1651. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1652. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1653. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1654. return this;
  1655. }
  1656. clampScalar( minVal, maxVal ) {
  1657. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1658. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1659. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1660. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1661. return this;
  1662. }
  1663. clampLength( min, max ) {
  1664. const length = this.length();
  1665. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1666. }
  1667. floor() {
  1668. this.x = Math.floor( this.x );
  1669. this.y = Math.floor( this.y );
  1670. this.z = Math.floor( this.z );
  1671. this.w = Math.floor( this.w );
  1672. return this;
  1673. }
  1674. ceil() {
  1675. this.x = Math.ceil( this.x );
  1676. this.y = Math.ceil( this.y );
  1677. this.z = Math.ceil( this.z );
  1678. this.w = Math.ceil( this.w );
  1679. return this;
  1680. }
  1681. round() {
  1682. this.x = Math.round( this.x );
  1683. this.y = Math.round( this.y );
  1684. this.z = Math.round( this.z );
  1685. this.w = Math.round( this.w );
  1686. return this;
  1687. }
  1688. roundToZero() {
  1689. this.x = Math.trunc( this.x );
  1690. this.y = Math.trunc( this.y );
  1691. this.z = Math.trunc( this.z );
  1692. this.w = Math.trunc( this.w );
  1693. return this;
  1694. }
  1695. negate() {
  1696. this.x = - this.x;
  1697. this.y = - this.y;
  1698. this.z = - this.z;
  1699. this.w = - this.w;
  1700. return this;
  1701. }
  1702. dot( v ) {
  1703. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1704. }
  1705. lengthSq() {
  1706. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1707. }
  1708. length() {
  1709. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1710. }
  1711. manhattanLength() {
  1712. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1713. }
  1714. normalize() {
  1715. return this.divideScalar( this.length() || 1 );
  1716. }
  1717. setLength( length ) {
  1718. return this.normalize().multiplyScalar( length );
  1719. }
  1720. lerp( v, alpha ) {
  1721. this.x += ( v.x - this.x ) * alpha;
  1722. this.y += ( v.y - this.y ) * alpha;
  1723. this.z += ( v.z - this.z ) * alpha;
  1724. this.w += ( v.w - this.w ) * alpha;
  1725. return this;
  1726. }
  1727. lerpVectors( v1, v2, alpha ) {
  1728. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1729. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1730. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1731. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1732. return this;
  1733. }
  1734. equals( v ) {
  1735. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1736. }
  1737. fromArray( array, offset = 0 ) {
  1738. this.x = array[ offset ];
  1739. this.y = array[ offset + 1 ];
  1740. this.z = array[ offset + 2 ];
  1741. this.w = array[ offset + 3 ];
  1742. return this;
  1743. }
  1744. toArray( array = [], offset = 0 ) {
  1745. array[ offset ] = this.x;
  1746. array[ offset + 1 ] = this.y;
  1747. array[ offset + 2 ] = this.z;
  1748. array[ offset + 3 ] = this.w;
  1749. return array;
  1750. }
  1751. fromBufferAttribute( attribute, index ) {
  1752. this.x = attribute.getX( index );
  1753. this.y = attribute.getY( index );
  1754. this.z = attribute.getZ( index );
  1755. this.w = attribute.getW( index );
  1756. return this;
  1757. }
  1758. random() {
  1759. this.x = Math.random();
  1760. this.y = Math.random();
  1761. this.z = Math.random();
  1762. this.w = Math.random();
  1763. return this;
  1764. }
  1765. *[ Symbol.iterator ]() {
  1766. yield this.x;
  1767. yield this.y;
  1768. yield this.z;
  1769. yield this.w;
  1770. }
  1771. }
  1772. /*
  1773. In options, we can specify:
  1774. * Texture parameters for an auto-generated target texture
  1775. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1776. */
  1777. class RenderTarget extends EventDispatcher {
  1778. constructor( width = 1, height = 1, options = {} ) {
  1779. super();
  1780. this.isRenderTarget = true;
  1781. this.width = width;
  1782. this.height = height;
  1783. this.depth = 1;
  1784. this.scissor = new Vector4( 0, 0, width, height );
  1785. this.scissorTest = false;
  1786. this.viewport = new Vector4( 0, 0, width, height );
  1787. const image = { width: width, height: height, depth: 1 };
  1788. options = Object.assign( {
  1789. generateMipmaps: false,
  1790. internalFormat: null,
  1791. minFilter: LinearFilter,
  1792. depthBuffer: true,
  1793. stencilBuffer: false,
  1794. depthTexture: null,
  1795. samples: 0,
  1796. count: 1
  1797. }, options );
  1798. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1799. texture.flipY = false;
  1800. texture.generateMipmaps = options.generateMipmaps;
  1801. texture.internalFormat = options.internalFormat;
  1802. this.textures = [];
  1803. const count = options.count;
  1804. for ( let i = 0; i < count; i ++ ) {
  1805. this.textures[ i ] = texture.clone();
  1806. this.textures[ i ].isRenderTargetTexture = true;
  1807. }
  1808. this.depthBuffer = options.depthBuffer;
  1809. this.stencilBuffer = options.stencilBuffer;
  1810. this.depthTexture = options.depthTexture;
  1811. this.samples = options.samples;
  1812. }
  1813. get texture() {
  1814. return this.textures[ 0 ];
  1815. }
  1816. set texture( value ) {
  1817. this.textures[ 0 ] = value;
  1818. }
  1819. setSize( width, height, depth = 1 ) {
  1820. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1821. this.width = width;
  1822. this.height = height;
  1823. this.depth = depth;
  1824. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1825. this.textures[ i ].image.width = width;
  1826. this.textures[ i ].image.height = height;
  1827. this.textures[ i ].image.depth = depth;
  1828. }
  1829. this.dispose();
  1830. }
  1831. this.viewport.set( 0, 0, width, height );
  1832. this.scissor.set( 0, 0, width, height );
  1833. }
  1834. clone() {
  1835. return new this.constructor().copy( this );
  1836. }
  1837. copy( source ) {
  1838. this.width = source.width;
  1839. this.height = source.height;
  1840. this.depth = source.depth;
  1841. this.scissor.copy( source.scissor );
  1842. this.scissorTest = source.scissorTest;
  1843. this.viewport.copy( source.viewport );
  1844. this.textures.length = 0;
  1845. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1846. this.textures[ i ] = source.textures[ i ].clone();
  1847. this.textures[ i ].isRenderTargetTexture = true;
  1848. }
  1849. // ensure image object is not shared, see #20328
  1850. const image = Object.assign( {}, source.texture.image );
  1851. this.texture.source = new Source( image );
  1852. this.depthBuffer = source.depthBuffer;
  1853. this.stencilBuffer = source.stencilBuffer;
  1854. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1855. this.samples = source.samples;
  1856. return this;
  1857. }
  1858. dispose() {
  1859. this.dispatchEvent( { type: 'dispose' } );
  1860. }
  1861. }
  1862. class WebGLRenderTarget extends RenderTarget {
  1863. constructor( width = 1, height = 1, options = {} ) {
  1864. super( width, height, options );
  1865. this.isWebGLRenderTarget = true;
  1866. }
  1867. }
  1868. class DataArrayTexture extends Texture {
  1869. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1870. super( null );
  1871. this.isDataArrayTexture = true;
  1872. this.image = { data, width, height, depth };
  1873. this.magFilter = NearestFilter;
  1874. this.minFilter = NearestFilter;
  1875. this.wrapR = ClampToEdgeWrapping;
  1876. this.generateMipmaps = false;
  1877. this.flipY = false;
  1878. this.unpackAlignment = 1;
  1879. }
  1880. }
  1881. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1882. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1883. super( width, height, options );
  1884. this.isWebGLArrayRenderTarget = true;
  1885. this.depth = depth;
  1886. this.texture = new DataArrayTexture( null, width, height, depth );
  1887. this.texture.isRenderTargetTexture = true;
  1888. }
  1889. }
  1890. class Data3DTexture extends Texture {
  1891. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1892. // We're going to add .setXXX() methods for setting properties later.
  1893. // Users can still set in DataTexture3D directly.
  1894. //
  1895. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1896. // texture.anisotropy = 16;
  1897. //
  1898. // See #14839
  1899. super( null );
  1900. this.isData3DTexture = true;
  1901. this.image = { data, width, height, depth };
  1902. this.magFilter = NearestFilter;
  1903. this.minFilter = NearestFilter;
  1904. this.wrapR = ClampToEdgeWrapping;
  1905. this.generateMipmaps = false;
  1906. this.flipY = false;
  1907. this.unpackAlignment = 1;
  1908. }
  1909. }
  1910. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1911. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1912. super( width, height, options );
  1913. this.isWebGL3DRenderTarget = true;
  1914. this.depth = depth;
  1915. this.texture = new Data3DTexture( null, width, height, depth );
  1916. this.texture.isRenderTargetTexture = true;
  1917. }
  1918. }
  1919. class Quaternion {
  1920. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1921. this.isQuaternion = true;
  1922. this._x = x;
  1923. this._y = y;
  1924. this._z = z;
  1925. this._w = w;
  1926. }
  1927. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1928. // fuzz-free, array-based Quaternion SLERP operation
  1929. let x0 = src0[ srcOffset0 + 0 ],
  1930. y0 = src0[ srcOffset0 + 1 ],
  1931. z0 = src0[ srcOffset0 + 2 ],
  1932. w0 = src0[ srcOffset0 + 3 ];
  1933. const x1 = src1[ srcOffset1 + 0 ],
  1934. y1 = src1[ srcOffset1 + 1 ],
  1935. z1 = src1[ srcOffset1 + 2 ],
  1936. w1 = src1[ srcOffset1 + 3 ];
  1937. if ( t === 0 ) {
  1938. dst[ dstOffset + 0 ] = x0;
  1939. dst[ dstOffset + 1 ] = y0;
  1940. dst[ dstOffset + 2 ] = z0;
  1941. dst[ dstOffset + 3 ] = w0;
  1942. return;
  1943. }
  1944. if ( t === 1 ) {
  1945. dst[ dstOffset + 0 ] = x1;
  1946. dst[ dstOffset + 1 ] = y1;
  1947. dst[ dstOffset + 2 ] = z1;
  1948. dst[ dstOffset + 3 ] = w1;
  1949. return;
  1950. }
  1951. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1952. let s = 1 - t;
  1953. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1954. dir = ( cos >= 0 ? 1 : - 1 ),
  1955. sqrSin = 1 - cos * cos;
  1956. // Skip the Slerp for tiny steps to avoid numeric problems:
  1957. if ( sqrSin > Number.EPSILON ) {
  1958. const sin = Math.sqrt( sqrSin ),
  1959. len = Math.atan2( sin, cos * dir );
  1960. s = Math.sin( s * len ) / sin;
  1961. t = Math.sin( t * len ) / sin;
  1962. }
  1963. const tDir = t * dir;
  1964. x0 = x0 * s + x1 * tDir;
  1965. y0 = y0 * s + y1 * tDir;
  1966. z0 = z0 * s + z1 * tDir;
  1967. w0 = w0 * s + w1 * tDir;
  1968. // Normalize in case we just did a lerp:
  1969. if ( s === 1 - t ) {
  1970. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1971. x0 *= f;
  1972. y0 *= f;
  1973. z0 *= f;
  1974. w0 *= f;
  1975. }
  1976. }
  1977. dst[ dstOffset ] = x0;
  1978. dst[ dstOffset + 1 ] = y0;
  1979. dst[ dstOffset + 2 ] = z0;
  1980. dst[ dstOffset + 3 ] = w0;
  1981. }
  1982. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1983. const x0 = src0[ srcOffset0 ];
  1984. const y0 = src0[ srcOffset0 + 1 ];
  1985. const z0 = src0[ srcOffset0 + 2 ];
  1986. const w0 = src0[ srcOffset0 + 3 ];
  1987. const x1 = src1[ srcOffset1 ];
  1988. const y1 = src1[ srcOffset1 + 1 ];
  1989. const z1 = src1[ srcOffset1 + 2 ];
  1990. const w1 = src1[ srcOffset1 + 3 ];
  1991. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1992. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1993. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1994. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1995. return dst;
  1996. }
  1997. get x() {
  1998. return this._x;
  1999. }
  2000. set x( value ) {
  2001. this._x = value;
  2002. this._onChangeCallback();
  2003. }
  2004. get y() {
  2005. return this._y;
  2006. }
  2007. set y( value ) {
  2008. this._y = value;
  2009. this._onChangeCallback();
  2010. }
  2011. get z() {
  2012. return this._z;
  2013. }
  2014. set z( value ) {
  2015. this._z = value;
  2016. this._onChangeCallback();
  2017. }
  2018. get w() {
  2019. return this._w;
  2020. }
  2021. set w( value ) {
  2022. this._w = value;
  2023. this._onChangeCallback();
  2024. }
  2025. set( x, y, z, w ) {
  2026. this._x = x;
  2027. this._y = y;
  2028. this._z = z;
  2029. this._w = w;
  2030. this._onChangeCallback();
  2031. return this;
  2032. }
  2033. clone() {
  2034. return new this.constructor( this._x, this._y, this._z, this._w );
  2035. }
  2036. copy( quaternion ) {
  2037. this._x = quaternion.x;
  2038. this._y = quaternion.y;
  2039. this._z = quaternion.z;
  2040. this._w = quaternion.w;
  2041. this._onChangeCallback();
  2042. return this;
  2043. }
  2044. setFromEuler( euler, update = true ) {
  2045. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2046. // http://www.mathworks.com/matlabcentral/fileexchange/
  2047. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2048. // content/SpinCalc.m
  2049. const cos = Math.cos;
  2050. const sin = Math.sin;
  2051. const c1 = cos( x / 2 );
  2052. const c2 = cos( y / 2 );
  2053. const c3 = cos( z / 2 );
  2054. const s1 = sin( x / 2 );
  2055. const s2 = sin( y / 2 );
  2056. const s3 = sin( z / 2 );
  2057. switch ( order ) {
  2058. case 'XYZ':
  2059. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2060. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2061. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2062. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2063. break;
  2064. case 'YXZ':
  2065. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2066. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2067. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2068. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2069. break;
  2070. case 'ZXY':
  2071. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2072. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2073. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2074. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2075. break;
  2076. case 'ZYX':
  2077. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2078. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2079. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2080. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2081. break;
  2082. case 'YZX':
  2083. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2084. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2085. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2086. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2087. break;
  2088. case 'XZY':
  2089. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2090. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2091. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2092. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2093. break;
  2094. default:
  2095. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2096. }
  2097. if ( update === true ) this._onChangeCallback();
  2098. return this;
  2099. }
  2100. setFromAxisAngle( axis, angle ) {
  2101. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2102. // assumes axis is normalized
  2103. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2104. this._x = axis.x * s;
  2105. this._y = axis.y * s;
  2106. this._z = axis.z * s;
  2107. this._w = Math.cos( halfAngle );
  2108. this._onChangeCallback();
  2109. return this;
  2110. }
  2111. setFromRotationMatrix( m ) {
  2112. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2113. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2114. const te = m.elements,
  2115. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2116. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2117. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2118. trace = m11 + m22 + m33;
  2119. if ( trace > 0 ) {
  2120. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2121. this._w = 0.25 / s;
  2122. this._x = ( m32 - m23 ) * s;
  2123. this._y = ( m13 - m31 ) * s;
  2124. this._z = ( m21 - m12 ) * s;
  2125. } else if ( m11 > m22 && m11 > m33 ) {
  2126. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2127. this._w = ( m32 - m23 ) / s;
  2128. this._x = 0.25 * s;
  2129. this._y = ( m12 + m21 ) / s;
  2130. this._z = ( m13 + m31 ) / s;
  2131. } else if ( m22 > m33 ) {
  2132. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2133. this._w = ( m13 - m31 ) / s;
  2134. this._x = ( m12 + m21 ) / s;
  2135. this._y = 0.25 * s;
  2136. this._z = ( m23 + m32 ) / s;
  2137. } else {
  2138. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2139. this._w = ( m21 - m12 ) / s;
  2140. this._x = ( m13 + m31 ) / s;
  2141. this._y = ( m23 + m32 ) / s;
  2142. this._z = 0.25 * s;
  2143. }
  2144. this._onChangeCallback();
  2145. return this;
  2146. }
  2147. setFromUnitVectors( vFrom, vTo ) {
  2148. // assumes direction vectors vFrom and vTo are normalized
  2149. let r = vFrom.dot( vTo ) + 1;
  2150. if ( r < Number.EPSILON ) {
  2151. // vFrom and vTo point in opposite directions
  2152. r = 0;
  2153. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2154. this._x = - vFrom.y;
  2155. this._y = vFrom.x;
  2156. this._z = 0;
  2157. this._w = r;
  2158. } else {
  2159. this._x = 0;
  2160. this._y = - vFrom.z;
  2161. this._z = vFrom.y;
  2162. this._w = r;
  2163. }
  2164. } else {
  2165. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2166. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2167. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2168. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2169. this._w = r;
  2170. }
  2171. return this.normalize();
  2172. }
  2173. angleTo( q ) {
  2174. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2175. }
  2176. rotateTowards( q, step ) {
  2177. const angle = this.angleTo( q );
  2178. if ( angle === 0 ) return this;
  2179. const t = Math.min( 1, step / angle );
  2180. this.slerp( q, t );
  2181. return this;
  2182. }
  2183. identity() {
  2184. return this.set( 0, 0, 0, 1 );
  2185. }
  2186. invert() {
  2187. // quaternion is assumed to have unit length
  2188. return this.conjugate();
  2189. }
  2190. conjugate() {
  2191. this._x *= - 1;
  2192. this._y *= - 1;
  2193. this._z *= - 1;
  2194. this._onChangeCallback();
  2195. return this;
  2196. }
  2197. dot( v ) {
  2198. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2199. }
  2200. lengthSq() {
  2201. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2202. }
  2203. length() {
  2204. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2205. }
  2206. normalize() {
  2207. let l = this.length();
  2208. if ( l === 0 ) {
  2209. this._x = 0;
  2210. this._y = 0;
  2211. this._z = 0;
  2212. this._w = 1;
  2213. } else {
  2214. l = 1 / l;
  2215. this._x = this._x * l;
  2216. this._y = this._y * l;
  2217. this._z = this._z * l;
  2218. this._w = this._w * l;
  2219. }
  2220. this._onChangeCallback();
  2221. return this;
  2222. }
  2223. multiply( q ) {
  2224. return this.multiplyQuaternions( this, q );
  2225. }
  2226. premultiply( q ) {
  2227. return this.multiplyQuaternions( q, this );
  2228. }
  2229. multiplyQuaternions( a, b ) {
  2230. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2231. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2232. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2233. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2234. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2235. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2236. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2237. this._onChangeCallback();
  2238. return this;
  2239. }
  2240. slerp( qb, t ) {
  2241. if ( t === 0 ) return this;
  2242. if ( t === 1 ) return this.copy( qb );
  2243. const x = this._x, y = this._y, z = this._z, w = this._w;
  2244. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2245. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2246. if ( cosHalfTheta < 0 ) {
  2247. this._w = - qb._w;
  2248. this._x = - qb._x;
  2249. this._y = - qb._y;
  2250. this._z = - qb._z;
  2251. cosHalfTheta = - cosHalfTheta;
  2252. } else {
  2253. this.copy( qb );
  2254. }
  2255. if ( cosHalfTheta >= 1.0 ) {
  2256. this._w = w;
  2257. this._x = x;
  2258. this._y = y;
  2259. this._z = z;
  2260. return this;
  2261. }
  2262. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2263. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2264. const s = 1 - t;
  2265. this._w = s * w + t * this._w;
  2266. this._x = s * x + t * this._x;
  2267. this._y = s * y + t * this._y;
  2268. this._z = s * z + t * this._z;
  2269. this.normalize(); // normalize calls _onChangeCallback()
  2270. return this;
  2271. }
  2272. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2273. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2274. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2275. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2276. this._w = ( w * ratioA + this._w * ratioB );
  2277. this._x = ( x * ratioA + this._x * ratioB );
  2278. this._y = ( y * ratioA + this._y * ratioB );
  2279. this._z = ( z * ratioA + this._z * ratioB );
  2280. this._onChangeCallback();
  2281. return this;
  2282. }
  2283. slerpQuaternions( qa, qb, t ) {
  2284. return this.copy( qa ).slerp( qb, t );
  2285. }
  2286. random() {
  2287. // sets this quaternion to a uniform random unit quaternnion
  2288. // Ken Shoemake
  2289. // Uniform random rotations
  2290. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2291. const theta1 = 2 * Math.PI * Math.random();
  2292. const theta2 = 2 * Math.PI * Math.random();
  2293. const x0 = Math.random();
  2294. const r1 = Math.sqrt( 1 - x0 );
  2295. const r2 = Math.sqrt( x0 );
  2296. return this.set(
  2297. r1 * Math.sin( theta1 ),
  2298. r1 * Math.cos( theta1 ),
  2299. r2 * Math.sin( theta2 ),
  2300. r2 * Math.cos( theta2 ),
  2301. );
  2302. }
  2303. equals( quaternion ) {
  2304. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2305. }
  2306. fromArray( array, offset = 0 ) {
  2307. this._x = array[ offset ];
  2308. this._y = array[ offset + 1 ];
  2309. this._z = array[ offset + 2 ];
  2310. this._w = array[ offset + 3 ];
  2311. this._onChangeCallback();
  2312. return this;
  2313. }
  2314. toArray( array = [], offset = 0 ) {
  2315. array[ offset ] = this._x;
  2316. array[ offset + 1 ] = this._y;
  2317. array[ offset + 2 ] = this._z;
  2318. array[ offset + 3 ] = this._w;
  2319. return array;
  2320. }
  2321. fromBufferAttribute( attribute, index ) {
  2322. this._x = attribute.getX( index );
  2323. this._y = attribute.getY( index );
  2324. this._z = attribute.getZ( index );
  2325. this._w = attribute.getW( index );
  2326. this._onChangeCallback();
  2327. return this;
  2328. }
  2329. toJSON() {
  2330. return this.toArray();
  2331. }
  2332. _onChange( callback ) {
  2333. this._onChangeCallback = callback;
  2334. return this;
  2335. }
  2336. _onChangeCallback() {}
  2337. *[ Symbol.iterator ]() {
  2338. yield this._x;
  2339. yield this._y;
  2340. yield this._z;
  2341. yield this._w;
  2342. }
  2343. }
  2344. class Vector3 {
  2345. constructor( x = 0, y = 0, z = 0 ) {
  2346. Vector3.prototype.isVector3 = true;
  2347. this.x = x;
  2348. this.y = y;
  2349. this.z = z;
  2350. }
  2351. set( x, y, z ) {
  2352. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2353. this.x = x;
  2354. this.y = y;
  2355. this.z = z;
  2356. return this;
  2357. }
  2358. setScalar( scalar ) {
  2359. this.x = scalar;
  2360. this.y = scalar;
  2361. this.z = scalar;
  2362. return this;
  2363. }
  2364. setX( x ) {
  2365. this.x = x;
  2366. return this;
  2367. }
  2368. setY( y ) {
  2369. this.y = y;
  2370. return this;
  2371. }
  2372. setZ( z ) {
  2373. this.z = z;
  2374. return this;
  2375. }
  2376. setComponent( index, value ) {
  2377. switch ( index ) {
  2378. case 0: this.x = value; break;
  2379. case 1: this.y = value; break;
  2380. case 2: this.z = value; break;
  2381. default: throw new Error( 'index is out of range: ' + index );
  2382. }
  2383. return this;
  2384. }
  2385. getComponent( index ) {
  2386. switch ( index ) {
  2387. case 0: return this.x;
  2388. case 1: return this.y;
  2389. case 2: return this.z;
  2390. default: throw new Error( 'index is out of range: ' + index );
  2391. }
  2392. }
  2393. clone() {
  2394. return new this.constructor( this.x, this.y, this.z );
  2395. }
  2396. copy( v ) {
  2397. this.x = v.x;
  2398. this.y = v.y;
  2399. this.z = v.z;
  2400. return this;
  2401. }
  2402. add( v ) {
  2403. this.x += v.x;
  2404. this.y += v.y;
  2405. this.z += v.z;
  2406. return this;
  2407. }
  2408. addScalar( s ) {
  2409. this.x += s;
  2410. this.y += s;
  2411. this.z += s;
  2412. return this;
  2413. }
  2414. addVectors( a, b ) {
  2415. this.x = a.x + b.x;
  2416. this.y = a.y + b.y;
  2417. this.z = a.z + b.z;
  2418. return this;
  2419. }
  2420. addScaledVector( v, s ) {
  2421. this.x += v.x * s;
  2422. this.y += v.y * s;
  2423. this.z += v.z * s;
  2424. return this;
  2425. }
  2426. sub( v ) {
  2427. this.x -= v.x;
  2428. this.y -= v.y;
  2429. this.z -= v.z;
  2430. return this;
  2431. }
  2432. subScalar( s ) {
  2433. this.x -= s;
  2434. this.y -= s;
  2435. this.z -= s;
  2436. return this;
  2437. }
  2438. subVectors( a, b ) {
  2439. this.x = a.x - b.x;
  2440. this.y = a.y - b.y;
  2441. this.z = a.z - b.z;
  2442. return this;
  2443. }
  2444. multiply( v ) {
  2445. this.x *= v.x;
  2446. this.y *= v.y;
  2447. this.z *= v.z;
  2448. return this;
  2449. }
  2450. multiplyScalar( scalar ) {
  2451. this.x *= scalar;
  2452. this.y *= scalar;
  2453. this.z *= scalar;
  2454. return this;
  2455. }
  2456. multiplyVectors( a, b ) {
  2457. this.x = a.x * b.x;
  2458. this.y = a.y * b.y;
  2459. this.z = a.z * b.z;
  2460. return this;
  2461. }
  2462. applyEuler( euler ) {
  2463. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2464. }
  2465. applyAxisAngle( axis, angle ) {
  2466. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2467. }
  2468. applyMatrix3( m ) {
  2469. const x = this.x, y = this.y, z = this.z;
  2470. const e = m.elements;
  2471. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2472. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2473. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2474. return this;
  2475. }
  2476. applyNormalMatrix( m ) {
  2477. return this.applyMatrix3( m ).normalize();
  2478. }
  2479. applyMatrix4( m ) {
  2480. const x = this.x, y = this.y, z = this.z;
  2481. const e = m.elements;
  2482. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2483. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2484. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2485. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2486. return this;
  2487. }
  2488. applyQuaternion( q ) {
  2489. // quaternion q is assumed to have unit length
  2490. const vx = this.x, vy = this.y, vz = this.z;
  2491. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2492. // t = 2 * cross( q.xyz, v );
  2493. const tx = 2 * ( qy * vz - qz * vy );
  2494. const ty = 2 * ( qz * vx - qx * vz );
  2495. const tz = 2 * ( qx * vy - qy * vx );
  2496. // v + q.w * t + cross( q.xyz, t );
  2497. this.x = vx + qw * tx + qy * tz - qz * ty;
  2498. this.y = vy + qw * ty + qz * tx - qx * tz;
  2499. this.z = vz + qw * tz + qx * ty - qy * tx;
  2500. return this;
  2501. }
  2502. project( camera ) {
  2503. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2504. }
  2505. unproject( camera ) {
  2506. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2507. }
  2508. transformDirection( m ) {
  2509. // input: THREE.Matrix4 affine matrix
  2510. // vector interpreted as a direction
  2511. const x = this.x, y = this.y, z = this.z;
  2512. const e = m.elements;
  2513. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2514. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2515. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2516. return this.normalize();
  2517. }
  2518. divide( v ) {
  2519. this.x /= v.x;
  2520. this.y /= v.y;
  2521. this.z /= v.z;
  2522. return this;
  2523. }
  2524. divideScalar( scalar ) {
  2525. return this.multiplyScalar( 1 / scalar );
  2526. }
  2527. min( v ) {
  2528. this.x = Math.min( this.x, v.x );
  2529. this.y = Math.min( this.y, v.y );
  2530. this.z = Math.min( this.z, v.z );
  2531. return this;
  2532. }
  2533. max( v ) {
  2534. this.x = Math.max( this.x, v.x );
  2535. this.y = Math.max( this.y, v.y );
  2536. this.z = Math.max( this.z, v.z );
  2537. return this;
  2538. }
  2539. clamp( min, max ) {
  2540. // assumes min < max, componentwise
  2541. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2542. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2543. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2544. return this;
  2545. }
  2546. clampScalar( minVal, maxVal ) {
  2547. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2548. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2549. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2550. return this;
  2551. }
  2552. clampLength( min, max ) {
  2553. const length = this.length();
  2554. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2555. }
  2556. floor() {
  2557. this.x = Math.floor( this.x );
  2558. this.y = Math.floor( this.y );
  2559. this.z = Math.floor( this.z );
  2560. return this;
  2561. }
  2562. ceil() {
  2563. this.x = Math.ceil( this.x );
  2564. this.y = Math.ceil( this.y );
  2565. this.z = Math.ceil( this.z );
  2566. return this;
  2567. }
  2568. round() {
  2569. this.x = Math.round( this.x );
  2570. this.y = Math.round( this.y );
  2571. this.z = Math.round( this.z );
  2572. return this;
  2573. }
  2574. roundToZero() {
  2575. this.x = Math.trunc( this.x );
  2576. this.y = Math.trunc( this.y );
  2577. this.z = Math.trunc( this.z );
  2578. return this;
  2579. }
  2580. negate() {
  2581. this.x = - this.x;
  2582. this.y = - this.y;
  2583. this.z = - this.z;
  2584. return this;
  2585. }
  2586. dot( v ) {
  2587. return this.x * v.x + this.y * v.y + this.z * v.z;
  2588. }
  2589. // TODO lengthSquared?
  2590. lengthSq() {
  2591. return this.x * this.x + this.y * this.y + this.z * this.z;
  2592. }
  2593. length() {
  2594. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2595. }
  2596. manhattanLength() {
  2597. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2598. }
  2599. normalize() {
  2600. return this.divideScalar( this.length() || 1 );
  2601. }
  2602. setLength( length ) {
  2603. return this.normalize().multiplyScalar( length );
  2604. }
  2605. lerp( v, alpha ) {
  2606. this.x += ( v.x - this.x ) * alpha;
  2607. this.y += ( v.y - this.y ) * alpha;
  2608. this.z += ( v.z - this.z ) * alpha;
  2609. return this;
  2610. }
  2611. lerpVectors( v1, v2, alpha ) {
  2612. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2613. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2614. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2615. return this;
  2616. }
  2617. cross( v ) {
  2618. return this.crossVectors( this, v );
  2619. }
  2620. crossVectors( a, b ) {
  2621. const ax = a.x, ay = a.y, az = a.z;
  2622. const bx = b.x, by = b.y, bz = b.z;
  2623. this.x = ay * bz - az * by;
  2624. this.y = az * bx - ax * bz;
  2625. this.z = ax * by - ay * bx;
  2626. return this;
  2627. }
  2628. projectOnVector( v ) {
  2629. const denominator = v.lengthSq();
  2630. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2631. const scalar = v.dot( this ) / denominator;
  2632. return this.copy( v ).multiplyScalar( scalar );
  2633. }
  2634. projectOnPlane( planeNormal ) {
  2635. _vector$c.copy( this ).projectOnVector( planeNormal );
  2636. return this.sub( _vector$c );
  2637. }
  2638. reflect( normal ) {
  2639. // reflect incident vector off plane orthogonal to normal
  2640. // normal is assumed to have unit length
  2641. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2642. }
  2643. angleTo( v ) {
  2644. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2645. if ( denominator === 0 ) return Math.PI / 2;
  2646. const theta = this.dot( v ) / denominator;
  2647. // clamp, to handle numerical problems
  2648. return Math.acos( clamp( theta, - 1, 1 ) );
  2649. }
  2650. distanceTo( v ) {
  2651. return Math.sqrt( this.distanceToSquared( v ) );
  2652. }
  2653. distanceToSquared( v ) {
  2654. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2655. return dx * dx + dy * dy + dz * dz;
  2656. }
  2657. manhattanDistanceTo( v ) {
  2658. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2659. }
  2660. setFromSpherical( s ) {
  2661. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2662. }
  2663. setFromSphericalCoords( radius, phi, theta ) {
  2664. const sinPhiRadius = Math.sin( phi ) * radius;
  2665. this.x = sinPhiRadius * Math.sin( theta );
  2666. this.y = Math.cos( phi ) * radius;
  2667. this.z = sinPhiRadius * Math.cos( theta );
  2668. return this;
  2669. }
  2670. setFromCylindrical( c ) {
  2671. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2672. }
  2673. setFromCylindricalCoords( radius, theta, y ) {
  2674. this.x = radius * Math.sin( theta );
  2675. this.y = y;
  2676. this.z = radius * Math.cos( theta );
  2677. return this;
  2678. }
  2679. setFromMatrixPosition( m ) {
  2680. const e = m.elements;
  2681. this.x = e[ 12 ];
  2682. this.y = e[ 13 ];
  2683. this.z = e[ 14 ];
  2684. return this;
  2685. }
  2686. setFromMatrixScale( m ) {
  2687. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2688. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2689. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2690. this.x = sx;
  2691. this.y = sy;
  2692. this.z = sz;
  2693. return this;
  2694. }
  2695. setFromMatrixColumn( m, index ) {
  2696. return this.fromArray( m.elements, index * 4 );
  2697. }
  2698. setFromMatrix3Column( m, index ) {
  2699. return this.fromArray( m.elements, index * 3 );
  2700. }
  2701. setFromEuler( e ) {
  2702. this.x = e._x;
  2703. this.y = e._y;
  2704. this.z = e._z;
  2705. return this;
  2706. }
  2707. setFromColor( c ) {
  2708. this.x = c.r;
  2709. this.y = c.g;
  2710. this.z = c.b;
  2711. return this;
  2712. }
  2713. equals( v ) {
  2714. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2715. }
  2716. fromArray( array, offset = 0 ) {
  2717. this.x = array[ offset ];
  2718. this.y = array[ offset + 1 ];
  2719. this.z = array[ offset + 2 ];
  2720. return this;
  2721. }
  2722. toArray( array = [], offset = 0 ) {
  2723. array[ offset ] = this.x;
  2724. array[ offset + 1 ] = this.y;
  2725. array[ offset + 2 ] = this.z;
  2726. return array;
  2727. }
  2728. fromBufferAttribute( attribute, index ) {
  2729. this.x = attribute.getX( index );
  2730. this.y = attribute.getY( index );
  2731. this.z = attribute.getZ( index );
  2732. return this;
  2733. }
  2734. random() {
  2735. this.x = Math.random();
  2736. this.y = Math.random();
  2737. this.z = Math.random();
  2738. return this;
  2739. }
  2740. randomDirection() {
  2741. // https://mathworld.wolfram.com/SpherePointPicking.html
  2742. const theta = Math.random() * Math.PI * 2;
  2743. const u = Math.random() * 2 - 1;
  2744. const c = Math.sqrt( 1 - u * u );
  2745. this.x = c * Math.cos( theta );
  2746. this.y = u;
  2747. this.z = c * Math.sin( theta );
  2748. return this;
  2749. }
  2750. *[ Symbol.iterator ]() {
  2751. yield this.x;
  2752. yield this.y;
  2753. yield this.z;
  2754. }
  2755. }
  2756. const _vector$c = /*@__PURE__*/ new Vector3();
  2757. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2758. class Box3 {
  2759. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2760. this.isBox3 = true;
  2761. this.min = min;
  2762. this.max = max;
  2763. }
  2764. set( min, max ) {
  2765. this.min.copy( min );
  2766. this.max.copy( max );
  2767. return this;
  2768. }
  2769. setFromArray( array ) {
  2770. this.makeEmpty();
  2771. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2772. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2773. }
  2774. return this;
  2775. }
  2776. setFromBufferAttribute( attribute ) {
  2777. this.makeEmpty();
  2778. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2779. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2780. }
  2781. return this;
  2782. }
  2783. setFromPoints( points ) {
  2784. this.makeEmpty();
  2785. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2786. this.expandByPoint( points[ i ] );
  2787. }
  2788. return this;
  2789. }
  2790. setFromCenterAndSize( center, size ) {
  2791. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2792. this.min.copy( center ).sub( halfSize );
  2793. this.max.copy( center ).add( halfSize );
  2794. return this;
  2795. }
  2796. setFromObject( object, precise = false ) {
  2797. this.makeEmpty();
  2798. return this.expandByObject( object, precise );
  2799. }
  2800. clone() {
  2801. return new this.constructor().copy( this );
  2802. }
  2803. copy( box ) {
  2804. this.min.copy( box.min );
  2805. this.max.copy( box.max );
  2806. return this;
  2807. }
  2808. makeEmpty() {
  2809. this.min.x = this.min.y = this.min.z = + Infinity;
  2810. this.max.x = this.max.y = this.max.z = - Infinity;
  2811. return this;
  2812. }
  2813. isEmpty() {
  2814. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2815. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2816. }
  2817. getCenter( target ) {
  2818. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2819. }
  2820. getSize( target ) {
  2821. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2822. }
  2823. expandByPoint( point ) {
  2824. this.min.min( point );
  2825. this.max.max( point );
  2826. return this;
  2827. }
  2828. expandByVector( vector ) {
  2829. this.min.sub( vector );
  2830. this.max.add( vector );
  2831. return this;
  2832. }
  2833. expandByScalar( scalar ) {
  2834. this.min.addScalar( - scalar );
  2835. this.max.addScalar( scalar );
  2836. return this;
  2837. }
  2838. expandByObject( object, precise = false ) {
  2839. // Computes the world-axis-aligned bounding box of an object (including its children),
  2840. // accounting for both the object's, and children's, world transforms
  2841. object.updateWorldMatrix( false, false );
  2842. const geometry = object.geometry;
  2843. if ( geometry !== undefined ) {
  2844. const positionAttribute = geometry.getAttribute( 'position' );
  2845. // precise AABB computation based on vertex data requires at least a position attribute.
  2846. // instancing isn't supported so far and uses the normal (conservative) code path.
  2847. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2848. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2849. if ( object.isMesh === true ) {
  2850. object.getVertexPosition( i, _vector$b );
  2851. } else {
  2852. _vector$b.fromBufferAttribute( positionAttribute, i );
  2853. }
  2854. _vector$b.applyMatrix4( object.matrixWorld );
  2855. this.expandByPoint( _vector$b );
  2856. }
  2857. } else {
  2858. if ( object.boundingBox !== undefined ) {
  2859. // object-level bounding box
  2860. if ( object.boundingBox === null ) {
  2861. object.computeBoundingBox();
  2862. }
  2863. _box$4.copy( object.boundingBox );
  2864. } else {
  2865. // geometry-level bounding box
  2866. if ( geometry.boundingBox === null ) {
  2867. geometry.computeBoundingBox();
  2868. }
  2869. _box$4.copy( geometry.boundingBox );
  2870. }
  2871. _box$4.applyMatrix4( object.matrixWorld );
  2872. this.union( _box$4 );
  2873. }
  2874. }
  2875. const children = object.children;
  2876. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2877. this.expandByObject( children[ i ], precise );
  2878. }
  2879. return this;
  2880. }
  2881. containsPoint( point ) {
  2882. return point.x < this.min.x || point.x > this.max.x ||
  2883. point.y < this.min.y || point.y > this.max.y ||
  2884. point.z < this.min.z || point.z > this.max.z ? false : true;
  2885. }
  2886. containsBox( box ) {
  2887. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2888. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2889. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2890. }
  2891. getParameter( point, target ) {
  2892. // This can potentially have a divide by zero if the box
  2893. // has a size dimension of 0.
  2894. return target.set(
  2895. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2896. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2897. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2898. );
  2899. }
  2900. intersectsBox( box ) {
  2901. // using 6 splitting planes to rule out intersections.
  2902. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2903. box.max.y < this.min.y || box.min.y > this.max.y ||
  2904. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2905. }
  2906. intersectsSphere( sphere ) {
  2907. // Find the point on the AABB closest to the sphere center.
  2908. this.clampPoint( sphere.center, _vector$b );
  2909. // If that point is inside the sphere, the AABB and sphere intersect.
  2910. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2911. }
  2912. intersectsPlane( plane ) {
  2913. // We compute the minimum and maximum dot product values. If those values
  2914. // are on the same side (back or front) of the plane, then there is no intersection.
  2915. let min, max;
  2916. if ( plane.normal.x > 0 ) {
  2917. min = plane.normal.x * this.min.x;
  2918. max = plane.normal.x * this.max.x;
  2919. } else {
  2920. min = plane.normal.x * this.max.x;
  2921. max = plane.normal.x * this.min.x;
  2922. }
  2923. if ( plane.normal.y > 0 ) {
  2924. min += plane.normal.y * this.min.y;
  2925. max += plane.normal.y * this.max.y;
  2926. } else {
  2927. min += plane.normal.y * this.max.y;
  2928. max += plane.normal.y * this.min.y;
  2929. }
  2930. if ( plane.normal.z > 0 ) {
  2931. min += plane.normal.z * this.min.z;
  2932. max += plane.normal.z * this.max.z;
  2933. } else {
  2934. min += plane.normal.z * this.max.z;
  2935. max += plane.normal.z * this.min.z;
  2936. }
  2937. return ( min <= - plane.constant && max >= - plane.constant );
  2938. }
  2939. intersectsTriangle( triangle ) {
  2940. if ( this.isEmpty() ) {
  2941. return false;
  2942. }
  2943. // compute box center and extents
  2944. this.getCenter( _center );
  2945. _extents.subVectors( this.max, _center );
  2946. // translate triangle to aabb origin
  2947. _v0$2.subVectors( triangle.a, _center );
  2948. _v1$7.subVectors( triangle.b, _center );
  2949. _v2$4.subVectors( triangle.c, _center );
  2950. // compute edge vectors for triangle
  2951. _f0.subVectors( _v1$7, _v0$2 );
  2952. _f1.subVectors( _v2$4, _v1$7 );
  2953. _f2.subVectors( _v0$2, _v2$4 );
  2954. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2955. // 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
  2956. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2957. let axes = [
  2958. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2959. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2960. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2961. ];
  2962. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2963. return false;
  2964. }
  2965. // test 3 face normals from the aabb
  2966. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2967. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2968. return false;
  2969. }
  2970. // finally testing the face normal of the triangle
  2971. // use already existing triangle edge vectors here
  2972. _triangleNormal.crossVectors( _f0, _f1 );
  2973. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2974. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2975. }
  2976. clampPoint( point, target ) {
  2977. return target.copy( point ).clamp( this.min, this.max );
  2978. }
  2979. distanceToPoint( point ) {
  2980. return this.clampPoint( point, _vector$b ).distanceTo( point );
  2981. }
  2982. getBoundingSphere( target ) {
  2983. if ( this.isEmpty() ) {
  2984. target.makeEmpty();
  2985. } else {
  2986. this.getCenter( target.center );
  2987. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2988. }
  2989. return target;
  2990. }
  2991. intersect( box ) {
  2992. this.min.max( box.min );
  2993. this.max.min( box.max );
  2994. // 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.
  2995. if ( this.isEmpty() ) this.makeEmpty();
  2996. return this;
  2997. }
  2998. union( box ) {
  2999. this.min.min( box.min );
  3000. this.max.max( box.max );
  3001. return this;
  3002. }
  3003. applyMatrix4( matrix ) {
  3004. // transform of empty box is an empty box.
  3005. if ( this.isEmpty() ) return this;
  3006. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3007. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3008. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3009. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3010. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3011. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3012. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3013. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3014. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3015. this.setFromPoints( _points );
  3016. return this;
  3017. }
  3018. translate( offset ) {
  3019. this.min.add( offset );
  3020. this.max.add( offset );
  3021. return this;
  3022. }
  3023. equals( box ) {
  3024. return box.min.equals( this.min ) && box.max.equals( this.max );
  3025. }
  3026. }
  3027. const _points = [
  3028. /*@__PURE__*/ new Vector3(),
  3029. /*@__PURE__*/ new Vector3(),
  3030. /*@__PURE__*/ new Vector3(),
  3031. /*@__PURE__*/ new Vector3(),
  3032. /*@__PURE__*/ new Vector3(),
  3033. /*@__PURE__*/ new Vector3(),
  3034. /*@__PURE__*/ new Vector3(),
  3035. /*@__PURE__*/ new Vector3()
  3036. ];
  3037. const _vector$b = /*@__PURE__*/ new Vector3();
  3038. const _box$4 = /*@__PURE__*/ new Box3();
  3039. // triangle centered vertices
  3040. const _v0$2 = /*@__PURE__*/ new Vector3();
  3041. const _v1$7 = /*@__PURE__*/ new Vector3();
  3042. const _v2$4 = /*@__PURE__*/ new Vector3();
  3043. // triangle edge vectors
  3044. const _f0 = /*@__PURE__*/ new Vector3();
  3045. const _f1 = /*@__PURE__*/ new Vector3();
  3046. const _f2 = /*@__PURE__*/ new Vector3();
  3047. const _center = /*@__PURE__*/ new Vector3();
  3048. const _extents = /*@__PURE__*/ new Vector3();
  3049. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3050. const _testAxis = /*@__PURE__*/ new Vector3();
  3051. function satForAxes( axes, v0, v1, v2, extents ) {
  3052. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3053. _testAxis.fromArray( axes, i );
  3054. // project the aabb onto the separating axis
  3055. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3056. // project all 3 vertices of the triangle onto the separating axis
  3057. const p0 = v0.dot( _testAxis );
  3058. const p1 = v1.dot( _testAxis );
  3059. const p2 = v2.dot( _testAxis );
  3060. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3061. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3062. // points of the projected triangle are outside the projected half-length of the aabb
  3063. // the axis is separating and we can exit
  3064. return false;
  3065. }
  3066. }
  3067. return true;
  3068. }
  3069. const _box$3 = /*@__PURE__*/ new Box3();
  3070. const _v1$6 = /*@__PURE__*/ new Vector3();
  3071. const _v2$3 = /*@__PURE__*/ new Vector3();
  3072. class Sphere {
  3073. constructor( center = new Vector3(), radius = - 1 ) {
  3074. this.isSphere = true;
  3075. this.center = center;
  3076. this.radius = radius;
  3077. }
  3078. set( center, radius ) {
  3079. this.center.copy( center );
  3080. this.radius = radius;
  3081. return this;
  3082. }
  3083. setFromPoints( points, optionalCenter ) {
  3084. const center = this.center;
  3085. if ( optionalCenter !== undefined ) {
  3086. center.copy( optionalCenter );
  3087. } else {
  3088. _box$3.setFromPoints( points ).getCenter( center );
  3089. }
  3090. let maxRadiusSq = 0;
  3091. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3092. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3093. }
  3094. this.radius = Math.sqrt( maxRadiusSq );
  3095. return this;
  3096. }
  3097. copy( sphere ) {
  3098. this.center.copy( sphere.center );
  3099. this.radius = sphere.radius;
  3100. return this;
  3101. }
  3102. isEmpty() {
  3103. return ( this.radius < 0 );
  3104. }
  3105. makeEmpty() {
  3106. this.center.set( 0, 0, 0 );
  3107. this.radius = - 1;
  3108. return this;
  3109. }
  3110. containsPoint( point ) {
  3111. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3112. }
  3113. distanceToPoint( point ) {
  3114. return ( point.distanceTo( this.center ) - this.radius );
  3115. }
  3116. intersectsSphere( sphere ) {
  3117. const radiusSum = this.radius + sphere.radius;
  3118. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3119. }
  3120. intersectsBox( box ) {
  3121. return box.intersectsSphere( this );
  3122. }
  3123. intersectsPlane( plane ) {
  3124. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3125. }
  3126. clampPoint( point, target ) {
  3127. const deltaLengthSq = this.center.distanceToSquared( point );
  3128. target.copy( point );
  3129. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3130. target.sub( this.center ).normalize();
  3131. target.multiplyScalar( this.radius ).add( this.center );
  3132. }
  3133. return target;
  3134. }
  3135. getBoundingBox( target ) {
  3136. if ( this.isEmpty() ) {
  3137. // Empty sphere produces empty bounding box
  3138. target.makeEmpty();
  3139. return target;
  3140. }
  3141. target.set( this.center, this.center );
  3142. target.expandByScalar( this.radius );
  3143. return target;
  3144. }
  3145. applyMatrix4( matrix ) {
  3146. this.center.applyMatrix4( matrix );
  3147. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3148. return this;
  3149. }
  3150. translate( offset ) {
  3151. this.center.add( offset );
  3152. return this;
  3153. }
  3154. expandByPoint( point ) {
  3155. if ( this.isEmpty() ) {
  3156. this.center.copy( point );
  3157. this.radius = 0;
  3158. return this;
  3159. }
  3160. _v1$6.subVectors( point, this.center );
  3161. const lengthSq = _v1$6.lengthSq();
  3162. if ( lengthSq > ( this.radius * this.radius ) ) {
  3163. // calculate the minimal sphere
  3164. const length = Math.sqrt( lengthSq );
  3165. const delta = ( length - this.radius ) * 0.5;
  3166. this.center.addScaledVector( _v1$6, delta / length );
  3167. this.radius += delta;
  3168. }
  3169. return this;
  3170. }
  3171. union( sphere ) {
  3172. if ( sphere.isEmpty() ) {
  3173. return this;
  3174. }
  3175. if ( this.isEmpty() ) {
  3176. this.copy( sphere );
  3177. return this;
  3178. }
  3179. if ( this.center.equals( sphere.center ) === true ) {
  3180. this.radius = Math.max( this.radius, sphere.radius );
  3181. } else {
  3182. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3183. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3184. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3185. }
  3186. return this;
  3187. }
  3188. equals( sphere ) {
  3189. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3190. }
  3191. clone() {
  3192. return new this.constructor().copy( this );
  3193. }
  3194. }
  3195. const _vector$a = /*@__PURE__*/ new Vector3();
  3196. const _segCenter = /*@__PURE__*/ new Vector3();
  3197. const _segDir = /*@__PURE__*/ new Vector3();
  3198. const _diff = /*@__PURE__*/ new Vector3();
  3199. const _edge1 = /*@__PURE__*/ new Vector3();
  3200. const _edge2 = /*@__PURE__*/ new Vector3();
  3201. const _normal$1 = /*@__PURE__*/ new Vector3();
  3202. class Ray {
  3203. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3204. this.origin = origin;
  3205. this.direction = direction;
  3206. }
  3207. set( origin, direction ) {
  3208. this.origin.copy( origin );
  3209. this.direction.copy( direction );
  3210. return this;
  3211. }
  3212. copy( ray ) {
  3213. this.origin.copy( ray.origin );
  3214. this.direction.copy( ray.direction );
  3215. return this;
  3216. }
  3217. at( t, target ) {
  3218. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3219. }
  3220. lookAt( v ) {
  3221. this.direction.copy( v ).sub( this.origin ).normalize();
  3222. return this;
  3223. }
  3224. recast( t ) {
  3225. this.origin.copy( this.at( t, _vector$a ) );
  3226. return this;
  3227. }
  3228. closestPointToPoint( point, target ) {
  3229. target.subVectors( point, this.origin );
  3230. const directionDistance = target.dot( this.direction );
  3231. if ( directionDistance < 0 ) {
  3232. return target.copy( this.origin );
  3233. }
  3234. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3235. }
  3236. distanceToPoint( point ) {
  3237. return Math.sqrt( this.distanceSqToPoint( point ) );
  3238. }
  3239. distanceSqToPoint( point ) {
  3240. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3241. // point behind the ray
  3242. if ( directionDistance < 0 ) {
  3243. return this.origin.distanceToSquared( point );
  3244. }
  3245. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3246. return _vector$a.distanceToSquared( point );
  3247. }
  3248. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3249. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3250. // It returns the min distance between the ray and the segment
  3251. // defined by v0 and v1
  3252. // It can also set two optional targets :
  3253. // - The closest point on the ray
  3254. // - The closest point on the segment
  3255. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3256. _segDir.copy( v1 ).sub( v0 ).normalize();
  3257. _diff.copy( this.origin ).sub( _segCenter );
  3258. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3259. const a01 = - this.direction.dot( _segDir );
  3260. const b0 = _diff.dot( this.direction );
  3261. const b1 = - _diff.dot( _segDir );
  3262. const c = _diff.lengthSq();
  3263. const det = Math.abs( 1 - a01 * a01 );
  3264. let s0, s1, sqrDist, extDet;
  3265. if ( det > 0 ) {
  3266. // The ray and segment are not parallel.
  3267. s0 = a01 * b1 - b0;
  3268. s1 = a01 * b0 - b1;
  3269. extDet = segExtent * det;
  3270. if ( s0 >= 0 ) {
  3271. if ( s1 >= - extDet ) {
  3272. if ( s1 <= extDet ) {
  3273. // region 0
  3274. // Minimum at interior points of ray and segment.
  3275. const invDet = 1 / det;
  3276. s0 *= invDet;
  3277. s1 *= invDet;
  3278. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3279. } else {
  3280. // region 1
  3281. s1 = segExtent;
  3282. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3283. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3284. }
  3285. } else {
  3286. // region 5
  3287. s1 = - segExtent;
  3288. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3289. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3290. }
  3291. } else {
  3292. if ( s1 <= - extDet ) {
  3293. // region 4
  3294. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3295. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3296. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3297. } else if ( s1 <= extDet ) {
  3298. // region 3
  3299. s0 = 0;
  3300. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3301. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3302. } else {
  3303. // region 2
  3304. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3305. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3306. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3307. }
  3308. }
  3309. } else {
  3310. // Ray and segment are parallel.
  3311. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3312. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3313. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3314. }
  3315. if ( optionalPointOnRay ) {
  3316. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3317. }
  3318. if ( optionalPointOnSegment ) {
  3319. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3320. }
  3321. return sqrDist;
  3322. }
  3323. intersectSphere( sphere, target ) {
  3324. _vector$a.subVectors( sphere.center, this.origin );
  3325. const tca = _vector$a.dot( this.direction );
  3326. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3327. const radius2 = sphere.radius * sphere.radius;
  3328. if ( d2 > radius2 ) return null;
  3329. const thc = Math.sqrt( radius2 - d2 );
  3330. // t0 = first intersect point - entrance on front of sphere
  3331. const t0 = tca - thc;
  3332. // t1 = second intersect point - exit point on back of sphere
  3333. const t1 = tca + thc;
  3334. // test to see if t1 is behind the ray - if so, return null
  3335. if ( t1 < 0 ) return null;
  3336. // test to see if t0 is behind the ray:
  3337. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3338. // in order to always return an intersect point that is in front of the ray.
  3339. if ( t0 < 0 ) return this.at( t1, target );
  3340. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3341. return this.at( t0, target );
  3342. }
  3343. intersectsSphere( sphere ) {
  3344. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3345. }
  3346. distanceToPlane( plane ) {
  3347. const denominator = plane.normal.dot( this.direction );
  3348. if ( denominator === 0 ) {
  3349. // line is coplanar, return origin
  3350. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3351. return 0;
  3352. }
  3353. // Null is preferable to undefined since undefined means.... it is undefined
  3354. return null;
  3355. }
  3356. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3357. // Return if the ray never intersects the plane
  3358. return t >= 0 ? t : null;
  3359. }
  3360. intersectPlane( plane, target ) {
  3361. const t = this.distanceToPlane( plane );
  3362. if ( t === null ) {
  3363. return null;
  3364. }
  3365. return this.at( t, target );
  3366. }
  3367. intersectsPlane( plane ) {
  3368. // check if the ray lies on the plane first
  3369. const distToPoint = plane.distanceToPoint( this.origin );
  3370. if ( distToPoint === 0 ) {
  3371. return true;
  3372. }
  3373. const denominator = plane.normal.dot( this.direction );
  3374. if ( denominator * distToPoint < 0 ) {
  3375. return true;
  3376. }
  3377. // ray origin is behind the plane (and is pointing behind it)
  3378. return false;
  3379. }
  3380. intersectBox( box, target ) {
  3381. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3382. const invdirx = 1 / this.direction.x,
  3383. invdiry = 1 / this.direction.y,
  3384. invdirz = 1 / this.direction.z;
  3385. const origin = this.origin;
  3386. if ( invdirx >= 0 ) {
  3387. tmin = ( box.min.x - origin.x ) * invdirx;
  3388. tmax = ( box.max.x - origin.x ) * invdirx;
  3389. } else {
  3390. tmin = ( box.max.x - origin.x ) * invdirx;
  3391. tmax = ( box.min.x - origin.x ) * invdirx;
  3392. }
  3393. if ( invdiry >= 0 ) {
  3394. tymin = ( box.min.y - origin.y ) * invdiry;
  3395. tymax = ( box.max.y - origin.y ) * invdiry;
  3396. } else {
  3397. tymin = ( box.max.y - origin.y ) * invdiry;
  3398. tymax = ( box.min.y - origin.y ) * invdiry;
  3399. }
  3400. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3401. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3402. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3403. if ( invdirz >= 0 ) {
  3404. tzmin = ( box.min.z - origin.z ) * invdirz;
  3405. tzmax = ( box.max.z - origin.z ) * invdirz;
  3406. } else {
  3407. tzmin = ( box.max.z - origin.z ) * invdirz;
  3408. tzmax = ( box.min.z - origin.z ) * invdirz;
  3409. }
  3410. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3411. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3412. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3413. //return point closest to the ray (positive side)
  3414. if ( tmax < 0 ) return null;
  3415. return this.at( tmin >= 0 ? tmin : tmax, target );
  3416. }
  3417. intersectsBox( box ) {
  3418. return this.intersectBox( box, _vector$a ) !== null;
  3419. }
  3420. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3421. // Compute the offset origin, edges, and normal.
  3422. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3423. _edge1.subVectors( b, a );
  3424. _edge2.subVectors( c, a );
  3425. _normal$1.crossVectors( _edge1, _edge2 );
  3426. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3427. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3428. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3429. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3430. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3431. let DdN = this.direction.dot( _normal$1 );
  3432. let sign;
  3433. if ( DdN > 0 ) {
  3434. if ( backfaceCulling ) return null;
  3435. sign = 1;
  3436. } else if ( DdN < 0 ) {
  3437. sign = - 1;
  3438. DdN = - DdN;
  3439. } else {
  3440. return null;
  3441. }
  3442. _diff.subVectors( this.origin, a );
  3443. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3444. // b1 < 0, no intersection
  3445. if ( DdQxE2 < 0 ) {
  3446. return null;
  3447. }
  3448. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3449. // b2 < 0, no intersection
  3450. if ( DdE1xQ < 0 ) {
  3451. return null;
  3452. }
  3453. // b1+b2 > 1, no intersection
  3454. if ( DdQxE2 + DdE1xQ > DdN ) {
  3455. return null;
  3456. }
  3457. // Line intersects triangle, check if ray does.
  3458. const QdN = - sign * _diff.dot( _normal$1 );
  3459. // t < 0, no intersection
  3460. if ( QdN < 0 ) {
  3461. return null;
  3462. }
  3463. // Ray intersects triangle.
  3464. return this.at( QdN / DdN, target );
  3465. }
  3466. applyMatrix4( matrix4 ) {
  3467. this.origin.applyMatrix4( matrix4 );
  3468. this.direction.transformDirection( matrix4 );
  3469. return this;
  3470. }
  3471. equals( ray ) {
  3472. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3473. }
  3474. clone() {
  3475. return new this.constructor().copy( this );
  3476. }
  3477. }
  3478. class Matrix4 {
  3479. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3480. Matrix4.prototype.isMatrix4 = true;
  3481. this.elements = [
  3482. 1, 0, 0, 0,
  3483. 0, 1, 0, 0,
  3484. 0, 0, 1, 0,
  3485. 0, 0, 0, 1
  3486. ];
  3487. if ( n11 !== undefined ) {
  3488. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3489. }
  3490. }
  3491. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3492. const te = this.elements;
  3493. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3494. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3495. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3496. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3497. return this;
  3498. }
  3499. identity() {
  3500. this.set(
  3501. 1, 0, 0, 0,
  3502. 0, 1, 0, 0,
  3503. 0, 0, 1, 0,
  3504. 0, 0, 0, 1
  3505. );
  3506. return this;
  3507. }
  3508. clone() {
  3509. return new Matrix4().fromArray( this.elements );
  3510. }
  3511. copy( m ) {
  3512. const te = this.elements;
  3513. const me = m.elements;
  3514. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3515. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3516. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3517. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3518. return this;
  3519. }
  3520. copyPosition( m ) {
  3521. const te = this.elements, me = m.elements;
  3522. te[ 12 ] = me[ 12 ];
  3523. te[ 13 ] = me[ 13 ];
  3524. te[ 14 ] = me[ 14 ];
  3525. return this;
  3526. }
  3527. setFromMatrix3( m ) {
  3528. const me = m.elements;
  3529. this.set(
  3530. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3531. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3532. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3533. 0, 0, 0, 1
  3534. );
  3535. return this;
  3536. }
  3537. extractBasis( xAxis, yAxis, zAxis ) {
  3538. xAxis.setFromMatrixColumn( this, 0 );
  3539. yAxis.setFromMatrixColumn( this, 1 );
  3540. zAxis.setFromMatrixColumn( this, 2 );
  3541. return this;
  3542. }
  3543. makeBasis( xAxis, yAxis, zAxis ) {
  3544. this.set(
  3545. xAxis.x, yAxis.x, zAxis.x, 0,
  3546. xAxis.y, yAxis.y, zAxis.y, 0,
  3547. xAxis.z, yAxis.z, zAxis.z, 0,
  3548. 0, 0, 0, 1
  3549. );
  3550. return this;
  3551. }
  3552. extractRotation( m ) {
  3553. // this method does not support reflection matrices
  3554. const te = this.elements;
  3555. const me = m.elements;
  3556. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3557. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3558. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3559. te[ 0 ] = me[ 0 ] * scaleX;
  3560. te[ 1 ] = me[ 1 ] * scaleX;
  3561. te[ 2 ] = me[ 2 ] * scaleX;
  3562. te[ 3 ] = 0;
  3563. te[ 4 ] = me[ 4 ] * scaleY;
  3564. te[ 5 ] = me[ 5 ] * scaleY;
  3565. te[ 6 ] = me[ 6 ] * scaleY;
  3566. te[ 7 ] = 0;
  3567. te[ 8 ] = me[ 8 ] * scaleZ;
  3568. te[ 9 ] = me[ 9 ] * scaleZ;
  3569. te[ 10 ] = me[ 10 ] * scaleZ;
  3570. te[ 11 ] = 0;
  3571. te[ 12 ] = 0;
  3572. te[ 13 ] = 0;
  3573. te[ 14 ] = 0;
  3574. te[ 15 ] = 1;
  3575. return this;
  3576. }
  3577. makeRotationFromEuler( euler ) {
  3578. const te = this.elements;
  3579. const x = euler.x, y = euler.y, z = euler.z;
  3580. const a = Math.cos( x ), b = Math.sin( x );
  3581. const c = Math.cos( y ), d = Math.sin( y );
  3582. const e = Math.cos( z ), f = Math.sin( z );
  3583. if ( euler.order === 'XYZ' ) {
  3584. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3585. te[ 0 ] = c * e;
  3586. te[ 4 ] = - c * f;
  3587. te[ 8 ] = d;
  3588. te[ 1 ] = af + be * d;
  3589. te[ 5 ] = ae - bf * d;
  3590. te[ 9 ] = - b * c;
  3591. te[ 2 ] = bf - ae * d;
  3592. te[ 6 ] = be + af * d;
  3593. te[ 10 ] = a * c;
  3594. } else if ( euler.order === 'YXZ' ) {
  3595. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3596. te[ 0 ] = ce + df * b;
  3597. te[ 4 ] = de * b - cf;
  3598. te[ 8 ] = a * d;
  3599. te[ 1 ] = a * f;
  3600. te[ 5 ] = a * e;
  3601. te[ 9 ] = - b;
  3602. te[ 2 ] = cf * b - de;
  3603. te[ 6 ] = df + ce * b;
  3604. te[ 10 ] = a * c;
  3605. } else if ( euler.order === 'ZXY' ) {
  3606. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3607. te[ 0 ] = ce - df * b;
  3608. te[ 4 ] = - a * f;
  3609. te[ 8 ] = de + cf * b;
  3610. te[ 1 ] = cf + de * b;
  3611. te[ 5 ] = a * e;
  3612. te[ 9 ] = df - ce * b;
  3613. te[ 2 ] = - a * d;
  3614. te[ 6 ] = b;
  3615. te[ 10 ] = a * c;
  3616. } else if ( euler.order === 'ZYX' ) {
  3617. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3618. te[ 0 ] = c * e;
  3619. te[ 4 ] = be * d - af;
  3620. te[ 8 ] = ae * d + bf;
  3621. te[ 1 ] = c * f;
  3622. te[ 5 ] = bf * d + ae;
  3623. te[ 9 ] = af * d - be;
  3624. te[ 2 ] = - d;
  3625. te[ 6 ] = b * c;
  3626. te[ 10 ] = a * c;
  3627. } else if ( euler.order === 'YZX' ) {
  3628. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3629. te[ 0 ] = c * e;
  3630. te[ 4 ] = bd - ac * f;
  3631. te[ 8 ] = bc * f + ad;
  3632. te[ 1 ] = f;
  3633. te[ 5 ] = a * e;
  3634. te[ 9 ] = - b * e;
  3635. te[ 2 ] = - d * e;
  3636. te[ 6 ] = ad * f + bc;
  3637. te[ 10 ] = ac - bd * f;
  3638. } else if ( euler.order === 'XZY' ) {
  3639. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3640. te[ 0 ] = c * e;
  3641. te[ 4 ] = - f;
  3642. te[ 8 ] = d * e;
  3643. te[ 1 ] = ac * f + bd;
  3644. te[ 5 ] = a * e;
  3645. te[ 9 ] = ad * f - bc;
  3646. te[ 2 ] = bc * f - ad;
  3647. te[ 6 ] = b * e;
  3648. te[ 10 ] = bd * f + ac;
  3649. }
  3650. // bottom row
  3651. te[ 3 ] = 0;
  3652. te[ 7 ] = 0;
  3653. te[ 11 ] = 0;
  3654. // last column
  3655. te[ 12 ] = 0;
  3656. te[ 13 ] = 0;
  3657. te[ 14 ] = 0;
  3658. te[ 15 ] = 1;
  3659. return this;
  3660. }
  3661. makeRotationFromQuaternion( q ) {
  3662. return this.compose( _zero, q, _one );
  3663. }
  3664. lookAt( eye, target, up ) {
  3665. const te = this.elements;
  3666. _z.subVectors( eye, target );
  3667. if ( _z.lengthSq() === 0 ) {
  3668. // eye and target are in the same position
  3669. _z.z = 1;
  3670. }
  3671. _z.normalize();
  3672. _x.crossVectors( up, _z );
  3673. if ( _x.lengthSq() === 0 ) {
  3674. // up and z are parallel
  3675. if ( Math.abs( up.z ) === 1 ) {
  3676. _z.x += 0.0001;
  3677. } else {
  3678. _z.z += 0.0001;
  3679. }
  3680. _z.normalize();
  3681. _x.crossVectors( up, _z );
  3682. }
  3683. _x.normalize();
  3684. _y.crossVectors( _z, _x );
  3685. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3686. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3687. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3688. return this;
  3689. }
  3690. multiply( m ) {
  3691. return this.multiplyMatrices( this, m );
  3692. }
  3693. premultiply( m ) {
  3694. return this.multiplyMatrices( m, this );
  3695. }
  3696. multiplyMatrices( a, b ) {
  3697. const ae = a.elements;
  3698. const be = b.elements;
  3699. const te = this.elements;
  3700. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3701. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3702. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3703. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3704. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3705. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3706. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3707. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3708. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3709. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3710. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3711. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3712. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3713. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3714. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3715. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3716. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3717. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3718. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3719. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3720. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3721. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3722. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3723. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3724. return this;
  3725. }
  3726. multiplyScalar( s ) {
  3727. const te = this.elements;
  3728. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3729. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3730. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3731. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3732. return this;
  3733. }
  3734. determinant() {
  3735. const te = this.elements;
  3736. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3737. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3738. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3739. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3740. //TODO: make this more efficient
  3741. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3742. return (
  3743. n41 * (
  3744. + n14 * n23 * n32
  3745. - n13 * n24 * n32
  3746. - n14 * n22 * n33
  3747. + n12 * n24 * n33
  3748. + n13 * n22 * n34
  3749. - n12 * n23 * n34
  3750. ) +
  3751. n42 * (
  3752. + n11 * n23 * n34
  3753. - n11 * n24 * n33
  3754. + n14 * n21 * n33
  3755. - n13 * n21 * n34
  3756. + n13 * n24 * n31
  3757. - n14 * n23 * n31
  3758. ) +
  3759. n43 * (
  3760. + n11 * n24 * n32
  3761. - n11 * n22 * n34
  3762. - n14 * n21 * n32
  3763. + n12 * n21 * n34
  3764. + n14 * n22 * n31
  3765. - n12 * n24 * n31
  3766. ) +
  3767. n44 * (
  3768. - n13 * n22 * n31
  3769. - n11 * n23 * n32
  3770. + n11 * n22 * n33
  3771. + n13 * n21 * n32
  3772. - n12 * n21 * n33
  3773. + n12 * n23 * n31
  3774. )
  3775. );
  3776. }
  3777. transpose() {
  3778. const te = this.elements;
  3779. let tmp;
  3780. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3781. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3782. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3783. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3784. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3785. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3786. return this;
  3787. }
  3788. setPosition( x, y, z ) {
  3789. const te = this.elements;
  3790. if ( x.isVector3 ) {
  3791. te[ 12 ] = x.x;
  3792. te[ 13 ] = x.y;
  3793. te[ 14 ] = x.z;
  3794. } else {
  3795. te[ 12 ] = x;
  3796. te[ 13 ] = y;
  3797. te[ 14 ] = z;
  3798. }
  3799. return this;
  3800. }
  3801. invert() {
  3802. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3803. const te = this.elements,
  3804. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3805. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3806. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3807. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3808. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3809. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3810. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3811. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3812. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3813. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3814. const detInv = 1 / det;
  3815. te[ 0 ] = t11 * detInv;
  3816. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3817. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3818. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3819. te[ 4 ] = t12 * detInv;
  3820. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3821. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3822. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3823. te[ 8 ] = t13 * detInv;
  3824. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3825. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3826. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3827. te[ 12 ] = t14 * detInv;
  3828. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3829. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3830. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3831. return this;
  3832. }
  3833. scale( v ) {
  3834. const te = this.elements;
  3835. const x = v.x, y = v.y, z = v.z;
  3836. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3837. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3838. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3839. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3840. return this;
  3841. }
  3842. getMaxScaleOnAxis() {
  3843. const te = this.elements;
  3844. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3845. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3846. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3847. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3848. }
  3849. makeTranslation( x, y, z ) {
  3850. if ( x.isVector3 ) {
  3851. this.set(
  3852. 1, 0, 0, x.x,
  3853. 0, 1, 0, x.y,
  3854. 0, 0, 1, x.z,
  3855. 0, 0, 0, 1
  3856. );
  3857. } else {
  3858. this.set(
  3859. 1, 0, 0, x,
  3860. 0, 1, 0, y,
  3861. 0, 0, 1, z,
  3862. 0, 0, 0, 1
  3863. );
  3864. }
  3865. return this;
  3866. }
  3867. makeRotationX( theta ) {
  3868. const c = Math.cos( theta ), s = Math.sin( theta );
  3869. this.set(
  3870. 1, 0, 0, 0,
  3871. 0, c, - s, 0,
  3872. 0, s, c, 0,
  3873. 0, 0, 0, 1
  3874. );
  3875. return this;
  3876. }
  3877. makeRotationY( theta ) {
  3878. const c = Math.cos( theta ), s = Math.sin( theta );
  3879. this.set(
  3880. c, 0, s, 0,
  3881. 0, 1, 0, 0,
  3882. - s, 0, c, 0,
  3883. 0, 0, 0, 1
  3884. );
  3885. return this;
  3886. }
  3887. makeRotationZ( theta ) {
  3888. const c = Math.cos( theta ), s = Math.sin( theta );
  3889. this.set(
  3890. c, - s, 0, 0,
  3891. s, c, 0, 0,
  3892. 0, 0, 1, 0,
  3893. 0, 0, 0, 1
  3894. );
  3895. return this;
  3896. }
  3897. makeRotationAxis( axis, angle ) {
  3898. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3899. const c = Math.cos( angle );
  3900. const s = Math.sin( angle );
  3901. const t = 1 - c;
  3902. const x = axis.x, y = axis.y, z = axis.z;
  3903. const tx = t * x, ty = t * y;
  3904. this.set(
  3905. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3906. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3907. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3908. 0, 0, 0, 1
  3909. );
  3910. return this;
  3911. }
  3912. makeScale( x, y, z ) {
  3913. this.set(
  3914. x, 0, 0, 0,
  3915. 0, y, 0, 0,
  3916. 0, 0, z, 0,
  3917. 0, 0, 0, 1
  3918. );
  3919. return this;
  3920. }
  3921. makeShear( xy, xz, yx, yz, zx, zy ) {
  3922. this.set(
  3923. 1, yx, zx, 0,
  3924. xy, 1, zy, 0,
  3925. xz, yz, 1, 0,
  3926. 0, 0, 0, 1
  3927. );
  3928. return this;
  3929. }
  3930. compose( position, quaternion, scale ) {
  3931. const te = this.elements;
  3932. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3933. const x2 = x + x, y2 = y + y, z2 = z + z;
  3934. const xx = x * x2, xy = x * y2, xz = x * z2;
  3935. const yy = y * y2, yz = y * z2, zz = z * z2;
  3936. const wx = w * x2, wy = w * y2, wz = w * z2;
  3937. const sx = scale.x, sy = scale.y, sz = scale.z;
  3938. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3939. te[ 1 ] = ( xy + wz ) * sx;
  3940. te[ 2 ] = ( xz - wy ) * sx;
  3941. te[ 3 ] = 0;
  3942. te[ 4 ] = ( xy - wz ) * sy;
  3943. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3944. te[ 6 ] = ( yz + wx ) * sy;
  3945. te[ 7 ] = 0;
  3946. te[ 8 ] = ( xz + wy ) * sz;
  3947. te[ 9 ] = ( yz - wx ) * sz;
  3948. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3949. te[ 11 ] = 0;
  3950. te[ 12 ] = position.x;
  3951. te[ 13 ] = position.y;
  3952. te[ 14 ] = position.z;
  3953. te[ 15 ] = 1;
  3954. return this;
  3955. }
  3956. decompose( position, quaternion, scale ) {
  3957. const te = this.elements;
  3958. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3959. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3960. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3961. // if determine is negative, we need to invert one scale
  3962. const det = this.determinant();
  3963. if ( det < 0 ) sx = - sx;
  3964. position.x = te[ 12 ];
  3965. position.y = te[ 13 ];
  3966. position.z = te[ 14 ];
  3967. // scale the rotation part
  3968. _m1$4.copy( this );
  3969. const invSX = 1 / sx;
  3970. const invSY = 1 / sy;
  3971. const invSZ = 1 / sz;
  3972. _m1$4.elements[ 0 ] *= invSX;
  3973. _m1$4.elements[ 1 ] *= invSX;
  3974. _m1$4.elements[ 2 ] *= invSX;
  3975. _m1$4.elements[ 4 ] *= invSY;
  3976. _m1$4.elements[ 5 ] *= invSY;
  3977. _m1$4.elements[ 6 ] *= invSY;
  3978. _m1$4.elements[ 8 ] *= invSZ;
  3979. _m1$4.elements[ 9 ] *= invSZ;
  3980. _m1$4.elements[ 10 ] *= invSZ;
  3981. quaternion.setFromRotationMatrix( _m1$4 );
  3982. scale.x = sx;
  3983. scale.y = sy;
  3984. scale.z = sz;
  3985. return this;
  3986. }
  3987. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  3988. const te = this.elements;
  3989. const x = 2 * near / ( right - left );
  3990. const y = 2 * near / ( top - bottom );
  3991. const a = ( right + left ) / ( right - left );
  3992. const b = ( top + bottom ) / ( top - bottom );
  3993. let c, d;
  3994. if ( coordinateSystem === WebGLCoordinateSystem ) {
  3995. c = - ( far + near ) / ( far - near );
  3996. d = ( - 2 * far * near ) / ( far - near );
  3997. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  3998. c = - far / ( far - near );
  3999. d = ( - far * near ) / ( far - near );
  4000. } else {
  4001. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4002. }
  4003. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4004. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4005. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4006. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4007. return this;
  4008. }
  4009. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4010. const te = this.elements;
  4011. const w = 1.0 / ( right - left );
  4012. const h = 1.0 / ( top - bottom );
  4013. const p = 1.0 / ( far - near );
  4014. const x = ( right + left ) * w;
  4015. const y = ( top + bottom ) * h;
  4016. let z, zInv;
  4017. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4018. z = ( far + near ) * p;
  4019. zInv = - 2 * p;
  4020. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4021. z = near * p;
  4022. zInv = - 1 * p;
  4023. } else {
  4024. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4025. }
  4026. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4027. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4028. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4029. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4030. return this;
  4031. }
  4032. equals( matrix ) {
  4033. const te = this.elements;
  4034. const me = matrix.elements;
  4035. for ( let i = 0; i < 16; i ++ ) {
  4036. if ( te[ i ] !== me[ i ] ) return false;
  4037. }
  4038. return true;
  4039. }
  4040. fromArray( array, offset = 0 ) {
  4041. for ( let i = 0; i < 16; i ++ ) {
  4042. this.elements[ i ] = array[ i + offset ];
  4043. }
  4044. return this;
  4045. }
  4046. toArray( array = [], offset = 0 ) {
  4047. const te = this.elements;
  4048. array[ offset ] = te[ 0 ];
  4049. array[ offset + 1 ] = te[ 1 ];
  4050. array[ offset + 2 ] = te[ 2 ];
  4051. array[ offset + 3 ] = te[ 3 ];
  4052. array[ offset + 4 ] = te[ 4 ];
  4053. array[ offset + 5 ] = te[ 5 ];
  4054. array[ offset + 6 ] = te[ 6 ];
  4055. array[ offset + 7 ] = te[ 7 ];
  4056. array[ offset + 8 ] = te[ 8 ];
  4057. array[ offset + 9 ] = te[ 9 ];
  4058. array[ offset + 10 ] = te[ 10 ];
  4059. array[ offset + 11 ] = te[ 11 ];
  4060. array[ offset + 12 ] = te[ 12 ];
  4061. array[ offset + 13 ] = te[ 13 ];
  4062. array[ offset + 14 ] = te[ 14 ];
  4063. array[ offset + 15 ] = te[ 15 ];
  4064. return array;
  4065. }
  4066. }
  4067. const _v1$5 = /*@__PURE__*/ new Vector3();
  4068. const _m1$4 = /*@__PURE__*/ new Matrix4();
  4069. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4070. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4071. const _x = /*@__PURE__*/ new Vector3();
  4072. const _y = /*@__PURE__*/ new Vector3();
  4073. const _z = /*@__PURE__*/ new Vector3();
  4074. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4075. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4076. class Euler {
  4077. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4078. this.isEuler = true;
  4079. this._x = x;
  4080. this._y = y;
  4081. this._z = z;
  4082. this._order = order;
  4083. }
  4084. get x() {
  4085. return this._x;
  4086. }
  4087. set x( value ) {
  4088. this._x = value;
  4089. this._onChangeCallback();
  4090. }
  4091. get y() {
  4092. return this._y;
  4093. }
  4094. set y( value ) {
  4095. this._y = value;
  4096. this._onChangeCallback();
  4097. }
  4098. get z() {
  4099. return this._z;
  4100. }
  4101. set z( value ) {
  4102. this._z = value;
  4103. this._onChangeCallback();
  4104. }
  4105. get order() {
  4106. return this._order;
  4107. }
  4108. set order( value ) {
  4109. this._order = value;
  4110. this._onChangeCallback();
  4111. }
  4112. set( x, y, z, order = this._order ) {
  4113. this._x = x;
  4114. this._y = y;
  4115. this._z = z;
  4116. this._order = order;
  4117. this._onChangeCallback();
  4118. return this;
  4119. }
  4120. clone() {
  4121. return new this.constructor( this._x, this._y, this._z, this._order );
  4122. }
  4123. copy( euler ) {
  4124. this._x = euler._x;
  4125. this._y = euler._y;
  4126. this._z = euler._z;
  4127. this._order = euler._order;
  4128. this._onChangeCallback();
  4129. return this;
  4130. }
  4131. setFromRotationMatrix( m, order = this._order, update = true ) {
  4132. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4133. const te = m.elements;
  4134. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4135. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4136. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4137. switch ( order ) {
  4138. case 'XYZ':
  4139. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4140. if ( Math.abs( m13 ) < 0.9999999 ) {
  4141. this._x = Math.atan2( - m23, m33 );
  4142. this._z = Math.atan2( - m12, m11 );
  4143. } else {
  4144. this._x = Math.atan2( m32, m22 );
  4145. this._z = 0;
  4146. }
  4147. break;
  4148. case 'YXZ':
  4149. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4150. if ( Math.abs( m23 ) < 0.9999999 ) {
  4151. this._y = Math.atan2( m13, m33 );
  4152. this._z = Math.atan2( m21, m22 );
  4153. } else {
  4154. this._y = Math.atan2( - m31, m11 );
  4155. this._z = 0;
  4156. }
  4157. break;
  4158. case 'ZXY':
  4159. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4160. if ( Math.abs( m32 ) < 0.9999999 ) {
  4161. this._y = Math.atan2( - m31, m33 );
  4162. this._z = Math.atan2( - m12, m22 );
  4163. } else {
  4164. this._y = 0;
  4165. this._z = Math.atan2( m21, m11 );
  4166. }
  4167. break;
  4168. case 'ZYX':
  4169. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4170. if ( Math.abs( m31 ) < 0.9999999 ) {
  4171. this._x = Math.atan2( m32, m33 );
  4172. this._z = Math.atan2( m21, m11 );
  4173. } else {
  4174. this._x = 0;
  4175. this._z = Math.atan2( - m12, m22 );
  4176. }
  4177. break;
  4178. case 'YZX':
  4179. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4180. if ( Math.abs( m21 ) < 0.9999999 ) {
  4181. this._x = Math.atan2( - m23, m22 );
  4182. this._y = Math.atan2( - m31, m11 );
  4183. } else {
  4184. this._x = 0;
  4185. this._y = Math.atan2( m13, m33 );
  4186. }
  4187. break;
  4188. case 'XZY':
  4189. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4190. if ( Math.abs( m12 ) < 0.9999999 ) {
  4191. this._x = Math.atan2( m32, m22 );
  4192. this._y = Math.atan2( m13, m11 );
  4193. } else {
  4194. this._x = Math.atan2( - m23, m33 );
  4195. this._y = 0;
  4196. }
  4197. break;
  4198. default:
  4199. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4200. }
  4201. this._order = order;
  4202. if ( update === true ) this._onChangeCallback();
  4203. return this;
  4204. }
  4205. setFromQuaternion( q, order, update ) {
  4206. _matrix$2.makeRotationFromQuaternion( q );
  4207. return this.setFromRotationMatrix( _matrix$2, order, update );
  4208. }
  4209. setFromVector3( v, order = this._order ) {
  4210. return this.set( v.x, v.y, v.z, order );
  4211. }
  4212. reorder( newOrder ) {
  4213. // WARNING: this discards revolution information -bhouston
  4214. _quaternion$3.setFromEuler( this );
  4215. return this.setFromQuaternion( _quaternion$3, newOrder );
  4216. }
  4217. equals( euler ) {
  4218. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4219. }
  4220. fromArray( array ) {
  4221. this._x = array[ 0 ];
  4222. this._y = array[ 1 ];
  4223. this._z = array[ 2 ];
  4224. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4225. this._onChangeCallback();
  4226. return this;
  4227. }
  4228. toArray( array = [], offset = 0 ) {
  4229. array[ offset ] = this._x;
  4230. array[ offset + 1 ] = this._y;
  4231. array[ offset + 2 ] = this._z;
  4232. array[ offset + 3 ] = this._order;
  4233. return array;
  4234. }
  4235. _onChange( callback ) {
  4236. this._onChangeCallback = callback;
  4237. return this;
  4238. }
  4239. _onChangeCallback() {}
  4240. *[ Symbol.iterator ]() {
  4241. yield this._x;
  4242. yield this._y;
  4243. yield this._z;
  4244. yield this._order;
  4245. }
  4246. }
  4247. Euler.DEFAULT_ORDER = 'XYZ';
  4248. class Layers {
  4249. constructor() {
  4250. this.mask = 1 | 0;
  4251. }
  4252. set( channel ) {
  4253. this.mask = ( 1 << channel | 0 ) >>> 0;
  4254. }
  4255. enable( channel ) {
  4256. this.mask |= 1 << channel | 0;
  4257. }
  4258. enableAll() {
  4259. this.mask = 0xffffffff | 0;
  4260. }
  4261. toggle( channel ) {
  4262. this.mask ^= 1 << channel | 0;
  4263. }
  4264. disable( channel ) {
  4265. this.mask &= ~ ( 1 << channel | 0 );
  4266. }
  4267. disableAll() {
  4268. this.mask = 0;
  4269. }
  4270. test( layers ) {
  4271. return ( this.mask & layers.mask ) !== 0;
  4272. }
  4273. isEnabled( channel ) {
  4274. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4275. }
  4276. }
  4277. let _object3DId = 0;
  4278. const _v1$4 = /*@__PURE__*/ new Vector3();
  4279. const _q1 = /*@__PURE__*/ new Quaternion();
  4280. const _m1$3 = /*@__PURE__*/ new Matrix4();
  4281. const _target = /*@__PURE__*/ new Vector3();
  4282. const _position$3 = /*@__PURE__*/ new Vector3();
  4283. const _scale$2 = /*@__PURE__*/ new Vector3();
  4284. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4285. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4286. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4287. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4288. const _addedEvent = { type: 'added' };
  4289. const _removedEvent = { type: 'removed' };
  4290. const _childaddedEvent = { type: 'childadded', child: null };
  4291. const _childremovedEvent = { type: 'childremoved', child: null };
  4292. class Object3D extends EventDispatcher {
  4293. constructor() {
  4294. super();
  4295. this.isObject3D = true;
  4296. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4297. this.uuid = generateUUID();
  4298. this.name = '';
  4299. this.type = 'Object3D';
  4300. this.parent = null;
  4301. this.children = [];
  4302. this.up = Object3D.DEFAULT_UP.clone();
  4303. const position = new Vector3();
  4304. const rotation = new Euler();
  4305. const quaternion = new Quaternion();
  4306. const scale = new Vector3( 1, 1, 1 );
  4307. function onRotationChange() {
  4308. quaternion.setFromEuler( rotation, false );
  4309. }
  4310. function onQuaternionChange() {
  4311. rotation.setFromQuaternion( quaternion, undefined, false );
  4312. }
  4313. rotation._onChange( onRotationChange );
  4314. quaternion._onChange( onQuaternionChange );
  4315. Object.defineProperties( this, {
  4316. position: {
  4317. configurable: true,
  4318. enumerable: true,
  4319. value: position
  4320. },
  4321. rotation: {
  4322. configurable: true,
  4323. enumerable: true,
  4324. value: rotation
  4325. },
  4326. quaternion: {
  4327. configurable: true,
  4328. enumerable: true,
  4329. value: quaternion
  4330. },
  4331. scale: {
  4332. configurable: true,
  4333. enumerable: true,
  4334. value: scale
  4335. },
  4336. modelViewMatrix: {
  4337. value: new Matrix4()
  4338. },
  4339. normalMatrix: {
  4340. value: new Matrix3()
  4341. }
  4342. } );
  4343. this.matrix = new Matrix4();
  4344. this.matrixWorld = new Matrix4();
  4345. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4346. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4347. this.matrixWorldNeedsUpdate = false;
  4348. this.layers = new Layers();
  4349. this.visible = true;
  4350. this.castShadow = false;
  4351. this.receiveShadow = false;
  4352. this.frustumCulled = true;
  4353. this.renderOrder = 0;
  4354. this.animations = [];
  4355. this.userData = {};
  4356. }
  4357. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4358. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4359. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4360. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4361. applyMatrix4( matrix ) {
  4362. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4363. this.matrix.premultiply( matrix );
  4364. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4365. }
  4366. applyQuaternion( q ) {
  4367. this.quaternion.premultiply( q );
  4368. return this;
  4369. }
  4370. setRotationFromAxisAngle( axis, angle ) {
  4371. // assumes axis is normalized
  4372. this.quaternion.setFromAxisAngle( axis, angle );
  4373. }
  4374. setRotationFromEuler( euler ) {
  4375. this.quaternion.setFromEuler( euler, true );
  4376. }
  4377. setRotationFromMatrix( m ) {
  4378. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4379. this.quaternion.setFromRotationMatrix( m );
  4380. }
  4381. setRotationFromQuaternion( q ) {
  4382. // assumes q is normalized
  4383. this.quaternion.copy( q );
  4384. }
  4385. rotateOnAxis( axis, angle ) {
  4386. // rotate object on axis in object space
  4387. // axis is assumed to be normalized
  4388. _q1.setFromAxisAngle( axis, angle );
  4389. this.quaternion.multiply( _q1 );
  4390. return this;
  4391. }
  4392. rotateOnWorldAxis( axis, angle ) {
  4393. // rotate object on axis in world space
  4394. // axis is assumed to be normalized
  4395. // method assumes no rotated parent
  4396. _q1.setFromAxisAngle( axis, angle );
  4397. this.quaternion.premultiply( _q1 );
  4398. return this;
  4399. }
  4400. rotateX( angle ) {
  4401. return this.rotateOnAxis( _xAxis, angle );
  4402. }
  4403. rotateY( angle ) {
  4404. return this.rotateOnAxis( _yAxis, angle );
  4405. }
  4406. rotateZ( angle ) {
  4407. return this.rotateOnAxis( _zAxis, angle );
  4408. }
  4409. translateOnAxis( axis, distance ) {
  4410. // translate object by distance along axis in object space
  4411. // axis is assumed to be normalized
  4412. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4413. this.position.add( _v1$4.multiplyScalar( distance ) );
  4414. return this;
  4415. }
  4416. translateX( distance ) {
  4417. return this.translateOnAxis( _xAxis, distance );
  4418. }
  4419. translateY( distance ) {
  4420. return this.translateOnAxis( _yAxis, distance );
  4421. }
  4422. translateZ( distance ) {
  4423. return this.translateOnAxis( _zAxis, distance );
  4424. }
  4425. localToWorld( vector ) {
  4426. this.updateWorldMatrix( true, false );
  4427. return vector.applyMatrix4( this.matrixWorld );
  4428. }
  4429. worldToLocal( vector ) {
  4430. this.updateWorldMatrix( true, false );
  4431. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  4432. }
  4433. lookAt( x, y, z ) {
  4434. // This method does not support objects having non-uniformly-scaled parent(s)
  4435. if ( x.isVector3 ) {
  4436. _target.copy( x );
  4437. } else {
  4438. _target.set( x, y, z );
  4439. }
  4440. const parent = this.parent;
  4441. this.updateWorldMatrix( true, false );
  4442. _position$3.setFromMatrixPosition( this.matrixWorld );
  4443. if ( this.isCamera || this.isLight ) {
  4444. _m1$3.lookAt( _position$3, _target, this.up );
  4445. } else {
  4446. _m1$3.lookAt( _target, _position$3, this.up );
  4447. }
  4448. this.quaternion.setFromRotationMatrix( _m1$3 );
  4449. if ( parent ) {
  4450. _m1$3.extractRotation( parent.matrixWorld );
  4451. _q1.setFromRotationMatrix( _m1$3 );
  4452. this.quaternion.premultiply( _q1.invert() );
  4453. }
  4454. }
  4455. add( object ) {
  4456. if ( arguments.length > 1 ) {
  4457. for ( let i = 0; i < arguments.length; i ++ ) {
  4458. this.add( arguments[ i ] );
  4459. }
  4460. return this;
  4461. }
  4462. if ( object === this ) {
  4463. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4464. return this;
  4465. }
  4466. if ( object && object.isObject3D ) {
  4467. object.removeFromParent();
  4468. object.parent = this;
  4469. this.children.push( object );
  4470. object.dispatchEvent( _addedEvent );
  4471. _childaddedEvent.child = object;
  4472. this.dispatchEvent( _childaddedEvent );
  4473. _childaddedEvent.child = null;
  4474. } else {
  4475. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4476. }
  4477. return this;
  4478. }
  4479. remove( object ) {
  4480. if ( arguments.length > 1 ) {
  4481. for ( let i = 0; i < arguments.length; i ++ ) {
  4482. this.remove( arguments[ i ] );
  4483. }
  4484. return this;
  4485. }
  4486. const index = this.children.indexOf( object );
  4487. if ( index !== - 1 ) {
  4488. object.parent = null;
  4489. this.children.splice( index, 1 );
  4490. object.dispatchEvent( _removedEvent );
  4491. _childremovedEvent.child = object;
  4492. this.dispatchEvent( _childremovedEvent );
  4493. _childremovedEvent.child = null;
  4494. }
  4495. return this;
  4496. }
  4497. removeFromParent() {
  4498. const parent = this.parent;
  4499. if ( parent !== null ) {
  4500. parent.remove( this );
  4501. }
  4502. return this;
  4503. }
  4504. clear() {
  4505. return this.remove( ... this.children );
  4506. }
  4507. attach( object ) {
  4508. // adds object as a child of this, while maintaining the object's world transform
  4509. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4510. this.updateWorldMatrix( true, false );
  4511. _m1$3.copy( this.matrixWorld ).invert();
  4512. if ( object.parent !== null ) {
  4513. object.parent.updateWorldMatrix( true, false );
  4514. _m1$3.multiply( object.parent.matrixWorld );
  4515. }
  4516. object.applyMatrix4( _m1$3 );
  4517. object.removeFromParent();
  4518. object.parent = this;
  4519. this.children.push( object );
  4520. object.updateWorldMatrix( false, true );
  4521. object.dispatchEvent( _addedEvent );
  4522. _childaddedEvent.child = object;
  4523. this.dispatchEvent( _childaddedEvent );
  4524. _childaddedEvent.child = null;
  4525. return this;
  4526. }
  4527. getObjectById( id ) {
  4528. return this.getObjectByProperty( 'id', id );
  4529. }
  4530. getObjectByName( name ) {
  4531. return this.getObjectByProperty( 'name', name );
  4532. }
  4533. getObjectByProperty( name, value ) {
  4534. if ( this[ name ] === value ) return this;
  4535. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4536. const child = this.children[ i ];
  4537. const object = child.getObjectByProperty( name, value );
  4538. if ( object !== undefined ) {
  4539. return object;
  4540. }
  4541. }
  4542. return undefined;
  4543. }
  4544. getObjectsByProperty( name, value, result = [] ) {
  4545. if ( this[ name ] === value ) result.push( this );
  4546. const children = this.children;
  4547. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4548. children[ i ].getObjectsByProperty( name, value, result );
  4549. }
  4550. return result;
  4551. }
  4552. getWorldPosition( target ) {
  4553. this.updateWorldMatrix( true, false );
  4554. return target.setFromMatrixPosition( this.matrixWorld );
  4555. }
  4556. getWorldQuaternion( target ) {
  4557. this.updateWorldMatrix( true, false );
  4558. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4559. return target;
  4560. }
  4561. getWorldScale( target ) {
  4562. this.updateWorldMatrix( true, false );
  4563. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4564. return target;
  4565. }
  4566. getWorldDirection( target ) {
  4567. this.updateWorldMatrix( true, false );
  4568. const e = this.matrixWorld.elements;
  4569. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4570. }
  4571. raycast( /* raycaster, intersects */ ) {}
  4572. traverse( callback ) {
  4573. callback( this );
  4574. const children = this.children;
  4575. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4576. children[ i ].traverse( callback );
  4577. }
  4578. }
  4579. traverseVisible( callback ) {
  4580. if ( this.visible === false ) return;
  4581. callback( this );
  4582. const children = this.children;
  4583. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4584. children[ i ].traverseVisible( callback );
  4585. }
  4586. }
  4587. traverseAncestors( callback ) {
  4588. const parent = this.parent;
  4589. if ( parent !== null ) {
  4590. callback( parent );
  4591. parent.traverseAncestors( callback );
  4592. }
  4593. }
  4594. updateMatrix() {
  4595. this.matrix.compose( this.position, this.quaternion, this.scale );
  4596. this.matrixWorldNeedsUpdate = true;
  4597. }
  4598. updateMatrixWorld( force ) {
  4599. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4600. if ( this.matrixWorldNeedsUpdate || force ) {
  4601. if ( this.parent === null ) {
  4602. this.matrixWorld.copy( this.matrix );
  4603. } else {
  4604. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4605. }
  4606. this.matrixWorldNeedsUpdate = false;
  4607. force = true;
  4608. }
  4609. // update children
  4610. const children = this.children;
  4611. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4612. const child = children[ i ];
  4613. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4614. child.updateMatrixWorld( force );
  4615. }
  4616. }
  4617. }
  4618. updateWorldMatrix( updateParents, updateChildren ) {
  4619. const parent = this.parent;
  4620. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4621. parent.updateWorldMatrix( true, false );
  4622. }
  4623. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4624. if ( this.parent === null ) {
  4625. this.matrixWorld.copy( this.matrix );
  4626. } else {
  4627. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4628. }
  4629. // update children
  4630. if ( updateChildren === true ) {
  4631. const children = this.children;
  4632. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4633. const child = children[ i ];
  4634. if ( child.matrixWorldAutoUpdate === true ) {
  4635. child.updateWorldMatrix( false, true );
  4636. }
  4637. }
  4638. }
  4639. }
  4640. toJSON( meta ) {
  4641. // meta is a string when called from JSON.stringify
  4642. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4643. const output = {};
  4644. // meta is a hash used to collect geometries, materials.
  4645. // not providing it implies that this is the root object
  4646. // being serialized.
  4647. if ( isRootObject ) {
  4648. // initialize meta obj
  4649. meta = {
  4650. geometries: {},
  4651. materials: {},
  4652. textures: {},
  4653. images: {},
  4654. shapes: {},
  4655. skeletons: {},
  4656. animations: {},
  4657. nodes: {}
  4658. };
  4659. output.metadata = {
  4660. version: 4.6,
  4661. type: 'Object',
  4662. generator: 'Object3D.toJSON'
  4663. };
  4664. }
  4665. // standard Object3D serialization
  4666. const object = {};
  4667. object.uuid = this.uuid;
  4668. object.type = this.type;
  4669. if ( this.name !== '' ) object.name = this.name;
  4670. if ( this.castShadow === true ) object.castShadow = true;
  4671. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4672. if ( this.visible === false ) object.visible = false;
  4673. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4674. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4675. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4676. object.layers = this.layers.mask;
  4677. object.matrix = this.matrix.toArray();
  4678. object.up = this.up.toArray();
  4679. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4680. // object specific properties
  4681. if ( this.isInstancedMesh ) {
  4682. object.type = 'InstancedMesh';
  4683. object.count = this.count;
  4684. object.instanceMatrix = this.instanceMatrix.toJSON();
  4685. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4686. }
  4687. if ( this.isBatchedMesh ) {
  4688. object.type = 'BatchedMesh';
  4689. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4690. object.sortObjects = this.sortObjects;
  4691. object.drawRanges = this._drawRanges;
  4692. object.reservedRanges = this._reservedRanges;
  4693. object.visibility = this._visibility;
  4694. object.active = this._active;
  4695. object.bounds = this._bounds.map( bound => ( {
  4696. boxInitialized: bound.boxInitialized,
  4697. boxMin: bound.box.min.toArray(),
  4698. boxMax: bound.box.max.toArray(),
  4699. sphereInitialized: bound.sphereInitialized,
  4700. sphereRadius: bound.sphere.radius,
  4701. sphereCenter: bound.sphere.center.toArray()
  4702. } ) );
  4703. object.maxGeometryCount = this._maxGeometryCount;
  4704. object.maxVertexCount = this._maxVertexCount;
  4705. object.maxIndexCount = this._maxIndexCount;
  4706. object.geometryInitialized = this._geometryInitialized;
  4707. object.geometryCount = this._geometryCount;
  4708. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4709. if ( this.boundingSphere !== null ) {
  4710. object.boundingSphere = {
  4711. center: object.boundingSphere.center.toArray(),
  4712. radius: object.boundingSphere.radius
  4713. };
  4714. }
  4715. if ( this.boundingBox !== null ) {
  4716. object.boundingBox = {
  4717. min: object.boundingBox.min.toArray(),
  4718. max: object.boundingBox.max.toArray()
  4719. };
  4720. }
  4721. }
  4722. //
  4723. function serialize( library, element ) {
  4724. if ( library[ element.uuid ] === undefined ) {
  4725. library[ element.uuid ] = element.toJSON( meta );
  4726. }
  4727. return element.uuid;
  4728. }
  4729. if ( this.isScene ) {
  4730. if ( this.background ) {
  4731. if ( this.background.isColor ) {
  4732. object.background = this.background.toJSON();
  4733. } else if ( this.background.isTexture ) {
  4734. object.background = this.background.toJSON( meta ).uuid;
  4735. }
  4736. }
  4737. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4738. object.environment = this.environment.toJSON( meta ).uuid;
  4739. }
  4740. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4741. object.geometry = serialize( meta.geometries, this.geometry );
  4742. const parameters = this.geometry.parameters;
  4743. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4744. const shapes = parameters.shapes;
  4745. if ( Array.isArray( shapes ) ) {
  4746. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4747. const shape = shapes[ i ];
  4748. serialize( meta.shapes, shape );
  4749. }
  4750. } else {
  4751. serialize( meta.shapes, shapes );
  4752. }
  4753. }
  4754. }
  4755. if ( this.isSkinnedMesh ) {
  4756. object.bindMode = this.bindMode;
  4757. object.bindMatrix = this.bindMatrix.toArray();
  4758. if ( this.skeleton !== undefined ) {
  4759. serialize( meta.skeletons, this.skeleton );
  4760. object.skeleton = this.skeleton.uuid;
  4761. }
  4762. }
  4763. if ( this.material !== undefined ) {
  4764. if ( Array.isArray( this.material ) ) {
  4765. const uuids = [];
  4766. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4767. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4768. }
  4769. object.material = uuids;
  4770. } else {
  4771. object.material = serialize( meta.materials, this.material );
  4772. }
  4773. }
  4774. //
  4775. if ( this.children.length > 0 ) {
  4776. object.children = [];
  4777. for ( let i = 0; i < this.children.length; i ++ ) {
  4778. object.children.push( this.children[ i ].toJSON( meta ).object );
  4779. }
  4780. }
  4781. //
  4782. if ( this.animations.length > 0 ) {
  4783. object.animations = [];
  4784. for ( let i = 0; i < this.animations.length; i ++ ) {
  4785. const animation = this.animations[ i ];
  4786. object.animations.push( serialize( meta.animations, animation ) );
  4787. }
  4788. }
  4789. if ( isRootObject ) {
  4790. const geometries = extractFromCache( meta.geometries );
  4791. const materials = extractFromCache( meta.materials );
  4792. const textures = extractFromCache( meta.textures );
  4793. const images = extractFromCache( meta.images );
  4794. const shapes = extractFromCache( meta.shapes );
  4795. const skeletons = extractFromCache( meta.skeletons );
  4796. const animations = extractFromCache( meta.animations );
  4797. const nodes = extractFromCache( meta.nodes );
  4798. if ( geometries.length > 0 ) output.geometries = geometries;
  4799. if ( materials.length > 0 ) output.materials = materials;
  4800. if ( textures.length > 0 ) output.textures = textures;
  4801. if ( images.length > 0 ) output.images = images;
  4802. if ( shapes.length > 0 ) output.shapes = shapes;
  4803. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4804. if ( animations.length > 0 ) output.animations = animations;
  4805. if ( nodes.length > 0 ) output.nodes = nodes;
  4806. }
  4807. output.object = object;
  4808. return output;
  4809. // extract data from the cache hash
  4810. // remove metadata on each item
  4811. // and return as array
  4812. function extractFromCache( cache ) {
  4813. const values = [];
  4814. for ( const key in cache ) {
  4815. const data = cache[ key ];
  4816. delete data.metadata;
  4817. values.push( data );
  4818. }
  4819. return values;
  4820. }
  4821. }
  4822. clone( recursive ) {
  4823. return new this.constructor().copy( this, recursive );
  4824. }
  4825. copy( source, recursive = true ) {
  4826. this.name = source.name;
  4827. this.up.copy( source.up );
  4828. this.position.copy( source.position );
  4829. this.rotation.order = source.rotation.order;
  4830. this.quaternion.copy( source.quaternion );
  4831. this.scale.copy( source.scale );
  4832. this.matrix.copy( source.matrix );
  4833. this.matrixWorld.copy( source.matrixWorld );
  4834. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4835. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4836. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4837. this.layers.mask = source.layers.mask;
  4838. this.visible = source.visible;
  4839. this.castShadow = source.castShadow;
  4840. this.receiveShadow = source.receiveShadow;
  4841. this.frustumCulled = source.frustumCulled;
  4842. this.renderOrder = source.renderOrder;
  4843. this.animations = source.animations.slice();
  4844. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4845. if ( recursive === true ) {
  4846. for ( let i = 0; i < source.children.length; i ++ ) {
  4847. const child = source.children[ i ];
  4848. this.add( child.clone() );
  4849. }
  4850. }
  4851. return this;
  4852. }
  4853. }
  4854. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4855. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4856. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4857. const _v0$1 = /*@__PURE__*/ new Vector3();
  4858. const _v1$3 = /*@__PURE__*/ new Vector3();
  4859. const _v2$2 = /*@__PURE__*/ new Vector3();
  4860. const _v3$2 = /*@__PURE__*/ new Vector3();
  4861. const _vab = /*@__PURE__*/ new Vector3();
  4862. const _vac = /*@__PURE__*/ new Vector3();
  4863. const _vbc = /*@__PURE__*/ new Vector3();
  4864. const _vap = /*@__PURE__*/ new Vector3();
  4865. const _vbp = /*@__PURE__*/ new Vector3();
  4866. const _vcp = /*@__PURE__*/ new Vector3();
  4867. class Triangle {
  4868. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4869. this.a = a;
  4870. this.b = b;
  4871. this.c = c;
  4872. }
  4873. static getNormal( a, b, c, target ) {
  4874. target.subVectors( c, b );
  4875. _v0$1.subVectors( a, b );
  4876. target.cross( _v0$1 );
  4877. const targetLengthSq = target.lengthSq();
  4878. if ( targetLengthSq > 0 ) {
  4879. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4880. }
  4881. return target.set( 0, 0, 0 );
  4882. }
  4883. // static/instance method to calculate barycentric coordinates
  4884. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4885. static getBarycoord( point, a, b, c, target ) {
  4886. _v0$1.subVectors( c, a );
  4887. _v1$3.subVectors( b, a );
  4888. _v2$2.subVectors( point, a );
  4889. const dot00 = _v0$1.dot( _v0$1 );
  4890. const dot01 = _v0$1.dot( _v1$3 );
  4891. const dot02 = _v0$1.dot( _v2$2 );
  4892. const dot11 = _v1$3.dot( _v1$3 );
  4893. const dot12 = _v1$3.dot( _v2$2 );
  4894. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4895. // collinear or singular triangle
  4896. if ( denom === 0 ) {
  4897. target.set( 0, 0, 0 );
  4898. return null;
  4899. }
  4900. const invDenom = 1 / denom;
  4901. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4902. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4903. // barycentric coordinates must always sum to 1
  4904. return target.set( 1 - u - v, v, u );
  4905. }
  4906. static containsPoint( point, a, b, c ) {
  4907. // if the triangle is degenerate then we can't contain a point
  4908. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4909. return false;
  4910. }
  4911. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4912. }
  4913. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4914. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4915. target.x = 0;
  4916. target.y = 0;
  4917. if ( 'z' in target ) target.z = 0;
  4918. if ( 'w' in target ) target.w = 0;
  4919. return null;
  4920. }
  4921. target.setScalar( 0 );
  4922. target.addScaledVector( v1, _v3$2.x );
  4923. target.addScaledVector( v2, _v3$2.y );
  4924. target.addScaledVector( v3, _v3$2.z );
  4925. return target;
  4926. }
  4927. static isFrontFacing( a, b, c, direction ) {
  4928. _v0$1.subVectors( c, b );
  4929. _v1$3.subVectors( a, b );
  4930. // strictly front facing
  4931. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4932. }
  4933. set( a, b, c ) {
  4934. this.a.copy( a );
  4935. this.b.copy( b );
  4936. this.c.copy( c );
  4937. return this;
  4938. }
  4939. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4940. this.a.copy( points[ i0 ] );
  4941. this.b.copy( points[ i1 ] );
  4942. this.c.copy( points[ i2 ] );
  4943. return this;
  4944. }
  4945. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4946. this.a.fromBufferAttribute( attribute, i0 );
  4947. this.b.fromBufferAttribute( attribute, i1 );
  4948. this.c.fromBufferAttribute( attribute, i2 );
  4949. return this;
  4950. }
  4951. clone() {
  4952. return new this.constructor().copy( this );
  4953. }
  4954. copy( triangle ) {
  4955. this.a.copy( triangle.a );
  4956. this.b.copy( triangle.b );
  4957. this.c.copy( triangle.c );
  4958. return this;
  4959. }
  4960. getArea() {
  4961. _v0$1.subVectors( this.c, this.b );
  4962. _v1$3.subVectors( this.a, this.b );
  4963. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4964. }
  4965. getMidpoint( target ) {
  4966. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4967. }
  4968. getNormal( target ) {
  4969. return Triangle.getNormal( this.a, this.b, this.c, target );
  4970. }
  4971. getPlane( target ) {
  4972. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4973. }
  4974. getBarycoord( point, target ) {
  4975. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4976. }
  4977. getInterpolation( point, v1, v2, v3, target ) {
  4978. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  4979. }
  4980. containsPoint( point ) {
  4981. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4982. }
  4983. isFrontFacing( direction ) {
  4984. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4985. }
  4986. intersectsBox( box ) {
  4987. return box.intersectsTriangle( this );
  4988. }
  4989. closestPointToPoint( p, target ) {
  4990. const a = this.a, b = this.b, c = this.c;
  4991. let v, w;
  4992. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4993. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4994. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4995. // basically, we're distinguishing which of the voronoi regions of the triangle
  4996. // the point lies in with the minimum amount of redundant computation.
  4997. _vab.subVectors( b, a );
  4998. _vac.subVectors( c, a );
  4999. _vap.subVectors( p, a );
  5000. const d1 = _vab.dot( _vap );
  5001. const d2 = _vac.dot( _vap );
  5002. if ( d1 <= 0 && d2 <= 0 ) {
  5003. // vertex region of A; barycentric coords (1, 0, 0)
  5004. return target.copy( a );
  5005. }
  5006. _vbp.subVectors( p, b );
  5007. const d3 = _vab.dot( _vbp );
  5008. const d4 = _vac.dot( _vbp );
  5009. if ( d3 >= 0 && d4 <= d3 ) {
  5010. // vertex region of B; barycentric coords (0, 1, 0)
  5011. return target.copy( b );
  5012. }
  5013. const vc = d1 * d4 - d3 * d2;
  5014. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5015. v = d1 / ( d1 - d3 );
  5016. // edge region of AB; barycentric coords (1-v, v, 0)
  5017. return target.copy( a ).addScaledVector( _vab, v );
  5018. }
  5019. _vcp.subVectors( p, c );
  5020. const d5 = _vab.dot( _vcp );
  5021. const d6 = _vac.dot( _vcp );
  5022. if ( d6 >= 0 && d5 <= d6 ) {
  5023. // vertex region of C; barycentric coords (0, 0, 1)
  5024. return target.copy( c );
  5025. }
  5026. const vb = d5 * d2 - d1 * d6;
  5027. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5028. w = d2 / ( d2 - d6 );
  5029. // edge region of AC; barycentric coords (1-w, 0, w)
  5030. return target.copy( a ).addScaledVector( _vac, w );
  5031. }
  5032. const va = d3 * d6 - d5 * d4;
  5033. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5034. _vbc.subVectors( c, b );
  5035. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5036. // edge region of BC; barycentric coords (0, 1-w, w)
  5037. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5038. }
  5039. // face region
  5040. const denom = 1 / ( va + vb + vc );
  5041. // u = va * denom
  5042. v = vb * denom;
  5043. w = vc * denom;
  5044. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5045. }
  5046. equals( triangle ) {
  5047. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5048. }
  5049. }
  5050. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5051. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5052. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5053. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5054. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5055. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5056. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5057. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5058. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5059. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5060. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5061. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5062. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5063. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5064. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5065. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5066. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5067. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5068. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5069. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5070. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5071. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5072. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5073. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5074. const _hslA = { h: 0, s: 0, l: 0 };
  5075. const _hslB = { h: 0, s: 0, l: 0 };
  5076. function hue2rgb( p, q, t ) {
  5077. if ( t < 0 ) t += 1;
  5078. if ( t > 1 ) t -= 1;
  5079. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5080. if ( t < 1 / 2 ) return q;
  5081. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5082. return p;
  5083. }
  5084. class Color {
  5085. constructor( r, g, b ) {
  5086. this.isColor = true;
  5087. this.r = 1;
  5088. this.g = 1;
  5089. this.b = 1;
  5090. return this.set( r, g, b );
  5091. }
  5092. set( r, g, b ) {
  5093. if ( g === undefined && b === undefined ) {
  5094. // r is THREE.Color, hex or string
  5095. const value = r;
  5096. if ( value && value.isColor ) {
  5097. this.copy( value );
  5098. } else if ( typeof value === 'number' ) {
  5099. this.setHex( value );
  5100. } else if ( typeof value === 'string' ) {
  5101. this.setStyle( value );
  5102. }
  5103. } else {
  5104. this.setRGB( r, g, b );
  5105. }
  5106. return this;
  5107. }
  5108. setScalar( scalar ) {
  5109. this.r = scalar;
  5110. this.g = scalar;
  5111. this.b = scalar;
  5112. return this;
  5113. }
  5114. setHex( hex, colorSpace = SRGBColorSpace ) {
  5115. hex = Math.floor( hex );
  5116. this.r = ( hex >> 16 & 255 ) / 255;
  5117. this.g = ( hex >> 8 & 255 ) / 255;
  5118. this.b = ( hex & 255 ) / 255;
  5119. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5120. return this;
  5121. }
  5122. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5123. this.r = r;
  5124. this.g = g;
  5125. this.b = b;
  5126. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5127. return this;
  5128. }
  5129. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5130. // h,s,l ranges are in 0.0 - 1.0
  5131. h = euclideanModulo( h, 1 );
  5132. s = clamp( s, 0, 1 );
  5133. l = clamp( l, 0, 1 );
  5134. if ( s === 0 ) {
  5135. this.r = this.g = this.b = l;
  5136. } else {
  5137. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5138. const q = ( 2 * l ) - p;
  5139. this.r = hue2rgb( q, p, h + 1 / 3 );
  5140. this.g = hue2rgb( q, p, h );
  5141. this.b = hue2rgb( q, p, h - 1 / 3 );
  5142. }
  5143. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5144. return this;
  5145. }
  5146. setStyle( style, colorSpace = SRGBColorSpace ) {
  5147. function handleAlpha( string ) {
  5148. if ( string === undefined ) return;
  5149. if ( parseFloat( string ) < 1 ) {
  5150. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5151. }
  5152. }
  5153. let m;
  5154. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5155. // rgb / hsl
  5156. let color;
  5157. const name = m[ 1 ];
  5158. const components = m[ 2 ];
  5159. switch ( name ) {
  5160. case 'rgb':
  5161. case 'rgba':
  5162. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5163. // rgb(255,0,0) rgba(255,0,0,0.5)
  5164. handleAlpha( color[ 4 ] );
  5165. return this.setRGB(
  5166. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5167. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5168. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5169. colorSpace
  5170. );
  5171. }
  5172. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5173. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5174. handleAlpha( color[ 4 ] );
  5175. return this.setRGB(
  5176. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5177. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5178. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5179. colorSpace
  5180. );
  5181. }
  5182. break;
  5183. case 'hsl':
  5184. case 'hsla':
  5185. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5186. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5187. handleAlpha( color[ 4 ] );
  5188. return this.setHSL(
  5189. parseFloat( color[ 1 ] ) / 360,
  5190. parseFloat( color[ 2 ] ) / 100,
  5191. parseFloat( color[ 3 ] ) / 100,
  5192. colorSpace
  5193. );
  5194. }
  5195. break;
  5196. default:
  5197. console.warn( 'THREE.Color: Unknown color model ' + style );
  5198. }
  5199. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5200. // hex color
  5201. const hex = m[ 1 ];
  5202. const size = hex.length;
  5203. if ( size === 3 ) {
  5204. // #ff0
  5205. return this.setRGB(
  5206. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5207. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5208. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5209. colorSpace
  5210. );
  5211. } else if ( size === 6 ) {
  5212. // #ff0000
  5213. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5214. } else {
  5215. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5216. }
  5217. } else if ( style && style.length > 0 ) {
  5218. return this.setColorName( style, colorSpace );
  5219. }
  5220. return this;
  5221. }
  5222. setColorName( style, colorSpace = SRGBColorSpace ) {
  5223. // color keywords
  5224. const hex = _colorKeywords[ style.toLowerCase() ];
  5225. if ( hex !== undefined ) {
  5226. // red
  5227. this.setHex( hex, colorSpace );
  5228. } else {
  5229. // unknown color
  5230. console.warn( 'THREE.Color: Unknown color ' + style );
  5231. }
  5232. return this;
  5233. }
  5234. clone() {
  5235. return new this.constructor( this.r, this.g, this.b );
  5236. }
  5237. copy( color ) {
  5238. this.r = color.r;
  5239. this.g = color.g;
  5240. this.b = color.b;
  5241. return this;
  5242. }
  5243. copySRGBToLinear( color ) {
  5244. this.r = SRGBToLinear( color.r );
  5245. this.g = SRGBToLinear( color.g );
  5246. this.b = SRGBToLinear( color.b );
  5247. return this;
  5248. }
  5249. copyLinearToSRGB( color ) {
  5250. this.r = LinearToSRGB( color.r );
  5251. this.g = LinearToSRGB( color.g );
  5252. this.b = LinearToSRGB( color.b );
  5253. return this;
  5254. }
  5255. convertSRGBToLinear() {
  5256. this.copySRGBToLinear( this );
  5257. return this;
  5258. }
  5259. convertLinearToSRGB() {
  5260. this.copyLinearToSRGB( this );
  5261. return this;
  5262. }
  5263. getHex( colorSpace = SRGBColorSpace ) {
  5264. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5265. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  5266. }
  5267. getHexString( colorSpace = SRGBColorSpace ) {
  5268. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5269. }
  5270. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5271. // h,s,l ranges are in 0.0 - 1.0
  5272. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5273. const r = _color.r, g = _color.g, b = _color.b;
  5274. const max = Math.max( r, g, b );
  5275. const min = Math.min( r, g, b );
  5276. let hue, saturation;
  5277. const lightness = ( min + max ) / 2.0;
  5278. if ( min === max ) {
  5279. hue = 0;
  5280. saturation = 0;
  5281. } else {
  5282. const delta = max - min;
  5283. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5284. switch ( max ) {
  5285. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5286. case g: hue = ( b - r ) / delta + 2; break;
  5287. case b: hue = ( r - g ) / delta + 4; break;
  5288. }
  5289. hue /= 6;
  5290. }
  5291. target.h = hue;
  5292. target.s = saturation;
  5293. target.l = lightness;
  5294. return target;
  5295. }
  5296. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5297. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5298. target.r = _color.r;
  5299. target.g = _color.g;
  5300. target.b = _color.b;
  5301. return target;
  5302. }
  5303. getStyle( colorSpace = SRGBColorSpace ) {
  5304. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5305. const r = _color.r, g = _color.g, b = _color.b;
  5306. if ( colorSpace !== SRGBColorSpace ) {
  5307. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5308. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5309. }
  5310. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5311. }
  5312. offsetHSL( h, s, l ) {
  5313. this.getHSL( _hslA );
  5314. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5315. }
  5316. add( color ) {
  5317. this.r += color.r;
  5318. this.g += color.g;
  5319. this.b += color.b;
  5320. return this;
  5321. }
  5322. addColors( color1, color2 ) {
  5323. this.r = color1.r + color2.r;
  5324. this.g = color1.g + color2.g;
  5325. this.b = color1.b + color2.b;
  5326. return this;
  5327. }
  5328. addScalar( s ) {
  5329. this.r += s;
  5330. this.g += s;
  5331. this.b += s;
  5332. return this;
  5333. }
  5334. sub( color ) {
  5335. this.r = Math.max( 0, this.r - color.r );
  5336. this.g = Math.max( 0, this.g - color.g );
  5337. this.b = Math.max( 0, this.b - color.b );
  5338. return this;
  5339. }
  5340. multiply( color ) {
  5341. this.r *= color.r;
  5342. this.g *= color.g;
  5343. this.b *= color.b;
  5344. return this;
  5345. }
  5346. multiplyScalar( s ) {
  5347. this.r *= s;
  5348. this.g *= s;
  5349. this.b *= s;
  5350. return this;
  5351. }
  5352. lerp( color, alpha ) {
  5353. this.r += ( color.r - this.r ) * alpha;
  5354. this.g += ( color.g - this.g ) * alpha;
  5355. this.b += ( color.b - this.b ) * alpha;
  5356. return this;
  5357. }
  5358. lerpColors( color1, color2, alpha ) {
  5359. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5360. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5361. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5362. return this;
  5363. }
  5364. lerpHSL( color, alpha ) {
  5365. this.getHSL( _hslA );
  5366. color.getHSL( _hslB );
  5367. const h = lerp( _hslA.h, _hslB.h, alpha );
  5368. const s = lerp( _hslA.s, _hslB.s, alpha );
  5369. const l = lerp( _hslA.l, _hslB.l, alpha );
  5370. this.setHSL( h, s, l );
  5371. return this;
  5372. }
  5373. setFromVector3( v ) {
  5374. this.r = v.x;
  5375. this.g = v.y;
  5376. this.b = v.z;
  5377. return this;
  5378. }
  5379. applyMatrix3( m ) {
  5380. const r = this.r, g = this.g, b = this.b;
  5381. const e = m.elements;
  5382. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5383. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5384. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5385. return this;
  5386. }
  5387. equals( c ) {
  5388. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5389. }
  5390. fromArray( array, offset = 0 ) {
  5391. this.r = array[ offset ];
  5392. this.g = array[ offset + 1 ];
  5393. this.b = array[ offset + 2 ];
  5394. return this;
  5395. }
  5396. toArray( array = [], offset = 0 ) {
  5397. array[ offset ] = this.r;
  5398. array[ offset + 1 ] = this.g;
  5399. array[ offset + 2 ] = this.b;
  5400. return array;
  5401. }
  5402. fromBufferAttribute( attribute, index ) {
  5403. this.r = attribute.getX( index );
  5404. this.g = attribute.getY( index );
  5405. this.b = attribute.getZ( index );
  5406. return this;
  5407. }
  5408. toJSON() {
  5409. return this.getHex();
  5410. }
  5411. *[ Symbol.iterator ]() {
  5412. yield this.r;
  5413. yield this.g;
  5414. yield this.b;
  5415. }
  5416. }
  5417. const _color = /*@__PURE__*/ new Color();
  5418. Color.NAMES = _colorKeywords;
  5419. let _materialId = 0;
  5420. class Material extends EventDispatcher {
  5421. constructor() {
  5422. super();
  5423. this.isMaterial = true;
  5424. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5425. this.uuid = generateUUID();
  5426. this.name = '';
  5427. this.type = 'Material';
  5428. this.blending = NormalBlending;
  5429. this.side = FrontSide;
  5430. this.vertexColors = false;
  5431. this.opacity = 1;
  5432. this.transparent = false;
  5433. this.alphaHash = false;
  5434. this.blendSrc = SrcAlphaFactor;
  5435. this.blendDst = OneMinusSrcAlphaFactor;
  5436. this.blendEquation = AddEquation;
  5437. this.blendSrcAlpha = null;
  5438. this.blendDstAlpha = null;
  5439. this.blendEquationAlpha = null;
  5440. this.blendColor = new Color( 0, 0, 0 );
  5441. this.blendAlpha = 0;
  5442. this.depthFunc = LessEqualDepth;
  5443. this.depthTest = true;
  5444. this.depthWrite = true;
  5445. this.stencilWriteMask = 0xff;
  5446. this.stencilFunc = AlwaysStencilFunc;
  5447. this.stencilRef = 0;
  5448. this.stencilFuncMask = 0xff;
  5449. this.stencilFail = KeepStencilOp;
  5450. this.stencilZFail = KeepStencilOp;
  5451. this.stencilZPass = KeepStencilOp;
  5452. this.stencilWrite = false;
  5453. this.clippingPlanes = null;
  5454. this.clipIntersection = false;
  5455. this.clipShadows = false;
  5456. this.shadowSide = null;
  5457. this.colorWrite = true;
  5458. this.precision = null; // override the renderer's default precision for this material
  5459. this.polygonOffset = false;
  5460. this.polygonOffsetFactor = 0;
  5461. this.polygonOffsetUnits = 0;
  5462. this.dithering = false;
  5463. this.alphaToCoverage = false;
  5464. this.premultipliedAlpha = false;
  5465. this.forceSinglePass = false;
  5466. this.visible = true;
  5467. this.toneMapped = true;
  5468. this.userData = {};
  5469. this.version = 0;
  5470. this._alphaTest = 0;
  5471. }
  5472. get alphaTest() {
  5473. return this._alphaTest;
  5474. }
  5475. set alphaTest( value ) {
  5476. if ( this._alphaTest > 0 !== value > 0 ) {
  5477. this.version ++;
  5478. }
  5479. this._alphaTest = value;
  5480. }
  5481. onBuild( /* shaderobject, renderer */ ) {}
  5482. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5483. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5484. customProgramCacheKey() {
  5485. return this.onBeforeCompile.toString();
  5486. }
  5487. setValues( values ) {
  5488. if ( values === undefined ) return;
  5489. for ( const key in values ) {
  5490. const newValue = values[ key ];
  5491. if ( newValue === undefined ) {
  5492. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5493. continue;
  5494. }
  5495. const currentValue = this[ key ];
  5496. if ( currentValue === undefined ) {
  5497. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5498. continue;
  5499. }
  5500. if ( currentValue && currentValue.isColor ) {
  5501. currentValue.set( newValue );
  5502. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5503. currentValue.copy( newValue );
  5504. } else {
  5505. this[ key ] = newValue;
  5506. }
  5507. }
  5508. }
  5509. toJSON( meta ) {
  5510. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5511. if ( isRootObject ) {
  5512. meta = {
  5513. textures: {},
  5514. images: {}
  5515. };
  5516. }
  5517. const data = {
  5518. metadata: {
  5519. version: 4.6,
  5520. type: 'Material',
  5521. generator: 'Material.toJSON'
  5522. }
  5523. };
  5524. // standard Material serialization
  5525. data.uuid = this.uuid;
  5526. data.type = this.type;
  5527. if ( this.name !== '' ) data.name = this.name;
  5528. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5529. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5530. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5531. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5532. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5533. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5534. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5535. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5536. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5537. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5538. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5539. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5540. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5541. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5542. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5543. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5544. }
  5545. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5546. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5547. }
  5548. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5549. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5550. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5551. }
  5552. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5553. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5554. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5555. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5556. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5557. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5558. }
  5559. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5560. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5561. }
  5562. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5563. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5564. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5565. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5566. }
  5567. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5568. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5569. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5570. if ( this.lightMap && this.lightMap.isTexture ) {
  5571. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5572. data.lightMapIntensity = this.lightMapIntensity;
  5573. }
  5574. if ( this.aoMap && this.aoMap.isTexture ) {
  5575. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5576. data.aoMapIntensity = this.aoMapIntensity;
  5577. }
  5578. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5579. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5580. data.bumpScale = this.bumpScale;
  5581. }
  5582. if ( this.normalMap && this.normalMap.isTexture ) {
  5583. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5584. data.normalMapType = this.normalMapType;
  5585. data.normalScale = this.normalScale.toArray();
  5586. }
  5587. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5588. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5589. data.displacementScale = this.displacementScale;
  5590. data.displacementBias = this.displacementBias;
  5591. }
  5592. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5593. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5594. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5595. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5596. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5597. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5598. if ( this.envMap && this.envMap.isTexture ) {
  5599. data.envMap = this.envMap.toJSON( meta ).uuid;
  5600. if ( this.combine !== undefined ) data.combine = this.combine;
  5601. }
  5602. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5603. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5604. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5605. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5606. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5607. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5608. }
  5609. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5610. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5611. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5612. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5613. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5614. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5615. if ( this.size !== undefined ) data.size = this.size;
  5616. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5617. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5618. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5619. if ( this.side !== FrontSide ) data.side = this.side;
  5620. if ( this.vertexColors === true ) data.vertexColors = true;
  5621. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5622. if ( this.transparent === true ) data.transparent = true;
  5623. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5624. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5625. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5626. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5627. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5628. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5629. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5630. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5631. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5632. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5633. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5634. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5635. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5636. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5637. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5638. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5639. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5640. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5641. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5642. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5643. // rotation (SpriteMaterial)
  5644. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5645. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5646. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5647. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5648. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5649. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5650. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5651. if ( this.scale !== undefined ) data.scale = this.scale;
  5652. if ( this.dithering === true ) data.dithering = true;
  5653. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5654. if ( this.alphaHash === true ) data.alphaHash = true;
  5655. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5656. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5657. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5658. if ( this.wireframe === true ) data.wireframe = true;
  5659. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5660. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5661. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5662. if ( this.flatShading === true ) data.flatShading = true;
  5663. if ( this.visible === false ) data.visible = false;
  5664. if ( this.toneMapped === false ) data.toneMapped = false;
  5665. if ( this.fog === false ) data.fog = false;
  5666. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5667. // TODO: Copied from Object3D.toJSON
  5668. function extractFromCache( cache ) {
  5669. const values = [];
  5670. for ( const key in cache ) {
  5671. const data = cache[ key ];
  5672. delete data.metadata;
  5673. values.push( data );
  5674. }
  5675. return values;
  5676. }
  5677. if ( isRootObject ) {
  5678. const textures = extractFromCache( meta.textures );
  5679. const images = extractFromCache( meta.images );
  5680. if ( textures.length > 0 ) data.textures = textures;
  5681. if ( images.length > 0 ) data.images = images;
  5682. }
  5683. return data;
  5684. }
  5685. clone() {
  5686. return new this.constructor().copy( this );
  5687. }
  5688. copy( source ) {
  5689. this.name = source.name;
  5690. this.blending = source.blending;
  5691. this.side = source.side;
  5692. this.vertexColors = source.vertexColors;
  5693. this.opacity = source.opacity;
  5694. this.transparent = source.transparent;
  5695. this.blendSrc = source.blendSrc;
  5696. this.blendDst = source.blendDst;
  5697. this.blendEquation = source.blendEquation;
  5698. this.blendSrcAlpha = source.blendSrcAlpha;
  5699. this.blendDstAlpha = source.blendDstAlpha;
  5700. this.blendEquationAlpha = source.blendEquationAlpha;
  5701. this.blendColor.copy( source.blendColor );
  5702. this.blendAlpha = source.blendAlpha;
  5703. this.depthFunc = source.depthFunc;
  5704. this.depthTest = source.depthTest;
  5705. this.depthWrite = source.depthWrite;
  5706. this.stencilWriteMask = source.stencilWriteMask;
  5707. this.stencilFunc = source.stencilFunc;
  5708. this.stencilRef = source.stencilRef;
  5709. this.stencilFuncMask = source.stencilFuncMask;
  5710. this.stencilFail = source.stencilFail;
  5711. this.stencilZFail = source.stencilZFail;
  5712. this.stencilZPass = source.stencilZPass;
  5713. this.stencilWrite = source.stencilWrite;
  5714. const srcPlanes = source.clippingPlanes;
  5715. let dstPlanes = null;
  5716. if ( srcPlanes !== null ) {
  5717. const n = srcPlanes.length;
  5718. dstPlanes = new Array( n );
  5719. for ( let i = 0; i !== n; ++ i ) {
  5720. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5721. }
  5722. }
  5723. this.clippingPlanes = dstPlanes;
  5724. this.clipIntersection = source.clipIntersection;
  5725. this.clipShadows = source.clipShadows;
  5726. this.shadowSide = source.shadowSide;
  5727. this.colorWrite = source.colorWrite;
  5728. this.precision = source.precision;
  5729. this.polygonOffset = source.polygonOffset;
  5730. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5731. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5732. this.dithering = source.dithering;
  5733. this.alphaTest = source.alphaTest;
  5734. this.alphaHash = source.alphaHash;
  5735. this.alphaToCoverage = source.alphaToCoverage;
  5736. this.premultipliedAlpha = source.premultipliedAlpha;
  5737. this.forceSinglePass = source.forceSinglePass;
  5738. this.visible = source.visible;
  5739. this.toneMapped = source.toneMapped;
  5740. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5741. return this;
  5742. }
  5743. dispose() {
  5744. this.dispatchEvent( { type: 'dispose' } );
  5745. }
  5746. set needsUpdate( value ) {
  5747. if ( value === true ) this.version ++;
  5748. }
  5749. }
  5750. class MeshBasicMaterial extends Material {
  5751. constructor( parameters ) {
  5752. super();
  5753. this.isMeshBasicMaterial = true;
  5754. this.type = 'MeshBasicMaterial';
  5755. this.color = new Color( 0xffffff ); // emissive
  5756. this.map = null;
  5757. this.lightMap = null;
  5758. this.lightMapIntensity = 1.0;
  5759. this.aoMap = null;
  5760. this.aoMapIntensity = 1.0;
  5761. this.specularMap = null;
  5762. this.alphaMap = null;
  5763. this.envMap = null;
  5764. this.envMapRotation = new Euler();
  5765. this.combine = MultiplyOperation;
  5766. this.reflectivity = 1;
  5767. this.refractionRatio = 0.98;
  5768. this.wireframe = false;
  5769. this.wireframeLinewidth = 1;
  5770. this.wireframeLinecap = 'round';
  5771. this.wireframeLinejoin = 'round';
  5772. this.fog = true;
  5773. this.setValues( parameters );
  5774. }
  5775. copy( source ) {
  5776. super.copy( source );
  5777. this.color.copy( source.color );
  5778. this.map = source.map;
  5779. this.lightMap = source.lightMap;
  5780. this.lightMapIntensity = source.lightMapIntensity;
  5781. this.aoMap = source.aoMap;
  5782. this.aoMapIntensity = source.aoMapIntensity;
  5783. this.specularMap = source.specularMap;
  5784. this.alphaMap = source.alphaMap;
  5785. this.envMap = source.envMap;
  5786. this.envMapRotation.copy( source.envMapRotation );
  5787. this.combine = source.combine;
  5788. this.reflectivity = source.reflectivity;
  5789. this.refractionRatio = source.refractionRatio;
  5790. this.wireframe = source.wireframe;
  5791. this.wireframeLinewidth = source.wireframeLinewidth;
  5792. this.wireframeLinecap = source.wireframeLinecap;
  5793. this.wireframeLinejoin = source.wireframeLinejoin;
  5794. this.fog = source.fog;
  5795. return this;
  5796. }
  5797. }
  5798. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5799. const _tables = /*@__PURE__*/ _generateTables();
  5800. function _generateTables() {
  5801. // float32 to float16 helpers
  5802. const buffer = new ArrayBuffer( 4 );
  5803. const floatView = new Float32Array( buffer );
  5804. const uint32View = new Uint32Array( buffer );
  5805. const baseTable = new Uint32Array( 512 );
  5806. const shiftTable = new Uint32Array( 512 );
  5807. for ( let i = 0; i < 256; ++ i ) {
  5808. const e = i - 127;
  5809. // very small number (0, -0)
  5810. if ( e < - 27 ) {
  5811. baseTable[ i ] = 0x0000;
  5812. baseTable[ i | 0x100 ] = 0x8000;
  5813. shiftTable[ i ] = 24;
  5814. shiftTable[ i | 0x100 ] = 24;
  5815. // small number (denorm)
  5816. } else if ( e < - 14 ) {
  5817. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5818. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5819. shiftTable[ i ] = - e - 1;
  5820. shiftTable[ i | 0x100 ] = - e - 1;
  5821. // normal number
  5822. } else if ( e <= 15 ) {
  5823. baseTable[ i ] = ( e + 15 ) << 10;
  5824. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5825. shiftTable[ i ] = 13;
  5826. shiftTable[ i | 0x100 ] = 13;
  5827. // large number (Infinity, -Infinity)
  5828. } else if ( e < 128 ) {
  5829. baseTable[ i ] = 0x7c00;
  5830. baseTable[ i | 0x100 ] = 0xfc00;
  5831. shiftTable[ i ] = 24;
  5832. shiftTable[ i | 0x100 ] = 24;
  5833. // stay (NaN, Infinity, -Infinity)
  5834. } else {
  5835. baseTable[ i ] = 0x7c00;
  5836. baseTable[ i | 0x100 ] = 0xfc00;
  5837. shiftTable[ i ] = 13;
  5838. shiftTable[ i | 0x100 ] = 13;
  5839. }
  5840. }
  5841. // float16 to float32 helpers
  5842. const mantissaTable = new Uint32Array( 2048 );
  5843. const exponentTable = new Uint32Array( 64 );
  5844. const offsetTable = new Uint32Array( 64 );
  5845. for ( let i = 1; i < 1024; ++ i ) {
  5846. let m = i << 13; // zero pad mantissa bits
  5847. let e = 0; // zero exponent
  5848. // normalized
  5849. while ( ( m & 0x00800000 ) === 0 ) {
  5850. m <<= 1;
  5851. e -= 0x00800000; // decrement exponent
  5852. }
  5853. m &= ~ 0x00800000; // clear leading 1 bit
  5854. e += 0x38800000; // adjust bias
  5855. mantissaTable[ i ] = m | e;
  5856. }
  5857. for ( let i = 1024; i < 2048; ++ i ) {
  5858. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5859. }
  5860. for ( let i = 1; i < 31; ++ i ) {
  5861. exponentTable[ i ] = i << 23;
  5862. }
  5863. exponentTable[ 31 ] = 0x47800000;
  5864. exponentTable[ 32 ] = 0x80000000;
  5865. for ( let i = 33; i < 63; ++ i ) {
  5866. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5867. }
  5868. exponentTable[ 63 ] = 0xc7800000;
  5869. for ( let i = 1; i < 64; ++ i ) {
  5870. if ( i !== 32 ) {
  5871. offsetTable[ i ] = 1024;
  5872. }
  5873. }
  5874. return {
  5875. floatView: floatView,
  5876. uint32View: uint32View,
  5877. baseTable: baseTable,
  5878. shiftTable: shiftTable,
  5879. mantissaTable: mantissaTable,
  5880. exponentTable: exponentTable,
  5881. offsetTable: offsetTable
  5882. };
  5883. }
  5884. // float32 to float16
  5885. function toHalfFloat( val ) {
  5886. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5887. val = clamp( val, - 65504, 65504 );
  5888. _tables.floatView[ 0 ] = val;
  5889. const f = _tables.uint32View[ 0 ];
  5890. const e = ( f >> 23 ) & 0x1ff;
  5891. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5892. }
  5893. // float16 to float32
  5894. function fromHalfFloat( val ) {
  5895. const m = val >> 10;
  5896. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5897. return _tables.floatView[ 0 ];
  5898. }
  5899. const DataUtils = {
  5900. toHalfFloat: toHalfFloat,
  5901. fromHalfFloat: fromHalfFloat,
  5902. };
  5903. const _vector$9 = /*@__PURE__*/ new Vector3();
  5904. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5905. class BufferAttribute {
  5906. constructor( array, itemSize, normalized = false ) {
  5907. if ( Array.isArray( array ) ) {
  5908. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5909. }
  5910. this.isBufferAttribute = true;
  5911. this.name = '';
  5912. this.array = array;
  5913. this.itemSize = itemSize;
  5914. this.count = array !== undefined ? array.length / itemSize : 0;
  5915. this.normalized = normalized;
  5916. this.usage = StaticDrawUsage;
  5917. this._updateRange = { offset: 0, count: - 1 };
  5918. this.updateRanges = [];
  5919. this.gpuType = FloatType;
  5920. this.version = 0;
  5921. }
  5922. onUploadCallback() {}
  5923. set needsUpdate( value ) {
  5924. if ( value === true ) this.version ++;
  5925. }
  5926. get updateRange() {
  5927. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5928. return this._updateRange;
  5929. }
  5930. setUsage( value ) {
  5931. this.usage = value;
  5932. return this;
  5933. }
  5934. addUpdateRange( start, count ) {
  5935. this.updateRanges.push( { start, count } );
  5936. }
  5937. clearUpdateRanges() {
  5938. this.updateRanges.length = 0;
  5939. }
  5940. copy( source ) {
  5941. this.name = source.name;
  5942. this.array = new source.array.constructor( source.array );
  5943. this.itemSize = source.itemSize;
  5944. this.count = source.count;
  5945. this.normalized = source.normalized;
  5946. this.usage = source.usage;
  5947. this.gpuType = source.gpuType;
  5948. return this;
  5949. }
  5950. copyAt( index1, attribute, index2 ) {
  5951. index1 *= this.itemSize;
  5952. index2 *= attribute.itemSize;
  5953. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5954. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5955. }
  5956. return this;
  5957. }
  5958. copyArray( array ) {
  5959. this.array.set( array );
  5960. return this;
  5961. }
  5962. applyMatrix3( m ) {
  5963. if ( this.itemSize === 2 ) {
  5964. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5965. _vector2$1.fromBufferAttribute( this, i );
  5966. _vector2$1.applyMatrix3( m );
  5967. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5968. }
  5969. } else if ( this.itemSize === 3 ) {
  5970. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5971. _vector$9.fromBufferAttribute( this, i );
  5972. _vector$9.applyMatrix3( m );
  5973. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5974. }
  5975. }
  5976. return this;
  5977. }
  5978. applyMatrix4( m ) {
  5979. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5980. _vector$9.fromBufferAttribute( this, i );
  5981. _vector$9.applyMatrix4( m );
  5982. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5983. }
  5984. return this;
  5985. }
  5986. applyNormalMatrix( m ) {
  5987. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5988. _vector$9.fromBufferAttribute( this, i );
  5989. _vector$9.applyNormalMatrix( m );
  5990. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5991. }
  5992. return this;
  5993. }
  5994. transformDirection( m ) {
  5995. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5996. _vector$9.fromBufferAttribute( this, i );
  5997. _vector$9.transformDirection( m );
  5998. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5999. }
  6000. return this;
  6001. }
  6002. set( value, offset = 0 ) {
  6003. // Matching BufferAttribute constructor, do not normalize the array.
  6004. this.array.set( value, offset );
  6005. return this;
  6006. }
  6007. getComponent( index, component ) {
  6008. let value = this.array[ index * this.itemSize + component ];
  6009. if ( this.normalized ) value = denormalize( value, this.array );
  6010. return value;
  6011. }
  6012. setComponent( index, component, value ) {
  6013. if ( this.normalized ) value = normalize( value, this.array );
  6014. this.array[ index * this.itemSize + component ] = value;
  6015. return this;
  6016. }
  6017. getX( index ) {
  6018. let x = this.array[ index * this.itemSize ];
  6019. if ( this.normalized ) x = denormalize( x, this.array );
  6020. return x;
  6021. }
  6022. setX( index, x ) {
  6023. if ( this.normalized ) x = normalize( x, this.array );
  6024. this.array[ index * this.itemSize ] = x;
  6025. return this;
  6026. }
  6027. getY( index ) {
  6028. let y = this.array[ index * this.itemSize + 1 ];
  6029. if ( this.normalized ) y = denormalize( y, this.array );
  6030. return y;
  6031. }
  6032. setY( index, y ) {
  6033. if ( this.normalized ) y = normalize( y, this.array );
  6034. this.array[ index * this.itemSize + 1 ] = y;
  6035. return this;
  6036. }
  6037. getZ( index ) {
  6038. let z = this.array[ index * this.itemSize + 2 ];
  6039. if ( this.normalized ) z = denormalize( z, this.array );
  6040. return z;
  6041. }
  6042. setZ( index, z ) {
  6043. if ( this.normalized ) z = normalize( z, this.array );
  6044. this.array[ index * this.itemSize + 2 ] = z;
  6045. return this;
  6046. }
  6047. getW( index ) {
  6048. let w = this.array[ index * this.itemSize + 3 ];
  6049. if ( this.normalized ) w = denormalize( w, this.array );
  6050. return w;
  6051. }
  6052. setW( index, w ) {
  6053. if ( this.normalized ) w = normalize( w, this.array );
  6054. this.array[ index * this.itemSize + 3 ] = w;
  6055. return this;
  6056. }
  6057. setXY( index, x, y ) {
  6058. index *= this.itemSize;
  6059. if ( this.normalized ) {
  6060. x = normalize( x, this.array );
  6061. y = normalize( y, this.array );
  6062. }
  6063. this.array[ index + 0 ] = x;
  6064. this.array[ index + 1 ] = y;
  6065. return this;
  6066. }
  6067. setXYZ( index, x, y, z ) {
  6068. index *= this.itemSize;
  6069. if ( this.normalized ) {
  6070. x = normalize( x, this.array );
  6071. y = normalize( y, this.array );
  6072. z = normalize( z, this.array );
  6073. }
  6074. this.array[ index + 0 ] = x;
  6075. this.array[ index + 1 ] = y;
  6076. this.array[ index + 2 ] = z;
  6077. return this;
  6078. }
  6079. setXYZW( index, x, y, z, w ) {
  6080. index *= this.itemSize;
  6081. if ( this.normalized ) {
  6082. x = normalize( x, this.array );
  6083. y = normalize( y, this.array );
  6084. z = normalize( z, this.array );
  6085. w = normalize( w, this.array );
  6086. }
  6087. this.array[ index + 0 ] = x;
  6088. this.array[ index + 1 ] = y;
  6089. this.array[ index + 2 ] = z;
  6090. this.array[ index + 3 ] = w;
  6091. return this;
  6092. }
  6093. onUpload( callback ) {
  6094. this.onUploadCallback = callback;
  6095. return this;
  6096. }
  6097. clone() {
  6098. return new this.constructor( this.array, this.itemSize ).copy( this );
  6099. }
  6100. toJSON() {
  6101. const data = {
  6102. itemSize: this.itemSize,
  6103. type: this.array.constructor.name,
  6104. array: Array.from( this.array ),
  6105. normalized: this.normalized
  6106. };
  6107. if ( this.name !== '' ) data.name = this.name;
  6108. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6109. return data;
  6110. }
  6111. }
  6112. //
  6113. class Int8BufferAttribute extends BufferAttribute {
  6114. constructor( array, itemSize, normalized ) {
  6115. super( new Int8Array( array ), itemSize, normalized );
  6116. }
  6117. }
  6118. class Uint8BufferAttribute extends BufferAttribute {
  6119. constructor( array, itemSize, normalized ) {
  6120. super( new Uint8Array( array ), itemSize, normalized );
  6121. }
  6122. }
  6123. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6124. constructor( array, itemSize, normalized ) {
  6125. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6126. }
  6127. }
  6128. class Int16BufferAttribute extends BufferAttribute {
  6129. constructor( array, itemSize, normalized ) {
  6130. super( new Int16Array( array ), itemSize, normalized );
  6131. }
  6132. }
  6133. class Uint16BufferAttribute extends BufferAttribute {
  6134. constructor( array, itemSize, normalized ) {
  6135. super( new Uint16Array( array ), itemSize, normalized );
  6136. }
  6137. }
  6138. class Int32BufferAttribute extends BufferAttribute {
  6139. constructor( array, itemSize, normalized ) {
  6140. super( new Int32Array( array ), itemSize, normalized );
  6141. }
  6142. }
  6143. class Uint32BufferAttribute extends BufferAttribute {
  6144. constructor( array, itemSize, normalized ) {
  6145. super( new Uint32Array( array ), itemSize, normalized );
  6146. }
  6147. }
  6148. class Float16BufferAttribute extends BufferAttribute {
  6149. constructor( array, itemSize, normalized ) {
  6150. super( new Uint16Array( array ), itemSize, normalized );
  6151. this.isFloat16BufferAttribute = true;
  6152. }
  6153. getX( index ) {
  6154. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6155. if ( this.normalized ) x = denormalize( x, this.array );
  6156. return x;
  6157. }
  6158. setX( index, x ) {
  6159. if ( this.normalized ) x = normalize( x, this.array );
  6160. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6161. return this;
  6162. }
  6163. getY( index ) {
  6164. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6165. if ( this.normalized ) y = denormalize( y, this.array );
  6166. return y;
  6167. }
  6168. setY( index, y ) {
  6169. if ( this.normalized ) y = normalize( y, this.array );
  6170. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6171. return this;
  6172. }
  6173. getZ( index ) {
  6174. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6175. if ( this.normalized ) z = denormalize( z, this.array );
  6176. return z;
  6177. }
  6178. setZ( index, z ) {
  6179. if ( this.normalized ) z = normalize( z, this.array );
  6180. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6181. return this;
  6182. }
  6183. getW( index ) {
  6184. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6185. if ( this.normalized ) w = denormalize( w, this.array );
  6186. return w;
  6187. }
  6188. setW( index, w ) {
  6189. if ( this.normalized ) w = normalize( w, this.array );
  6190. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6191. return this;
  6192. }
  6193. setXY( index, x, y ) {
  6194. index *= this.itemSize;
  6195. if ( this.normalized ) {
  6196. x = normalize( x, this.array );
  6197. y = normalize( y, this.array );
  6198. }
  6199. this.array[ index + 0 ] = toHalfFloat( x );
  6200. this.array[ index + 1 ] = toHalfFloat( y );
  6201. return this;
  6202. }
  6203. setXYZ( index, x, y, z ) {
  6204. index *= this.itemSize;
  6205. if ( this.normalized ) {
  6206. x = normalize( x, this.array );
  6207. y = normalize( y, this.array );
  6208. z = normalize( z, this.array );
  6209. }
  6210. this.array[ index + 0 ] = toHalfFloat( x );
  6211. this.array[ index + 1 ] = toHalfFloat( y );
  6212. this.array[ index + 2 ] = toHalfFloat( z );
  6213. return this;
  6214. }
  6215. setXYZW( index, x, y, z, w ) {
  6216. index *= this.itemSize;
  6217. if ( this.normalized ) {
  6218. x = normalize( x, this.array );
  6219. y = normalize( y, this.array );
  6220. z = normalize( z, this.array );
  6221. w = normalize( w, this.array );
  6222. }
  6223. this.array[ index + 0 ] = toHalfFloat( x );
  6224. this.array[ index + 1 ] = toHalfFloat( y );
  6225. this.array[ index + 2 ] = toHalfFloat( z );
  6226. this.array[ index + 3 ] = toHalfFloat( w );
  6227. return this;
  6228. }
  6229. }
  6230. class Float32BufferAttribute extends BufferAttribute {
  6231. constructor( array, itemSize, normalized ) {
  6232. super( new Float32Array( array ), itemSize, normalized );
  6233. }
  6234. }
  6235. let _id$2 = 0;
  6236. const _m1$2 = /*@__PURE__*/ new Matrix4();
  6237. const _obj = /*@__PURE__*/ new Object3D();
  6238. const _offset = /*@__PURE__*/ new Vector3();
  6239. const _box$2 = /*@__PURE__*/ new Box3();
  6240. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6241. const _vector$8 = /*@__PURE__*/ new Vector3();
  6242. class BufferGeometry extends EventDispatcher {
  6243. constructor() {
  6244. super();
  6245. this.isBufferGeometry = true;
  6246. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  6247. this.uuid = generateUUID();
  6248. this.name = '';
  6249. this.type = 'BufferGeometry';
  6250. this.index = null;
  6251. this.attributes = {};
  6252. this.morphAttributes = {};
  6253. this.morphTargetsRelative = false;
  6254. this.groups = [];
  6255. this.boundingBox = null;
  6256. this.boundingSphere = null;
  6257. this.drawRange = { start: 0, count: Infinity };
  6258. this.userData = {};
  6259. }
  6260. getIndex() {
  6261. return this.index;
  6262. }
  6263. setIndex( index ) {
  6264. if ( Array.isArray( index ) ) {
  6265. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6266. } else {
  6267. this.index = index;
  6268. }
  6269. return this;
  6270. }
  6271. getAttribute( name ) {
  6272. return this.attributes[ name ];
  6273. }
  6274. setAttribute( name, attribute ) {
  6275. this.attributes[ name ] = attribute;
  6276. return this;
  6277. }
  6278. deleteAttribute( name ) {
  6279. delete this.attributes[ name ];
  6280. return this;
  6281. }
  6282. hasAttribute( name ) {
  6283. return this.attributes[ name ] !== undefined;
  6284. }
  6285. addGroup( start, count, materialIndex = 0 ) {
  6286. this.groups.push( {
  6287. start: start,
  6288. count: count,
  6289. materialIndex: materialIndex
  6290. } );
  6291. }
  6292. clearGroups() {
  6293. this.groups = [];
  6294. }
  6295. setDrawRange( start, count ) {
  6296. this.drawRange.start = start;
  6297. this.drawRange.count = count;
  6298. }
  6299. applyMatrix4( matrix ) {
  6300. const position = this.attributes.position;
  6301. if ( position !== undefined ) {
  6302. position.applyMatrix4( matrix );
  6303. position.needsUpdate = true;
  6304. }
  6305. const normal = this.attributes.normal;
  6306. if ( normal !== undefined ) {
  6307. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6308. normal.applyNormalMatrix( normalMatrix );
  6309. normal.needsUpdate = true;
  6310. }
  6311. const tangent = this.attributes.tangent;
  6312. if ( tangent !== undefined ) {
  6313. tangent.transformDirection( matrix );
  6314. tangent.needsUpdate = true;
  6315. }
  6316. if ( this.boundingBox !== null ) {
  6317. this.computeBoundingBox();
  6318. }
  6319. if ( this.boundingSphere !== null ) {
  6320. this.computeBoundingSphere();
  6321. }
  6322. return this;
  6323. }
  6324. applyQuaternion( q ) {
  6325. _m1$2.makeRotationFromQuaternion( q );
  6326. this.applyMatrix4( _m1$2 );
  6327. return this;
  6328. }
  6329. rotateX( angle ) {
  6330. // rotate geometry around world x-axis
  6331. _m1$2.makeRotationX( angle );
  6332. this.applyMatrix4( _m1$2 );
  6333. return this;
  6334. }
  6335. rotateY( angle ) {
  6336. // rotate geometry around world y-axis
  6337. _m1$2.makeRotationY( angle );
  6338. this.applyMatrix4( _m1$2 );
  6339. return this;
  6340. }
  6341. rotateZ( angle ) {
  6342. // rotate geometry around world z-axis
  6343. _m1$2.makeRotationZ( angle );
  6344. this.applyMatrix4( _m1$2 );
  6345. return this;
  6346. }
  6347. translate( x, y, z ) {
  6348. // translate geometry
  6349. _m1$2.makeTranslation( x, y, z );
  6350. this.applyMatrix4( _m1$2 );
  6351. return this;
  6352. }
  6353. scale( x, y, z ) {
  6354. // scale geometry
  6355. _m1$2.makeScale( x, y, z );
  6356. this.applyMatrix4( _m1$2 );
  6357. return this;
  6358. }
  6359. lookAt( vector ) {
  6360. _obj.lookAt( vector );
  6361. _obj.updateMatrix();
  6362. this.applyMatrix4( _obj.matrix );
  6363. return this;
  6364. }
  6365. center() {
  6366. this.computeBoundingBox();
  6367. this.boundingBox.getCenter( _offset ).negate();
  6368. this.translate( _offset.x, _offset.y, _offset.z );
  6369. return this;
  6370. }
  6371. setFromPoints( points ) {
  6372. const position = [];
  6373. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6374. const point = points[ i ];
  6375. position.push( point.x, point.y, point.z || 0 );
  6376. }
  6377. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6378. return this;
  6379. }
  6380. computeBoundingBox() {
  6381. if ( this.boundingBox === null ) {
  6382. this.boundingBox = new Box3();
  6383. }
  6384. const position = this.attributes.position;
  6385. const morphAttributesPosition = this.morphAttributes.position;
  6386. if ( position && position.isGLBufferAttribute ) {
  6387. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6388. this.boundingBox.set(
  6389. new Vector3( - Infinity, - Infinity, - Infinity ),
  6390. new Vector3( + Infinity, + Infinity, + Infinity )
  6391. );
  6392. return;
  6393. }
  6394. if ( position !== undefined ) {
  6395. this.boundingBox.setFromBufferAttribute( position );
  6396. // process morph attributes if present
  6397. if ( morphAttributesPosition ) {
  6398. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6399. const morphAttribute = morphAttributesPosition[ i ];
  6400. _box$2.setFromBufferAttribute( morphAttribute );
  6401. if ( this.morphTargetsRelative ) {
  6402. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6403. this.boundingBox.expandByPoint( _vector$8 );
  6404. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6405. this.boundingBox.expandByPoint( _vector$8 );
  6406. } else {
  6407. this.boundingBox.expandByPoint( _box$2.min );
  6408. this.boundingBox.expandByPoint( _box$2.max );
  6409. }
  6410. }
  6411. }
  6412. } else {
  6413. this.boundingBox.makeEmpty();
  6414. }
  6415. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6416. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6417. }
  6418. }
  6419. computeBoundingSphere() {
  6420. if ( this.boundingSphere === null ) {
  6421. this.boundingSphere = new Sphere();
  6422. }
  6423. const position = this.attributes.position;
  6424. const morphAttributesPosition = this.morphAttributes.position;
  6425. if ( position && position.isGLBufferAttribute ) {
  6426. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6427. this.boundingSphere.set( new Vector3(), Infinity );
  6428. return;
  6429. }
  6430. if ( position ) {
  6431. // first, find the center of the bounding sphere
  6432. const center = this.boundingSphere.center;
  6433. _box$2.setFromBufferAttribute( position );
  6434. // process morph attributes if present
  6435. if ( morphAttributesPosition ) {
  6436. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6437. const morphAttribute = morphAttributesPosition[ i ];
  6438. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6439. if ( this.morphTargetsRelative ) {
  6440. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6441. _box$2.expandByPoint( _vector$8 );
  6442. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6443. _box$2.expandByPoint( _vector$8 );
  6444. } else {
  6445. _box$2.expandByPoint( _boxMorphTargets.min );
  6446. _box$2.expandByPoint( _boxMorphTargets.max );
  6447. }
  6448. }
  6449. }
  6450. _box$2.getCenter( center );
  6451. // second, try to find a boundingSphere with a radius smaller than the
  6452. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6453. let maxRadiusSq = 0;
  6454. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6455. _vector$8.fromBufferAttribute( position, i );
  6456. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6457. }
  6458. // process morph attributes if present
  6459. if ( morphAttributesPosition ) {
  6460. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6461. const morphAttribute = morphAttributesPosition[ i ];
  6462. const morphTargetsRelative = this.morphTargetsRelative;
  6463. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6464. _vector$8.fromBufferAttribute( morphAttribute, j );
  6465. if ( morphTargetsRelative ) {
  6466. _offset.fromBufferAttribute( position, j );
  6467. _vector$8.add( _offset );
  6468. }
  6469. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6470. }
  6471. }
  6472. }
  6473. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6474. if ( isNaN( this.boundingSphere.radius ) ) {
  6475. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6476. }
  6477. }
  6478. }
  6479. computeTangents() {
  6480. const index = this.index;
  6481. const attributes = this.attributes;
  6482. // based on http://www.terathon.com/code/tangent.html
  6483. // (per vertex tangents)
  6484. if ( index === null ||
  6485. attributes.position === undefined ||
  6486. attributes.normal === undefined ||
  6487. attributes.uv === undefined ) {
  6488. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6489. return;
  6490. }
  6491. const positionAttribute = attributes.position;
  6492. const normalAttribute = attributes.normal;
  6493. const uvAttribute = attributes.uv;
  6494. if ( this.hasAttribute( 'tangent' ) === false ) {
  6495. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6496. }
  6497. const tangentAttribute = this.getAttribute( 'tangent' );
  6498. const tan1 = [], tan2 = [];
  6499. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6500. tan1[ i ] = new Vector3();
  6501. tan2[ i ] = new Vector3();
  6502. }
  6503. const vA = new Vector3(),
  6504. vB = new Vector3(),
  6505. vC = new Vector3(),
  6506. uvA = new Vector2(),
  6507. uvB = new Vector2(),
  6508. uvC = new Vector2(),
  6509. sdir = new Vector3(),
  6510. tdir = new Vector3();
  6511. function handleTriangle( a, b, c ) {
  6512. vA.fromBufferAttribute( positionAttribute, a );
  6513. vB.fromBufferAttribute( positionAttribute, b );
  6514. vC.fromBufferAttribute( positionAttribute, c );
  6515. uvA.fromBufferAttribute( uvAttribute, a );
  6516. uvB.fromBufferAttribute( uvAttribute, b );
  6517. uvC.fromBufferAttribute( uvAttribute, c );
  6518. vB.sub( vA );
  6519. vC.sub( vA );
  6520. uvB.sub( uvA );
  6521. uvC.sub( uvA );
  6522. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6523. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6524. if ( ! isFinite( r ) ) return;
  6525. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6526. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6527. tan1[ a ].add( sdir );
  6528. tan1[ b ].add( sdir );
  6529. tan1[ c ].add( sdir );
  6530. tan2[ a ].add( tdir );
  6531. tan2[ b ].add( tdir );
  6532. tan2[ c ].add( tdir );
  6533. }
  6534. let groups = this.groups;
  6535. if ( groups.length === 0 ) {
  6536. groups = [ {
  6537. start: 0,
  6538. count: index.count
  6539. } ];
  6540. }
  6541. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6542. const group = groups[ i ];
  6543. const start = group.start;
  6544. const count = group.count;
  6545. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6546. handleTriangle(
  6547. index.getX( j + 0 ),
  6548. index.getX( j + 1 ),
  6549. index.getX( j + 2 )
  6550. );
  6551. }
  6552. }
  6553. const tmp = new Vector3(), tmp2 = new Vector3();
  6554. const n = new Vector3(), n2 = new Vector3();
  6555. function handleVertex( v ) {
  6556. n.fromBufferAttribute( normalAttribute, v );
  6557. n2.copy( n );
  6558. const t = tan1[ v ];
  6559. // Gram-Schmidt orthogonalize
  6560. tmp.copy( t );
  6561. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6562. // Calculate handedness
  6563. tmp2.crossVectors( n2, t );
  6564. const test = tmp2.dot( tan2[ v ] );
  6565. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6566. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6567. }
  6568. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6569. const group = groups[ i ];
  6570. const start = group.start;
  6571. const count = group.count;
  6572. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6573. handleVertex( index.getX( j + 0 ) );
  6574. handleVertex( index.getX( j + 1 ) );
  6575. handleVertex( index.getX( j + 2 ) );
  6576. }
  6577. }
  6578. }
  6579. computeVertexNormals() {
  6580. const index = this.index;
  6581. const positionAttribute = this.getAttribute( 'position' );
  6582. if ( positionAttribute !== undefined ) {
  6583. let normalAttribute = this.getAttribute( 'normal' );
  6584. if ( normalAttribute === undefined ) {
  6585. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6586. this.setAttribute( 'normal', normalAttribute );
  6587. } else {
  6588. // reset existing normals to zero
  6589. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6590. normalAttribute.setXYZ( i, 0, 0, 0 );
  6591. }
  6592. }
  6593. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6594. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6595. const cb = new Vector3(), ab = new Vector3();
  6596. // indexed elements
  6597. if ( index ) {
  6598. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6599. const vA = index.getX( i + 0 );
  6600. const vB = index.getX( i + 1 );
  6601. const vC = index.getX( i + 2 );
  6602. pA.fromBufferAttribute( positionAttribute, vA );
  6603. pB.fromBufferAttribute( positionAttribute, vB );
  6604. pC.fromBufferAttribute( positionAttribute, vC );
  6605. cb.subVectors( pC, pB );
  6606. ab.subVectors( pA, pB );
  6607. cb.cross( ab );
  6608. nA.fromBufferAttribute( normalAttribute, vA );
  6609. nB.fromBufferAttribute( normalAttribute, vB );
  6610. nC.fromBufferAttribute( normalAttribute, vC );
  6611. nA.add( cb );
  6612. nB.add( cb );
  6613. nC.add( cb );
  6614. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6615. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6616. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6617. }
  6618. } else {
  6619. // non-indexed elements (unconnected triangle soup)
  6620. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6621. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6622. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6623. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6624. cb.subVectors( pC, pB );
  6625. ab.subVectors( pA, pB );
  6626. cb.cross( ab );
  6627. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6628. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6629. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6630. }
  6631. }
  6632. this.normalizeNormals();
  6633. normalAttribute.needsUpdate = true;
  6634. }
  6635. }
  6636. normalizeNormals() {
  6637. const normals = this.attributes.normal;
  6638. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6639. _vector$8.fromBufferAttribute( normals, i );
  6640. _vector$8.normalize();
  6641. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6642. }
  6643. }
  6644. toNonIndexed() {
  6645. function convertBufferAttribute( attribute, indices ) {
  6646. const array = attribute.array;
  6647. const itemSize = attribute.itemSize;
  6648. const normalized = attribute.normalized;
  6649. const array2 = new array.constructor( indices.length * itemSize );
  6650. let index = 0, index2 = 0;
  6651. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6652. if ( attribute.isInterleavedBufferAttribute ) {
  6653. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6654. } else {
  6655. index = indices[ i ] * itemSize;
  6656. }
  6657. for ( let j = 0; j < itemSize; j ++ ) {
  6658. array2[ index2 ++ ] = array[ index ++ ];
  6659. }
  6660. }
  6661. return new BufferAttribute( array2, itemSize, normalized );
  6662. }
  6663. //
  6664. if ( this.index === null ) {
  6665. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6666. return this;
  6667. }
  6668. const geometry2 = new BufferGeometry();
  6669. const indices = this.index.array;
  6670. const attributes = this.attributes;
  6671. // attributes
  6672. for ( const name in attributes ) {
  6673. const attribute = attributes[ name ];
  6674. const newAttribute = convertBufferAttribute( attribute, indices );
  6675. geometry2.setAttribute( name, newAttribute );
  6676. }
  6677. // morph attributes
  6678. const morphAttributes = this.morphAttributes;
  6679. for ( const name in morphAttributes ) {
  6680. const morphArray = [];
  6681. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6682. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6683. const attribute = morphAttribute[ i ];
  6684. const newAttribute = convertBufferAttribute( attribute, indices );
  6685. morphArray.push( newAttribute );
  6686. }
  6687. geometry2.morphAttributes[ name ] = morphArray;
  6688. }
  6689. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6690. // groups
  6691. const groups = this.groups;
  6692. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6693. const group = groups[ i ];
  6694. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6695. }
  6696. return geometry2;
  6697. }
  6698. toJSON() {
  6699. const data = {
  6700. metadata: {
  6701. version: 4.6,
  6702. type: 'BufferGeometry',
  6703. generator: 'BufferGeometry.toJSON'
  6704. }
  6705. };
  6706. // standard BufferGeometry serialization
  6707. data.uuid = this.uuid;
  6708. data.type = this.type;
  6709. if ( this.name !== '' ) data.name = this.name;
  6710. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6711. if ( this.parameters !== undefined ) {
  6712. const parameters = this.parameters;
  6713. for ( const key in parameters ) {
  6714. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6715. }
  6716. return data;
  6717. }
  6718. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6719. data.data = { attributes: {} };
  6720. const index = this.index;
  6721. if ( index !== null ) {
  6722. data.data.index = {
  6723. type: index.array.constructor.name,
  6724. array: Array.prototype.slice.call( index.array )
  6725. };
  6726. }
  6727. const attributes = this.attributes;
  6728. for ( const key in attributes ) {
  6729. const attribute = attributes[ key ];
  6730. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6731. }
  6732. const morphAttributes = {};
  6733. let hasMorphAttributes = false;
  6734. for ( const key in this.morphAttributes ) {
  6735. const attributeArray = this.morphAttributes[ key ];
  6736. const array = [];
  6737. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6738. const attribute = attributeArray[ i ];
  6739. array.push( attribute.toJSON( data.data ) );
  6740. }
  6741. if ( array.length > 0 ) {
  6742. morphAttributes[ key ] = array;
  6743. hasMorphAttributes = true;
  6744. }
  6745. }
  6746. if ( hasMorphAttributes ) {
  6747. data.data.morphAttributes = morphAttributes;
  6748. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6749. }
  6750. const groups = this.groups;
  6751. if ( groups.length > 0 ) {
  6752. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6753. }
  6754. const boundingSphere = this.boundingSphere;
  6755. if ( boundingSphere !== null ) {
  6756. data.data.boundingSphere = {
  6757. center: boundingSphere.center.toArray(),
  6758. radius: boundingSphere.radius
  6759. };
  6760. }
  6761. return data;
  6762. }
  6763. clone() {
  6764. return new this.constructor().copy( this );
  6765. }
  6766. copy( source ) {
  6767. // reset
  6768. this.index = null;
  6769. this.attributes = {};
  6770. this.morphAttributes = {};
  6771. this.groups = [];
  6772. this.boundingBox = null;
  6773. this.boundingSphere = null;
  6774. // used for storing cloned, shared data
  6775. const data = {};
  6776. // name
  6777. this.name = source.name;
  6778. // index
  6779. const index = source.index;
  6780. if ( index !== null ) {
  6781. this.setIndex( index.clone( data ) );
  6782. }
  6783. // attributes
  6784. const attributes = source.attributes;
  6785. for ( const name in attributes ) {
  6786. const attribute = attributes[ name ];
  6787. this.setAttribute( name, attribute.clone( data ) );
  6788. }
  6789. // morph attributes
  6790. const morphAttributes = source.morphAttributes;
  6791. for ( const name in morphAttributes ) {
  6792. const array = [];
  6793. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6794. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6795. array.push( morphAttribute[ i ].clone( data ) );
  6796. }
  6797. this.morphAttributes[ name ] = array;
  6798. }
  6799. this.morphTargetsRelative = source.morphTargetsRelative;
  6800. // groups
  6801. const groups = source.groups;
  6802. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6803. const group = groups[ i ];
  6804. this.addGroup( group.start, group.count, group.materialIndex );
  6805. }
  6806. // bounding box
  6807. const boundingBox = source.boundingBox;
  6808. if ( boundingBox !== null ) {
  6809. this.boundingBox = boundingBox.clone();
  6810. }
  6811. // bounding sphere
  6812. const boundingSphere = source.boundingSphere;
  6813. if ( boundingSphere !== null ) {
  6814. this.boundingSphere = boundingSphere.clone();
  6815. }
  6816. // draw range
  6817. this.drawRange.start = source.drawRange.start;
  6818. this.drawRange.count = source.drawRange.count;
  6819. // user data
  6820. this.userData = source.userData;
  6821. return this;
  6822. }
  6823. dispose() {
  6824. this.dispatchEvent( { type: 'dispose' } );
  6825. }
  6826. }
  6827. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6828. const _ray$3 = /*@__PURE__*/ new Ray();
  6829. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6830. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6831. const _vA$1 = /*@__PURE__*/ new Vector3();
  6832. const _vB$1 = /*@__PURE__*/ new Vector3();
  6833. const _vC$1 = /*@__PURE__*/ new Vector3();
  6834. const _tempA = /*@__PURE__*/ new Vector3();
  6835. const _morphA = /*@__PURE__*/ new Vector3();
  6836. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6837. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6838. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6839. const _normalA = /*@__PURE__*/ new Vector3();
  6840. const _normalB = /*@__PURE__*/ new Vector3();
  6841. const _normalC = /*@__PURE__*/ new Vector3();
  6842. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6843. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6844. class Mesh extends Object3D {
  6845. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6846. super();
  6847. this.isMesh = true;
  6848. this.type = 'Mesh';
  6849. this.geometry = geometry;
  6850. this.material = material;
  6851. this.updateMorphTargets();
  6852. }
  6853. copy( source, recursive ) {
  6854. super.copy( source, recursive );
  6855. if ( source.morphTargetInfluences !== undefined ) {
  6856. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6857. }
  6858. if ( source.morphTargetDictionary !== undefined ) {
  6859. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6860. }
  6861. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6862. this.geometry = source.geometry;
  6863. return this;
  6864. }
  6865. updateMorphTargets() {
  6866. const geometry = this.geometry;
  6867. const morphAttributes = geometry.morphAttributes;
  6868. const keys = Object.keys( morphAttributes );
  6869. if ( keys.length > 0 ) {
  6870. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6871. if ( morphAttribute !== undefined ) {
  6872. this.morphTargetInfluences = [];
  6873. this.morphTargetDictionary = {};
  6874. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6875. const name = morphAttribute[ m ].name || String( m );
  6876. this.morphTargetInfluences.push( 0 );
  6877. this.morphTargetDictionary[ name ] = m;
  6878. }
  6879. }
  6880. }
  6881. }
  6882. getVertexPosition( index, target ) {
  6883. const geometry = this.geometry;
  6884. const position = geometry.attributes.position;
  6885. const morphPosition = geometry.morphAttributes.position;
  6886. const morphTargetsRelative = geometry.morphTargetsRelative;
  6887. target.fromBufferAttribute( position, index );
  6888. const morphInfluences = this.morphTargetInfluences;
  6889. if ( morphPosition && morphInfluences ) {
  6890. _morphA.set( 0, 0, 0 );
  6891. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6892. const influence = morphInfluences[ i ];
  6893. const morphAttribute = morphPosition[ i ];
  6894. if ( influence === 0 ) continue;
  6895. _tempA.fromBufferAttribute( morphAttribute, index );
  6896. if ( morphTargetsRelative ) {
  6897. _morphA.addScaledVector( _tempA, influence );
  6898. } else {
  6899. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6900. }
  6901. }
  6902. target.add( _morphA );
  6903. }
  6904. return target;
  6905. }
  6906. raycast( raycaster, intersects ) {
  6907. const geometry = this.geometry;
  6908. const material = this.material;
  6909. const matrixWorld = this.matrixWorld;
  6910. if ( material === undefined ) return;
  6911. // test with bounding sphere in world space
  6912. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6913. _sphere$6.copy( geometry.boundingSphere );
  6914. _sphere$6.applyMatrix4( matrixWorld );
  6915. // check distance from ray origin to bounding sphere
  6916. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6917. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6918. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6919. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6920. }
  6921. // convert ray to local space of mesh
  6922. _inverseMatrix$3.copy( matrixWorld ).invert();
  6923. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6924. // test with bounding box in local space
  6925. if ( geometry.boundingBox !== null ) {
  6926. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6927. }
  6928. // test for intersections with geometry
  6929. this._computeIntersections( raycaster, intersects, _ray$3 );
  6930. }
  6931. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6932. let intersection;
  6933. const geometry = this.geometry;
  6934. const material = this.material;
  6935. const index = geometry.index;
  6936. const position = geometry.attributes.position;
  6937. const uv = geometry.attributes.uv;
  6938. const uv1 = geometry.attributes.uv1;
  6939. const normal = geometry.attributes.normal;
  6940. const groups = geometry.groups;
  6941. const drawRange = geometry.drawRange;
  6942. if ( index !== null ) {
  6943. // indexed buffer geometry
  6944. if ( Array.isArray( material ) ) {
  6945. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6946. const group = groups[ i ];
  6947. const groupMaterial = material[ group.materialIndex ];
  6948. const start = Math.max( group.start, drawRange.start );
  6949. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6950. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6951. const a = index.getX( j );
  6952. const b = index.getX( j + 1 );
  6953. const c = index.getX( j + 2 );
  6954. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6955. if ( intersection ) {
  6956. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6957. intersection.face.materialIndex = group.materialIndex;
  6958. intersects.push( intersection );
  6959. }
  6960. }
  6961. }
  6962. } else {
  6963. const start = Math.max( 0, drawRange.start );
  6964. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6965. for ( let i = start, il = end; i < il; i += 3 ) {
  6966. const a = index.getX( i );
  6967. const b = index.getX( i + 1 );
  6968. const c = index.getX( i + 2 );
  6969. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6970. if ( intersection ) {
  6971. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6972. intersects.push( intersection );
  6973. }
  6974. }
  6975. }
  6976. } else if ( position !== undefined ) {
  6977. // non-indexed buffer geometry
  6978. if ( Array.isArray( material ) ) {
  6979. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6980. const group = groups[ i ];
  6981. const groupMaterial = material[ group.materialIndex ];
  6982. const start = Math.max( group.start, drawRange.start );
  6983. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6984. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6985. const a = j;
  6986. const b = j + 1;
  6987. const c = j + 2;
  6988. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6989. if ( intersection ) {
  6990. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6991. intersection.face.materialIndex = group.materialIndex;
  6992. intersects.push( intersection );
  6993. }
  6994. }
  6995. }
  6996. } else {
  6997. const start = Math.max( 0, drawRange.start );
  6998. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6999. for ( let i = start, il = end; i < il; i += 3 ) {
  7000. const a = i;
  7001. const b = i + 1;
  7002. const c = i + 2;
  7003. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7004. if ( intersection ) {
  7005. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7006. intersects.push( intersection );
  7007. }
  7008. }
  7009. }
  7010. }
  7011. }
  7012. }
  7013. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  7014. let intersect;
  7015. if ( material.side === BackSide ) {
  7016. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7017. } else {
  7018. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7019. }
  7020. if ( intersect === null ) return null;
  7021. _intersectionPointWorld.copy( point );
  7022. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7023. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7024. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7025. return {
  7026. distance: distance,
  7027. point: _intersectionPointWorld.clone(),
  7028. object: object
  7029. };
  7030. }
  7031. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7032. object.getVertexPosition( a, _vA$1 );
  7033. object.getVertexPosition( b, _vB$1 );
  7034. object.getVertexPosition( c, _vC$1 );
  7035. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7036. if ( intersection ) {
  7037. if ( uv ) {
  7038. _uvA$1.fromBufferAttribute( uv, a );
  7039. _uvB$1.fromBufferAttribute( uv, b );
  7040. _uvC$1.fromBufferAttribute( uv, c );
  7041. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7042. }
  7043. if ( uv1 ) {
  7044. _uvA$1.fromBufferAttribute( uv1, a );
  7045. _uvB$1.fromBufferAttribute( uv1, b );
  7046. _uvC$1.fromBufferAttribute( uv1, c );
  7047. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7048. }
  7049. if ( normal ) {
  7050. _normalA.fromBufferAttribute( normal, a );
  7051. _normalB.fromBufferAttribute( normal, b );
  7052. _normalC.fromBufferAttribute( normal, c );
  7053. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7054. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7055. intersection.normal.multiplyScalar( - 1 );
  7056. }
  7057. }
  7058. const face = {
  7059. a: a,
  7060. b: b,
  7061. c: c,
  7062. normal: new Vector3(),
  7063. materialIndex: 0
  7064. };
  7065. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7066. intersection.face = face;
  7067. }
  7068. return intersection;
  7069. }
  7070. class BoxGeometry extends BufferGeometry {
  7071. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7072. super();
  7073. this.type = 'BoxGeometry';
  7074. this.parameters = {
  7075. width: width,
  7076. height: height,
  7077. depth: depth,
  7078. widthSegments: widthSegments,
  7079. heightSegments: heightSegments,
  7080. depthSegments: depthSegments
  7081. };
  7082. const scope = this;
  7083. // segments
  7084. widthSegments = Math.floor( widthSegments );
  7085. heightSegments = Math.floor( heightSegments );
  7086. depthSegments = Math.floor( depthSegments );
  7087. // buffers
  7088. const indices = [];
  7089. const vertices = [];
  7090. const normals = [];
  7091. const uvs = [];
  7092. // helper variables
  7093. let numberOfVertices = 0;
  7094. let groupStart = 0;
  7095. // build each side of the box geometry
  7096. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7097. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7098. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7099. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7100. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7101. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7102. // build geometry
  7103. this.setIndex( indices );
  7104. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7105. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7106. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7107. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7108. const segmentWidth = width / gridX;
  7109. const segmentHeight = height / gridY;
  7110. const widthHalf = width / 2;
  7111. const heightHalf = height / 2;
  7112. const depthHalf = depth / 2;
  7113. const gridX1 = gridX + 1;
  7114. const gridY1 = gridY + 1;
  7115. let vertexCounter = 0;
  7116. let groupCount = 0;
  7117. const vector = new Vector3();
  7118. // generate vertices, normals and uvs
  7119. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7120. const y = iy * segmentHeight - heightHalf;
  7121. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7122. const x = ix * segmentWidth - widthHalf;
  7123. // set values to correct vector component
  7124. vector[ u ] = x * udir;
  7125. vector[ v ] = y * vdir;
  7126. vector[ w ] = depthHalf;
  7127. // now apply vector to vertex buffer
  7128. vertices.push( vector.x, vector.y, vector.z );
  7129. // set values to correct vector component
  7130. vector[ u ] = 0;
  7131. vector[ v ] = 0;
  7132. vector[ w ] = depth > 0 ? 1 : - 1;
  7133. // now apply vector to normal buffer
  7134. normals.push( vector.x, vector.y, vector.z );
  7135. // uvs
  7136. uvs.push( ix / gridX );
  7137. uvs.push( 1 - ( iy / gridY ) );
  7138. // counters
  7139. vertexCounter += 1;
  7140. }
  7141. }
  7142. // indices
  7143. // 1. you need three indices to draw a single face
  7144. // 2. a single segment consists of two faces
  7145. // 3. so we need to generate six (2*3) indices per segment
  7146. for ( let iy = 0; iy < gridY; iy ++ ) {
  7147. for ( let ix = 0; ix < gridX; ix ++ ) {
  7148. const a = numberOfVertices + ix + gridX1 * iy;
  7149. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7150. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7151. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7152. // faces
  7153. indices.push( a, b, d );
  7154. indices.push( b, c, d );
  7155. // increase counter
  7156. groupCount += 6;
  7157. }
  7158. }
  7159. // add a group to the geometry. this will ensure multi material support
  7160. scope.addGroup( groupStart, groupCount, materialIndex );
  7161. // calculate new start value for groups
  7162. groupStart += groupCount;
  7163. // update total number of vertices
  7164. numberOfVertices += vertexCounter;
  7165. }
  7166. }
  7167. copy( source ) {
  7168. super.copy( source );
  7169. this.parameters = Object.assign( {}, source.parameters );
  7170. return this;
  7171. }
  7172. static fromJSON( data ) {
  7173. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7174. }
  7175. }
  7176. /**
  7177. * Uniform Utilities
  7178. */
  7179. function cloneUniforms( src ) {
  7180. const dst = {};
  7181. for ( const u in src ) {
  7182. dst[ u ] = {};
  7183. for ( const p in src[ u ] ) {
  7184. const property = src[ u ][ p ];
  7185. if ( property && ( property.isColor ||
  7186. property.isMatrix3 || property.isMatrix4 ||
  7187. property.isVector2 || property.isVector3 || property.isVector4 ||
  7188. property.isTexture || property.isQuaternion ) ) {
  7189. if ( property.isRenderTargetTexture ) {
  7190. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7191. dst[ u ][ p ] = null;
  7192. } else {
  7193. dst[ u ][ p ] = property.clone();
  7194. }
  7195. } else if ( Array.isArray( property ) ) {
  7196. dst[ u ][ p ] = property.slice();
  7197. } else {
  7198. dst[ u ][ p ] = property;
  7199. }
  7200. }
  7201. }
  7202. return dst;
  7203. }
  7204. function mergeUniforms( uniforms ) {
  7205. const merged = {};
  7206. for ( let u = 0; u < uniforms.length; u ++ ) {
  7207. const tmp = cloneUniforms( uniforms[ u ] );
  7208. for ( const p in tmp ) {
  7209. merged[ p ] = tmp[ p ];
  7210. }
  7211. }
  7212. return merged;
  7213. }
  7214. function cloneUniformsGroups( src ) {
  7215. const dst = [];
  7216. for ( let u = 0; u < src.length; u ++ ) {
  7217. dst.push( src[ u ].clone() );
  7218. }
  7219. return dst;
  7220. }
  7221. function getUnlitUniformColorSpace( renderer ) {
  7222. const currentRenderTarget = renderer.getRenderTarget();
  7223. if ( currentRenderTarget === null ) {
  7224. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7225. return renderer.outputColorSpace;
  7226. }
  7227. // https://github.com/mrdoob/three.js/issues/27868
  7228. if ( currentRenderTarget.isXRRenderTarget === true ) {
  7229. return currentRenderTarget.texture.colorSpace;
  7230. }
  7231. return ColorManagement.workingColorSpace;
  7232. }
  7233. // Legacy
  7234. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7235. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7236. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7237. class ShaderMaterial extends Material {
  7238. constructor( parameters ) {
  7239. super();
  7240. this.isShaderMaterial = true;
  7241. this.type = 'ShaderMaterial';
  7242. this.defines = {};
  7243. this.uniforms = {};
  7244. this.uniformsGroups = [];
  7245. this.vertexShader = default_vertex;
  7246. this.fragmentShader = default_fragment;
  7247. this.linewidth = 1;
  7248. this.wireframe = false;
  7249. this.wireframeLinewidth = 1;
  7250. this.fog = false; // set to use scene fog
  7251. this.lights = false; // set to use scene lights
  7252. this.clipping = false; // set to use user-defined clipping planes
  7253. this.forceSinglePass = true;
  7254. this.extensions = {
  7255. clipCullDistance: false, // set to use vertex shader clipping
  7256. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7257. };
  7258. // When rendered geometry doesn't include these attributes but the material does,
  7259. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7260. this.defaultAttributeValues = {
  7261. 'color': [ 1, 1, 1 ],
  7262. 'uv': [ 0, 0 ],
  7263. 'uv1': [ 0, 0 ]
  7264. };
  7265. this.index0AttributeName = undefined;
  7266. this.uniformsNeedUpdate = false;
  7267. this.glslVersion = null;
  7268. if ( parameters !== undefined ) {
  7269. this.setValues( parameters );
  7270. }
  7271. }
  7272. copy( source ) {
  7273. super.copy( source );
  7274. this.fragmentShader = source.fragmentShader;
  7275. this.vertexShader = source.vertexShader;
  7276. this.uniforms = cloneUniforms( source.uniforms );
  7277. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7278. this.defines = Object.assign( {}, source.defines );
  7279. this.wireframe = source.wireframe;
  7280. this.wireframeLinewidth = source.wireframeLinewidth;
  7281. this.fog = source.fog;
  7282. this.lights = source.lights;
  7283. this.clipping = source.clipping;
  7284. this.extensions = Object.assign( {}, source.extensions );
  7285. this.glslVersion = source.glslVersion;
  7286. return this;
  7287. }
  7288. toJSON( meta ) {
  7289. const data = super.toJSON( meta );
  7290. data.glslVersion = this.glslVersion;
  7291. data.uniforms = {};
  7292. for ( const name in this.uniforms ) {
  7293. const uniform = this.uniforms[ name ];
  7294. const value = uniform.value;
  7295. if ( value && value.isTexture ) {
  7296. data.uniforms[ name ] = {
  7297. type: 't',
  7298. value: value.toJSON( meta ).uuid
  7299. };
  7300. } else if ( value && value.isColor ) {
  7301. data.uniforms[ name ] = {
  7302. type: 'c',
  7303. value: value.getHex()
  7304. };
  7305. } else if ( value && value.isVector2 ) {
  7306. data.uniforms[ name ] = {
  7307. type: 'v2',
  7308. value: value.toArray()
  7309. };
  7310. } else if ( value && value.isVector3 ) {
  7311. data.uniforms[ name ] = {
  7312. type: 'v3',
  7313. value: value.toArray()
  7314. };
  7315. } else if ( value && value.isVector4 ) {
  7316. data.uniforms[ name ] = {
  7317. type: 'v4',
  7318. value: value.toArray()
  7319. };
  7320. } else if ( value && value.isMatrix3 ) {
  7321. data.uniforms[ name ] = {
  7322. type: 'm3',
  7323. value: value.toArray()
  7324. };
  7325. } else if ( value && value.isMatrix4 ) {
  7326. data.uniforms[ name ] = {
  7327. type: 'm4',
  7328. value: value.toArray()
  7329. };
  7330. } else {
  7331. data.uniforms[ name ] = {
  7332. value: value
  7333. };
  7334. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7335. }
  7336. }
  7337. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7338. data.vertexShader = this.vertexShader;
  7339. data.fragmentShader = this.fragmentShader;
  7340. data.lights = this.lights;
  7341. data.clipping = this.clipping;
  7342. const extensions = {};
  7343. for ( const key in this.extensions ) {
  7344. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7345. }
  7346. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7347. return data;
  7348. }
  7349. }
  7350. class Camera extends Object3D {
  7351. constructor() {
  7352. super();
  7353. this.isCamera = true;
  7354. this.type = 'Camera';
  7355. this.matrixWorldInverse = new Matrix4();
  7356. this.projectionMatrix = new Matrix4();
  7357. this.projectionMatrixInverse = new Matrix4();
  7358. this.coordinateSystem = WebGLCoordinateSystem;
  7359. }
  7360. copy( source, recursive ) {
  7361. super.copy( source, recursive );
  7362. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7363. this.projectionMatrix.copy( source.projectionMatrix );
  7364. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7365. this.coordinateSystem = source.coordinateSystem;
  7366. return this;
  7367. }
  7368. getWorldDirection( target ) {
  7369. return super.getWorldDirection( target ).negate();
  7370. }
  7371. updateMatrixWorld( force ) {
  7372. super.updateMatrixWorld( force );
  7373. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7374. }
  7375. updateWorldMatrix( updateParents, updateChildren ) {
  7376. super.updateWorldMatrix( updateParents, updateChildren );
  7377. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7378. }
  7379. clone() {
  7380. return new this.constructor().copy( this );
  7381. }
  7382. }
  7383. const _v3$1 = /*@__PURE__*/ new Vector3();
  7384. const _minTarget = /*@__PURE__*/ new Vector2();
  7385. const _maxTarget = /*@__PURE__*/ new Vector2();
  7386. class PerspectiveCamera extends Camera {
  7387. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7388. super();
  7389. this.isPerspectiveCamera = true;
  7390. this.type = 'PerspectiveCamera';
  7391. this.fov = fov;
  7392. this.zoom = 1;
  7393. this.near = near;
  7394. this.far = far;
  7395. this.focus = 10;
  7396. this.aspect = aspect;
  7397. this.view = null;
  7398. this.filmGauge = 35; // width of the film (default in millimeters)
  7399. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7400. this.updateProjectionMatrix();
  7401. }
  7402. copy( source, recursive ) {
  7403. super.copy( source, recursive );
  7404. this.fov = source.fov;
  7405. this.zoom = source.zoom;
  7406. this.near = source.near;
  7407. this.far = source.far;
  7408. this.focus = source.focus;
  7409. this.aspect = source.aspect;
  7410. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7411. this.filmGauge = source.filmGauge;
  7412. this.filmOffset = source.filmOffset;
  7413. return this;
  7414. }
  7415. /**
  7416. * Sets the FOV by focal length in respect to the current .filmGauge.
  7417. *
  7418. * The default film gauge is 35, so that the focal length can be specified for
  7419. * a 35mm (full frame) camera.
  7420. *
  7421. * Values for focal length and film gauge must have the same unit.
  7422. */
  7423. setFocalLength( focalLength ) {
  7424. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7425. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7426. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7427. this.updateProjectionMatrix();
  7428. }
  7429. /**
  7430. * Calculates the focal length from the current .fov and .filmGauge.
  7431. */
  7432. getFocalLength() {
  7433. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7434. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7435. }
  7436. getEffectiveFOV() {
  7437. return RAD2DEG * 2 * Math.atan(
  7438. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7439. }
  7440. getFilmWidth() {
  7441. // film not completely covered in portrait format (aspect < 1)
  7442. return this.filmGauge * Math.min( this.aspect, 1 );
  7443. }
  7444. getFilmHeight() {
  7445. // film not completely covered in landscape format (aspect > 1)
  7446. return this.filmGauge / Math.max( this.aspect, 1 );
  7447. }
  7448. /**
  7449. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7450. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7451. */
  7452. getViewBounds( distance, minTarget, maxTarget ) {
  7453. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7454. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7455. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7456. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7457. }
  7458. /**
  7459. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7460. * Copies the result into the target Vector2, where x is width and y is height.
  7461. */
  7462. getViewSize( distance, target ) {
  7463. this.getViewBounds( distance, _minTarget, _maxTarget );
  7464. return target.subVectors( _maxTarget, _minTarget );
  7465. }
  7466. /**
  7467. * Sets an offset in a larger frustum. This is useful for multi-window or
  7468. * multi-monitor/multi-machine setups.
  7469. *
  7470. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7471. * the monitors are in grid like this
  7472. *
  7473. * +---+---+---+
  7474. * | A | B | C |
  7475. * +---+---+---+
  7476. * | D | E | F |
  7477. * +---+---+---+
  7478. *
  7479. * then for each monitor you would call it like this
  7480. *
  7481. * const w = 1920;
  7482. * const h = 1080;
  7483. * const fullWidth = w * 3;
  7484. * const fullHeight = h * 2;
  7485. *
  7486. * --A--
  7487. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7488. * --B--
  7489. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7490. * --C--
  7491. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7492. * --D--
  7493. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7494. * --E--
  7495. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7496. * --F--
  7497. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7498. *
  7499. * Note there is no reason monitors have to be the same size or in a grid.
  7500. */
  7501. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7502. this.aspect = fullWidth / fullHeight;
  7503. if ( this.view === null ) {
  7504. this.view = {
  7505. enabled: true,
  7506. fullWidth: 1,
  7507. fullHeight: 1,
  7508. offsetX: 0,
  7509. offsetY: 0,
  7510. width: 1,
  7511. height: 1
  7512. };
  7513. }
  7514. this.view.enabled = true;
  7515. this.view.fullWidth = fullWidth;
  7516. this.view.fullHeight = fullHeight;
  7517. this.view.offsetX = x;
  7518. this.view.offsetY = y;
  7519. this.view.width = width;
  7520. this.view.height = height;
  7521. this.updateProjectionMatrix();
  7522. }
  7523. clearViewOffset() {
  7524. if ( this.view !== null ) {
  7525. this.view.enabled = false;
  7526. }
  7527. this.updateProjectionMatrix();
  7528. }
  7529. updateProjectionMatrix() {
  7530. const near = this.near;
  7531. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7532. let height = 2 * top;
  7533. let width = this.aspect * height;
  7534. let left = - 0.5 * width;
  7535. const view = this.view;
  7536. if ( this.view !== null && this.view.enabled ) {
  7537. const fullWidth = view.fullWidth,
  7538. fullHeight = view.fullHeight;
  7539. left += view.offsetX * width / fullWidth;
  7540. top -= view.offsetY * height / fullHeight;
  7541. width *= view.width / fullWidth;
  7542. height *= view.height / fullHeight;
  7543. }
  7544. const skew = this.filmOffset;
  7545. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7546. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7547. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7548. }
  7549. toJSON( meta ) {
  7550. const data = super.toJSON( meta );
  7551. data.object.fov = this.fov;
  7552. data.object.zoom = this.zoom;
  7553. data.object.near = this.near;
  7554. data.object.far = this.far;
  7555. data.object.focus = this.focus;
  7556. data.object.aspect = this.aspect;
  7557. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7558. data.object.filmGauge = this.filmGauge;
  7559. data.object.filmOffset = this.filmOffset;
  7560. return data;
  7561. }
  7562. }
  7563. const fov = - 90; // negative fov is not an error
  7564. const aspect = 1;
  7565. class CubeCamera extends Object3D {
  7566. constructor( near, far, renderTarget ) {
  7567. super();
  7568. this.type = 'CubeCamera';
  7569. this.renderTarget = renderTarget;
  7570. this.coordinateSystem = null;
  7571. this.activeMipmapLevel = 0;
  7572. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7573. cameraPX.layers = this.layers;
  7574. this.add( cameraPX );
  7575. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7576. cameraNX.layers = this.layers;
  7577. this.add( cameraNX );
  7578. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7579. cameraPY.layers = this.layers;
  7580. this.add( cameraPY );
  7581. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7582. cameraNY.layers = this.layers;
  7583. this.add( cameraNY );
  7584. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7585. cameraPZ.layers = this.layers;
  7586. this.add( cameraPZ );
  7587. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7588. cameraNZ.layers = this.layers;
  7589. this.add( cameraNZ );
  7590. }
  7591. updateCoordinateSystem() {
  7592. const coordinateSystem = this.coordinateSystem;
  7593. const cameras = this.children.concat();
  7594. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7595. for ( const camera of cameras ) this.remove( camera );
  7596. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7597. cameraPX.up.set( 0, 1, 0 );
  7598. cameraPX.lookAt( 1, 0, 0 );
  7599. cameraNX.up.set( 0, 1, 0 );
  7600. cameraNX.lookAt( - 1, 0, 0 );
  7601. cameraPY.up.set( 0, 0, - 1 );
  7602. cameraPY.lookAt( 0, 1, 0 );
  7603. cameraNY.up.set( 0, 0, 1 );
  7604. cameraNY.lookAt( 0, - 1, 0 );
  7605. cameraPZ.up.set( 0, 1, 0 );
  7606. cameraPZ.lookAt( 0, 0, 1 );
  7607. cameraNZ.up.set( 0, 1, 0 );
  7608. cameraNZ.lookAt( 0, 0, - 1 );
  7609. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7610. cameraPX.up.set( 0, - 1, 0 );
  7611. cameraPX.lookAt( - 1, 0, 0 );
  7612. cameraNX.up.set( 0, - 1, 0 );
  7613. cameraNX.lookAt( 1, 0, 0 );
  7614. cameraPY.up.set( 0, 0, 1 );
  7615. cameraPY.lookAt( 0, 1, 0 );
  7616. cameraNY.up.set( 0, 0, - 1 );
  7617. cameraNY.lookAt( 0, - 1, 0 );
  7618. cameraPZ.up.set( 0, - 1, 0 );
  7619. cameraPZ.lookAt( 0, 0, 1 );
  7620. cameraNZ.up.set( 0, - 1, 0 );
  7621. cameraNZ.lookAt( 0, 0, - 1 );
  7622. } else {
  7623. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7624. }
  7625. for ( const camera of cameras ) {
  7626. this.add( camera );
  7627. camera.updateMatrixWorld();
  7628. }
  7629. }
  7630. update( renderer, scene ) {
  7631. if ( this.parent === null ) this.updateMatrixWorld();
  7632. const { renderTarget, activeMipmapLevel } = this;
  7633. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7634. this.coordinateSystem = renderer.coordinateSystem;
  7635. this.updateCoordinateSystem();
  7636. }
  7637. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7638. const currentRenderTarget = renderer.getRenderTarget();
  7639. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7640. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7641. const currentXrEnabled = renderer.xr.enabled;
  7642. renderer.xr.enabled = false;
  7643. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7644. renderTarget.texture.generateMipmaps = false;
  7645. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7646. renderer.render( scene, cameraPX );
  7647. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7648. renderer.render( scene, cameraNX );
  7649. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7650. renderer.render( scene, cameraPY );
  7651. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7652. renderer.render( scene, cameraNY );
  7653. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7654. renderer.render( scene, cameraPZ );
  7655. // mipmaps are generated during the last call of render()
  7656. // at this point, all sides of the cube render target are defined
  7657. renderTarget.texture.generateMipmaps = generateMipmaps;
  7658. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7659. renderer.render( scene, cameraNZ );
  7660. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7661. renderer.xr.enabled = currentXrEnabled;
  7662. renderTarget.texture.needsPMREMUpdate = true;
  7663. }
  7664. }
  7665. class CubeTexture extends Texture {
  7666. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7667. images = images !== undefined ? images : [];
  7668. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7669. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7670. this.isCubeTexture = true;
  7671. this.flipY = false;
  7672. }
  7673. get images() {
  7674. return this.image;
  7675. }
  7676. set images( value ) {
  7677. this.image = value;
  7678. }
  7679. }
  7680. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7681. constructor( size = 1, options = {} ) {
  7682. super( size, size, options );
  7683. this.isWebGLCubeRenderTarget = true;
  7684. const image = { width: size, height: size, depth: 1 };
  7685. const images = [ image, image, image, image, image, image ];
  7686. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7687. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7688. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7689. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7690. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7691. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7692. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7693. this.texture.isRenderTargetTexture = true;
  7694. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7695. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7696. }
  7697. fromEquirectangularTexture( renderer, texture ) {
  7698. this.texture.type = texture.type;
  7699. this.texture.colorSpace = texture.colorSpace;
  7700. this.texture.generateMipmaps = texture.generateMipmaps;
  7701. this.texture.minFilter = texture.minFilter;
  7702. this.texture.magFilter = texture.magFilter;
  7703. const shader = {
  7704. uniforms: {
  7705. tEquirect: { value: null },
  7706. },
  7707. vertexShader: /* glsl */`
  7708. varying vec3 vWorldDirection;
  7709. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7710. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7711. }
  7712. void main() {
  7713. vWorldDirection = transformDirection( position, modelMatrix );
  7714. #include <begin_vertex>
  7715. #include <project_vertex>
  7716. }
  7717. `,
  7718. fragmentShader: /* glsl */`
  7719. uniform sampler2D tEquirect;
  7720. varying vec3 vWorldDirection;
  7721. #include <common>
  7722. void main() {
  7723. vec3 direction = normalize( vWorldDirection );
  7724. vec2 sampleUV = equirectUv( direction );
  7725. gl_FragColor = texture2D( tEquirect, sampleUV );
  7726. }
  7727. `
  7728. };
  7729. const geometry = new BoxGeometry( 5, 5, 5 );
  7730. const material = new ShaderMaterial( {
  7731. name: 'CubemapFromEquirect',
  7732. uniforms: cloneUniforms( shader.uniforms ),
  7733. vertexShader: shader.vertexShader,
  7734. fragmentShader: shader.fragmentShader,
  7735. side: BackSide,
  7736. blending: NoBlending
  7737. } );
  7738. material.uniforms.tEquirect.value = texture;
  7739. const mesh = new Mesh( geometry, material );
  7740. const currentMinFilter = texture.minFilter;
  7741. // Avoid blurred poles
  7742. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7743. const camera = new CubeCamera( 1, 10, this );
  7744. camera.update( renderer, mesh );
  7745. texture.minFilter = currentMinFilter;
  7746. mesh.geometry.dispose();
  7747. mesh.material.dispose();
  7748. return this;
  7749. }
  7750. clear( renderer, color, depth, stencil ) {
  7751. const currentRenderTarget = renderer.getRenderTarget();
  7752. for ( let i = 0; i < 6; i ++ ) {
  7753. renderer.setRenderTarget( this, i );
  7754. renderer.clear( color, depth, stencil );
  7755. }
  7756. renderer.setRenderTarget( currentRenderTarget );
  7757. }
  7758. }
  7759. const _vector1 = /*@__PURE__*/ new Vector3();
  7760. const _vector2 = /*@__PURE__*/ new Vector3();
  7761. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7762. class Plane {
  7763. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7764. this.isPlane = true;
  7765. // normal is assumed to be normalized
  7766. this.normal = normal;
  7767. this.constant = constant;
  7768. }
  7769. set( normal, constant ) {
  7770. this.normal.copy( normal );
  7771. this.constant = constant;
  7772. return this;
  7773. }
  7774. setComponents( x, y, z, w ) {
  7775. this.normal.set( x, y, z );
  7776. this.constant = w;
  7777. return this;
  7778. }
  7779. setFromNormalAndCoplanarPoint( normal, point ) {
  7780. this.normal.copy( normal );
  7781. this.constant = - point.dot( this.normal );
  7782. return this;
  7783. }
  7784. setFromCoplanarPoints( a, b, c ) {
  7785. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7786. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7787. this.setFromNormalAndCoplanarPoint( normal, a );
  7788. return this;
  7789. }
  7790. copy( plane ) {
  7791. this.normal.copy( plane.normal );
  7792. this.constant = plane.constant;
  7793. return this;
  7794. }
  7795. normalize() {
  7796. // Note: will lead to a divide by zero if the plane is invalid.
  7797. const inverseNormalLength = 1.0 / this.normal.length();
  7798. this.normal.multiplyScalar( inverseNormalLength );
  7799. this.constant *= inverseNormalLength;
  7800. return this;
  7801. }
  7802. negate() {
  7803. this.constant *= - 1;
  7804. this.normal.negate();
  7805. return this;
  7806. }
  7807. distanceToPoint( point ) {
  7808. return this.normal.dot( point ) + this.constant;
  7809. }
  7810. distanceToSphere( sphere ) {
  7811. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7812. }
  7813. projectPoint( point, target ) {
  7814. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7815. }
  7816. intersectLine( line, target ) {
  7817. const direction = line.delta( _vector1 );
  7818. const denominator = this.normal.dot( direction );
  7819. if ( denominator === 0 ) {
  7820. // line is coplanar, return origin
  7821. if ( this.distanceToPoint( line.start ) === 0 ) {
  7822. return target.copy( line.start );
  7823. }
  7824. // Unsure if this is the correct method to handle this case.
  7825. return null;
  7826. }
  7827. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7828. if ( t < 0 || t > 1 ) {
  7829. return null;
  7830. }
  7831. return target.copy( line.start ).addScaledVector( direction, t );
  7832. }
  7833. intersectsLine( line ) {
  7834. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7835. const startSign = this.distanceToPoint( line.start );
  7836. const endSign = this.distanceToPoint( line.end );
  7837. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7838. }
  7839. intersectsBox( box ) {
  7840. return box.intersectsPlane( this );
  7841. }
  7842. intersectsSphere( sphere ) {
  7843. return sphere.intersectsPlane( this );
  7844. }
  7845. coplanarPoint( target ) {
  7846. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7847. }
  7848. applyMatrix4( matrix, optionalNormalMatrix ) {
  7849. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7850. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7851. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7852. this.constant = - referencePoint.dot( normal );
  7853. return this;
  7854. }
  7855. translate( offset ) {
  7856. this.constant -= offset.dot( this.normal );
  7857. return this;
  7858. }
  7859. equals( plane ) {
  7860. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7861. }
  7862. clone() {
  7863. return new this.constructor().copy( this );
  7864. }
  7865. }
  7866. const _sphere$5 = /*@__PURE__*/ new Sphere();
  7867. const _vector$7 = /*@__PURE__*/ new Vector3();
  7868. class Frustum {
  7869. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7870. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7871. }
  7872. set( p0, p1, p2, p3, p4, p5 ) {
  7873. const planes = this.planes;
  7874. planes[ 0 ].copy( p0 );
  7875. planes[ 1 ].copy( p1 );
  7876. planes[ 2 ].copy( p2 );
  7877. planes[ 3 ].copy( p3 );
  7878. planes[ 4 ].copy( p4 );
  7879. planes[ 5 ].copy( p5 );
  7880. return this;
  7881. }
  7882. copy( frustum ) {
  7883. const planes = this.planes;
  7884. for ( let i = 0; i < 6; i ++ ) {
  7885. planes[ i ].copy( frustum.planes[ i ] );
  7886. }
  7887. return this;
  7888. }
  7889. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7890. const planes = this.planes;
  7891. const me = m.elements;
  7892. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7893. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7894. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7895. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7896. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7897. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7898. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7899. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7900. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7901. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7902. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7903. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7904. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7905. } else {
  7906. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7907. }
  7908. return this;
  7909. }
  7910. intersectsObject( object ) {
  7911. if ( object.boundingSphere !== undefined ) {
  7912. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7913. _sphere$5.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7914. } else {
  7915. const geometry = object.geometry;
  7916. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7917. _sphere$5.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7918. }
  7919. return this.intersectsSphere( _sphere$5 );
  7920. }
  7921. intersectsSprite( sprite ) {
  7922. _sphere$5.center.set( 0, 0, 0 );
  7923. _sphere$5.radius = 0.7071067811865476;
  7924. _sphere$5.applyMatrix4( sprite.matrixWorld );
  7925. return this.intersectsSphere( _sphere$5 );
  7926. }
  7927. intersectsSphere( sphere ) {
  7928. const planes = this.planes;
  7929. const center = sphere.center;
  7930. const negRadius = - sphere.radius;
  7931. for ( let i = 0; i < 6; i ++ ) {
  7932. const distance = planes[ i ].distanceToPoint( center );
  7933. if ( distance < negRadius ) {
  7934. return false;
  7935. }
  7936. }
  7937. return true;
  7938. }
  7939. intersectsBox( box ) {
  7940. const planes = this.planes;
  7941. for ( let i = 0; i < 6; i ++ ) {
  7942. const plane = planes[ i ];
  7943. // corner at max distance
  7944. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7945. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7946. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7947. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7948. return false;
  7949. }
  7950. }
  7951. return true;
  7952. }
  7953. containsPoint( point ) {
  7954. const planes = this.planes;
  7955. for ( let i = 0; i < 6; i ++ ) {
  7956. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7957. return false;
  7958. }
  7959. }
  7960. return true;
  7961. }
  7962. clone() {
  7963. return new this.constructor().copy( this );
  7964. }
  7965. }
  7966. function WebGLAnimation() {
  7967. let context = null;
  7968. let isAnimating = false;
  7969. let animationLoop = null;
  7970. let requestId = null;
  7971. function onAnimationFrame( time, frame ) {
  7972. animationLoop( time, frame );
  7973. requestId = context.requestAnimationFrame( onAnimationFrame );
  7974. }
  7975. return {
  7976. start: function () {
  7977. if ( isAnimating === true ) return;
  7978. if ( animationLoop === null ) return;
  7979. requestId = context.requestAnimationFrame( onAnimationFrame );
  7980. isAnimating = true;
  7981. },
  7982. stop: function () {
  7983. context.cancelAnimationFrame( requestId );
  7984. isAnimating = false;
  7985. },
  7986. setAnimationLoop: function ( callback ) {
  7987. animationLoop = callback;
  7988. },
  7989. setContext: function ( value ) {
  7990. context = value;
  7991. }
  7992. };
  7993. }
  7994. function WebGLAttributes( gl ) {
  7995. const buffers = new WeakMap();
  7996. function createBuffer( attribute, bufferType ) {
  7997. const array = attribute.array;
  7998. const usage = attribute.usage;
  7999. const size = array.byteLength;
  8000. const buffer = gl.createBuffer();
  8001. gl.bindBuffer( bufferType, buffer );
  8002. gl.bufferData( bufferType, array, usage );
  8003. attribute.onUploadCallback();
  8004. let type;
  8005. if ( array instanceof Float32Array ) {
  8006. type = gl.FLOAT;
  8007. } else if ( array instanceof Uint16Array ) {
  8008. if ( attribute.isFloat16BufferAttribute ) {
  8009. type = gl.HALF_FLOAT;
  8010. } else {
  8011. type = gl.UNSIGNED_SHORT;
  8012. }
  8013. } else if ( array instanceof Int16Array ) {
  8014. type = gl.SHORT;
  8015. } else if ( array instanceof Uint32Array ) {
  8016. type = gl.UNSIGNED_INT;
  8017. } else if ( array instanceof Int32Array ) {
  8018. type = gl.INT;
  8019. } else if ( array instanceof Int8Array ) {
  8020. type = gl.BYTE;
  8021. } else if ( array instanceof Uint8Array ) {
  8022. type = gl.UNSIGNED_BYTE;
  8023. } else if ( array instanceof Uint8ClampedArray ) {
  8024. type = gl.UNSIGNED_BYTE;
  8025. } else {
  8026. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  8027. }
  8028. return {
  8029. buffer: buffer,
  8030. type: type,
  8031. bytesPerElement: array.BYTES_PER_ELEMENT,
  8032. version: attribute.version,
  8033. size: size
  8034. };
  8035. }
  8036. function updateBuffer( buffer, attribute, bufferType ) {
  8037. const array = attribute.array;
  8038. const updateRange = attribute._updateRange; // @deprecated, r159
  8039. const updateRanges = attribute.updateRanges;
  8040. gl.bindBuffer( bufferType, buffer );
  8041. if ( updateRange.count === - 1 && updateRanges.length === 0 ) {
  8042. // Not using update ranges
  8043. gl.bufferSubData( bufferType, 0, array );
  8044. }
  8045. if ( updateRanges.length !== 0 ) {
  8046. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  8047. const range = updateRanges[ i ];
  8048. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  8049. array, range.start, range.count );
  8050. }
  8051. attribute.clearUpdateRanges();
  8052. }
  8053. // @deprecated, r159
  8054. if ( updateRange.count !== - 1 ) {
  8055. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8056. array, updateRange.offset, updateRange.count );
  8057. updateRange.count = - 1; // reset range
  8058. }
  8059. attribute.onUploadCallback();
  8060. }
  8061. //
  8062. function get( attribute ) {
  8063. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8064. return buffers.get( attribute );
  8065. }
  8066. function remove( attribute ) {
  8067. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8068. const data = buffers.get( attribute );
  8069. if ( data ) {
  8070. gl.deleteBuffer( data.buffer );
  8071. buffers.delete( attribute );
  8072. }
  8073. }
  8074. function update( attribute, bufferType ) {
  8075. if ( attribute.isGLBufferAttribute ) {
  8076. const cached = buffers.get( attribute );
  8077. if ( ! cached || cached.version < attribute.version ) {
  8078. buffers.set( attribute, {
  8079. buffer: attribute.buffer,
  8080. type: attribute.type,
  8081. bytesPerElement: attribute.elementSize,
  8082. version: attribute.version
  8083. } );
  8084. }
  8085. return;
  8086. }
  8087. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8088. const data = buffers.get( attribute );
  8089. if ( data === undefined ) {
  8090. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8091. } else if ( data.version < attribute.version ) {
  8092. if ( data.size !== attribute.array.byteLength ) {
  8093. throw new Error( 'THREE.WebGLAttributes: The size of the buffer attribute\'s array buffer does not match the original size. Resizing buffer attributes is not supported.' );
  8094. }
  8095. updateBuffer( data.buffer, attribute, bufferType );
  8096. data.version = attribute.version;
  8097. }
  8098. }
  8099. return {
  8100. get: get,
  8101. remove: remove,
  8102. update: update
  8103. };
  8104. }
  8105. class PlaneGeometry extends BufferGeometry {
  8106. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8107. super();
  8108. this.type = 'PlaneGeometry';
  8109. this.parameters = {
  8110. width: width,
  8111. height: height,
  8112. widthSegments: widthSegments,
  8113. heightSegments: heightSegments
  8114. };
  8115. const width_half = width / 2;
  8116. const height_half = height / 2;
  8117. const gridX = Math.floor( widthSegments );
  8118. const gridY = Math.floor( heightSegments );
  8119. const gridX1 = gridX + 1;
  8120. const gridY1 = gridY + 1;
  8121. const segment_width = width / gridX;
  8122. const segment_height = height / gridY;
  8123. //
  8124. const indices = [];
  8125. const vertices = [];
  8126. const normals = [];
  8127. const uvs = [];
  8128. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8129. const y = iy * segment_height - height_half;
  8130. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8131. const x = ix * segment_width - width_half;
  8132. vertices.push( x, - y, 0 );
  8133. normals.push( 0, 0, 1 );
  8134. uvs.push( ix / gridX );
  8135. uvs.push( 1 - ( iy / gridY ) );
  8136. }
  8137. }
  8138. for ( let iy = 0; iy < gridY; iy ++ ) {
  8139. for ( let ix = 0; ix < gridX; ix ++ ) {
  8140. const a = ix + gridX1 * iy;
  8141. const b = ix + gridX1 * ( iy + 1 );
  8142. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8143. const d = ( ix + 1 ) + gridX1 * iy;
  8144. indices.push( a, b, d );
  8145. indices.push( b, c, d );
  8146. }
  8147. }
  8148. this.setIndex( indices );
  8149. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8150. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8151. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8152. }
  8153. copy( source ) {
  8154. super.copy( source );
  8155. this.parameters = Object.assign( {}, source.parameters );
  8156. return this;
  8157. }
  8158. static fromJSON( data ) {
  8159. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8160. }
  8161. }
  8162. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  8163. var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif";
  8164. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8165. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8166. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif";
  8167. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8168. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  8169. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8170. var batching_pars_vertex = "#ifdef USE_BATCHING\n\tattribute float batchId;\n\tuniform highp sampler2D batchingTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif";
  8171. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( batchId );\n#endif";
  8172. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  8173. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8174. var bsdfs = "float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated";
  8175. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  8176. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  8177. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif";
  8178. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8179. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8180. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8181. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8182. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8183. 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";
  8184. 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";
  8185. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\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}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated";
  8186. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  8187. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  8188. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8189. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8190. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8191. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8192. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8193. var colorspace_pars_fragment = "\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}";
  8194. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  8195. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  8196. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  8197. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  8198. 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";
  8199. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8200. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8201. 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";
  8202. 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";
  8203. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}";
  8204. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8205. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8206. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8207. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert";
  8208. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( LEGACY_LIGHTS )\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#else\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#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, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  8209. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  8210. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8211. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon";
  8212. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8213. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong";
  8214. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  8215. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  8216. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  8217. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  8218. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif";
  8219. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8220. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8221. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8222. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  8223. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\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\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  8224. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8225. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  8226. var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8227. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8228. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8229. var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[MORPHTARGETS_COUNT];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif";
  8230. 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";
  8231. 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";
  8232. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t#endif\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\t#ifndef USE_INSTANCING_MORPH\n\t\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\t#endif\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";
  8233. 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";
  8234. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;";
  8235. var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  8236. 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";
  8237. 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";
  8238. 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";
  8239. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif";
  8240. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  8241. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif";
  8242. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif";
  8243. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8244. var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8245. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  8246. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8247. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  8248. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8249. 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";
  8250. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8251. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8252. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 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\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n#endif";
  8253. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8254. var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif";
  8255. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8256. 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";
  8257. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif";
  8258. 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";
  8259. 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";
  8260. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  8261. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8262. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8263. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 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}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tfloat startCompression = 0.8 - 0.04;\n\tfloat desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min(color.r, min(color.g, color.b));\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max(color.r, max(color.g, color.b));\n\tif (peak < startCompression) return color;\n\tfloat d = 1. - startCompression;\n\tfloat newPeak = 1. - d * d / (peak + d - startCompression);\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / (desaturation * (peak - newPeak) + 1.);\n\treturn mix(color, newPeak * vec3(1, 1, 1), g);\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8264. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif";
  8265. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t\n\t\t#else\n\t\t\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif";
  8266. var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  8267. var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  8268. var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif";
  8269. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8270. const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  8271. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8272. const vertex$g = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  8273. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8274. 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}";
  8275. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8276. const vertex$e = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  8277. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8278. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  8279. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8280. 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}";
  8281. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8282. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8283. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8284. const vertex$a = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8285. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8286. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8287. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8288. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  8289. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8290. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8291. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8292. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8293. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8294. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  8295. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8296. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8297. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8298. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8299. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8300. const vertex$2 = "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8301. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8302. 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}";
  8303. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8304. const ShaderChunk = {
  8305. alphahash_fragment: alphahash_fragment,
  8306. alphahash_pars_fragment: alphahash_pars_fragment,
  8307. alphamap_fragment: alphamap_fragment,
  8308. alphamap_pars_fragment: alphamap_pars_fragment,
  8309. alphatest_fragment: alphatest_fragment,
  8310. alphatest_pars_fragment: alphatest_pars_fragment,
  8311. aomap_fragment: aomap_fragment,
  8312. aomap_pars_fragment: aomap_pars_fragment,
  8313. batching_pars_vertex: batching_pars_vertex,
  8314. batching_vertex: batching_vertex,
  8315. begin_vertex: begin_vertex,
  8316. beginnormal_vertex: beginnormal_vertex,
  8317. bsdfs: bsdfs,
  8318. iridescence_fragment: iridescence_fragment,
  8319. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8320. clipping_planes_fragment: clipping_planes_fragment,
  8321. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8322. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8323. clipping_planes_vertex: clipping_planes_vertex,
  8324. color_fragment: color_fragment,
  8325. color_pars_fragment: color_pars_fragment,
  8326. color_pars_vertex: color_pars_vertex,
  8327. color_vertex: color_vertex,
  8328. common: common,
  8329. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8330. defaultnormal_vertex: defaultnormal_vertex,
  8331. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8332. displacementmap_vertex: displacementmap_vertex,
  8333. emissivemap_fragment: emissivemap_fragment,
  8334. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8335. colorspace_fragment: colorspace_fragment,
  8336. colorspace_pars_fragment: colorspace_pars_fragment,
  8337. envmap_fragment: envmap_fragment,
  8338. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8339. envmap_pars_fragment: envmap_pars_fragment,
  8340. envmap_pars_vertex: envmap_pars_vertex,
  8341. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8342. envmap_vertex: envmap_vertex,
  8343. fog_vertex: fog_vertex,
  8344. fog_pars_vertex: fog_pars_vertex,
  8345. fog_fragment: fog_fragment,
  8346. fog_pars_fragment: fog_pars_fragment,
  8347. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8348. lightmap_fragment: lightmap_fragment,
  8349. lightmap_pars_fragment: lightmap_pars_fragment,
  8350. lights_lambert_fragment: lights_lambert_fragment,
  8351. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8352. lights_pars_begin: lights_pars_begin,
  8353. lights_toon_fragment: lights_toon_fragment,
  8354. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8355. lights_phong_fragment: lights_phong_fragment,
  8356. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8357. lights_physical_fragment: lights_physical_fragment,
  8358. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8359. lights_fragment_begin: lights_fragment_begin,
  8360. lights_fragment_maps: lights_fragment_maps,
  8361. lights_fragment_end: lights_fragment_end,
  8362. logdepthbuf_fragment: logdepthbuf_fragment,
  8363. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8364. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8365. logdepthbuf_vertex: logdepthbuf_vertex,
  8366. map_fragment: map_fragment,
  8367. map_pars_fragment: map_pars_fragment,
  8368. map_particle_fragment: map_particle_fragment,
  8369. map_particle_pars_fragment: map_particle_pars_fragment,
  8370. metalnessmap_fragment: metalnessmap_fragment,
  8371. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8372. morphinstance_vertex: morphinstance_vertex,
  8373. morphcolor_vertex: morphcolor_vertex,
  8374. morphnormal_vertex: morphnormal_vertex,
  8375. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8376. morphtarget_vertex: morphtarget_vertex,
  8377. normal_fragment_begin: normal_fragment_begin,
  8378. normal_fragment_maps: normal_fragment_maps,
  8379. normal_pars_fragment: normal_pars_fragment,
  8380. normal_pars_vertex: normal_pars_vertex,
  8381. normal_vertex: normal_vertex,
  8382. normalmap_pars_fragment: normalmap_pars_fragment,
  8383. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8384. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8385. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8386. iridescence_pars_fragment: iridescence_pars_fragment,
  8387. opaque_fragment: opaque_fragment,
  8388. packing: packing,
  8389. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8390. project_vertex: project_vertex,
  8391. dithering_fragment: dithering_fragment,
  8392. dithering_pars_fragment: dithering_pars_fragment,
  8393. roughnessmap_fragment: roughnessmap_fragment,
  8394. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8395. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8396. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8397. shadowmap_vertex: shadowmap_vertex,
  8398. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8399. skinbase_vertex: skinbase_vertex,
  8400. skinning_pars_vertex: skinning_pars_vertex,
  8401. skinning_vertex: skinning_vertex,
  8402. skinnormal_vertex: skinnormal_vertex,
  8403. specularmap_fragment: specularmap_fragment,
  8404. specularmap_pars_fragment: specularmap_pars_fragment,
  8405. tonemapping_fragment: tonemapping_fragment,
  8406. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8407. transmission_fragment: transmission_fragment,
  8408. transmission_pars_fragment: transmission_pars_fragment,
  8409. uv_pars_fragment: uv_pars_fragment,
  8410. uv_pars_vertex: uv_pars_vertex,
  8411. uv_vertex: uv_vertex,
  8412. worldpos_vertex: worldpos_vertex,
  8413. background_vert: vertex$h,
  8414. background_frag: fragment$h,
  8415. backgroundCube_vert: vertex$g,
  8416. backgroundCube_frag: fragment$g,
  8417. cube_vert: vertex$f,
  8418. cube_frag: fragment$f,
  8419. depth_vert: vertex$e,
  8420. depth_frag: fragment$e,
  8421. distanceRGBA_vert: vertex$d,
  8422. distanceRGBA_frag: fragment$d,
  8423. equirect_vert: vertex$c,
  8424. equirect_frag: fragment$c,
  8425. linedashed_vert: vertex$b,
  8426. linedashed_frag: fragment$b,
  8427. meshbasic_vert: vertex$a,
  8428. meshbasic_frag: fragment$a,
  8429. meshlambert_vert: vertex$9,
  8430. meshlambert_frag: fragment$9,
  8431. meshmatcap_vert: vertex$8,
  8432. meshmatcap_frag: fragment$8,
  8433. meshnormal_vert: vertex$7,
  8434. meshnormal_frag: fragment$7,
  8435. meshphong_vert: vertex$6,
  8436. meshphong_frag: fragment$6,
  8437. meshphysical_vert: vertex$5,
  8438. meshphysical_frag: fragment$5,
  8439. meshtoon_vert: vertex$4,
  8440. meshtoon_frag: fragment$4,
  8441. points_vert: vertex$3,
  8442. points_frag: fragment$3,
  8443. shadow_vert: vertex$2,
  8444. shadow_frag: fragment$2,
  8445. sprite_vert: vertex$1,
  8446. sprite_frag: fragment$1
  8447. };
  8448. /**
  8449. * Uniforms library for shared webgl shaders
  8450. */
  8451. const UniformsLib = {
  8452. common: {
  8453. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8454. opacity: { value: 1.0 },
  8455. map: { value: null },
  8456. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8457. alphaMap: { value: null },
  8458. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8459. alphaTest: { value: 0 }
  8460. },
  8461. specularmap: {
  8462. specularMap: { value: null },
  8463. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8464. },
  8465. envmap: {
  8466. envMap: { value: null },
  8467. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  8468. flipEnvMap: { value: - 1 },
  8469. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8470. ior: { value: 1.5 }, // physical
  8471. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8472. },
  8473. aomap: {
  8474. aoMap: { value: null },
  8475. aoMapIntensity: { value: 1 },
  8476. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8477. },
  8478. lightmap: {
  8479. lightMap: { value: null },
  8480. lightMapIntensity: { value: 1 },
  8481. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8482. },
  8483. bumpmap: {
  8484. bumpMap: { value: null },
  8485. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8486. bumpScale: { value: 1 }
  8487. },
  8488. normalmap: {
  8489. normalMap: { value: null },
  8490. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8491. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8492. },
  8493. displacementmap: {
  8494. displacementMap: { value: null },
  8495. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8496. displacementScale: { value: 1 },
  8497. displacementBias: { value: 0 }
  8498. },
  8499. emissivemap: {
  8500. emissiveMap: { value: null },
  8501. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8502. },
  8503. metalnessmap: {
  8504. metalnessMap: { value: null },
  8505. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8506. },
  8507. roughnessmap: {
  8508. roughnessMap: { value: null },
  8509. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8510. },
  8511. gradientmap: {
  8512. gradientMap: { value: null }
  8513. },
  8514. fog: {
  8515. fogDensity: { value: 0.00025 },
  8516. fogNear: { value: 1 },
  8517. fogFar: { value: 2000 },
  8518. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8519. },
  8520. lights: {
  8521. ambientLightColor: { value: [] },
  8522. lightProbe: { value: [] },
  8523. directionalLights: { value: [], properties: {
  8524. direction: {},
  8525. color: {}
  8526. } },
  8527. directionalLightShadows: { value: [], properties: {
  8528. shadowBias: {},
  8529. shadowNormalBias: {},
  8530. shadowRadius: {},
  8531. shadowMapSize: {}
  8532. } },
  8533. directionalShadowMap: { value: [] },
  8534. directionalShadowMatrix: { value: [] },
  8535. spotLights: { value: [], properties: {
  8536. color: {},
  8537. position: {},
  8538. direction: {},
  8539. distance: {},
  8540. coneCos: {},
  8541. penumbraCos: {},
  8542. decay: {}
  8543. } },
  8544. spotLightShadows: { value: [], properties: {
  8545. shadowBias: {},
  8546. shadowNormalBias: {},
  8547. shadowRadius: {},
  8548. shadowMapSize: {}
  8549. } },
  8550. spotLightMap: { value: [] },
  8551. spotShadowMap: { value: [] },
  8552. spotLightMatrix: { value: [] },
  8553. pointLights: { value: [], properties: {
  8554. color: {},
  8555. position: {},
  8556. decay: {},
  8557. distance: {}
  8558. } },
  8559. pointLightShadows: { value: [], properties: {
  8560. shadowBias: {},
  8561. shadowNormalBias: {},
  8562. shadowRadius: {},
  8563. shadowMapSize: {},
  8564. shadowCameraNear: {},
  8565. shadowCameraFar: {}
  8566. } },
  8567. pointShadowMap: { value: [] },
  8568. pointShadowMatrix: { value: [] },
  8569. hemisphereLights: { value: [], properties: {
  8570. direction: {},
  8571. skyColor: {},
  8572. groundColor: {}
  8573. } },
  8574. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8575. rectAreaLights: { value: [], properties: {
  8576. color: {},
  8577. position: {},
  8578. width: {},
  8579. height: {}
  8580. } },
  8581. ltc_1: { value: null },
  8582. ltc_2: { value: null }
  8583. },
  8584. points: {
  8585. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8586. opacity: { value: 1.0 },
  8587. size: { value: 1.0 },
  8588. scale: { value: 1.0 },
  8589. map: { value: null },
  8590. alphaMap: { value: null },
  8591. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8592. alphaTest: { value: 0 },
  8593. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8594. },
  8595. sprite: {
  8596. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8597. opacity: { value: 1.0 },
  8598. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8599. rotation: { value: 0.0 },
  8600. map: { value: null },
  8601. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8602. alphaMap: { value: null },
  8603. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8604. alphaTest: { value: 0 }
  8605. }
  8606. };
  8607. const ShaderLib = {
  8608. basic: {
  8609. uniforms: /*@__PURE__*/ mergeUniforms( [
  8610. UniformsLib.common,
  8611. UniformsLib.specularmap,
  8612. UniformsLib.envmap,
  8613. UniformsLib.aomap,
  8614. UniformsLib.lightmap,
  8615. UniformsLib.fog
  8616. ] ),
  8617. vertexShader: ShaderChunk.meshbasic_vert,
  8618. fragmentShader: ShaderChunk.meshbasic_frag
  8619. },
  8620. lambert: {
  8621. uniforms: /*@__PURE__*/ mergeUniforms( [
  8622. UniformsLib.common,
  8623. UniformsLib.specularmap,
  8624. UniformsLib.envmap,
  8625. UniformsLib.aomap,
  8626. UniformsLib.lightmap,
  8627. UniformsLib.emissivemap,
  8628. UniformsLib.bumpmap,
  8629. UniformsLib.normalmap,
  8630. UniformsLib.displacementmap,
  8631. UniformsLib.fog,
  8632. UniformsLib.lights,
  8633. {
  8634. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8635. }
  8636. ] ),
  8637. vertexShader: ShaderChunk.meshlambert_vert,
  8638. fragmentShader: ShaderChunk.meshlambert_frag
  8639. },
  8640. phong: {
  8641. uniforms: /*@__PURE__*/ mergeUniforms( [
  8642. UniformsLib.common,
  8643. UniformsLib.specularmap,
  8644. UniformsLib.envmap,
  8645. UniformsLib.aomap,
  8646. UniformsLib.lightmap,
  8647. UniformsLib.emissivemap,
  8648. UniformsLib.bumpmap,
  8649. UniformsLib.normalmap,
  8650. UniformsLib.displacementmap,
  8651. UniformsLib.fog,
  8652. UniformsLib.lights,
  8653. {
  8654. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8655. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8656. shininess: { value: 30 }
  8657. }
  8658. ] ),
  8659. vertexShader: ShaderChunk.meshphong_vert,
  8660. fragmentShader: ShaderChunk.meshphong_frag
  8661. },
  8662. standard: {
  8663. uniforms: /*@__PURE__*/ mergeUniforms( [
  8664. UniformsLib.common,
  8665. UniformsLib.envmap,
  8666. UniformsLib.aomap,
  8667. UniformsLib.lightmap,
  8668. UniformsLib.emissivemap,
  8669. UniformsLib.bumpmap,
  8670. UniformsLib.normalmap,
  8671. UniformsLib.displacementmap,
  8672. UniformsLib.roughnessmap,
  8673. UniformsLib.metalnessmap,
  8674. UniformsLib.fog,
  8675. UniformsLib.lights,
  8676. {
  8677. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8678. roughness: { value: 1.0 },
  8679. metalness: { value: 0.0 },
  8680. envMapIntensity: { value: 1 }
  8681. }
  8682. ] ),
  8683. vertexShader: ShaderChunk.meshphysical_vert,
  8684. fragmentShader: ShaderChunk.meshphysical_frag
  8685. },
  8686. toon: {
  8687. uniforms: /*@__PURE__*/ mergeUniforms( [
  8688. UniformsLib.common,
  8689. UniformsLib.aomap,
  8690. UniformsLib.lightmap,
  8691. UniformsLib.emissivemap,
  8692. UniformsLib.bumpmap,
  8693. UniformsLib.normalmap,
  8694. UniformsLib.displacementmap,
  8695. UniformsLib.gradientmap,
  8696. UniformsLib.fog,
  8697. UniformsLib.lights,
  8698. {
  8699. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8700. }
  8701. ] ),
  8702. vertexShader: ShaderChunk.meshtoon_vert,
  8703. fragmentShader: ShaderChunk.meshtoon_frag
  8704. },
  8705. matcap: {
  8706. uniforms: /*@__PURE__*/ mergeUniforms( [
  8707. UniformsLib.common,
  8708. UniformsLib.bumpmap,
  8709. UniformsLib.normalmap,
  8710. UniformsLib.displacementmap,
  8711. UniformsLib.fog,
  8712. {
  8713. matcap: { value: null }
  8714. }
  8715. ] ),
  8716. vertexShader: ShaderChunk.meshmatcap_vert,
  8717. fragmentShader: ShaderChunk.meshmatcap_frag
  8718. },
  8719. points: {
  8720. uniforms: /*@__PURE__*/ mergeUniforms( [
  8721. UniformsLib.points,
  8722. UniformsLib.fog
  8723. ] ),
  8724. vertexShader: ShaderChunk.points_vert,
  8725. fragmentShader: ShaderChunk.points_frag
  8726. },
  8727. dashed: {
  8728. uniforms: /*@__PURE__*/ mergeUniforms( [
  8729. UniformsLib.common,
  8730. UniformsLib.fog,
  8731. {
  8732. scale: { value: 1 },
  8733. dashSize: { value: 1 },
  8734. totalSize: { value: 2 }
  8735. }
  8736. ] ),
  8737. vertexShader: ShaderChunk.linedashed_vert,
  8738. fragmentShader: ShaderChunk.linedashed_frag
  8739. },
  8740. depth: {
  8741. uniforms: /*@__PURE__*/ mergeUniforms( [
  8742. UniformsLib.common,
  8743. UniformsLib.displacementmap
  8744. ] ),
  8745. vertexShader: ShaderChunk.depth_vert,
  8746. fragmentShader: ShaderChunk.depth_frag
  8747. },
  8748. normal: {
  8749. uniforms: /*@__PURE__*/ mergeUniforms( [
  8750. UniformsLib.common,
  8751. UniformsLib.bumpmap,
  8752. UniformsLib.normalmap,
  8753. UniformsLib.displacementmap,
  8754. {
  8755. opacity: { value: 1.0 }
  8756. }
  8757. ] ),
  8758. vertexShader: ShaderChunk.meshnormal_vert,
  8759. fragmentShader: ShaderChunk.meshnormal_frag
  8760. },
  8761. sprite: {
  8762. uniforms: /*@__PURE__*/ mergeUniforms( [
  8763. UniformsLib.sprite,
  8764. UniformsLib.fog
  8765. ] ),
  8766. vertexShader: ShaderChunk.sprite_vert,
  8767. fragmentShader: ShaderChunk.sprite_frag
  8768. },
  8769. background: {
  8770. uniforms: {
  8771. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8772. t2D: { value: null },
  8773. backgroundIntensity: { value: 1 }
  8774. },
  8775. vertexShader: ShaderChunk.background_vert,
  8776. fragmentShader: ShaderChunk.background_frag
  8777. },
  8778. backgroundCube: {
  8779. uniforms: {
  8780. envMap: { value: null },
  8781. flipEnvMap: { value: - 1 },
  8782. backgroundBlurriness: { value: 0 },
  8783. backgroundIntensity: { value: 1 },
  8784. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  8785. },
  8786. vertexShader: ShaderChunk.backgroundCube_vert,
  8787. fragmentShader: ShaderChunk.backgroundCube_frag
  8788. },
  8789. cube: {
  8790. uniforms: {
  8791. tCube: { value: null },
  8792. tFlip: { value: - 1 },
  8793. opacity: { value: 1.0 }
  8794. },
  8795. vertexShader: ShaderChunk.cube_vert,
  8796. fragmentShader: ShaderChunk.cube_frag
  8797. },
  8798. equirect: {
  8799. uniforms: {
  8800. tEquirect: { value: null },
  8801. },
  8802. vertexShader: ShaderChunk.equirect_vert,
  8803. fragmentShader: ShaderChunk.equirect_frag
  8804. },
  8805. distanceRGBA: {
  8806. uniforms: /*@__PURE__*/ mergeUniforms( [
  8807. UniformsLib.common,
  8808. UniformsLib.displacementmap,
  8809. {
  8810. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8811. nearDistance: { value: 1 },
  8812. farDistance: { value: 1000 }
  8813. }
  8814. ] ),
  8815. vertexShader: ShaderChunk.distanceRGBA_vert,
  8816. fragmentShader: ShaderChunk.distanceRGBA_frag
  8817. },
  8818. shadow: {
  8819. uniforms: /*@__PURE__*/ mergeUniforms( [
  8820. UniformsLib.lights,
  8821. UniformsLib.fog,
  8822. {
  8823. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8824. opacity: { value: 1.0 }
  8825. },
  8826. ] ),
  8827. vertexShader: ShaderChunk.shadow_vert,
  8828. fragmentShader: ShaderChunk.shadow_frag
  8829. }
  8830. };
  8831. ShaderLib.physical = {
  8832. uniforms: /*@__PURE__*/ mergeUniforms( [
  8833. ShaderLib.standard.uniforms,
  8834. {
  8835. clearcoat: { value: 0 },
  8836. clearcoatMap: { value: null },
  8837. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8838. clearcoatNormalMap: { value: null },
  8839. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8840. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8841. clearcoatRoughness: { value: 0 },
  8842. clearcoatRoughnessMap: { value: null },
  8843. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8844. dispersion: { value: 0 },
  8845. iridescence: { value: 0 },
  8846. iridescenceMap: { value: null },
  8847. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8848. iridescenceIOR: { value: 1.3 },
  8849. iridescenceThicknessMinimum: { value: 100 },
  8850. iridescenceThicknessMaximum: { value: 400 },
  8851. iridescenceThicknessMap: { value: null },
  8852. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8853. sheen: { value: 0 },
  8854. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8855. sheenColorMap: { value: null },
  8856. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8857. sheenRoughness: { value: 1 },
  8858. sheenRoughnessMap: { value: null },
  8859. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8860. transmission: { value: 0 },
  8861. transmissionMap: { value: null },
  8862. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8863. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8864. transmissionSamplerMap: { value: null },
  8865. thickness: { value: 0 },
  8866. thicknessMap: { value: null },
  8867. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8868. attenuationDistance: { value: 0 },
  8869. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8870. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8871. specularColorMap: { value: null },
  8872. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8873. specularIntensity: { value: 1 },
  8874. specularIntensityMap: { value: null },
  8875. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8876. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8877. anisotropyMap: { value: null },
  8878. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8879. }
  8880. ] ),
  8881. vertexShader: ShaderChunk.meshphysical_vert,
  8882. fragmentShader: ShaderChunk.meshphysical_frag
  8883. };
  8884. const _rgb = { r: 0, b: 0, g: 0 };
  8885. const _e1$1 = /*@__PURE__*/ new Euler();
  8886. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8887. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8888. const clearColor = new Color( 0x000000 );
  8889. let clearAlpha = alpha === true ? 0 : 1;
  8890. let planeMesh;
  8891. let boxMesh;
  8892. let currentBackground = null;
  8893. let currentBackgroundVersion = 0;
  8894. let currentTonemapping = null;
  8895. function render( renderList, scene ) {
  8896. let forceClear = false;
  8897. let background = scene.isScene === true ? scene.background : null;
  8898. if ( background && background.isTexture ) {
  8899. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8900. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8901. }
  8902. if ( background === null ) {
  8903. setClear( clearColor, clearAlpha );
  8904. } else if ( background && background.isColor ) {
  8905. setClear( background, 1 );
  8906. forceClear = true;
  8907. }
  8908. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  8909. if ( environmentBlendMode === 'additive' ) {
  8910. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8911. } else if ( environmentBlendMode === 'alpha-blend' ) {
  8912. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8913. }
  8914. if ( renderer.autoClear || forceClear ) {
  8915. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8916. }
  8917. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8918. if ( boxMesh === undefined ) {
  8919. boxMesh = new Mesh(
  8920. new BoxGeometry( 1, 1, 1 ),
  8921. new ShaderMaterial( {
  8922. name: 'BackgroundCubeMaterial',
  8923. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8924. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8925. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8926. side: BackSide,
  8927. depthTest: false,
  8928. depthWrite: false,
  8929. fog: false
  8930. } )
  8931. );
  8932. boxMesh.geometry.deleteAttribute( 'normal' );
  8933. boxMesh.geometry.deleteAttribute( 'uv' );
  8934. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8935. this.matrixWorld.copyPosition( camera.matrixWorld );
  8936. };
  8937. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8938. Object.defineProperty( boxMesh.material, 'envMap', {
  8939. get: function () {
  8940. return this.uniforms.envMap.value;
  8941. }
  8942. } );
  8943. objects.update( boxMesh );
  8944. }
  8945. _e1$1.copy( scene.backgroundRotation );
  8946. // accommodate left-handed frame
  8947. _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1;
  8948. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  8949. // environment maps which are not cube render targets or PMREMs follow a different convention
  8950. _e1$1.y *= - 1;
  8951. _e1$1.z *= - 1;
  8952. }
  8953. boxMesh.material.uniforms.envMap.value = background;
  8954. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8955. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8956. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8957. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  8958. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8959. if ( currentBackground !== background ||
  8960. currentBackgroundVersion !== background.version ||
  8961. currentTonemapping !== renderer.toneMapping ) {
  8962. boxMesh.material.needsUpdate = true;
  8963. currentBackground = background;
  8964. currentBackgroundVersion = background.version;
  8965. currentTonemapping = renderer.toneMapping;
  8966. }
  8967. boxMesh.layers.enableAll();
  8968. // push to the pre-sorted opaque render list
  8969. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8970. } else if ( background && background.isTexture ) {
  8971. if ( planeMesh === undefined ) {
  8972. planeMesh = new Mesh(
  8973. new PlaneGeometry( 2, 2 ),
  8974. new ShaderMaterial( {
  8975. name: 'BackgroundMaterial',
  8976. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8977. vertexShader: ShaderLib.background.vertexShader,
  8978. fragmentShader: ShaderLib.background.fragmentShader,
  8979. side: FrontSide,
  8980. depthTest: false,
  8981. depthWrite: false,
  8982. fog: false
  8983. } )
  8984. );
  8985. planeMesh.geometry.deleteAttribute( 'normal' );
  8986. // add "map" material property so the renderer can evaluate it like for built-in materials
  8987. Object.defineProperty( planeMesh.material, 'map', {
  8988. get: function () {
  8989. return this.uniforms.t2D.value;
  8990. }
  8991. } );
  8992. objects.update( planeMesh );
  8993. }
  8994. planeMesh.material.uniforms.t2D.value = background;
  8995. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8996. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8997. if ( background.matrixAutoUpdate === true ) {
  8998. background.updateMatrix();
  8999. }
  9000. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9001. if ( currentBackground !== background ||
  9002. currentBackgroundVersion !== background.version ||
  9003. currentTonemapping !== renderer.toneMapping ) {
  9004. planeMesh.material.needsUpdate = true;
  9005. currentBackground = background;
  9006. currentBackgroundVersion = background.version;
  9007. currentTonemapping = renderer.toneMapping;
  9008. }
  9009. planeMesh.layers.enableAll();
  9010. // push to the pre-sorted opaque render list
  9011. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9012. }
  9013. }
  9014. function setClear( color, alpha ) {
  9015. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  9016. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  9017. }
  9018. return {
  9019. getClearColor: function () {
  9020. return clearColor;
  9021. },
  9022. setClearColor: function ( color, alpha = 1 ) {
  9023. clearColor.set( color );
  9024. clearAlpha = alpha;
  9025. setClear( clearColor, clearAlpha );
  9026. },
  9027. getClearAlpha: function () {
  9028. return clearAlpha;
  9029. },
  9030. setClearAlpha: function ( alpha ) {
  9031. clearAlpha = alpha;
  9032. setClear( clearColor, clearAlpha );
  9033. },
  9034. render: render
  9035. };
  9036. }
  9037. function WebGLBindingStates( gl, attributes ) {
  9038. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9039. const bindingStates = {};
  9040. const defaultState = createBindingState( null );
  9041. let currentState = defaultState;
  9042. let forceUpdate = false;
  9043. function setup( object, material, program, geometry, index ) {
  9044. let updateBuffers = false;
  9045. const state = getBindingState( geometry, program, material );
  9046. if ( currentState !== state ) {
  9047. currentState = state;
  9048. bindVertexArrayObject( currentState.object );
  9049. }
  9050. updateBuffers = needsUpdate( object, geometry, program, index );
  9051. if ( updateBuffers ) saveCache( object, geometry, program, index );
  9052. if ( index !== null ) {
  9053. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9054. }
  9055. if ( updateBuffers || forceUpdate ) {
  9056. forceUpdate = false;
  9057. setupVertexAttributes( object, material, program, geometry );
  9058. if ( index !== null ) {
  9059. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  9060. }
  9061. }
  9062. }
  9063. function createVertexArrayObject() {
  9064. return gl.createVertexArray();
  9065. }
  9066. function bindVertexArrayObject( vao ) {
  9067. return gl.bindVertexArray( vao );
  9068. }
  9069. function deleteVertexArrayObject( vao ) {
  9070. return gl.deleteVertexArray( vao );
  9071. }
  9072. function getBindingState( geometry, program, material ) {
  9073. const wireframe = ( material.wireframe === true );
  9074. let programMap = bindingStates[ geometry.id ];
  9075. if ( programMap === undefined ) {
  9076. programMap = {};
  9077. bindingStates[ geometry.id ] = programMap;
  9078. }
  9079. let stateMap = programMap[ program.id ];
  9080. if ( stateMap === undefined ) {
  9081. stateMap = {};
  9082. programMap[ program.id ] = stateMap;
  9083. }
  9084. let state = stateMap[ wireframe ];
  9085. if ( state === undefined ) {
  9086. state = createBindingState( createVertexArrayObject() );
  9087. stateMap[ wireframe ] = state;
  9088. }
  9089. return state;
  9090. }
  9091. function createBindingState( vao ) {
  9092. const newAttributes = [];
  9093. const enabledAttributes = [];
  9094. const attributeDivisors = [];
  9095. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9096. newAttributes[ i ] = 0;
  9097. enabledAttributes[ i ] = 0;
  9098. attributeDivisors[ i ] = 0;
  9099. }
  9100. return {
  9101. // for backward compatibility on non-VAO support browser
  9102. geometry: null,
  9103. program: null,
  9104. wireframe: false,
  9105. newAttributes: newAttributes,
  9106. enabledAttributes: enabledAttributes,
  9107. attributeDivisors: attributeDivisors,
  9108. object: vao,
  9109. attributes: {},
  9110. index: null
  9111. };
  9112. }
  9113. function needsUpdate( object, geometry, program, index ) {
  9114. const cachedAttributes = currentState.attributes;
  9115. const geometryAttributes = geometry.attributes;
  9116. let attributesNum = 0;
  9117. const programAttributes = program.getAttributes();
  9118. for ( const name in programAttributes ) {
  9119. const programAttribute = programAttributes[ name ];
  9120. if ( programAttribute.location >= 0 ) {
  9121. const cachedAttribute = cachedAttributes[ name ];
  9122. let geometryAttribute = geometryAttributes[ name ];
  9123. if ( geometryAttribute === undefined ) {
  9124. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9125. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9126. }
  9127. if ( cachedAttribute === undefined ) return true;
  9128. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9129. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9130. attributesNum ++;
  9131. }
  9132. }
  9133. if ( currentState.attributesNum !== attributesNum ) return true;
  9134. if ( currentState.index !== index ) return true;
  9135. return false;
  9136. }
  9137. function saveCache( object, geometry, program, index ) {
  9138. const cache = {};
  9139. const attributes = geometry.attributes;
  9140. let attributesNum = 0;
  9141. const programAttributes = program.getAttributes();
  9142. for ( const name in programAttributes ) {
  9143. const programAttribute = programAttributes[ name ];
  9144. if ( programAttribute.location >= 0 ) {
  9145. let attribute = attributes[ name ];
  9146. if ( attribute === undefined ) {
  9147. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9148. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9149. }
  9150. const data = {};
  9151. data.attribute = attribute;
  9152. if ( attribute && attribute.data ) {
  9153. data.data = attribute.data;
  9154. }
  9155. cache[ name ] = data;
  9156. attributesNum ++;
  9157. }
  9158. }
  9159. currentState.attributes = cache;
  9160. currentState.attributesNum = attributesNum;
  9161. currentState.index = index;
  9162. }
  9163. function initAttributes() {
  9164. const newAttributes = currentState.newAttributes;
  9165. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9166. newAttributes[ i ] = 0;
  9167. }
  9168. }
  9169. function enableAttribute( attribute ) {
  9170. enableAttributeAndDivisor( attribute, 0 );
  9171. }
  9172. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9173. const newAttributes = currentState.newAttributes;
  9174. const enabledAttributes = currentState.enabledAttributes;
  9175. const attributeDivisors = currentState.attributeDivisors;
  9176. newAttributes[ attribute ] = 1;
  9177. if ( enabledAttributes[ attribute ] === 0 ) {
  9178. gl.enableVertexAttribArray( attribute );
  9179. enabledAttributes[ attribute ] = 1;
  9180. }
  9181. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9182. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  9183. attributeDivisors[ attribute ] = meshPerAttribute;
  9184. }
  9185. }
  9186. function disableUnusedAttributes() {
  9187. const newAttributes = currentState.newAttributes;
  9188. const enabledAttributes = currentState.enabledAttributes;
  9189. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9190. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9191. gl.disableVertexAttribArray( i );
  9192. enabledAttributes[ i ] = 0;
  9193. }
  9194. }
  9195. }
  9196. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9197. if ( integer === true ) {
  9198. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9199. } else {
  9200. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9201. }
  9202. }
  9203. function setupVertexAttributes( object, material, program, geometry ) {
  9204. initAttributes();
  9205. const geometryAttributes = geometry.attributes;
  9206. const programAttributes = program.getAttributes();
  9207. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9208. for ( const name in programAttributes ) {
  9209. const programAttribute = programAttributes[ name ];
  9210. if ( programAttribute.location >= 0 ) {
  9211. let geometryAttribute = geometryAttributes[ name ];
  9212. if ( geometryAttribute === undefined ) {
  9213. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9214. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9215. }
  9216. if ( geometryAttribute !== undefined ) {
  9217. const normalized = geometryAttribute.normalized;
  9218. const size = geometryAttribute.itemSize;
  9219. const attribute = attributes.get( geometryAttribute );
  9220. // TODO Attribute may not be available on context restore
  9221. if ( attribute === undefined ) continue;
  9222. const buffer = attribute.buffer;
  9223. const type = attribute.type;
  9224. const bytesPerElement = attribute.bytesPerElement;
  9225. // check for integer attributes
  9226. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  9227. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9228. const data = geometryAttribute.data;
  9229. const stride = data.stride;
  9230. const offset = geometryAttribute.offset;
  9231. if ( data.isInstancedInterleavedBuffer ) {
  9232. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9233. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9234. }
  9235. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9236. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9237. }
  9238. } else {
  9239. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9240. enableAttribute( programAttribute.location + i );
  9241. }
  9242. }
  9243. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9244. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9245. vertexAttribPointer(
  9246. programAttribute.location + i,
  9247. size / programAttribute.locationSize,
  9248. type,
  9249. normalized,
  9250. stride * bytesPerElement,
  9251. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9252. integer
  9253. );
  9254. }
  9255. } else {
  9256. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9257. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9258. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9259. }
  9260. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9261. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9262. }
  9263. } else {
  9264. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9265. enableAttribute( programAttribute.location + i );
  9266. }
  9267. }
  9268. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9269. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9270. vertexAttribPointer(
  9271. programAttribute.location + i,
  9272. size / programAttribute.locationSize,
  9273. type,
  9274. normalized,
  9275. size * bytesPerElement,
  9276. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9277. integer
  9278. );
  9279. }
  9280. }
  9281. } else if ( materialDefaultAttributeValues !== undefined ) {
  9282. const value = materialDefaultAttributeValues[ name ];
  9283. if ( value !== undefined ) {
  9284. switch ( value.length ) {
  9285. case 2:
  9286. gl.vertexAttrib2fv( programAttribute.location, value );
  9287. break;
  9288. case 3:
  9289. gl.vertexAttrib3fv( programAttribute.location, value );
  9290. break;
  9291. case 4:
  9292. gl.vertexAttrib4fv( programAttribute.location, value );
  9293. break;
  9294. default:
  9295. gl.vertexAttrib1fv( programAttribute.location, value );
  9296. }
  9297. }
  9298. }
  9299. }
  9300. }
  9301. disableUnusedAttributes();
  9302. }
  9303. function dispose() {
  9304. reset();
  9305. for ( const geometryId in bindingStates ) {
  9306. const programMap = bindingStates[ geometryId ];
  9307. for ( const programId in programMap ) {
  9308. const stateMap = programMap[ programId ];
  9309. for ( const wireframe in stateMap ) {
  9310. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9311. delete stateMap[ wireframe ];
  9312. }
  9313. delete programMap[ programId ];
  9314. }
  9315. delete bindingStates[ geometryId ];
  9316. }
  9317. }
  9318. function releaseStatesOfGeometry( geometry ) {
  9319. if ( bindingStates[ geometry.id ] === undefined ) return;
  9320. const programMap = bindingStates[ geometry.id ];
  9321. for ( const programId in programMap ) {
  9322. const stateMap = programMap[ programId ];
  9323. for ( const wireframe in stateMap ) {
  9324. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9325. delete stateMap[ wireframe ];
  9326. }
  9327. delete programMap[ programId ];
  9328. }
  9329. delete bindingStates[ geometry.id ];
  9330. }
  9331. function releaseStatesOfProgram( program ) {
  9332. for ( const geometryId in bindingStates ) {
  9333. const programMap = bindingStates[ geometryId ];
  9334. if ( programMap[ program.id ] === undefined ) continue;
  9335. const stateMap = programMap[ program.id ];
  9336. for ( const wireframe in stateMap ) {
  9337. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9338. delete stateMap[ wireframe ];
  9339. }
  9340. delete programMap[ program.id ];
  9341. }
  9342. }
  9343. function reset() {
  9344. resetDefaultState();
  9345. forceUpdate = true;
  9346. if ( currentState === defaultState ) return;
  9347. currentState = defaultState;
  9348. bindVertexArrayObject( currentState.object );
  9349. }
  9350. // for backward-compatibility
  9351. function resetDefaultState() {
  9352. defaultState.geometry = null;
  9353. defaultState.program = null;
  9354. defaultState.wireframe = false;
  9355. }
  9356. return {
  9357. setup: setup,
  9358. reset: reset,
  9359. resetDefaultState: resetDefaultState,
  9360. dispose: dispose,
  9361. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9362. releaseStatesOfProgram: releaseStatesOfProgram,
  9363. initAttributes: initAttributes,
  9364. enableAttribute: enableAttribute,
  9365. disableUnusedAttributes: disableUnusedAttributes
  9366. };
  9367. }
  9368. function WebGLBufferRenderer( gl, extensions, info ) {
  9369. let mode;
  9370. function setMode( value ) {
  9371. mode = value;
  9372. }
  9373. function render( start, count ) {
  9374. gl.drawArrays( mode, start, count );
  9375. info.update( count, mode, 1 );
  9376. }
  9377. function renderInstances( start, count, primcount ) {
  9378. if ( primcount === 0 ) return;
  9379. gl.drawArraysInstanced( mode, start, count, primcount );
  9380. info.update( count, mode, primcount );
  9381. }
  9382. function renderMultiDraw( starts, counts, drawCount ) {
  9383. if ( drawCount === 0 ) return;
  9384. const extension = extensions.get( 'WEBGL_multi_draw' );
  9385. if ( extension === null ) {
  9386. for ( let i = 0; i < drawCount; i ++ ) {
  9387. this.render( starts[ i ], counts[ i ] );
  9388. }
  9389. } else {
  9390. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  9391. let elementCount = 0;
  9392. for ( let i = 0; i < drawCount; i ++ ) {
  9393. elementCount += counts[ i ];
  9394. }
  9395. info.update( elementCount, mode, 1 );
  9396. }
  9397. }
  9398. //
  9399. this.setMode = setMode;
  9400. this.render = render;
  9401. this.renderInstances = renderInstances;
  9402. this.renderMultiDraw = renderMultiDraw;
  9403. }
  9404. function WebGLCapabilities( gl, extensions, parameters ) {
  9405. let maxAnisotropy;
  9406. function getMaxAnisotropy() {
  9407. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9408. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9409. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9410. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9411. } else {
  9412. maxAnisotropy = 0;
  9413. }
  9414. return maxAnisotropy;
  9415. }
  9416. function getMaxPrecision( precision ) {
  9417. if ( precision === 'highp' ) {
  9418. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9419. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9420. return 'highp';
  9421. }
  9422. precision = 'mediump';
  9423. }
  9424. if ( precision === 'mediump' ) {
  9425. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9426. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9427. return 'mediump';
  9428. }
  9429. }
  9430. return 'lowp';
  9431. }
  9432. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9433. const maxPrecision = getMaxPrecision( precision );
  9434. if ( maxPrecision !== precision ) {
  9435. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9436. precision = maxPrecision;
  9437. }
  9438. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9439. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9440. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9441. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9442. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9443. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9444. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9445. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9446. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9447. const vertexTextures = maxVertexTextures > 0;
  9448. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  9449. return {
  9450. isWebGL2: true, // keeping this for backwards compatibility
  9451. getMaxAnisotropy: getMaxAnisotropy,
  9452. getMaxPrecision: getMaxPrecision,
  9453. precision: precision,
  9454. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9455. maxTextures: maxTextures,
  9456. maxVertexTextures: maxVertexTextures,
  9457. maxTextureSize: maxTextureSize,
  9458. maxCubemapSize: maxCubemapSize,
  9459. maxAttributes: maxAttributes,
  9460. maxVertexUniforms: maxVertexUniforms,
  9461. maxVaryings: maxVaryings,
  9462. maxFragmentUniforms: maxFragmentUniforms,
  9463. vertexTextures: vertexTextures,
  9464. maxSamples: maxSamples
  9465. };
  9466. }
  9467. function WebGLClipping( properties ) {
  9468. const scope = this;
  9469. let globalState = null,
  9470. numGlobalPlanes = 0,
  9471. localClippingEnabled = false,
  9472. renderingShadows = false;
  9473. const plane = new Plane(),
  9474. viewNormalMatrix = new Matrix3(),
  9475. uniform = { value: null, needsUpdate: false };
  9476. this.uniform = uniform;
  9477. this.numPlanes = 0;
  9478. this.numIntersection = 0;
  9479. this.init = function ( planes, enableLocalClipping ) {
  9480. const enabled =
  9481. planes.length !== 0 ||
  9482. enableLocalClipping ||
  9483. // enable state of previous frame - the clipping code has to
  9484. // run another frame in order to reset the state:
  9485. numGlobalPlanes !== 0 ||
  9486. localClippingEnabled;
  9487. localClippingEnabled = enableLocalClipping;
  9488. numGlobalPlanes = planes.length;
  9489. return enabled;
  9490. };
  9491. this.beginShadows = function () {
  9492. renderingShadows = true;
  9493. projectPlanes( null );
  9494. };
  9495. this.endShadows = function () {
  9496. renderingShadows = false;
  9497. };
  9498. this.setGlobalState = function ( planes, camera ) {
  9499. globalState = projectPlanes( planes, camera, 0 );
  9500. };
  9501. this.setState = function ( material, camera, useCache ) {
  9502. const planes = material.clippingPlanes,
  9503. clipIntersection = material.clipIntersection,
  9504. clipShadows = material.clipShadows;
  9505. const materialProperties = properties.get( material );
  9506. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9507. // there's no local clipping
  9508. if ( renderingShadows ) {
  9509. // there's no global clipping
  9510. projectPlanes( null );
  9511. } else {
  9512. resetGlobalState();
  9513. }
  9514. } else {
  9515. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9516. lGlobal = nGlobal * 4;
  9517. let dstArray = materialProperties.clippingState || null;
  9518. uniform.value = dstArray; // ensure unique state
  9519. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9520. for ( let i = 0; i !== lGlobal; ++ i ) {
  9521. dstArray[ i ] = globalState[ i ];
  9522. }
  9523. materialProperties.clippingState = dstArray;
  9524. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9525. this.numPlanes += nGlobal;
  9526. }
  9527. };
  9528. function resetGlobalState() {
  9529. if ( uniform.value !== globalState ) {
  9530. uniform.value = globalState;
  9531. uniform.needsUpdate = numGlobalPlanes > 0;
  9532. }
  9533. scope.numPlanes = numGlobalPlanes;
  9534. scope.numIntersection = 0;
  9535. }
  9536. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9537. const nPlanes = planes !== null ? planes.length : 0;
  9538. let dstArray = null;
  9539. if ( nPlanes !== 0 ) {
  9540. dstArray = uniform.value;
  9541. if ( skipTransform !== true || dstArray === null ) {
  9542. const flatSize = dstOffset + nPlanes * 4,
  9543. viewMatrix = camera.matrixWorldInverse;
  9544. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9545. if ( dstArray === null || dstArray.length < flatSize ) {
  9546. dstArray = new Float32Array( flatSize );
  9547. }
  9548. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9549. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9550. plane.normal.toArray( dstArray, i4 );
  9551. dstArray[ i4 + 3 ] = plane.constant;
  9552. }
  9553. }
  9554. uniform.value = dstArray;
  9555. uniform.needsUpdate = true;
  9556. }
  9557. scope.numPlanes = nPlanes;
  9558. scope.numIntersection = 0;
  9559. return dstArray;
  9560. }
  9561. }
  9562. function WebGLCubeMaps( renderer ) {
  9563. let cubemaps = new WeakMap();
  9564. function mapTextureMapping( texture, mapping ) {
  9565. if ( mapping === EquirectangularReflectionMapping ) {
  9566. texture.mapping = CubeReflectionMapping;
  9567. } else if ( mapping === EquirectangularRefractionMapping ) {
  9568. texture.mapping = CubeRefractionMapping;
  9569. }
  9570. return texture;
  9571. }
  9572. function get( texture ) {
  9573. if ( texture && texture.isTexture ) {
  9574. const mapping = texture.mapping;
  9575. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9576. if ( cubemaps.has( texture ) ) {
  9577. const cubemap = cubemaps.get( texture ).texture;
  9578. return mapTextureMapping( cubemap, texture.mapping );
  9579. } else {
  9580. const image = texture.image;
  9581. if ( image && image.height > 0 ) {
  9582. const renderTarget = new WebGLCubeRenderTarget( image.height );
  9583. renderTarget.fromEquirectangularTexture( renderer, texture );
  9584. cubemaps.set( texture, renderTarget );
  9585. texture.addEventListener( 'dispose', onTextureDispose );
  9586. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9587. } else {
  9588. // image not yet ready. try the conversion next frame
  9589. return null;
  9590. }
  9591. }
  9592. }
  9593. }
  9594. return texture;
  9595. }
  9596. function onTextureDispose( event ) {
  9597. const texture = event.target;
  9598. texture.removeEventListener( 'dispose', onTextureDispose );
  9599. const cubemap = cubemaps.get( texture );
  9600. if ( cubemap !== undefined ) {
  9601. cubemaps.delete( texture );
  9602. cubemap.dispose();
  9603. }
  9604. }
  9605. function dispose() {
  9606. cubemaps = new WeakMap();
  9607. }
  9608. return {
  9609. get: get,
  9610. dispose: dispose
  9611. };
  9612. }
  9613. class OrthographicCamera extends Camera {
  9614. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9615. super();
  9616. this.isOrthographicCamera = true;
  9617. this.type = 'OrthographicCamera';
  9618. this.zoom = 1;
  9619. this.view = null;
  9620. this.left = left;
  9621. this.right = right;
  9622. this.top = top;
  9623. this.bottom = bottom;
  9624. this.near = near;
  9625. this.far = far;
  9626. this.updateProjectionMatrix();
  9627. }
  9628. copy( source, recursive ) {
  9629. super.copy( source, recursive );
  9630. this.left = source.left;
  9631. this.right = source.right;
  9632. this.top = source.top;
  9633. this.bottom = source.bottom;
  9634. this.near = source.near;
  9635. this.far = source.far;
  9636. this.zoom = source.zoom;
  9637. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9638. return this;
  9639. }
  9640. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9641. if ( this.view === null ) {
  9642. this.view = {
  9643. enabled: true,
  9644. fullWidth: 1,
  9645. fullHeight: 1,
  9646. offsetX: 0,
  9647. offsetY: 0,
  9648. width: 1,
  9649. height: 1
  9650. };
  9651. }
  9652. this.view.enabled = true;
  9653. this.view.fullWidth = fullWidth;
  9654. this.view.fullHeight = fullHeight;
  9655. this.view.offsetX = x;
  9656. this.view.offsetY = y;
  9657. this.view.width = width;
  9658. this.view.height = height;
  9659. this.updateProjectionMatrix();
  9660. }
  9661. clearViewOffset() {
  9662. if ( this.view !== null ) {
  9663. this.view.enabled = false;
  9664. }
  9665. this.updateProjectionMatrix();
  9666. }
  9667. updateProjectionMatrix() {
  9668. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9669. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9670. const cx = ( this.right + this.left ) / 2;
  9671. const cy = ( this.top + this.bottom ) / 2;
  9672. let left = cx - dx;
  9673. let right = cx + dx;
  9674. let top = cy + dy;
  9675. let bottom = cy - dy;
  9676. if ( this.view !== null && this.view.enabled ) {
  9677. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9678. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9679. left += scaleW * this.view.offsetX;
  9680. right = left + scaleW * this.view.width;
  9681. top -= scaleH * this.view.offsetY;
  9682. bottom = top - scaleH * this.view.height;
  9683. }
  9684. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9685. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9686. }
  9687. toJSON( meta ) {
  9688. const data = super.toJSON( meta );
  9689. data.object.zoom = this.zoom;
  9690. data.object.left = this.left;
  9691. data.object.right = this.right;
  9692. data.object.top = this.top;
  9693. data.object.bottom = this.bottom;
  9694. data.object.near = this.near;
  9695. data.object.far = this.far;
  9696. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9697. return data;
  9698. }
  9699. }
  9700. const LOD_MIN = 4;
  9701. // The standard deviations (radians) associated with the extra mips. These are
  9702. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9703. // geometric shadowing function. These sigma values squared must match the
  9704. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9705. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9706. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9707. // samples and exit early, but not recompile the shader.
  9708. const MAX_SAMPLES = 20;
  9709. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9710. const _clearColor = /*@__PURE__*/ new Color();
  9711. let _oldTarget = null;
  9712. let _oldActiveCubeFace = 0;
  9713. let _oldActiveMipmapLevel = 0;
  9714. let _oldXrEnabled = false;
  9715. // Golden Ratio
  9716. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9717. const INV_PHI = 1 / PHI;
  9718. // Vertices of a dodecahedron (except the opposites, which represent the
  9719. // same axis), used as axis directions evenly spread on a sphere.
  9720. const _axisDirections = [
  9721. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9722. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9723. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9724. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9725. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9726. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9727. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9728. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9729. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9730. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9731. /**
  9732. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9733. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9734. * blur to be quickly accessed based on material roughness. It is packed into a
  9735. * special CubeUV format that allows us to perform custom interpolation so that
  9736. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9737. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9738. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9739. * higher roughness levels. In this way we maintain resolution to smoothly
  9740. * interpolate diffuse lighting while limiting sampling computation.
  9741. *
  9742. * Paper: Fast, Accurate Image-Based Lighting
  9743. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9744. */
  9745. class PMREMGenerator {
  9746. constructor( renderer ) {
  9747. this._renderer = renderer;
  9748. this._pingPongRenderTarget = null;
  9749. this._lodMax = 0;
  9750. this._cubeSize = 0;
  9751. this._lodPlanes = [];
  9752. this._sizeLods = [];
  9753. this._sigmas = [];
  9754. this._blurMaterial = null;
  9755. this._cubemapMaterial = null;
  9756. this._equirectMaterial = null;
  9757. this._compileMaterial( this._blurMaterial );
  9758. }
  9759. /**
  9760. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9761. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9762. * in radians to be applied to the scene before PMREM generation. Optional near
  9763. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9764. * is placed at the origin).
  9765. */
  9766. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9767. _oldTarget = this._renderer.getRenderTarget();
  9768. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9769. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9770. _oldXrEnabled = this._renderer.xr.enabled;
  9771. this._renderer.xr.enabled = false;
  9772. this._setSize( 256 );
  9773. const cubeUVRenderTarget = this._allocateTargets();
  9774. cubeUVRenderTarget.depthBuffer = true;
  9775. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9776. if ( sigma > 0 ) {
  9777. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9778. }
  9779. this._applyPMREM( cubeUVRenderTarget );
  9780. this._cleanup( cubeUVRenderTarget );
  9781. return cubeUVRenderTarget;
  9782. }
  9783. /**
  9784. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9785. * or HDR. The ideal input image size is 1k (1024 x 512),
  9786. * as this matches best with the 256 x 256 cubemap output.
  9787. * The smallest supported equirectangular image size is 64 x 32.
  9788. */
  9789. fromEquirectangular( equirectangular, renderTarget = null ) {
  9790. return this._fromTexture( equirectangular, renderTarget );
  9791. }
  9792. /**
  9793. * Generates a PMREM from an cubemap texture, which can be either LDR
  9794. * or HDR. The ideal input cube size is 256 x 256,
  9795. * as this matches best with the 256 x 256 cubemap output.
  9796. * The smallest supported cube size is 16 x 16.
  9797. */
  9798. fromCubemap( cubemap, renderTarget = null ) {
  9799. return this._fromTexture( cubemap, renderTarget );
  9800. }
  9801. /**
  9802. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9803. * your texture's network fetch for increased concurrency.
  9804. */
  9805. compileCubemapShader() {
  9806. if ( this._cubemapMaterial === null ) {
  9807. this._cubemapMaterial = _getCubemapMaterial();
  9808. this._compileMaterial( this._cubemapMaterial );
  9809. }
  9810. }
  9811. /**
  9812. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9813. * your texture's network fetch for increased concurrency.
  9814. */
  9815. compileEquirectangularShader() {
  9816. if ( this._equirectMaterial === null ) {
  9817. this._equirectMaterial = _getEquirectMaterial();
  9818. this._compileMaterial( this._equirectMaterial );
  9819. }
  9820. }
  9821. /**
  9822. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9823. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9824. * one of them will cause any others to also become unusable.
  9825. */
  9826. dispose() {
  9827. this._dispose();
  9828. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9829. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9830. }
  9831. // private interface
  9832. _setSize( cubeSize ) {
  9833. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9834. this._cubeSize = Math.pow( 2, this._lodMax );
  9835. }
  9836. _dispose() {
  9837. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9838. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9839. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9840. this._lodPlanes[ i ].dispose();
  9841. }
  9842. }
  9843. _cleanup( outputTarget ) {
  9844. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  9845. this._renderer.xr.enabled = _oldXrEnabled;
  9846. outputTarget.scissorTest = false;
  9847. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9848. }
  9849. _fromTexture( texture, renderTarget ) {
  9850. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9851. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9852. } else { // Equirectangular
  9853. this._setSize( texture.image.width / 4 );
  9854. }
  9855. _oldTarget = this._renderer.getRenderTarget();
  9856. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9857. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9858. _oldXrEnabled = this._renderer.xr.enabled;
  9859. this._renderer.xr.enabled = false;
  9860. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9861. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9862. this._applyPMREM( cubeUVRenderTarget );
  9863. this._cleanup( cubeUVRenderTarget );
  9864. return cubeUVRenderTarget;
  9865. }
  9866. _allocateTargets() {
  9867. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9868. const height = 4 * this._cubeSize;
  9869. const params = {
  9870. magFilter: LinearFilter,
  9871. minFilter: LinearFilter,
  9872. generateMipmaps: false,
  9873. type: HalfFloatType,
  9874. format: RGBAFormat,
  9875. colorSpace: LinearSRGBColorSpace,
  9876. depthBuffer: false
  9877. };
  9878. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9879. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9880. if ( this._pingPongRenderTarget !== null ) {
  9881. this._dispose();
  9882. }
  9883. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9884. const { _lodMax } = this;
  9885. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9886. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9887. }
  9888. return cubeUVRenderTarget;
  9889. }
  9890. _compileMaterial( material ) {
  9891. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9892. this._renderer.compile( tmpMesh, _flatCamera );
  9893. }
  9894. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9895. const fov = 90;
  9896. const aspect = 1;
  9897. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9898. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9899. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9900. const renderer = this._renderer;
  9901. const originalAutoClear = renderer.autoClear;
  9902. const toneMapping = renderer.toneMapping;
  9903. renderer.getClearColor( _clearColor );
  9904. renderer.toneMapping = NoToneMapping;
  9905. renderer.autoClear = false;
  9906. const backgroundMaterial = new MeshBasicMaterial( {
  9907. name: 'PMREM.Background',
  9908. side: BackSide,
  9909. depthWrite: false,
  9910. depthTest: false,
  9911. } );
  9912. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9913. let useSolidColor = false;
  9914. const background = scene.background;
  9915. if ( background ) {
  9916. if ( background.isColor ) {
  9917. backgroundMaterial.color.copy( background );
  9918. scene.background = null;
  9919. useSolidColor = true;
  9920. }
  9921. } else {
  9922. backgroundMaterial.color.copy( _clearColor );
  9923. useSolidColor = true;
  9924. }
  9925. for ( let i = 0; i < 6; i ++ ) {
  9926. const col = i % 3;
  9927. if ( col === 0 ) {
  9928. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9929. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9930. } else if ( col === 1 ) {
  9931. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9932. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9933. } else {
  9934. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9935. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9936. }
  9937. const size = this._cubeSize;
  9938. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9939. renderer.setRenderTarget( cubeUVRenderTarget );
  9940. if ( useSolidColor ) {
  9941. renderer.render( backgroundBox, cubeCamera );
  9942. }
  9943. renderer.render( scene, cubeCamera );
  9944. }
  9945. backgroundBox.geometry.dispose();
  9946. backgroundBox.material.dispose();
  9947. renderer.toneMapping = toneMapping;
  9948. renderer.autoClear = originalAutoClear;
  9949. scene.background = background;
  9950. }
  9951. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9952. const renderer = this._renderer;
  9953. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9954. if ( isCubeTexture ) {
  9955. if ( this._cubemapMaterial === null ) {
  9956. this._cubemapMaterial = _getCubemapMaterial();
  9957. }
  9958. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9959. } else {
  9960. if ( this._equirectMaterial === null ) {
  9961. this._equirectMaterial = _getEquirectMaterial();
  9962. }
  9963. }
  9964. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9965. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9966. const uniforms = material.uniforms;
  9967. uniforms[ 'envMap' ].value = texture;
  9968. const size = this._cubeSize;
  9969. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9970. renderer.setRenderTarget( cubeUVRenderTarget );
  9971. renderer.render( mesh, _flatCamera );
  9972. }
  9973. _applyPMREM( cubeUVRenderTarget ) {
  9974. const renderer = this._renderer;
  9975. const autoClear = renderer.autoClear;
  9976. renderer.autoClear = false;
  9977. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9978. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9979. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9980. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9981. }
  9982. renderer.autoClear = autoClear;
  9983. }
  9984. /**
  9985. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9986. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9987. * the blur latitudinally (around the poles), and then longitudinally (towards
  9988. * the poles) to approximate the orthogonally-separable blur. It is least
  9989. * accurate at the poles, but still does a decent job.
  9990. */
  9991. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9992. const pingPongRenderTarget = this._pingPongRenderTarget;
  9993. this._halfBlur(
  9994. cubeUVRenderTarget,
  9995. pingPongRenderTarget,
  9996. lodIn,
  9997. lodOut,
  9998. sigma,
  9999. 'latitudinal',
  10000. poleAxis );
  10001. this._halfBlur(
  10002. pingPongRenderTarget,
  10003. cubeUVRenderTarget,
  10004. lodOut,
  10005. lodOut,
  10006. sigma,
  10007. 'longitudinal',
  10008. poleAxis );
  10009. }
  10010. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  10011. const renderer = this._renderer;
  10012. const blurMaterial = this._blurMaterial;
  10013. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  10014. console.error(
  10015. 'blur direction must be either latitudinal or longitudinal!' );
  10016. }
  10017. // Number of standard deviations at which to cut off the discrete approximation.
  10018. const STANDARD_DEVIATIONS = 3;
  10019. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  10020. const blurUniforms = blurMaterial.uniforms;
  10021. const pixels = this._sizeLods[ lodIn ] - 1;
  10022. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  10023. const sigmaPixels = sigmaRadians / radiansPerPixel;
  10024. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  10025. if ( samples > MAX_SAMPLES ) {
  10026. console.warn( `sigmaRadians, ${
  10027. sigmaRadians}, is too large and will clip, as it requested ${
  10028. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  10029. }
  10030. const weights = [];
  10031. let sum = 0;
  10032. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  10033. const x = i / sigmaPixels;
  10034. const weight = Math.exp( - x * x / 2 );
  10035. weights.push( weight );
  10036. if ( i === 0 ) {
  10037. sum += weight;
  10038. } else if ( i < samples ) {
  10039. sum += 2 * weight;
  10040. }
  10041. }
  10042. for ( let i = 0; i < weights.length; i ++ ) {
  10043. weights[ i ] = weights[ i ] / sum;
  10044. }
  10045. blurUniforms[ 'envMap' ].value = targetIn.texture;
  10046. blurUniforms[ 'samples' ].value = samples;
  10047. blurUniforms[ 'weights' ].value = weights;
  10048. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  10049. if ( poleAxis ) {
  10050. blurUniforms[ 'poleAxis' ].value = poleAxis;
  10051. }
  10052. const { _lodMax } = this;
  10053. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  10054. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  10055. const outputSize = this._sizeLods[ lodOut ];
  10056. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  10057. const y = 4 * ( this._cubeSize - outputSize );
  10058. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10059. renderer.setRenderTarget( targetOut );
  10060. renderer.render( blurMesh, _flatCamera );
  10061. }
  10062. }
  10063. function _createPlanes( lodMax ) {
  10064. const lodPlanes = [];
  10065. const sizeLods = [];
  10066. const sigmas = [];
  10067. let lod = lodMax;
  10068. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10069. for ( let i = 0; i < totalLods; i ++ ) {
  10070. const sizeLod = Math.pow( 2, lod );
  10071. sizeLods.push( sizeLod );
  10072. let sigma = 1.0 / sizeLod;
  10073. if ( i > lodMax - LOD_MIN ) {
  10074. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  10075. } else if ( i === 0 ) {
  10076. sigma = 0;
  10077. }
  10078. sigmas.push( sigma );
  10079. const texelSize = 1.0 / ( sizeLod - 2 );
  10080. const min = - texelSize;
  10081. const max = 1 + texelSize;
  10082. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10083. const cubeFaces = 6;
  10084. const vertices = 6;
  10085. const positionSize = 3;
  10086. const uvSize = 2;
  10087. const faceIndexSize = 1;
  10088. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10089. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10090. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10091. for ( let face = 0; face < cubeFaces; face ++ ) {
  10092. const x = ( face % 3 ) * 2 / 3 - 1;
  10093. const y = face > 2 ? 0 : - 1;
  10094. const coordinates = [
  10095. x, y, 0,
  10096. x + 2 / 3, y, 0,
  10097. x + 2 / 3, y + 1, 0,
  10098. x, y, 0,
  10099. x + 2 / 3, y + 1, 0,
  10100. x, y + 1, 0
  10101. ];
  10102. position.set( coordinates, positionSize * vertices * face );
  10103. uv.set( uv1, uvSize * vertices * face );
  10104. const fill = [ face, face, face, face, face, face ];
  10105. faceIndex.set( fill, faceIndexSize * vertices * face );
  10106. }
  10107. const planes = new BufferGeometry();
  10108. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10109. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10110. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10111. lodPlanes.push( planes );
  10112. if ( lod > LOD_MIN ) {
  10113. lod --;
  10114. }
  10115. }
  10116. return { lodPlanes, sizeLods, sigmas };
  10117. }
  10118. function _createRenderTarget( width, height, params ) {
  10119. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10120. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10121. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10122. cubeUVRenderTarget.scissorTest = true;
  10123. return cubeUVRenderTarget;
  10124. }
  10125. function _setViewport( target, x, y, width, height ) {
  10126. target.viewport.set( x, y, width, height );
  10127. target.scissor.set( x, y, width, height );
  10128. }
  10129. function _getBlurShader( lodMax, width, height ) {
  10130. const weights = new Float32Array( MAX_SAMPLES );
  10131. const poleAxis = new Vector3( 0, 1, 0 );
  10132. const shaderMaterial = new ShaderMaterial( {
  10133. name: 'SphericalGaussianBlur',
  10134. defines: {
  10135. 'n': MAX_SAMPLES,
  10136. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10137. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10138. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10139. },
  10140. uniforms: {
  10141. 'envMap': { value: null },
  10142. 'samples': { value: 1 },
  10143. 'weights': { value: weights },
  10144. 'latitudinal': { value: false },
  10145. 'dTheta': { value: 0 },
  10146. 'mipInt': { value: 0 },
  10147. 'poleAxis': { value: poleAxis }
  10148. },
  10149. vertexShader: _getCommonVertexShader(),
  10150. fragmentShader: /* glsl */`
  10151. precision mediump float;
  10152. precision mediump int;
  10153. varying vec3 vOutputDirection;
  10154. uniform sampler2D envMap;
  10155. uniform int samples;
  10156. uniform float weights[ n ];
  10157. uniform bool latitudinal;
  10158. uniform float dTheta;
  10159. uniform float mipInt;
  10160. uniform vec3 poleAxis;
  10161. #define ENVMAP_TYPE_CUBE_UV
  10162. #include <cube_uv_reflection_fragment>
  10163. vec3 getSample( float theta, vec3 axis ) {
  10164. float cosTheta = cos( theta );
  10165. // Rodrigues' axis-angle rotation
  10166. vec3 sampleDirection = vOutputDirection * cosTheta
  10167. + cross( axis, vOutputDirection ) * sin( theta )
  10168. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10169. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10170. }
  10171. void main() {
  10172. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10173. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10174. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10175. }
  10176. axis = normalize( axis );
  10177. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10178. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10179. for ( int i = 1; i < n; i++ ) {
  10180. if ( i >= samples ) {
  10181. break;
  10182. }
  10183. float theta = dTheta * float( i );
  10184. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10185. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10186. }
  10187. }
  10188. `,
  10189. blending: NoBlending,
  10190. depthTest: false,
  10191. depthWrite: false
  10192. } );
  10193. return shaderMaterial;
  10194. }
  10195. function _getEquirectMaterial() {
  10196. return new ShaderMaterial( {
  10197. name: 'EquirectangularToCubeUV',
  10198. uniforms: {
  10199. 'envMap': { value: null }
  10200. },
  10201. vertexShader: _getCommonVertexShader(),
  10202. fragmentShader: /* glsl */`
  10203. precision mediump float;
  10204. precision mediump int;
  10205. varying vec3 vOutputDirection;
  10206. uniform sampler2D envMap;
  10207. #include <common>
  10208. void main() {
  10209. vec3 outputDirection = normalize( vOutputDirection );
  10210. vec2 uv = equirectUv( outputDirection );
  10211. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10212. }
  10213. `,
  10214. blending: NoBlending,
  10215. depthTest: false,
  10216. depthWrite: false
  10217. } );
  10218. }
  10219. function _getCubemapMaterial() {
  10220. return new ShaderMaterial( {
  10221. name: 'CubemapToCubeUV',
  10222. uniforms: {
  10223. 'envMap': { value: null },
  10224. 'flipEnvMap': { value: - 1 }
  10225. },
  10226. vertexShader: _getCommonVertexShader(),
  10227. fragmentShader: /* glsl */`
  10228. precision mediump float;
  10229. precision mediump int;
  10230. uniform float flipEnvMap;
  10231. varying vec3 vOutputDirection;
  10232. uniform samplerCube envMap;
  10233. void main() {
  10234. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10235. }
  10236. `,
  10237. blending: NoBlending,
  10238. depthTest: false,
  10239. depthWrite: false
  10240. } );
  10241. }
  10242. function _getCommonVertexShader() {
  10243. return /* glsl */`
  10244. precision mediump float;
  10245. precision mediump int;
  10246. attribute float faceIndex;
  10247. varying vec3 vOutputDirection;
  10248. // RH coordinate system; PMREM face-indexing convention
  10249. vec3 getDirection( vec2 uv, float face ) {
  10250. uv = 2.0 * uv - 1.0;
  10251. vec3 direction = vec3( uv, 1.0 );
  10252. if ( face == 0.0 ) {
  10253. direction = direction.zyx; // ( 1, v, u ) pos x
  10254. } else if ( face == 1.0 ) {
  10255. direction = direction.xzy;
  10256. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10257. } else if ( face == 2.0 ) {
  10258. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10259. } else if ( face == 3.0 ) {
  10260. direction = direction.zyx;
  10261. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10262. } else if ( face == 4.0 ) {
  10263. direction = direction.xzy;
  10264. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10265. } else if ( face == 5.0 ) {
  10266. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10267. }
  10268. return direction;
  10269. }
  10270. void main() {
  10271. vOutputDirection = getDirection( uv, faceIndex );
  10272. gl_Position = vec4( position, 1.0 );
  10273. }
  10274. `;
  10275. }
  10276. function WebGLCubeUVMaps( renderer ) {
  10277. let cubeUVmaps = new WeakMap();
  10278. let pmremGenerator = null;
  10279. function get( texture ) {
  10280. if ( texture && texture.isTexture ) {
  10281. const mapping = texture.mapping;
  10282. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10283. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10284. // equirect/cube map to cubeUV conversion
  10285. if ( isEquirectMap || isCubeMap ) {
  10286. let renderTarget = cubeUVmaps.get( texture );
  10287. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  10288. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  10289. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10290. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10291. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10292. cubeUVmaps.set( texture, renderTarget );
  10293. return renderTarget.texture;
  10294. } else {
  10295. if ( renderTarget !== undefined ) {
  10296. return renderTarget.texture;
  10297. } else {
  10298. const image = texture.image;
  10299. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10300. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10301. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10302. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10303. cubeUVmaps.set( texture, renderTarget );
  10304. texture.addEventListener( 'dispose', onTextureDispose );
  10305. return renderTarget.texture;
  10306. } else {
  10307. // image not yet ready. try the conversion next frame
  10308. return null;
  10309. }
  10310. }
  10311. }
  10312. }
  10313. }
  10314. return texture;
  10315. }
  10316. function isCubeTextureComplete( image ) {
  10317. let count = 0;
  10318. const length = 6;
  10319. for ( let i = 0; i < length; i ++ ) {
  10320. if ( image[ i ] !== undefined ) count ++;
  10321. }
  10322. return count === length;
  10323. }
  10324. function onTextureDispose( event ) {
  10325. const texture = event.target;
  10326. texture.removeEventListener( 'dispose', onTextureDispose );
  10327. const cubemapUV = cubeUVmaps.get( texture );
  10328. if ( cubemapUV !== undefined ) {
  10329. cubeUVmaps.delete( texture );
  10330. cubemapUV.dispose();
  10331. }
  10332. }
  10333. function dispose() {
  10334. cubeUVmaps = new WeakMap();
  10335. if ( pmremGenerator !== null ) {
  10336. pmremGenerator.dispose();
  10337. pmremGenerator = null;
  10338. }
  10339. }
  10340. return {
  10341. get: get,
  10342. dispose: dispose
  10343. };
  10344. }
  10345. function WebGLExtensions( gl ) {
  10346. const extensions = {};
  10347. function getExtension( name ) {
  10348. if ( extensions[ name ] !== undefined ) {
  10349. return extensions[ name ];
  10350. }
  10351. let extension;
  10352. switch ( name ) {
  10353. case 'WEBGL_depth_texture':
  10354. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10355. break;
  10356. case 'EXT_texture_filter_anisotropic':
  10357. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10358. break;
  10359. case 'WEBGL_compressed_texture_s3tc':
  10360. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10361. break;
  10362. case 'WEBGL_compressed_texture_pvrtc':
  10363. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10364. break;
  10365. default:
  10366. extension = gl.getExtension( name );
  10367. }
  10368. extensions[ name ] = extension;
  10369. return extension;
  10370. }
  10371. return {
  10372. has: function ( name ) {
  10373. return getExtension( name ) !== null;
  10374. },
  10375. init: function () {
  10376. getExtension( 'EXT_color_buffer_float' );
  10377. getExtension( 'WEBGL_clip_cull_distance' );
  10378. getExtension( 'OES_texture_float_linear' );
  10379. getExtension( 'EXT_color_buffer_half_float' );
  10380. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10381. getExtension( 'WEBGL_render_shared_exponent' );
  10382. },
  10383. get: function ( name ) {
  10384. const extension = getExtension( name );
  10385. if ( extension === null ) {
  10386. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10387. }
  10388. return extension;
  10389. }
  10390. };
  10391. }
  10392. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10393. const geometries = {};
  10394. const wireframeAttributes = new WeakMap();
  10395. function onGeometryDispose( event ) {
  10396. const geometry = event.target;
  10397. if ( geometry.index !== null ) {
  10398. attributes.remove( geometry.index );
  10399. }
  10400. for ( const name in geometry.attributes ) {
  10401. attributes.remove( geometry.attributes[ name ] );
  10402. }
  10403. for ( const name in geometry.morphAttributes ) {
  10404. const array = geometry.morphAttributes[ name ];
  10405. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10406. attributes.remove( array[ i ] );
  10407. }
  10408. }
  10409. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10410. delete geometries[ geometry.id ];
  10411. const attribute = wireframeAttributes.get( geometry );
  10412. if ( attribute ) {
  10413. attributes.remove( attribute );
  10414. wireframeAttributes.delete( geometry );
  10415. }
  10416. bindingStates.releaseStatesOfGeometry( geometry );
  10417. if ( geometry.isInstancedBufferGeometry === true ) {
  10418. delete geometry._maxInstanceCount;
  10419. }
  10420. //
  10421. info.memory.geometries --;
  10422. }
  10423. function get( object, geometry ) {
  10424. if ( geometries[ geometry.id ] === true ) return geometry;
  10425. geometry.addEventListener( 'dispose', onGeometryDispose );
  10426. geometries[ geometry.id ] = true;
  10427. info.memory.geometries ++;
  10428. return geometry;
  10429. }
  10430. function update( geometry ) {
  10431. const geometryAttributes = geometry.attributes;
  10432. // Updating index buffer in VAO now. See WebGLBindingStates.
  10433. for ( const name in geometryAttributes ) {
  10434. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10435. }
  10436. // morph targets
  10437. const morphAttributes = geometry.morphAttributes;
  10438. for ( const name in morphAttributes ) {
  10439. const array = morphAttributes[ name ];
  10440. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10441. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10442. }
  10443. }
  10444. }
  10445. function updateWireframeAttribute( geometry ) {
  10446. const indices = [];
  10447. const geometryIndex = geometry.index;
  10448. const geometryPosition = geometry.attributes.position;
  10449. let version = 0;
  10450. if ( geometryIndex !== null ) {
  10451. const array = geometryIndex.array;
  10452. version = geometryIndex.version;
  10453. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10454. const a = array[ i + 0 ];
  10455. const b = array[ i + 1 ];
  10456. const c = array[ i + 2 ];
  10457. indices.push( a, b, b, c, c, a );
  10458. }
  10459. } else if ( geometryPosition !== undefined ) {
  10460. const array = geometryPosition.array;
  10461. version = geometryPosition.version;
  10462. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10463. const a = i + 0;
  10464. const b = i + 1;
  10465. const c = i + 2;
  10466. indices.push( a, b, b, c, c, a );
  10467. }
  10468. } else {
  10469. return;
  10470. }
  10471. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10472. attribute.version = version;
  10473. // Updating index buffer in VAO now. See WebGLBindingStates
  10474. //
  10475. const previousAttribute = wireframeAttributes.get( geometry );
  10476. if ( previousAttribute ) attributes.remove( previousAttribute );
  10477. //
  10478. wireframeAttributes.set( geometry, attribute );
  10479. }
  10480. function getWireframeAttribute( geometry ) {
  10481. const currentAttribute = wireframeAttributes.get( geometry );
  10482. if ( currentAttribute ) {
  10483. const geometryIndex = geometry.index;
  10484. if ( geometryIndex !== null ) {
  10485. // if the attribute is obsolete, create a new one
  10486. if ( currentAttribute.version < geometryIndex.version ) {
  10487. updateWireframeAttribute( geometry );
  10488. }
  10489. }
  10490. } else {
  10491. updateWireframeAttribute( geometry );
  10492. }
  10493. return wireframeAttributes.get( geometry );
  10494. }
  10495. return {
  10496. get: get,
  10497. update: update,
  10498. getWireframeAttribute: getWireframeAttribute
  10499. };
  10500. }
  10501. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  10502. let mode;
  10503. function setMode( value ) {
  10504. mode = value;
  10505. }
  10506. let type, bytesPerElement;
  10507. function setIndex( value ) {
  10508. type = value.type;
  10509. bytesPerElement = value.bytesPerElement;
  10510. }
  10511. function render( start, count ) {
  10512. gl.drawElements( mode, count, type, start * bytesPerElement );
  10513. info.update( count, mode, 1 );
  10514. }
  10515. function renderInstances( start, count, primcount ) {
  10516. if ( primcount === 0 ) return;
  10517. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  10518. info.update( count, mode, primcount );
  10519. }
  10520. function renderMultiDraw( starts, counts, drawCount ) {
  10521. if ( drawCount === 0 ) return;
  10522. const extension = extensions.get( 'WEBGL_multi_draw' );
  10523. if ( extension === null ) {
  10524. for ( let i = 0; i < drawCount; i ++ ) {
  10525. this.render( starts[ i ] / bytesPerElement, counts[ i ] );
  10526. }
  10527. } else {
  10528. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  10529. let elementCount = 0;
  10530. for ( let i = 0; i < drawCount; i ++ ) {
  10531. elementCount += counts[ i ];
  10532. }
  10533. info.update( elementCount, mode, 1 );
  10534. }
  10535. }
  10536. //
  10537. this.setMode = setMode;
  10538. this.setIndex = setIndex;
  10539. this.render = render;
  10540. this.renderInstances = renderInstances;
  10541. this.renderMultiDraw = renderMultiDraw;
  10542. }
  10543. function WebGLInfo( gl ) {
  10544. const memory = {
  10545. geometries: 0,
  10546. textures: 0
  10547. };
  10548. const render = {
  10549. frame: 0,
  10550. calls: 0,
  10551. triangles: 0,
  10552. points: 0,
  10553. lines: 0
  10554. };
  10555. function update( count, mode, instanceCount ) {
  10556. render.calls ++;
  10557. switch ( mode ) {
  10558. case gl.TRIANGLES:
  10559. render.triangles += instanceCount * ( count / 3 );
  10560. break;
  10561. case gl.LINES:
  10562. render.lines += instanceCount * ( count / 2 );
  10563. break;
  10564. case gl.LINE_STRIP:
  10565. render.lines += instanceCount * ( count - 1 );
  10566. break;
  10567. case gl.LINE_LOOP:
  10568. render.lines += instanceCount * count;
  10569. break;
  10570. case gl.POINTS:
  10571. render.points += instanceCount * count;
  10572. break;
  10573. default:
  10574. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10575. break;
  10576. }
  10577. }
  10578. function reset() {
  10579. render.calls = 0;
  10580. render.triangles = 0;
  10581. render.points = 0;
  10582. render.lines = 0;
  10583. }
  10584. return {
  10585. memory: memory,
  10586. render: render,
  10587. programs: null,
  10588. autoReset: true,
  10589. reset: reset,
  10590. update: update
  10591. };
  10592. }
  10593. function WebGLMorphtargets( gl, capabilities, textures ) {
  10594. const morphTextures = new WeakMap();
  10595. const morph = new Vector4();
  10596. function update( object, geometry, program ) {
  10597. const objectInfluences = object.morphTargetInfluences;
  10598. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10599. // into an array of data textures. Each layer represents a single morph target.
  10600. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10601. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10602. let entry = morphTextures.get( geometry );
  10603. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10604. if ( entry !== undefined ) entry.texture.dispose();
  10605. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10606. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10607. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10608. const morphTargets = geometry.morphAttributes.position || [];
  10609. const morphNormals = geometry.morphAttributes.normal || [];
  10610. const morphColors = geometry.morphAttributes.color || [];
  10611. let vertexDataCount = 0;
  10612. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10613. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10614. if ( hasMorphColors === true ) vertexDataCount = 3;
  10615. let width = geometry.attributes.position.count * vertexDataCount;
  10616. let height = 1;
  10617. if ( width > capabilities.maxTextureSize ) {
  10618. height = Math.ceil( width / capabilities.maxTextureSize );
  10619. width = capabilities.maxTextureSize;
  10620. }
  10621. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10622. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10623. texture.type = FloatType;
  10624. texture.needsUpdate = true;
  10625. // fill buffer
  10626. const vertexDataStride = vertexDataCount * 4;
  10627. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10628. const morphTarget = morphTargets[ i ];
  10629. const morphNormal = morphNormals[ i ];
  10630. const morphColor = morphColors[ i ];
  10631. const offset = width * height * 4 * i;
  10632. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10633. const stride = j * vertexDataStride;
  10634. if ( hasMorphPosition === true ) {
  10635. morph.fromBufferAttribute( morphTarget, j );
  10636. buffer[ offset + stride + 0 ] = morph.x;
  10637. buffer[ offset + stride + 1 ] = morph.y;
  10638. buffer[ offset + stride + 2 ] = morph.z;
  10639. buffer[ offset + stride + 3 ] = 0;
  10640. }
  10641. if ( hasMorphNormals === true ) {
  10642. morph.fromBufferAttribute( morphNormal, j );
  10643. buffer[ offset + stride + 4 ] = morph.x;
  10644. buffer[ offset + stride + 5 ] = morph.y;
  10645. buffer[ offset + stride + 6 ] = morph.z;
  10646. buffer[ offset + stride + 7 ] = 0;
  10647. }
  10648. if ( hasMorphColors === true ) {
  10649. morph.fromBufferAttribute( morphColor, j );
  10650. buffer[ offset + stride + 8 ] = morph.x;
  10651. buffer[ offset + stride + 9 ] = morph.y;
  10652. buffer[ offset + stride + 10 ] = morph.z;
  10653. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10654. }
  10655. }
  10656. }
  10657. entry = {
  10658. count: morphTargetsCount,
  10659. texture: texture,
  10660. size: new Vector2( width, height )
  10661. };
  10662. morphTextures.set( geometry, entry );
  10663. function disposeTexture() {
  10664. texture.dispose();
  10665. morphTextures.delete( geometry );
  10666. geometry.removeEventListener( 'dispose', disposeTexture );
  10667. }
  10668. geometry.addEventListener( 'dispose', disposeTexture );
  10669. }
  10670. //
  10671. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  10672. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  10673. } else {
  10674. let morphInfluencesSum = 0;
  10675. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10676. morphInfluencesSum += objectInfluences[ i ];
  10677. }
  10678. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10679. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10680. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10681. }
  10682. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10683. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10684. }
  10685. return {
  10686. update: update
  10687. };
  10688. }
  10689. function WebGLObjects( gl, geometries, attributes, info ) {
  10690. let updateMap = new WeakMap();
  10691. function update( object ) {
  10692. const frame = info.render.frame;
  10693. const geometry = object.geometry;
  10694. const buffergeometry = geometries.get( object, geometry );
  10695. // Update once per frame
  10696. if ( updateMap.get( buffergeometry ) !== frame ) {
  10697. geometries.update( buffergeometry );
  10698. updateMap.set( buffergeometry, frame );
  10699. }
  10700. if ( object.isInstancedMesh ) {
  10701. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10702. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10703. }
  10704. if ( updateMap.get( object ) !== frame ) {
  10705. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10706. if ( object.instanceColor !== null ) {
  10707. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10708. }
  10709. updateMap.set( object, frame );
  10710. }
  10711. }
  10712. if ( object.isSkinnedMesh ) {
  10713. const skeleton = object.skeleton;
  10714. if ( updateMap.get( skeleton ) !== frame ) {
  10715. skeleton.update();
  10716. updateMap.set( skeleton, frame );
  10717. }
  10718. }
  10719. return buffergeometry;
  10720. }
  10721. function dispose() {
  10722. updateMap = new WeakMap();
  10723. }
  10724. function onInstancedMeshDispose( event ) {
  10725. const instancedMesh = event.target;
  10726. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10727. attributes.remove( instancedMesh.instanceMatrix );
  10728. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10729. }
  10730. return {
  10731. update: update,
  10732. dispose: dispose
  10733. };
  10734. }
  10735. class DepthTexture extends Texture {
  10736. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  10737. format = format !== undefined ? format : DepthFormat;
  10738. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10739. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10740. }
  10741. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10742. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10743. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10744. this.isDepthTexture = true;
  10745. this.image = { width: width, height: height };
  10746. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10747. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10748. this.flipY = false;
  10749. this.generateMipmaps = false;
  10750. this.compareFunction = null;
  10751. }
  10752. copy( source ) {
  10753. super.copy( source );
  10754. this.compareFunction = source.compareFunction;
  10755. return this;
  10756. }
  10757. toJSON( meta ) {
  10758. const data = super.toJSON( meta );
  10759. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10760. return data;
  10761. }
  10762. }
  10763. /**
  10764. * Uniforms of a program.
  10765. * Those form a tree structure with a special top-level container for the root,
  10766. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10767. *
  10768. *
  10769. * Properties of inner nodes including the top-level container:
  10770. *
  10771. * .seq - array of nested uniforms
  10772. * .map - nested uniforms by name
  10773. *
  10774. *
  10775. * Methods of all nodes except the top-level container:
  10776. *
  10777. * .setValue( gl, value, [textures] )
  10778. *
  10779. * uploads a uniform value(s)
  10780. * the 'textures' parameter is needed for sampler uniforms
  10781. *
  10782. *
  10783. * Static methods of the top-level container (textures factorizations):
  10784. *
  10785. * .upload( gl, seq, values, textures )
  10786. *
  10787. * sets uniforms in 'seq' to 'values[id].value'
  10788. *
  10789. * .seqWithValue( seq, values ) : filteredSeq
  10790. *
  10791. * filters 'seq' entries with corresponding entry in values
  10792. *
  10793. *
  10794. * Methods of the top-level container (textures factorizations):
  10795. *
  10796. * .setValue( gl, name, value, textures )
  10797. *
  10798. * sets uniform with name 'name' to 'value'
  10799. *
  10800. * .setOptional( gl, obj, prop )
  10801. *
  10802. * like .set for an optional property of the object
  10803. *
  10804. */
  10805. const emptyTexture = /*@__PURE__*/ new Texture();
  10806. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  10807. emptyShadowTexture.compareFunction = LessEqualCompare;
  10808. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10809. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10810. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10811. // --- Utilities ---
  10812. // Array Caches (provide typed arrays for temporary by size)
  10813. const arrayCacheF32 = [];
  10814. const arrayCacheI32 = [];
  10815. // Float32Array caches used for uploading Matrix uniforms
  10816. const mat4array = new Float32Array( 16 );
  10817. const mat3array = new Float32Array( 9 );
  10818. const mat2array = new Float32Array( 4 );
  10819. // Flattening for arrays of vectors and matrices
  10820. function flatten( array, nBlocks, blockSize ) {
  10821. const firstElem = array[ 0 ];
  10822. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10823. // unoptimized: ! isNaN( firstElem )
  10824. // see http://jacksondunstan.com/articles/983
  10825. const n = nBlocks * blockSize;
  10826. let r = arrayCacheF32[ n ];
  10827. if ( r === undefined ) {
  10828. r = new Float32Array( n );
  10829. arrayCacheF32[ n ] = r;
  10830. }
  10831. if ( nBlocks !== 0 ) {
  10832. firstElem.toArray( r, 0 );
  10833. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10834. offset += blockSize;
  10835. array[ i ].toArray( r, offset );
  10836. }
  10837. }
  10838. return r;
  10839. }
  10840. function arraysEqual( a, b ) {
  10841. if ( a.length !== b.length ) return false;
  10842. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10843. if ( a[ i ] !== b[ i ] ) return false;
  10844. }
  10845. return true;
  10846. }
  10847. function copyArray( a, b ) {
  10848. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10849. a[ i ] = b[ i ];
  10850. }
  10851. }
  10852. // Texture unit allocation
  10853. function allocTexUnits( textures, n ) {
  10854. let r = arrayCacheI32[ n ];
  10855. if ( r === undefined ) {
  10856. r = new Int32Array( n );
  10857. arrayCacheI32[ n ] = r;
  10858. }
  10859. for ( let i = 0; i !== n; ++ i ) {
  10860. r[ i ] = textures.allocateTextureUnit();
  10861. }
  10862. return r;
  10863. }
  10864. // --- Setters ---
  10865. // Note: Defining these methods externally, because they come in a bunch
  10866. // and this way their names minify.
  10867. // Single scalar
  10868. function setValueV1f( gl, v ) {
  10869. const cache = this.cache;
  10870. if ( cache[ 0 ] === v ) return;
  10871. gl.uniform1f( this.addr, v );
  10872. cache[ 0 ] = v;
  10873. }
  10874. // Single float vector (from flat array or THREE.VectorN)
  10875. function setValueV2f( gl, v ) {
  10876. const cache = this.cache;
  10877. if ( v.x !== undefined ) {
  10878. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10879. gl.uniform2f( this.addr, v.x, v.y );
  10880. cache[ 0 ] = v.x;
  10881. cache[ 1 ] = v.y;
  10882. }
  10883. } else {
  10884. if ( arraysEqual( cache, v ) ) return;
  10885. gl.uniform2fv( this.addr, v );
  10886. copyArray( cache, v );
  10887. }
  10888. }
  10889. function setValueV3f( gl, v ) {
  10890. const cache = this.cache;
  10891. if ( v.x !== undefined ) {
  10892. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10893. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10894. cache[ 0 ] = v.x;
  10895. cache[ 1 ] = v.y;
  10896. cache[ 2 ] = v.z;
  10897. }
  10898. } else if ( v.r !== undefined ) {
  10899. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10900. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10901. cache[ 0 ] = v.r;
  10902. cache[ 1 ] = v.g;
  10903. cache[ 2 ] = v.b;
  10904. }
  10905. } else {
  10906. if ( arraysEqual( cache, v ) ) return;
  10907. gl.uniform3fv( this.addr, v );
  10908. copyArray( cache, v );
  10909. }
  10910. }
  10911. function setValueV4f( gl, v ) {
  10912. const cache = this.cache;
  10913. if ( v.x !== undefined ) {
  10914. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10915. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10916. cache[ 0 ] = v.x;
  10917. cache[ 1 ] = v.y;
  10918. cache[ 2 ] = v.z;
  10919. cache[ 3 ] = v.w;
  10920. }
  10921. } else {
  10922. if ( arraysEqual( cache, v ) ) return;
  10923. gl.uniform4fv( this.addr, v );
  10924. copyArray( cache, v );
  10925. }
  10926. }
  10927. // Single matrix (from flat array or THREE.MatrixN)
  10928. function setValueM2( gl, v ) {
  10929. const cache = this.cache;
  10930. const elements = v.elements;
  10931. if ( elements === undefined ) {
  10932. if ( arraysEqual( cache, v ) ) return;
  10933. gl.uniformMatrix2fv( this.addr, false, v );
  10934. copyArray( cache, v );
  10935. } else {
  10936. if ( arraysEqual( cache, elements ) ) return;
  10937. mat2array.set( elements );
  10938. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10939. copyArray( cache, elements );
  10940. }
  10941. }
  10942. function setValueM3( gl, v ) {
  10943. const cache = this.cache;
  10944. const elements = v.elements;
  10945. if ( elements === undefined ) {
  10946. if ( arraysEqual( cache, v ) ) return;
  10947. gl.uniformMatrix3fv( this.addr, false, v );
  10948. copyArray( cache, v );
  10949. } else {
  10950. if ( arraysEqual( cache, elements ) ) return;
  10951. mat3array.set( elements );
  10952. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10953. copyArray( cache, elements );
  10954. }
  10955. }
  10956. function setValueM4( gl, v ) {
  10957. const cache = this.cache;
  10958. const elements = v.elements;
  10959. if ( elements === undefined ) {
  10960. if ( arraysEqual( cache, v ) ) return;
  10961. gl.uniformMatrix4fv( this.addr, false, v );
  10962. copyArray( cache, v );
  10963. } else {
  10964. if ( arraysEqual( cache, elements ) ) return;
  10965. mat4array.set( elements );
  10966. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10967. copyArray( cache, elements );
  10968. }
  10969. }
  10970. // Single integer / boolean
  10971. function setValueV1i( gl, v ) {
  10972. const cache = this.cache;
  10973. if ( cache[ 0 ] === v ) return;
  10974. gl.uniform1i( this.addr, v );
  10975. cache[ 0 ] = v;
  10976. }
  10977. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10978. function setValueV2i( gl, v ) {
  10979. const cache = this.cache;
  10980. if ( v.x !== undefined ) {
  10981. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10982. gl.uniform2i( this.addr, v.x, v.y );
  10983. cache[ 0 ] = v.x;
  10984. cache[ 1 ] = v.y;
  10985. }
  10986. } else {
  10987. if ( arraysEqual( cache, v ) ) return;
  10988. gl.uniform2iv( this.addr, v );
  10989. copyArray( cache, v );
  10990. }
  10991. }
  10992. function setValueV3i( gl, v ) {
  10993. const cache = this.cache;
  10994. if ( v.x !== undefined ) {
  10995. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10996. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10997. cache[ 0 ] = v.x;
  10998. cache[ 1 ] = v.y;
  10999. cache[ 2 ] = v.z;
  11000. }
  11001. } else {
  11002. if ( arraysEqual( cache, v ) ) return;
  11003. gl.uniform3iv( this.addr, v );
  11004. copyArray( cache, v );
  11005. }
  11006. }
  11007. function setValueV4i( gl, v ) {
  11008. const cache = this.cache;
  11009. if ( v.x !== undefined ) {
  11010. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11011. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  11012. cache[ 0 ] = v.x;
  11013. cache[ 1 ] = v.y;
  11014. cache[ 2 ] = v.z;
  11015. cache[ 3 ] = v.w;
  11016. }
  11017. } else {
  11018. if ( arraysEqual( cache, v ) ) return;
  11019. gl.uniform4iv( this.addr, v );
  11020. copyArray( cache, v );
  11021. }
  11022. }
  11023. // Single unsigned integer
  11024. function setValueV1ui( gl, v ) {
  11025. const cache = this.cache;
  11026. if ( cache[ 0 ] === v ) return;
  11027. gl.uniform1ui( this.addr, v );
  11028. cache[ 0 ] = v;
  11029. }
  11030. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11031. function setValueV2ui( gl, v ) {
  11032. const cache = this.cache;
  11033. if ( v.x !== undefined ) {
  11034. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11035. gl.uniform2ui( this.addr, v.x, v.y );
  11036. cache[ 0 ] = v.x;
  11037. cache[ 1 ] = v.y;
  11038. }
  11039. } else {
  11040. if ( arraysEqual( cache, v ) ) return;
  11041. gl.uniform2uiv( this.addr, v );
  11042. copyArray( cache, v );
  11043. }
  11044. }
  11045. function setValueV3ui( gl, v ) {
  11046. const cache = this.cache;
  11047. if ( v.x !== undefined ) {
  11048. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11049. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11050. cache[ 0 ] = v.x;
  11051. cache[ 1 ] = v.y;
  11052. cache[ 2 ] = v.z;
  11053. }
  11054. } else {
  11055. if ( arraysEqual( cache, v ) ) return;
  11056. gl.uniform3uiv( this.addr, v );
  11057. copyArray( cache, v );
  11058. }
  11059. }
  11060. function setValueV4ui( gl, v ) {
  11061. const cache = this.cache;
  11062. if ( v.x !== undefined ) {
  11063. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11064. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11065. cache[ 0 ] = v.x;
  11066. cache[ 1 ] = v.y;
  11067. cache[ 2 ] = v.z;
  11068. cache[ 3 ] = v.w;
  11069. }
  11070. } else {
  11071. if ( arraysEqual( cache, v ) ) return;
  11072. gl.uniform4uiv( this.addr, v );
  11073. copyArray( cache, v );
  11074. }
  11075. }
  11076. // Single texture (2D / Cube)
  11077. function setValueT1( gl, v, textures ) {
  11078. const cache = this.cache;
  11079. const unit = textures.allocateTextureUnit();
  11080. if ( cache[ 0 ] !== unit ) {
  11081. gl.uniform1i( this.addr, unit );
  11082. cache[ 0 ] = unit;
  11083. }
  11084. const emptyTexture2D = ( this.type === gl.SAMPLER_2D_SHADOW ) ? emptyShadowTexture : emptyTexture;
  11085. textures.setTexture2D( v || emptyTexture2D, unit );
  11086. }
  11087. function setValueT3D1( gl, v, textures ) {
  11088. const cache = this.cache;
  11089. const unit = textures.allocateTextureUnit();
  11090. if ( cache[ 0 ] !== unit ) {
  11091. gl.uniform1i( this.addr, unit );
  11092. cache[ 0 ] = unit;
  11093. }
  11094. textures.setTexture3D( v || empty3dTexture, unit );
  11095. }
  11096. function setValueT6( gl, v, textures ) {
  11097. const cache = this.cache;
  11098. const unit = textures.allocateTextureUnit();
  11099. if ( cache[ 0 ] !== unit ) {
  11100. gl.uniform1i( this.addr, unit );
  11101. cache[ 0 ] = unit;
  11102. }
  11103. textures.setTextureCube( v || emptyCubeTexture, unit );
  11104. }
  11105. function setValueT2DArray1( gl, v, textures ) {
  11106. const cache = this.cache;
  11107. const unit = textures.allocateTextureUnit();
  11108. if ( cache[ 0 ] !== unit ) {
  11109. gl.uniform1i( this.addr, unit );
  11110. cache[ 0 ] = unit;
  11111. }
  11112. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11113. }
  11114. // Helper to pick the right setter for the singular case
  11115. function getSingularSetter( type ) {
  11116. switch ( type ) {
  11117. case 0x1406: return setValueV1f; // FLOAT
  11118. case 0x8b50: return setValueV2f; // _VEC2
  11119. case 0x8b51: return setValueV3f; // _VEC3
  11120. case 0x8b52: return setValueV4f; // _VEC4
  11121. case 0x8b5a: return setValueM2; // _MAT2
  11122. case 0x8b5b: return setValueM3; // _MAT3
  11123. case 0x8b5c: return setValueM4; // _MAT4
  11124. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11125. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11126. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11127. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11128. case 0x1405: return setValueV1ui; // UINT
  11129. case 0x8dc6: return setValueV2ui; // _VEC2
  11130. case 0x8dc7: return setValueV3ui; // _VEC3
  11131. case 0x8dc8: return setValueV4ui; // _VEC4
  11132. case 0x8b5e: // SAMPLER_2D
  11133. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11134. case 0x8dca: // INT_SAMPLER_2D
  11135. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11136. case 0x8b62: // SAMPLER_2D_SHADOW
  11137. return setValueT1;
  11138. case 0x8b5f: // SAMPLER_3D
  11139. case 0x8dcb: // INT_SAMPLER_3D
  11140. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11141. return setValueT3D1;
  11142. case 0x8b60: // SAMPLER_CUBE
  11143. case 0x8dcc: // INT_SAMPLER_CUBE
  11144. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11145. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11146. return setValueT6;
  11147. case 0x8dc1: // SAMPLER_2D_ARRAY
  11148. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11149. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11150. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11151. return setValueT2DArray1;
  11152. }
  11153. }
  11154. // Array of scalars
  11155. function setValueV1fArray( gl, v ) {
  11156. gl.uniform1fv( this.addr, v );
  11157. }
  11158. // Array of vectors (from flat array or array of THREE.VectorN)
  11159. function setValueV2fArray( gl, v ) {
  11160. const data = flatten( v, this.size, 2 );
  11161. gl.uniform2fv( this.addr, data );
  11162. }
  11163. function setValueV3fArray( gl, v ) {
  11164. const data = flatten( v, this.size, 3 );
  11165. gl.uniform3fv( this.addr, data );
  11166. }
  11167. function setValueV4fArray( gl, v ) {
  11168. const data = flatten( v, this.size, 4 );
  11169. gl.uniform4fv( this.addr, data );
  11170. }
  11171. // Array of matrices (from flat array or array of THREE.MatrixN)
  11172. function setValueM2Array( gl, v ) {
  11173. const data = flatten( v, this.size, 4 );
  11174. gl.uniformMatrix2fv( this.addr, false, data );
  11175. }
  11176. function setValueM3Array( gl, v ) {
  11177. const data = flatten( v, this.size, 9 );
  11178. gl.uniformMatrix3fv( this.addr, false, data );
  11179. }
  11180. function setValueM4Array( gl, v ) {
  11181. const data = flatten( v, this.size, 16 );
  11182. gl.uniformMatrix4fv( this.addr, false, data );
  11183. }
  11184. // Array of integer / boolean
  11185. function setValueV1iArray( gl, v ) {
  11186. gl.uniform1iv( this.addr, v );
  11187. }
  11188. // Array of integer / boolean vectors (from flat array)
  11189. function setValueV2iArray( gl, v ) {
  11190. gl.uniform2iv( this.addr, v );
  11191. }
  11192. function setValueV3iArray( gl, v ) {
  11193. gl.uniform3iv( this.addr, v );
  11194. }
  11195. function setValueV4iArray( gl, v ) {
  11196. gl.uniform4iv( this.addr, v );
  11197. }
  11198. // Array of unsigned integer
  11199. function setValueV1uiArray( gl, v ) {
  11200. gl.uniform1uiv( this.addr, v );
  11201. }
  11202. // Array of unsigned integer vectors (from flat array)
  11203. function setValueV2uiArray( gl, v ) {
  11204. gl.uniform2uiv( this.addr, v );
  11205. }
  11206. function setValueV3uiArray( gl, v ) {
  11207. gl.uniform3uiv( this.addr, v );
  11208. }
  11209. function setValueV4uiArray( gl, v ) {
  11210. gl.uniform4uiv( this.addr, v );
  11211. }
  11212. // Array of textures (2D / 3D / Cube / 2DArray)
  11213. function setValueT1Array( gl, v, textures ) {
  11214. const cache = this.cache;
  11215. const n = v.length;
  11216. const units = allocTexUnits( textures, n );
  11217. if ( ! arraysEqual( cache, units ) ) {
  11218. gl.uniform1iv( this.addr, units );
  11219. copyArray( cache, units );
  11220. }
  11221. for ( let i = 0; i !== n; ++ i ) {
  11222. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11223. }
  11224. }
  11225. function setValueT3DArray( gl, v, textures ) {
  11226. const cache = this.cache;
  11227. const n = v.length;
  11228. const units = allocTexUnits( textures, n );
  11229. if ( ! arraysEqual( cache, units ) ) {
  11230. gl.uniform1iv( this.addr, units );
  11231. copyArray( cache, units );
  11232. }
  11233. for ( let i = 0; i !== n; ++ i ) {
  11234. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11235. }
  11236. }
  11237. function setValueT6Array( gl, v, textures ) {
  11238. const cache = this.cache;
  11239. const n = v.length;
  11240. const units = allocTexUnits( textures, n );
  11241. if ( ! arraysEqual( cache, units ) ) {
  11242. gl.uniform1iv( this.addr, units );
  11243. copyArray( cache, units );
  11244. }
  11245. for ( let i = 0; i !== n; ++ i ) {
  11246. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11247. }
  11248. }
  11249. function setValueT2DArrayArray( gl, v, textures ) {
  11250. const cache = this.cache;
  11251. const n = v.length;
  11252. const units = allocTexUnits( textures, n );
  11253. if ( ! arraysEqual( cache, units ) ) {
  11254. gl.uniform1iv( this.addr, units );
  11255. copyArray( cache, units );
  11256. }
  11257. for ( let i = 0; i !== n; ++ i ) {
  11258. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11259. }
  11260. }
  11261. // Helper to pick the right setter for a pure (bottom-level) array
  11262. function getPureArraySetter( type ) {
  11263. switch ( type ) {
  11264. case 0x1406: return setValueV1fArray; // FLOAT
  11265. case 0x8b50: return setValueV2fArray; // _VEC2
  11266. case 0x8b51: return setValueV3fArray; // _VEC3
  11267. case 0x8b52: return setValueV4fArray; // _VEC4
  11268. case 0x8b5a: return setValueM2Array; // _MAT2
  11269. case 0x8b5b: return setValueM3Array; // _MAT3
  11270. case 0x8b5c: return setValueM4Array; // _MAT4
  11271. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11272. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11273. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11274. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11275. case 0x1405: return setValueV1uiArray; // UINT
  11276. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11277. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11278. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11279. case 0x8b5e: // SAMPLER_2D
  11280. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11281. case 0x8dca: // INT_SAMPLER_2D
  11282. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11283. case 0x8b62: // SAMPLER_2D_SHADOW
  11284. return setValueT1Array;
  11285. case 0x8b5f: // SAMPLER_3D
  11286. case 0x8dcb: // INT_SAMPLER_3D
  11287. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11288. return setValueT3DArray;
  11289. case 0x8b60: // SAMPLER_CUBE
  11290. case 0x8dcc: // INT_SAMPLER_CUBE
  11291. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11292. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11293. return setValueT6Array;
  11294. case 0x8dc1: // SAMPLER_2D_ARRAY
  11295. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11296. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11297. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11298. return setValueT2DArrayArray;
  11299. }
  11300. }
  11301. // --- Uniform Classes ---
  11302. class SingleUniform {
  11303. constructor( id, activeInfo, addr ) {
  11304. this.id = id;
  11305. this.addr = addr;
  11306. this.cache = [];
  11307. this.type = activeInfo.type;
  11308. this.setValue = getSingularSetter( activeInfo.type );
  11309. // this.path = activeInfo.name; // DEBUG
  11310. }
  11311. }
  11312. class PureArrayUniform {
  11313. constructor( id, activeInfo, addr ) {
  11314. this.id = id;
  11315. this.addr = addr;
  11316. this.cache = [];
  11317. this.type = activeInfo.type;
  11318. this.size = activeInfo.size;
  11319. this.setValue = getPureArraySetter( activeInfo.type );
  11320. // this.path = activeInfo.name; // DEBUG
  11321. }
  11322. }
  11323. class StructuredUniform {
  11324. constructor( id ) {
  11325. this.id = id;
  11326. this.seq = [];
  11327. this.map = {};
  11328. }
  11329. setValue( gl, value, textures ) {
  11330. const seq = this.seq;
  11331. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11332. const u = seq[ i ];
  11333. u.setValue( gl, value[ u.id ], textures );
  11334. }
  11335. }
  11336. }
  11337. // --- Top-level ---
  11338. // Parser - builds up the property tree from the path strings
  11339. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11340. // extracts
  11341. // - the identifier (member name or array index)
  11342. // - followed by an optional right bracket (found when array index)
  11343. // - followed by an optional left bracket or dot (type of subscript)
  11344. //
  11345. // Note: These portions can be read in a non-overlapping fashion and
  11346. // allow straightforward parsing of the hierarchy that WebGL encodes
  11347. // in the uniform names.
  11348. function addUniform( container, uniformObject ) {
  11349. container.seq.push( uniformObject );
  11350. container.map[ uniformObject.id ] = uniformObject;
  11351. }
  11352. function parseUniform( activeInfo, addr, container ) {
  11353. const path = activeInfo.name,
  11354. pathLength = path.length;
  11355. // reset RegExp object, because of the early exit of a previous run
  11356. RePathPart.lastIndex = 0;
  11357. while ( true ) {
  11358. const match = RePathPart.exec( path ),
  11359. matchEnd = RePathPart.lastIndex;
  11360. let id = match[ 1 ];
  11361. const idIsIndex = match[ 2 ] === ']',
  11362. subscript = match[ 3 ];
  11363. if ( idIsIndex ) id = id | 0; // convert to integer
  11364. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11365. // bare name or "pure" bottom-level array "[0]" suffix
  11366. addUniform( container, subscript === undefined ?
  11367. new SingleUniform( id, activeInfo, addr ) :
  11368. new PureArrayUniform( id, activeInfo, addr ) );
  11369. break;
  11370. } else {
  11371. // step into inner node / create it in case it doesn't exist
  11372. const map = container.map;
  11373. let next = map[ id ];
  11374. if ( next === undefined ) {
  11375. next = new StructuredUniform( id );
  11376. addUniform( container, next );
  11377. }
  11378. container = next;
  11379. }
  11380. }
  11381. }
  11382. // Root Container
  11383. class WebGLUniforms {
  11384. constructor( gl, program ) {
  11385. this.seq = [];
  11386. this.map = {};
  11387. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11388. for ( let i = 0; i < n; ++ i ) {
  11389. const info = gl.getActiveUniform( program, i ),
  11390. addr = gl.getUniformLocation( program, info.name );
  11391. parseUniform( info, addr, this );
  11392. }
  11393. }
  11394. setValue( gl, name, value, textures ) {
  11395. const u = this.map[ name ];
  11396. if ( u !== undefined ) u.setValue( gl, value, textures );
  11397. }
  11398. setOptional( gl, object, name ) {
  11399. const v = object[ name ];
  11400. if ( v !== undefined ) this.setValue( gl, name, v );
  11401. }
  11402. static upload( gl, seq, values, textures ) {
  11403. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11404. const u = seq[ i ],
  11405. v = values[ u.id ];
  11406. if ( v.needsUpdate !== false ) {
  11407. // note: always updating when .needsUpdate is undefined
  11408. u.setValue( gl, v.value, textures );
  11409. }
  11410. }
  11411. }
  11412. static seqWithValue( seq, values ) {
  11413. const r = [];
  11414. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11415. const u = seq[ i ];
  11416. if ( u.id in values ) r.push( u );
  11417. }
  11418. return r;
  11419. }
  11420. }
  11421. function WebGLShader( gl, type, string ) {
  11422. const shader = gl.createShader( type );
  11423. gl.shaderSource( shader, string );
  11424. gl.compileShader( shader );
  11425. return shader;
  11426. }
  11427. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  11428. const COMPLETION_STATUS_KHR = 0x91B1;
  11429. let programIdCount = 0;
  11430. function handleSource( string, errorLine ) {
  11431. const lines = string.split( '\n' );
  11432. const lines2 = [];
  11433. const from = Math.max( errorLine - 6, 0 );
  11434. const to = Math.min( errorLine + 6, lines.length );
  11435. for ( let i = from; i < to; i ++ ) {
  11436. const line = i + 1;
  11437. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11438. }
  11439. return lines2.join( '\n' );
  11440. }
  11441. function getEncodingComponents( colorSpace ) {
  11442. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  11443. const encodingPrimaries = ColorManagement.getPrimaries( colorSpace );
  11444. let gamutMapping;
  11445. if ( workingPrimaries === encodingPrimaries ) {
  11446. gamutMapping = '';
  11447. } else if ( workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries ) {
  11448. gamutMapping = 'LinearDisplayP3ToLinearSRGB';
  11449. } else if ( workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries ) {
  11450. gamutMapping = 'LinearSRGBToLinearDisplayP3';
  11451. }
  11452. switch ( colorSpace ) {
  11453. case LinearSRGBColorSpace:
  11454. case LinearDisplayP3ColorSpace:
  11455. return [ gamutMapping, 'LinearTransferOETF' ];
  11456. case SRGBColorSpace:
  11457. case DisplayP3ColorSpace:
  11458. return [ gamutMapping, 'sRGBTransferOETF' ];
  11459. default:
  11460. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11461. return [ gamutMapping, 'LinearTransferOETF' ];
  11462. }
  11463. }
  11464. function getShaderErrors( gl, shader, type ) {
  11465. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11466. const errors = gl.getShaderInfoLog( shader ).trim();
  11467. if ( status && errors === '' ) return '';
  11468. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11469. if ( errorMatches ) {
  11470. // --enable-privileged-webgl-extension
  11471. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11472. const errorLine = parseInt( errorMatches[ 1 ] );
  11473. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11474. } else {
  11475. return errors;
  11476. }
  11477. }
  11478. function getTexelEncodingFunction( functionName, colorSpace ) {
  11479. const components = getEncodingComponents( colorSpace );
  11480. return `vec4 ${functionName}( vec4 value ) { return ${components[ 0 ]}( ${components[ 1 ]}( value ) ); }`;
  11481. }
  11482. function getToneMappingFunction( functionName, toneMapping ) {
  11483. let toneMappingName;
  11484. switch ( toneMapping ) {
  11485. case LinearToneMapping:
  11486. toneMappingName = 'Linear';
  11487. break;
  11488. case ReinhardToneMapping:
  11489. toneMappingName = 'Reinhard';
  11490. break;
  11491. case CineonToneMapping:
  11492. toneMappingName = 'OptimizedCineon';
  11493. break;
  11494. case ACESFilmicToneMapping:
  11495. toneMappingName = 'ACESFilmic';
  11496. break;
  11497. case AgXToneMapping:
  11498. toneMappingName = 'AgX';
  11499. break;
  11500. case NeutralToneMapping:
  11501. toneMappingName = 'Neutral';
  11502. break;
  11503. case CustomToneMapping:
  11504. toneMappingName = 'Custom';
  11505. break;
  11506. default:
  11507. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11508. toneMappingName = 'Linear';
  11509. }
  11510. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11511. }
  11512. function generateVertexExtensions( parameters ) {
  11513. const chunks = [
  11514. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  11515. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  11516. ];
  11517. return chunks.filter( filterEmptyLine ).join( '\n' );
  11518. }
  11519. function generateDefines( defines ) {
  11520. const chunks = [];
  11521. for ( const name in defines ) {
  11522. const value = defines[ name ];
  11523. if ( value === false ) continue;
  11524. chunks.push( '#define ' + name + ' ' + value );
  11525. }
  11526. return chunks.join( '\n' );
  11527. }
  11528. function fetchAttributeLocations( gl, program ) {
  11529. const attributes = {};
  11530. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11531. for ( let i = 0; i < n; i ++ ) {
  11532. const info = gl.getActiveAttrib( program, i );
  11533. const name = info.name;
  11534. let locationSize = 1;
  11535. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11536. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11537. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11538. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11539. attributes[ name ] = {
  11540. type: info.type,
  11541. location: gl.getAttribLocation( program, name ),
  11542. locationSize: locationSize
  11543. };
  11544. }
  11545. return attributes;
  11546. }
  11547. function filterEmptyLine( string ) {
  11548. return string !== '';
  11549. }
  11550. function replaceLightNums( string, parameters ) {
  11551. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11552. return string
  11553. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11554. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11555. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11556. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11557. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11558. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11559. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11560. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11561. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11562. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11563. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11564. }
  11565. function replaceClippingPlaneNums( string, parameters ) {
  11566. return string
  11567. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11568. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11569. }
  11570. // Resolve Includes
  11571. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11572. function resolveIncludes( string ) {
  11573. return string.replace( includePattern, includeReplacer );
  11574. }
  11575. const shaderChunkMap = new Map( [
  11576. [ 'encodings_fragment', 'colorspace_fragment' ], // @deprecated, r154
  11577. [ 'encodings_pars_fragment', 'colorspace_pars_fragment' ], // @deprecated, r154
  11578. [ 'output_fragment', 'opaque_fragment' ], // @deprecated, r154
  11579. ] );
  11580. function includeReplacer( match, include ) {
  11581. let string = ShaderChunk[ include ];
  11582. if ( string === undefined ) {
  11583. const newInclude = shaderChunkMap.get( include );
  11584. if ( newInclude !== undefined ) {
  11585. string = ShaderChunk[ newInclude ];
  11586. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  11587. } else {
  11588. throw new Error( 'Can not resolve #include <' + include + '>' );
  11589. }
  11590. }
  11591. return resolveIncludes( string );
  11592. }
  11593. // Unroll Loops
  11594. 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;
  11595. function unrollLoops( string ) {
  11596. return string.replace( unrollLoopPattern, loopReplacer );
  11597. }
  11598. function loopReplacer( match, start, end, snippet ) {
  11599. let string = '';
  11600. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11601. string += snippet
  11602. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11603. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11604. }
  11605. return string;
  11606. }
  11607. //
  11608. function generatePrecision( parameters ) {
  11609. let precisionstring = `precision ${parameters.precision} float;
  11610. precision ${parameters.precision} int;
  11611. precision ${parameters.precision} sampler2D;
  11612. precision ${parameters.precision} samplerCube;
  11613. precision ${parameters.precision} sampler3D;
  11614. precision ${parameters.precision} sampler2DArray;
  11615. precision ${parameters.precision} sampler2DShadow;
  11616. precision ${parameters.precision} samplerCubeShadow;
  11617. precision ${parameters.precision} sampler2DArrayShadow;
  11618. precision ${parameters.precision} isampler2D;
  11619. precision ${parameters.precision} isampler3D;
  11620. precision ${parameters.precision} isamplerCube;
  11621. precision ${parameters.precision} isampler2DArray;
  11622. precision ${parameters.precision} usampler2D;
  11623. precision ${parameters.precision} usampler3D;
  11624. precision ${parameters.precision} usamplerCube;
  11625. precision ${parameters.precision} usampler2DArray;
  11626. `;
  11627. if ( parameters.precision === 'highp' ) {
  11628. precisionstring += '\n#define HIGH_PRECISION';
  11629. } else if ( parameters.precision === 'mediump' ) {
  11630. precisionstring += '\n#define MEDIUM_PRECISION';
  11631. } else if ( parameters.precision === 'lowp' ) {
  11632. precisionstring += '\n#define LOW_PRECISION';
  11633. }
  11634. return precisionstring;
  11635. }
  11636. function generateShadowMapTypeDefine( parameters ) {
  11637. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11638. if ( parameters.shadowMapType === PCFShadowMap ) {
  11639. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11640. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11641. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11642. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11643. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11644. }
  11645. return shadowMapTypeDefine;
  11646. }
  11647. function generateEnvMapTypeDefine( parameters ) {
  11648. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11649. if ( parameters.envMap ) {
  11650. switch ( parameters.envMapMode ) {
  11651. case CubeReflectionMapping:
  11652. case CubeRefractionMapping:
  11653. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11654. break;
  11655. case CubeUVReflectionMapping:
  11656. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11657. break;
  11658. }
  11659. }
  11660. return envMapTypeDefine;
  11661. }
  11662. function generateEnvMapModeDefine( parameters ) {
  11663. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11664. if ( parameters.envMap ) {
  11665. switch ( parameters.envMapMode ) {
  11666. case CubeRefractionMapping:
  11667. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11668. break;
  11669. }
  11670. }
  11671. return envMapModeDefine;
  11672. }
  11673. function generateEnvMapBlendingDefine( parameters ) {
  11674. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11675. if ( parameters.envMap ) {
  11676. switch ( parameters.combine ) {
  11677. case MultiplyOperation:
  11678. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11679. break;
  11680. case MixOperation:
  11681. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11682. break;
  11683. case AddOperation:
  11684. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11685. break;
  11686. }
  11687. }
  11688. return envMapBlendingDefine;
  11689. }
  11690. function generateCubeUVSize( parameters ) {
  11691. const imageHeight = parameters.envMapCubeUVHeight;
  11692. if ( imageHeight === null ) return null;
  11693. const maxMip = Math.log2( imageHeight ) - 2;
  11694. const texelHeight = 1.0 / imageHeight;
  11695. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11696. return { texelWidth, texelHeight, maxMip };
  11697. }
  11698. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11699. // TODO Send this event to Three.js DevTools
  11700. // console.log( 'WebGLProgram', cacheKey );
  11701. const gl = renderer.getContext();
  11702. const defines = parameters.defines;
  11703. let vertexShader = parameters.vertexShader;
  11704. let fragmentShader = parameters.fragmentShader;
  11705. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11706. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11707. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11708. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11709. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11710. const customVertexExtensions = generateVertexExtensions( parameters );
  11711. const customDefines = generateDefines( defines );
  11712. const program = gl.createProgram();
  11713. let prefixVertex, prefixFragment;
  11714. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11715. if ( parameters.isRawShaderMaterial ) {
  11716. prefixVertex = [
  11717. '#define SHADER_TYPE ' + parameters.shaderType,
  11718. '#define SHADER_NAME ' + parameters.shaderName,
  11719. customDefines
  11720. ].filter( filterEmptyLine ).join( '\n' );
  11721. if ( prefixVertex.length > 0 ) {
  11722. prefixVertex += '\n';
  11723. }
  11724. prefixFragment = [
  11725. '#define SHADER_TYPE ' + parameters.shaderType,
  11726. '#define SHADER_NAME ' + parameters.shaderName,
  11727. customDefines
  11728. ].filter( filterEmptyLine ).join( '\n' );
  11729. if ( prefixFragment.length > 0 ) {
  11730. prefixFragment += '\n';
  11731. }
  11732. } else {
  11733. prefixVertex = [
  11734. generatePrecision( parameters ),
  11735. '#define SHADER_TYPE ' + parameters.shaderType,
  11736. '#define SHADER_NAME ' + parameters.shaderName,
  11737. customDefines,
  11738. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  11739. parameters.batching ? '#define USE_BATCHING' : '',
  11740. parameters.instancing ? '#define USE_INSTANCING' : '',
  11741. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11742. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  11743. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11744. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11745. parameters.map ? '#define USE_MAP' : '',
  11746. parameters.envMap ? '#define USE_ENVMAP' : '',
  11747. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11748. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11749. parameters.aoMap ? '#define USE_AOMAP' : '',
  11750. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11751. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11752. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11753. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11754. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11755. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11756. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11757. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11758. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11759. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11760. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11761. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11762. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11763. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11764. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11765. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11766. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11767. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11768. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11769. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11770. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11771. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11772. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11773. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11774. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11775. //
  11776. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11777. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11778. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11779. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11780. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11781. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11782. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11783. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11784. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11785. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11786. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11787. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11788. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11789. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11790. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11791. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11792. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11793. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11794. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11795. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11796. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11797. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11798. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11799. //
  11800. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11801. parameters.vertexColors ? '#define USE_COLOR' : '',
  11802. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11803. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11804. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11805. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11806. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11807. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11808. parameters.skinning ? '#define USE_SKINNING' : '',
  11809. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11810. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11811. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  11812. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11813. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11814. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11815. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11816. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11817. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11818. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11819. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11820. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11821. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11822. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11823. 'uniform mat4 modelMatrix;',
  11824. 'uniform mat4 modelViewMatrix;',
  11825. 'uniform mat4 projectionMatrix;',
  11826. 'uniform mat4 viewMatrix;',
  11827. 'uniform mat3 normalMatrix;',
  11828. 'uniform vec3 cameraPosition;',
  11829. 'uniform bool isOrthographic;',
  11830. '#ifdef USE_INSTANCING',
  11831. ' attribute mat4 instanceMatrix;',
  11832. '#endif',
  11833. '#ifdef USE_INSTANCING_COLOR',
  11834. ' attribute vec3 instanceColor;',
  11835. '#endif',
  11836. '#ifdef USE_INSTANCING_MORPH',
  11837. ' uniform sampler2D morphTexture;',
  11838. '#endif',
  11839. 'attribute vec3 position;',
  11840. 'attribute vec3 normal;',
  11841. 'attribute vec2 uv;',
  11842. '#ifdef USE_UV1',
  11843. ' attribute vec2 uv1;',
  11844. '#endif',
  11845. '#ifdef USE_UV2',
  11846. ' attribute vec2 uv2;',
  11847. '#endif',
  11848. '#ifdef USE_UV3',
  11849. ' attribute vec2 uv3;',
  11850. '#endif',
  11851. '#ifdef USE_TANGENT',
  11852. ' attribute vec4 tangent;',
  11853. '#endif',
  11854. '#if defined( USE_COLOR_ALPHA )',
  11855. ' attribute vec4 color;',
  11856. '#elif defined( USE_COLOR )',
  11857. ' attribute vec3 color;',
  11858. '#endif',
  11859. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11860. ' attribute vec3 morphTarget0;',
  11861. ' attribute vec3 morphTarget1;',
  11862. ' attribute vec3 morphTarget2;',
  11863. ' attribute vec3 morphTarget3;',
  11864. ' #ifdef USE_MORPHNORMALS',
  11865. ' attribute vec3 morphNormal0;',
  11866. ' attribute vec3 morphNormal1;',
  11867. ' attribute vec3 morphNormal2;',
  11868. ' attribute vec3 morphNormal3;',
  11869. ' #else',
  11870. ' attribute vec3 morphTarget4;',
  11871. ' attribute vec3 morphTarget5;',
  11872. ' attribute vec3 morphTarget6;',
  11873. ' attribute vec3 morphTarget7;',
  11874. ' #endif',
  11875. '#endif',
  11876. '#ifdef USE_SKINNING',
  11877. ' attribute vec4 skinIndex;',
  11878. ' attribute vec4 skinWeight;',
  11879. '#endif',
  11880. '\n'
  11881. ].filter( filterEmptyLine ).join( '\n' );
  11882. prefixFragment = [
  11883. generatePrecision( parameters ),
  11884. '#define SHADER_TYPE ' + parameters.shaderType,
  11885. '#define SHADER_NAME ' + parameters.shaderName,
  11886. customDefines,
  11887. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11888. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11889. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  11890. parameters.map ? '#define USE_MAP' : '',
  11891. parameters.matcap ? '#define USE_MATCAP' : '',
  11892. parameters.envMap ? '#define USE_ENVMAP' : '',
  11893. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11894. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11895. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11896. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11897. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11898. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11899. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11900. parameters.aoMap ? '#define USE_AOMAP' : '',
  11901. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11902. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11903. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11904. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11905. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11906. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11907. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11908. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11909. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11910. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11911. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11912. parameters.dispersion ? '#define USE_DISPERSION' : '',
  11913. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11914. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11915. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11916. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11917. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11918. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11919. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11920. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11921. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11922. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11923. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11924. parameters.sheen ? '#define USE_SHEEN' : '',
  11925. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11926. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11927. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11928. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11929. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11930. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11931. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11932. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11933. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11934. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11935. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11936. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11937. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11938. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11939. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11940. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11941. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11942. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11943. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11944. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11945. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11946. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11947. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11948. 'uniform mat4 viewMatrix;',
  11949. 'uniform vec3 cameraPosition;',
  11950. 'uniform bool isOrthographic;',
  11951. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11952. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11953. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11954. parameters.dithering ? '#define DITHERING' : '',
  11955. parameters.opaque ? '#define OPAQUE' : '',
  11956. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11957. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  11958. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11959. '\n'
  11960. ].filter( filterEmptyLine ).join( '\n' );
  11961. }
  11962. vertexShader = resolveIncludes( vertexShader );
  11963. vertexShader = replaceLightNums( vertexShader, parameters );
  11964. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11965. fragmentShader = resolveIncludes( fragmentShader );
  11966. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11967. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11968. vertexShader = unrollLoops( vertexShader );
  11969. fragmentShader = unrollLoops( fragmentShader );
  11970. if ( parameters.isRawShaderMaterial !== true ) {
  11971. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11972. versionString = '#version 300 es\n';
  11973. prefixVertex = [
  11974. customVertexExtensions,
  11975. '#define attribute in',
  11976. '#define varying out',
  11977. '#define texture2D texture'
  11978. ].join( '\n' ) + '\n' + prefixVertex;
  11979. prefixFragment = [
  11980. '#define varying in',
  11981. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11982. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11983. '#define gl_FragDepthEXT gl_FragDepth',
  11984. '#define texture2D texture',
  11985. '#define textureCube texture',
  11986. '#define texture2DProj textureProj',
  11987. '#define texture2DLodEXT textureLod',
  11988. '#define texture2DProjLodEXT textureProjLod',
  11989. '#define textureCubeLodEXT textureLod',
  11990. '#define texture2DGradEXT textureGrad',
  11991. '#define texture2DProjGradEXT textureProjGrad',
  11992. '#define textureCubeGradEXT textureGrad'
  11993. ].join( '\n' ) + '\n' + prefixFragment;
  11994. }
  11995. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11996. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11997. // console.log( '*VERTEX*', vertexGlsl );
  11998. // console.log( '*FRAGMENT*', fragmentGlsl );
  11999. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  12000. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  12001. gl.attachShader( program, glVertexShader );
  12002. gl.attachShader( program, glFragmentShader );
  12003. // Force a particular attribute to index 0.
  12004. if ( parameters.index0AttributeName !== undefined ) {
  12005. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  12006. } else if ( parameters.morphTargets === true ) {
  12007. // programs with morphTargets displace position out of attribute 0
  12008. gl.bindAttribLocation( program, 0, 'position' );
  12009. }
  12010. gl.linkProgram( program );
  12011. function onFirstUse( self ) {
  12012. // check for link errors
  12013. if ( renderer.debug.checkShaderErrors ) {
  12014. const programLog = gl.getProgramInfoLog( program ).trim();
  12015. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  12016. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  12017. let runnable = true;
  12018. let haveDiagnostics = true;
  12019. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  12020. runnable = false;
  12021. if ( typeof renderer.debug.onShaderError === 'function' ) {
  12022. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  12023. } else {
  12024. // default error reporting
  12025. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  12026. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  12027. console.error(
  12028. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  12029. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  12030. 'Material Name: ' + self.name + '\n' +
  12031. 'Material Type: ' + self.type + '\n\n' +
  12032. 'Program Info Log: ' + programLog + '\n' +
  12033. vertexErrors + '\n' +
  12034. fragmentErrors
  12035. );
  12036. }
  12037. } else if ( programLog !== '' ) {
  12038. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  12039. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12040. haveDiagnostics = false;
  12041. }
  12042. if ( haveDiagnostics ) {
  12043. self.diagnostics = {
  12044. runnable: runnable,
  12045. programLog: programLog,
  12046. vertexShader: {
  12047. log: vertexLog,
  12048. prefix: prefixVertex
  12049. },
  12050. fragmentShader: {
  12051. log: fragmentLog,
  12052. prefix: prefixFragment
  12053. }
  12054. };
  12055. }
  12056. }
  12057. // Clean up
  12058. // Crashes in iOS9 and iOS10. #18402
  12059. // gl.detachShader( program, glVertexShader );
  12060. // gl.detachShader( program, glFragmentShader );
  12061. gl.deleteShader( glVertexShader );
  12062. gl.deleteShader( glFragmentShader );
  12063. cachedUniforms = new WebGLUniforms( gl, program );
  12064. cachedAttributes = fetchAttributeLocations( gl, program );
  12065. }
  12066. // set up caching for uniform locations
  12067. let cachedUniforms;
  12068. this.getUniforms = function () {
  12069. if ( cachedUniforms === undefined ) {
  12070. // Populates cachedUniforms and cachedAttributes
  12071. onFirstUse( this );
  12072. }
  12073. return cachedUniforms;
  12074. };
  12075. // set up caching for attribute locations
  12076. let cachedAttributes;
  12077. this.getAttributes = function () {
  12078. if ( cachedAttributes === undefined ) {
  12079. // Populates cachedAttributes and cachedUniforms
  12080. onFirstUse( this );
  12081. }
  12082. return cachedAttributes;
  12083. };
  12084. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  12085. // flag the program as ready immediately. It may cause a stall when it's first used.
  12086. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  12087. this.isReady = function () {
  12088. if ( programReady === false ) {
  12089. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  12090. }
  12091. return programReady;
  12092. };
  12093. // free resource
  12094. this.destroy = function () {
  12095. bindingStates.releaseStatesOfProgram( this );
  12096. gl.deleteProgram( program );
  12097. this.program = undefined;
  12098. };
  12099. //
  12100. this.type = parameters.shaderType;
  12101. this.name = parameters.shaderName;
  12102. this.id = programIdCount ++;
  12103. this.cacheKey = cacheKey;
  12104. this.usedTimes = 1;
  12105. this.program = program;
  12106. this.vertexShader = glVertexShader;
  12107. this.fragmentShader = glFragmentShader;
  12108. return this;
  12109. }
  12110. let _id$1 = 0;
  12111. class WebGLShaderCache {
  12112. constructor() {
  12113. this.shaderCache = new Map();
  12114. this.materialCache = new Map();
  12115. }
  12116. update( material ) {
  12117. const vertexShader = material.vertexShader;
  12118. const fragmentShader = material.fragmentShader;
  12119. const vertexShaderStage = this._getShaderStage( vertexShader );
  12120. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  12121. const materialShaders = this._getShaderCacheForMaterial( material );
  12122. if ( materialShaders.has( vertexShaderStage ) === false ) {
  12123. materialShaders.add( vertexShaderStage );
  12124. vertexShaderStage.usedTimes ++;
  12125. }
  12126. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12127. materialShaders.add( fragmentShaderStage );
  12128. fragmentShaderStage.usedTimes ++;
  12129. }
  12130. return this;
  12131. }
  12132. remove( material ) {
  12133. const materialShaders = this.materialCache.get( material );
  12134. for ( const shaderStage of materialShaders ) {
  12135. shaderStage.usedTimes --;
  12136. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12137. }
  12138. this.materialCache.delete( material );
  12139. return this;
  12140. }
  12141. getVertexShaderID( material ) {
  12142. return this._getShaderStage( material.vertexShader ).id;
  12143. }
  12144. getFragmentShaderID( material ) {
  12145. return this._getShaderStage( material.fragmentShader ).id;
  12146. }
  12147. dispose() {
  12148. this.shaderCache.clear();
  12149. this.materialCache.clear();
  12150. }
  12151. _getShaderCacheForMaterial( material ) {
  12152. const cache = this.materialCache;
  12153. let set = cache.get( material );
  12154. if ( set === undefined ) {
  12155. set = new Set();
  12156. cache.set( material, set );
  12157. }
  12158. return set;
  12159. }
  12160. _getShaderStage( code ) {
  12161. const cache = this.shaderCache;
  12162. let stage = cache.get( code );
  12163. if ( stage === undefined ) {
  12164. stage = new WebGLShaderStage( code );
  12165. cache.set( code, stage );
  12166. }
  12167. return stage;
  12168. }
  12169. }
  12170. class WebGLShaderStage {
  12171. constructor( code ) {
  12172. this.id = _id$1 ++;
  12173. this.code = code;
  12174. this.usedTimes = 0;
  12175. }
  12176. }
  12177. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12178. const _programLayers = new Layers();
  12179. const _customShaders = new WebGLShaderCache();
  12180. const _activeChannels = new Set();
  12181. const programs = [];
  12182. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12183. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12184. let precision = capabilities.precision;
  12185. const shaderIDs = {
  12186. MeshDepthMaterial: 'depth',
  12187. MeshDistanceMaterial: 'distanceRGBA',
  12188. MeshNormalMaterial: 'normal',
  12189. MeshBasicMaterial: 'basic',
  12190. MeshLambertMaterial: 'lambert',
  12191. MeshPhongMaterial: 'phong',
  12192. MeshToonMaterial: 'toon',
  12193. MeshStandardMaterial: 'physical',
  12194. MeshPhysicalMaterial: 'physical',
  12195. MeshMatcapMaterial: 'matcap',
  12196. LineBasicMaterial: 'basic',
  12197. LineDashedMaterial: 'dashed',
  12198. PointsMaterial: 'points',
  12199. ShadowMaterial: 'shadow',
  12200. SpriteMaterial: 'sprite'
  12201. };
  12202. function getChannel( value ) {
  12203. _activeChannels.add( value );
  12204. if ( value === 0 ) return 'uv';
  12205. return `uv${ value }`;
  12206. }
  12207. function getParameters( material, lights, shadows, scene, object ) {
  12208. const fog = scene.fog;
  12209. const geometry = object.geometry;
  12210. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12211. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12212. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12213. const shaderID = shaderIDs[ material.type ];
  12214. // heuristics to create shader parameters according to lights in the scene
  12215. // (not to blow over maxLights budget)
  12216. if ( material.precision !== null ) {
  12217. precision = capabilities.getMaxPrecision( material.precision );
  12218. if ( precision !== material.precision ) {
  12219. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12220. }
  12221. }
  12222. //
  12223. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12224. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12225. let morphTextureStride = 0;
  12226. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12227. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12228. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12229. //
  12230. let vertexShader, fragmentShader;
  12231. let customVertexShaderID, customFragmentShaderID;
  12232. if ( shaderID ) {
  12233. const shader = ShaderLib[ shaderID ];
  12234. vertexShader = shader.vertexShader;
  12235. fragmentShader = shader.fragmentShader;
  12236. } else {
  12237. vertexShader = material.vertexShader;
  12238. fragmentShader = material.fragmentShader;
  12239. _customShaders.update( material );
  12240. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12241. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12242. }
  12243. const currentRenderTarget = renderer.getRenderTarget();
  12244. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12245. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  12246. const HAS_MAP = !! material.map;
  12247. const HAS_MATCAP = !! material.matcap;
  12248. const HAS_ENVMAP = !! envMap;
  12249. const HAS_AOMAP = !! material.aoMap;
  12250. const HAS_LIGHTMAP = !! material.lightMap;
  12251. const HAS_BUMPMAP = !! material.bumpMap;
  12252. const HAS_NORMALMAP = !! material.normalMap;
  12253. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12254. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12255. const HAS_METALNESSMAP = !! material.metalnessMap;
  12256. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12257. const HAS_ANISOTROPY = material.anisotropy > 0;
  12258. const HAS_CLEARCOAT = material.clearcoat > 0;
  12259. const HAS_DISPERSION = material.dispersion > 0;
  12260. const HAS_IRIDESCENCE = material.iridescence > 0;
  12261. const HAS_SHEEN = material.sheen > 0;
  12262. const HAS_TRANSMISSION = material.transmission > 0;
  12263. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12264. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12265. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12266. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12267. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12268. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12269. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12270. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12271. const HAS_SPECULARMAP = !! material.specularMap;
  12272. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12273. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12274. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12275. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12276. const HAS_GRADIENTMAP = !! material.gradientMap;
  12277. const HAS_ALPHAMAP = !! material.alphaMap;
  12278. const HAS_ALPHATEST = material.alphaTest > 0;
  12279. const HAS_ALPHAHASH = !! material.alphaHash;
  12280. const HAS_EXTENSIONS = !! material.extensions;
  12281. let toneMapping = NoToneMapping;
  12282. if ( material.toneMapped ) {
  12283. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  12284. toneMapping = renderer.toneMapping;
  12285. }
  12286. }
  12287. const parameters = {
  12288. shaderID: shaderID,
  12289. shaderType: material.type,
  12290. shaderName: material.name,
  12291. vertexShader: vertexShader,
  12292. fragmentShader: fragmentShader,
  12293. defines: material.defines,
  12294. customVertexShaderID: customVertexShaderID,
  12295. customFragmentShaderID: customFragmentShaderID,
  12296. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12297. glslVersion: material.glslVersion,
  12298. precision: precision,
  12299. batching: IS_BATCHEDMESH,
  12300. instancing: IS_INSTANCEDMESH,
  12301. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12302. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  12303. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12304. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12305. alphaToCoverage: !! material.alphaToCoverage,
  12306. map: HAS_MAP,
  12307. matcap: HAS_MATCAP,
  12308. envMap: HAS_ENVMAP,
  12309. envMapMode: HAS_ENVMAP && envMap.mapping,
  12310. envMapCubeUVHeight: envMapCubeUVHeight,
  12311. aoMap: HAS_AOMAP,
  12312. lightMap: HAS_LIGHTMAP,
  12313. bumpMap: HAS_BUMPMAP,
  12314. normalMap: HAS_NORMALMAP,
  12315. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12316. emissiveMap: HAS_EMISSIVEMAP,
  12317. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12318. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12319. metalnessMap: HAS_METALNESSMAP,
  12320. roughnessMap: HAS_ROUGHNESSMAP,
  12321. anisotropy: HAS_ANISOTROPY,
  12322. anisotropyMap: HAS_ANISOTROPYMAP,
  12323. clearcoat: HAS_CLEARCOAT,
  12324. clearcoatMap: HAS_CLEARCOATMAP,
  12325. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12326. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12327. dispersion: HAS_DISPERSION,
  12328. iridescence: HAS_IRIDESCENCE,
  12329. iridescenceMap: HAS_IRIDESCENCEMAP,
  12330. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12331. sheen: HAS_SHEEN,
  12332. sheenColorMap: HAS_SHEEN_COLORMAP,
  12333. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12334. specularMap: HAS_SPECULARMAP,
  12335. specularColorMap: HAS_SPECULAR_COLORMAP,
  12336. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12337. transmission: HAS_TRANSMISSION,
  12338. transmissionMap: HAS_TRANSMISSIONMAP,
  12339. thicknessMap: HAS_THICKNESSMAP,
  12340. gradientMap: HAS_GRADIENTMAP,
  12341. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  12342. alphaMap: HAS_ALPHAMAP,
  12343. alphaTest: HAS_ALPHATEST,
  12344. alphaHash: HAS_ALPHAHASH,
  12345. combine: material.combine,
  12346. //
  12347. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12348. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12349. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12350. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12351. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12352. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12353. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12354. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12355. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12356. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12357. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12358. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12359. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12360. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12361. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12362. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12363. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12364. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12365. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12366. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12367. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12368. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12369. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12370. //
  12371. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12372. vertexColors: material.vertexColors,
  12373. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12374. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12375. fog: !! fog,
  12376. useFog: material.fog === true,
  12377. fogExp2: ( !! fog && fog.isFogExp2 ),
  12378. flatShading: material.flatShading === true,
  12379. sizeAttenuation: material.sizeAttenuation === true,
  12380. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12381. skinning: object.isSkinnedMesh === true,
  12382. morphTargets: geometry.morphAttributes.position !== undefined,
  12383. morphNormals: geometry.morphAttributes.normal !== undefined,
  12384. morphColors: geometry.morphAttributes.color !== undefined,
  12385. morphTargetsCount: morphTargetsCount,
  12386. morphTextureStride: morphTextureStride,
  12387. numDirLights: lights.directional.length,
  12388. numPointLights: lights.point.length,
  12389. numSpotLights: lights.spot.length,
  12390. numSpotLightMaps: lights.spotLightMap.length,
  12391. numRectAreaLights: lights.rectArea.length,
  12392. numHemiLights: lights.hemi.length,
  12393. numDirLightShadows: lights.directionalShadowMap.length,
  12394. numPointLightShadows: lights.pointShadowMap.length,
  12395. numSpotLightShadows: lights.spotShadowMap.length,
  12396. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12397. numLightProbes: lights.numLightProbes,
  12398. numClippingPlanes: clipping.numPlanes,
  12399. numClipIntersection: clipping.numIntersection,
  12400. dithering: material.dithering,
  12401. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12402. shadowMapType: renderer.shadowMap.type,
  12403. toneMapping: toneMapping,
  12404. useLegacyLights: renderer._useLegacyLights,
  12405. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  12406. premultipliedAlpha: material.premultipliedAlpha,
  12407. doubleSided: material.side === DoubleSide,
  12408. flipSided: material.side === BackSide,
  12409. useDepthPacking: material.depthPacking >= 0,
  12410. depthPacking: material.depthPacking || 0,
  12411. index0AttributeName: material.index0AttributeName,
  12412. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  12413. extensionMultiDraw: HAS_EXTENSIONS && material.extensions.multiDraw === true && extensions.has( 'WEBGL_multi_draw' ),
  12414. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  12415. customProgramCacheKey: material.customProgramCacheKey()
  12416. };
  12417. // the usage of getChannel() determines the active texture channels for this shader
  12418. parameters.vertexUv1s = _activeChannels.has( 1 );
  12419. parameters.vertexUv2s = _activeChannels.has( 2 );
  12420. parameters.vertexUv3s = _activeChannels.has( 3 );
  12421. _activeChannels.clear();
  12422. return parameters;
  12423. }
  12424. function getProgramCacheKey( parameters ) {
  12425. const array = [];
  12426. if ( parameters.shaderID ) {
  12427. array.push( parameters.shaderID );
  12428. } else {
  12429. array.push( parameters.customVertexShaderID );
  12430. array.push( parameters.customFragmentShaderID );
  12431. }
  12432. if ( parameters.defines !== undefined ) {
  12433. for ( const name in parameters.defines ) {
  12434. array.push( name );
  12435. array.push( parameters.defines[ name ] );
  12436. }
  12437. }
  12438. if ( parameters.isRawShaderMaterial === false ) {
  12439. getProgramCacheKeyParameters( array, parameters );
  12440. getProgramCacheKeyBooleans( array, parameters );
  12441. array.push( renderer.outputColorSpace );
  12442. }
  12443. array.push( parameters.customProgramCacheKey );
  12444. return array.join();
  12445. }
  12446. function getProgramCacheKeyParameters( array, parameters ) {
  12447. array.push( parameters.precision );
  12448. array.push( parameters.outputColorSpace );
  12449. array.push( parameters.envMapMode );
  12450. array.push( parameters.envMapCubeUVHeight );
  12451. array.push( parameters.mapUv );
  12452. array.push( parameters.alphaMapUv );
  12453. array.push( parameters.lightMapUv );
  12454. array.push( parameters.aoMapUv );
  12455. array.push( parameters.bumpMapUv );
  12456. array.push( parameters.normalMapUv );
  12457. array.push( parameters.displacementMapUv );
  12458. array.push( parameters.emissiveMapUv );
  12459. array.push( parameters.metalnessMapUv );
  12460. array.push( parameters.roughnessMapUv );
  12461. array.push( parameters.anisotropyMapUv );
  12462. array.push( parameters.clearcoatMapUv );
  12463. array.push( parameters.clearcoatNormalMapUv );
  12464. array.push( parameters.clearcoatRoughnessMapUv );
  12465. array.push( parameters.iridescenceMapUv );
  12466. array.push( parameters.iridescenceThicknessMapUv );
  12467. array.push( parameters.sheenColorMapUv );
  12468. array.push( parameters.sheenRoughnessMapUv );
  12469. array.push( parameters.specularMapUv );
  12470. array.push( parameters.specularColorMapUv );
  12471. array.push( parameters.specularIntensityMapUv );
  12472. array.push( parameters.transmissionMapUv );
  12473. array.push( parameters.thicknessMapUv );
  12474. array.push( parameters.combine );
  12475. array.push( parameters.fogExp2 );
  12476. array.push( parameters.sizeAttenuation );
  12477. array.push( parameters.morphTargetsCount );
  12478. array.push( parameters.morphAttributeCount );
  12479. array.push( parameters.numDirLights );
  12480. array.push( parameters.numPointLights );
  12481. array.push( parameters.numSpotLights );
  12482. array.push( parameters.numSpotLightMaps );
  12483. array.push( parameters.numHemiLights );
  12484. array.push( parameters.numRectAreaLights );
  12485. array.push( parameters.numDirLightShadows );
  12486. array.push( parameters.numPointLightShadows );
  12487. array.push( parameters.numSpotLightShadows );
  12488. array.push( parameters.numSpotLightShadowsWithMaps );
  12489. array.push( parameters.numLightProbes );
  12490. array.push( parameters.shadowMapType );
  12491. array.push( parameters.toneMapping );
  12492. array.push( parameters.numClippingPlanes );
  12493. array.push( parameters.numClipIntersection );
  12494. array.push( parameters.depthPacking );
  12495. }
  12496. function getProgramCacheKeyBooleans( array, parameters ) {
  12497. _programLayers.disableAll();
  12498. if ( parameters.supportsVertexTextures )
  12499. _programLayers.enable( 0 );
  12500. if ( parameters.instancing )
  12501. _programLayers.enable( 1 );
  12502. if ( parameters.instancingColor )
  12503. _programLayers.enable( 2 );
  12504. if ( parameters.instancingMorph )
  12505. _programLayers.enable( 3 );
  12506. if ( parameters.matcap )
  12507. _programLayers.enable( 4 );
  12508. if ( parameters.envMap )
  12509. _programLayers.enable( 5 );
  12510. if ( parameters.normalMapObjectSpace )
  12511. _programLayers.enable( 6 );
  12512. if ( parameters.normalMapTangentSpace )
  12513. _programLayers.enable( 7 );
  12514. if ( parameters.clearcoat )
  12515. _programLayers.enable( 8 );
  12516. if ( parameters.iridescence )
  12517. _programLayers.enable( 9 );
  12518. if ( parameters.alphaTest )
  12519. _programLayers.enable( 10 );
  12520. if ( parameters.vertexColors )
  12521. _programLayers.enable( 11 );
  12522. if ( parameters.vertexAlphas )
  12523. _programLayers.enable( 12 );
  12524. if ( parameters.vertexUv1s )
  12525. _programLayers.enable( 13 );
  12526. if ( parameters.vertexUv2s )
  12527. _programLayers.enable( 14 );
  12528. if ( parameters.vertexUv3s )
  12529. _programLayers.enable( 15 );
  12530. if ( parameters.vertexTangents )
  12531. _programLayers.enable( 16 );
  12532. if ( parameters.anisotropy )
  12533. _programLayers.enable( 17 );
  12534. if ( parameters.alphaHash )
  12535. _programLayers.enable( 18 );
  12536. if ( parameters.batching )
  12537. _programLayers.enable( 19 );
  12538. if ( parameters.dispersion )
  12539. _programLayers.enable( 20 );
  12540. array.push( _programLayers.mask );
  12541. _programLayers.disableAll();
  12542. if ( parameters.fog )
  12543. _programLayers.enable( 0 );
  12544. if ( parameters.useFog )
  12545. _programLayers.enable( 1 );
  12546. if ( parameters.flatShading )
  12547. _programLayers.enable( 2 );
  12548. if ( parameters.logarithmicDepthBuffer )
  12549. _programLayers.enable( 3 );
  12550. if ( parameters.skinning )
  12551. _programLayers.enable( 4 );
  12552. if ( parameters.morphTargets )
  12553. _programLayers.enable( 5 );
  12554. if ( parameters.morphNormals )
  12555. _programLayers.enable( 6 );
  12556. if ( parameters.morphColors )
  12557. _programLayers.enable( 7 );
  12558. if ( parameters.premultipliedAlpha )
  12559. _programLayers.enable( 8 );
  12560. if ( parameters.shadowMapEnabled )
  12561. _programLayers.enable( 9 );
  12562. if ( parameters.useLegacyLights )
  12563. _programLayers.enable( 10 );
  12564. if ( parameters.doubleSided )
  12565. _programLayers.enable( 11 );
  12566. if ( parameters.flipSided )
  12567. _programLayers.enable( 12 );
  12568. if ( parameters.useDepthPacking )
  12569. _programLayers.enable( 13 );
  12570. if ( parameters.dithering )
  12571. _programLayers.enable( 14 );
  12572. if ( parameters.transmission )
  12573. _programLayers.enable( 15 );
  12574. if ( parameters.sheen )
  12575. _programLayers.enable( 16 );
  12576. if ( parameters.opaque )
  12577. _programLayers.enable( 17 );
  12578. if ( parameters.pointsUvs )
  12579. _programLayers.enable( 18 );
  12580. if ( parameters.decodeVideoTexture )
  12581. _programLayers.enable( 19 );
  12582. if ( parameters.alphaToCoverage )
  12583. _programLayers.enable( 20 );
  12584. array.push( _programLayers.mask );
  12585. }
  12586. function getUniforms( material ) {
  12587. const shaderID = shaderIDs[ material.type ];
  12588. let uniforms;
  12589. if ( shaderID ) {
  12590. const shader = ShaderLib[ shaderID ];
  12591. uniforms = UniformsUtils.clone( shader.uniforms );
  12592. } else {
  12593. uniforms = material.uniforms;
  12594. }
  12595. return uniforms;
  12596. }
  12597. function acquireProgram( parameters, cacheKey ) {
  12598. let program;
  12599. // Check if code has been already compiled
  12600. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12601. const preexistingProgram = programs[ p ];
  12602. if ( preexistingProgram.cacheKey === cacheKey ) {
  12603. program = preexistingProgram;
  12604. ++ program.usedTimes;
  12605. break;
  12606. }
  12607. }
  12608. if ( program === undefined ) {
  12609. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12610. programs.push( program );
  12611. }
  12612. return program;
  12613. }
  12614. function releaseProgram( program ) {
  12615. if ( -- program.usedTimes === 0 ) {
  12616. // Remove from unordered set
  12617. const i = programs.indexOf( program );
  12618. programs[ i ] = programs[ programs.length - 1 ];
  12619. programs.pop();
  12620. // Free WebGL resources
  12621. program.destroy();
  12622. }
  12623. }
  12624. function releaseShaderCache( material ) {
  12625. _customShaders.remove( material );
  12626. }
  12627. function dispose() {
  12628. _customShaders.dispose();
  12629. }
  12630. return {
  12631. getParameters: getParameters,
  12632. getProgramCacheKey: getProgramCacheKey,
  12633. getUniforms: getUniforms,
  12634. acquireProgram: acquireProgram,
  12635. releaseProgram: releaseProgram,
  12636. releaseShaderCache: releaseShaderCache,
  12637. // Exposed for resource monitoring & error feedback via renderer.info:
  12638. programs: programs,
  12639. dispose: dispose
  12640. };
  12641. }
  12642. function WebGLProperties() {
  12643. let properties = new WeakMap();
  12644. function get( object ) {
  12645. let map = properties.get( object );
  12646. if ( map === undefined ) {
  12647. map = {};
  12648. properties.set( object, map );
  12649. }
  12650. return map;
  12651. }
  12652. function remove( object ) {
  12653. properties.delete( object );
  12654. }
  12655. function update( object, key, value ) {
  12656. properties.get( object )[ key ] = value;
  12657. }
  12658. function dispose() {
  12659. properties = new WeakMap();
  12660. }
  12661. return {
  12662. get: get,
  12663. remove: remove,
  12664. update: update,
  12665. dispose: dispose
  12666. };
  12667. }
  12668. function painterSortStable( a, b ) {
  12669. if ( a.groupOrder !== b.groupOrder ) {
  12670. return a.groupOrder - b.groupOrder;
  12671. } else if ( a.renderOrder !== b.renderOrder ) {
  12672. return a.renderOrder - b.renderOrder;
  12673. } else if ( a.material.id !== b.material.id ) {
  12674. return a.material.id - b.material.id;
  12675. } else if ( a.z !== b.z ) {
  12676. return a.z - b.z;
  12677. } else {
  12678. return a.id - b.id;
  12679. }
  12680. }
  12681. function reversePainterSortStable( a, b ) {
  12682. if ( a.groupOrder !== b.groupOrder ) {
  12683. return a.groupOrder - b.groupOrder;
  12684. } else if ( a.renderOrder !== b.renderOrder ) {
  12685. return a.renderOrder - b.renderOrder;
  12686. } else if ( a.z !== b.z ) {
  12687. return b.z - a.z;
  12688. } else {
  12689. return a.id - b.id;
  12690. }
  12691. }
  12692. function WebGLRenderList() {
  12693. const renderItems = [];
  12694. let renderItemsIndex = 0;
  12695. const opaque = [];
  12696. const transmissive = [];
  12697. const transparent = [];
  12698. function init() {
  12699. renderItemsIndex = 0;
  12700. opaque.length = 0;
  12701. transmissive.length = 0;
  12702. transparent.length = 0;
  12703. }
  12704. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12705. let renderItem = renderItems[ renderItemsIndex ];
  12706. if ( renderItem === undefined ) {
  12707. renderItem = {
  12708. id: object.id,
  12709. object: object,
  12710. geometry: geometry,
  12711. material: material,
  12712. groupOrder: groupOrder,
  12713. renderOrder: object.renderOrder,
  12714. z: z,
  12715. group: group
  12716. };
  12717. renderItems[ renderItemsIndex ] = renderItem;
  12718. } else {
  12719. renderItem.id = object.id;
  12720. renderItem.object = object;
  12721. renderItem.geometry = geometry;
  12722. renderItem.material = material;
  12723. renderItem.groupOrder = groupOrder;
  12724. renderItem.renderOrder = object.renderOrder;
  12725. renderItem.z = z;
  12726. renderItem.group = group;
  12727. }
  12728. renderItemsIndex ++;
  12729. return renderItem;
  12730. }
  12731. function push( object, geometry, material, groupOrder, z, group ) {
  12732. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12733. if ( material.transmission > 0.0 ) {
  12734. transmissive.push( renderItem );
  12735. } else if ( material.transparent === true ) {
  12736. transparent.push( renderItem );
  12737. } else {
  12738. opaque.push( renderItem );
  12739. }
  12740. }
  12741. function unshift( object, geometry, material, groupOrder, z, group ) {
  12742. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12743. if ( material.transmission > 0.0 ) {
  12744. transmissive.unshift( renderItem );
  12745. } else if ( material.transparent === true ) {
  12746. transparent.unshift( renderItem );
  12747. } else {
  12748. opaque.unshift( renderItem );
  12749. }
  12750. }
  12751. function sort( customOpaqueSort, customTransparentSort ) {
  12752. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12753. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12754. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12755. }
  12756. function finish() {
  12757. // Clear references from inactive renderItems in the list
  12758. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12759. const renderItem = renderItems[ i ];
  12760. if ( renderItem.id === null ) break;
  12761. renderItem.id = null;
  12762. renderItem.object = null;
  12763. renderItem.geometry = null;
  12764. renderItem.material = null;
  12765. renderItem.group = null;
  12766. }
  12767. }
  12768. return {
  12769. opaque: opaque,
  12770. transmissive: transmissive,
  12771. transparent: transparent,
  12772. init: init,
  12773. push: push,
  12774. unshift: unshift,
  12775. finish: finish,
  12776. sort: sort
  12777. };
  12778. }
  12779. function WebGLRenderLists() {
  12780. let lists = new WeakMap();
  12781. function get( scene, renderCallDepth ) {
  12782. const listArray = lists.get( scene );
  12783. let list;
  12784. if ( listArray === undefined ) {
  12785. list = new WebGLRenderList();
  12786. lists.set( scene, [ list ] );
  12787. } else {
  12788. if ( renderCallDepth >= listArray.length ) {
  12789. list = new WebGLRenderList();
  12790. listArray.push( list );
  12791. } else {
  12792. list = listArray[ renderCallDepth ];
  12793. }
  12794. }
  12795. return list;
  12796. }
  12797. function dispose() {
  12798. lists = new WeakMap();
  12799. }
  12800. return {
  12801. get: get,
  12802. dispose: dispose
  12803. };
  12804. }
  12805. function UniformsCache() {
  12806. const lights = {};
  12807. return {
  12808. get: function ( light ) {
  12809. if ( lights[ light.id ] !== undefined ) {
  12810. return lights[ light.id ];
  12811. }
  12812. let uniforms;
  12813. switch ( light.type ) {
  12814. case 'DirectionalLight':
  12815. uniforms = {
  12816. direction: new Vector3(),
  12817. color: new Color()
  12818. };
  12819. break;
  12820. case 'SpotLight':
  12821. uniforms = {
  12822. position: new Vector3(),
  12823. direction: new Vector3(),
  12824. color: new Color(),
  12825. distance: 0,
  12826. coneCos: 0,
  12827. penumbraCos: 0,
  12828. decay: 0
  12829. };
  12830. break;
  12831. case 'PointLight':
  12832. uniforms = {
  12833. position: new Vector3(),
  12834. color: new Color(),
  12835. distance: 0,
  12836. decay: 0
  12837. };
  12838. break;
  12839. case 'HemisphereLight':
  12840. uniforms = {
  12841. direction: new Vector3(),
  12842. skyColor: new Color(),
  12843. groundColor: new Color()
  12844. };
  12845. break;
  12846. case 'RectAreaLight':
  12847. uniforms = {
  12848. color: new Color(),
  12849. position: new Vector3(),
  12850. halfWidth: new Vector3(),
  12851. halfHeight: new Vector3()
  12852. };
  12853. break;
  12854. }
  12855. lights[ light.id ] = uniforms;
  12856. return uniforms;
  12857. }
  12858. };
  12859. }
  12860. function ShadowUniformsCache() {
  12861. const lights = {};
  12862. return {
  12863. get: function ( light ) {
  12864. if ( lights[ light.id ] !== undefined ) {
  12865. return lights[ light.id ];
  12866. }
  12867. let uniforms;
  12868. switch ( light.type ) {
  12869. case 'DirectionalLight':
  12870. uniforms = {
  12871. shadowBias: 0,
  12872. shadowNormalBias: 0,
  12873. shadowRadius: 1,
  12874. shadowMapSize: new Vector2()
  12875. };
  12876. break;
  12877. case 'SpotLight':
  12878. uniforms = {
  12879. shadowBias: 0,
  12880. shadowNormalBias: 0,
  12881. shadowRadius: 1,
  12882. shadowMapSize: new Vector2()
  12883. };
  12884. break;
  12885. case 'PointLight':
  12886. uniforms = {
  12887. shadowBias: 0,
  12888. shadowNormalBias: 0,
  12889. shadowRadius: 1,
  12890. shadowMapSize: new Vector2(),
  12891. shadowCameraNear: 1,
  12892. shadowCameraFar: 1000
  12893. };
  12894. break;
  12895. // TODO (abelnation): set RectAreaLight shadow uniforms
  12896. }
  12897. lights[ light.id ] = uniforms;
  12898. return uniforms;
  12899. }
  12900. };
  12901. }
  12902. let nextVersion = 0;
  12903. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12904. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12905. }
  12906. function WebGLLights( extensions ) {
  12907. const cache = new UniformsCache();
  12908. const shadowCache = ShadowUniformsCache();
  12909. const state = {
  12910. version: 0,
  12911. hash: {
  12912. directionalLength: - 1,
  12913. pointLength: - 1,
  12914. spotLength: - 1,
  12915. rectAreaLength: - 1,
  12916. hemiLength: - 1,
  12917. numDirectionalShadows: - 1,
  12918. numPointShadows: - 1,
  12919. numSpotShadows: - 1,
  12920. numSpotMaps: - 1,
  12921. numLightProbes: - 1
  12922. },
  12923. ambient: [ 0, 0, 0 ],
  12924. probe: [],
  12925. directional: [],
  12926. directionalShadow: [],
  12927. directionalShadowMap: [],
  12928. directionalShadowMatrix: [],
  12929. spot: [],
  12930. spotLightMap: [],
  12931. spotShadow: [],
  12932. spotShadowMap: [],
  12933. spotLightMatrix: [],
  12934. rectArea: [],
  12935. rectAreaLTC1: null,
  12936. rectAreaLTC2: null,
  12937. point: [],
  12938. pointShadow: [],
  12939. pointShadowMap: [],
  12940. pointShadowMatrix: [],
  12941. hemi: [],
  12942. numSpotLightShadowsWithMaps: 0,
  12943. numLightProbes: 0
  12944. };
  12945. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12946. const vector3 = new Vector3();
  12947. const matrix4 = new Matrix4();
  12948. const matrix42 = new Matrix4();
  12949. function setup( lights, useLegacyLights ) {
  12950. let r = 0, g = 0, b = 0;
  12951. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12952. let directionalLength = 0;
  12953. let pointLength = 0;
  12954. let spotLength = 0;
  12955. let rectAreaLength = 0;
  12956. let hemiLength = 0;
  12957. let numDirectionalShadows = 0;
  12958. let numPointShadows = 0;
  12959. let numSpotShadows = 0;
  12960. let numSpotMaps = 0;
  12961. let numSpotShadowsWithMaps = 0;
  12962. let numLightProbes = 0;
  12963. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12964. lights.sort( shadowCastingAndTexturingLightsFirst );
  12965. // artist-friendly light intensity scaling factor
  12966. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12967. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12968. const light = lights[ i ];
  12969. const color = light.color;
  12970. const intensity = light.intensity;
  12971. const distance = light.distance;
  12972. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12973. if ( light.isAmbientLight ) {
  12974. r += color.r * intensity * scaleFactor;
  12975. g += color.g * intensity * scaleFactor;
  12976. b += color.b * intensity * scaleFactor;
  12977. } else if ( light.isLightProbe ) {
  12978. for ( let j = 0; j < 9; j ++ ) {
  12979. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12980. }
  12981. numLightProbes ++;
  12982. } else if ( light.isDirectionalLight ) {
  12983. const uniforms = cache.get( light );
  12984. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12985. if ( light.castShadow ) {
  12986. const shadow = light.shadow;
  12987. const shadowUniforms = shadowCache.get( light );
  12988. shadowUniforms.shadowBias = shadow.bias;
  12989. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12990. shadowUniforms.shadowRadius = shadow.radius;
  12991. shadowUniforms.shadowMapSize = shadow.mapSize;
  12992. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12993. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12994. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12995. numDirectionalShadows ++;
  12996. }
  12997. state.directional[ directionalLength ] = uniforms;
  12998. directionalLength ++;
  12999. } else if ( light.isSpotLight ) {
  13000. const uniforms = cache.get( light );
  13001. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13002. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  13003. uniforms.distance = distance;
  13004. uniforms.coneCos = Math.cos( light.angle );
  13005. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13006. uniforms.decay = light.decay;
  13007. state.spot[ spotLength ] = uniforms;
  13008. const shadow = light.shadow;
  13009. if ( light.map ) {
  13010. state.spotLightMap[ numSpotMaps ] = light.map;
  13011. numSpotMaps ++;
  13012. // make sure the lightMatrix is up to date
  13013. // TODO : do it if required only
  13014. shadow.updateMatrices( light );
  13015. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  13016. }
  13017. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  13018. if ( light.castShadow ) {
  13019. const shadowUniforms = shadowCache.get( light );
  13020. shadowUniforms.shadowBias = shadow.bias;
  13021. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13022. shadowUniforms.shadowRadius = shadow.radius;
  13023. shadowUniforms.shadowMapSize = shadow.mapSize;
  13024. state.spotShadow[ spotLength ] = shadowUniforms;
  13025. state.spotShadowMap[ spotLength ] = shadowMap;
  13026. numSpotShadows ++;
  13027. }
  13028. spotLength ++;
  13029. } else if ( light.isRectAreaLight ) {
  13030. const uniforms = cache.get( light );
  13031. uniforms.color.copy( color ).multiplyScalar( intensity );
  13032. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13033. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13034. state.rectArea[ rectAreaLength ] = uniforms;
  13035. rectAreaLength ++;
  13036. } else if ( light.isPointLight ) {
  13037. const uniforms = cache.get( light );
  13038. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  13039. uniforms.distance = light.distance;
  13040. uniforms.decay = light.decay;
  13041. if ( light.castShadow ) {
  13042. const shadow = light.shadow;
  13043. const shadowUniforms = shadowCache.get( light );
  13044. shadowUniforms.shadowBias = shadow.bias;
  13045. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13046. shadowUniforms.shadowRadius = shadow.radius;
  13047. shadowUniforms.shadowMapSize = shadow.mapSize;
  13048. shadowUniforms.shadowCameraNear = shadow.camera.near;
  13049. shadowUniforms.shadowCameraFar = shadow.camera.far;
  13050. state.pointShadow[ pointLength ] = shadowUniforms;
  13051. state.pointShadowMap[ pointLength ] = shadowMap;
  13052. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13053. numPointShadows ++;
  13054. }
  13055. state.point[ pointLength ] = uniforms;
  13056. pointLength ++;
  13057. } else if ( light.isHemisphereLight ) {
  13058. const uniforms = cache.get( light );
  13059. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  13060. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  13061. state.hemi[ hemiLength ] = uniforms;
  13062. hemiLength ++;
  13063. }
  13064. }
  13065. if ( rectAreaLength > 0 ) {
  13066. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13067. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13068. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13069. } else {
  13070. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13071. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13072. }
  13073. }
  13074. state.ambient[ 0 ] = r;
  13075. state.ambient[ 1 ] = g;
  13076. state.ambient[ 2 ] = b;
  13077. const hash = state.hash;
  13078. if ( hash.directionalLength !== directionalLength ||
  13079. hash.pointLength !== pointLength ||
  13080. hash.spotLength !== spotLength ||
  13081. hash.rectAreaLength !== rectAreaLength ||
  13082. hash.hemiLength !== hemiLength ||
  13083. hash.numDirectionalShadows !== numDirectionalShadows ||
  13084. hash.numPointShadows !== numPointShadows ||
  13085. hash.numSpotShadows !== numSpotShadows ||
  13086. hash.numSpotMaps !== numSpotMaps ||
  13087. hash.numLightProbes !== numLightProbes ) {
  13088. state.directional.length = directionalLength;
  13089. state.spot.length = spotLength;
  13090. state.rectArea.length = rectAreaLength;
  13091. state.point.length = pointLength;
  13092. state.hemi.length = hemiLength;
  13093. state.directionalShadow.length = numDirectionalShadows;
  13094. state.directionalShadowMap.length = numDirectionalShadows;
  13095. state.pointShadow.length = numPointShadows;
  13096. state.pointShadowMap.length = numPointShadows;
  13097. state.spotShadow.length = numSpotShadows;
  13098. state.spotShadowMap.length = numSpotShadows;
  13099. state.directionalShadowMatrix.length = numDirectionalShadows;
  13100. state.pointShadowMatrix.length = numPointShadows;
  13101. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  13102. state.spotLightMap.length = numSpotMaps;
  13103. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  13104. state.numLightProbes = numLightProbes;
  13105. hash.directionalLength = directionalLength;
  13106. hash.pointLength = pointLength;
  13107. hash.spotLength = spotLength;
  13108. hash.rectAreaLength = rectAreaLength;
  13109. hash.hemiLength = hemiLength;
  13110. hash.numDirectionalShadows = numDirectionalShadows;
  13111. hash.numPointShadows = numPointShadows;
  13112. hash.numSpotShadows = numSpotShadows;
  13113. hash.numSpotMaps = numSpotMaps;
  13114. hash.numLightProbes = numLightProbes;
  13115. state.version = nextVersion ++;
  13116. }
  13117. }
  13118. function setupView( lights, camera ) {
  13119. let directionalLength = 0;
  13120. let pointLength = 0;
  13121. let spotLength = 0;
  13122. let rectAreaLength = 0;
  13123. let hemiLength = 0;
  13124. const viewMatrix = camera.matrixWorldInverse;
  13125. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13126. const light = lights[ i ];
  13127. if ( light.isDirectionalLight ) {
  13128. const uniforms = state.directional[ directionalLength ];
  13129. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13130. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13131. uniforms.direction.sub( vector3 );
  13132. uniforms.direction.transformDirection( viewMatrix );
  13133. directionalLength ++;
  13134. } else if ( light.isSpotLight ) {
  13135. const uniforms = state.spot[ spotLength ];
  13136. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13137. uniforms.position.applyMatrix4( viewMatrix );
  13138. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13139. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13140. uniforms.direction.sub( vector3 );
  13141. uniforms.direction.transformDirection( viewMatrix );
  13142. spotLength ++;
  13143. } else if ( light.isRectAreaLight ) {
  13144. const uniforms = state.rectArea[ rectAreaLength ];
  13145. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13146. uniforms.position.applyMatrix4( viewMatrix );
  13147. // extract local rotation of light to derive width/height half vectors
  13148. matrix42.identity();
  13149. matrix4.copy( light.matrixWorld );
  13150. matrix4.premultiply( viewMatrix );
  13151. matrix42.extractRotation( matrix4 );
  13152. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13153. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13154. uniforms.halfWidth.applyMatrix4( matrix42 );
  13155. uniforms.halfHeight.applyMatrix4( matrix42 );
  13156. rectAreaLength ++;
  13157. } else if ( light.isPointLight ) {
  13158. const uniforms = state.point[ pointLength ];
  13159. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13160. uniforms.position.applyMatrix4( viewMatrix );
  13161. pointLength ++;
  13162. } else if ( light.isHemisphereLight ) {
  13163. const uniforms = state.hemi[ hemiLength ];
  13164. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13165. uniforms.direction.transformDirection( viewMatrix );
  13166. hemiLength ++;
  13167. }
  13168. }
  13169. }
  13170. return {
  13171. setup: setup,
  13172. setupView: setupView,
  13173. state: state
  13174. };
  13175. }
  13176. function WebGLRenderState( extensions ) {
  13177. const lights = new WebGLLights( extensions );
  13178. const lightsArray = [];
  13179. const shadowsArray = [];
  13180. function init() {
  13181. lightsArray.length = 0;
  13182. shadowsArray.length = 0;
  13183. }
  13184. function pushLight( light ) {
  13185. lightsArray.push( light );
  13186. }
  13187. function pushShadow( shadowLight ) {
  13188. shadowsArray.push( shadowLight );
  13189. }
  13190. function setupLights( useLegacyLights ) {
  13191. lights.setup( lightsArray, useLegacyLights );
  13192. }
  13193. function setupLightsView( camera ) {
  13194. lights.setupView( lightsArray, camera );
  13195. }
  13196. const state = {
  13197. lightsArray: lightsArray,
  13198. shadowsArray: shadowsArray,
  13199. lights: lights,
  13200. transmissionRenderTarget: null
  13201. };
  13202. return {
  13203. init: init,
  13204. state: state,
  13205. setupLights: setupLights,
  13206. setupLightsView: setupLightsView,
  13207. pushLight: pushLight,
  13208. pushShadow: pushShadow
  13209. };
  13210. }
  13211. function WebGLRenderStates( extensions ) {
  13212. let renderStates = new WeakMap();
  13213. function get( scene, renderCallDepth = 0 ) {
  13214. const renderStateArray = renderStates.get( scene );
  13215. let renderState;
  13216. if ( renderStateArray === undefined ) {
  13217. renderState = new WebGLRenderState( extensions );
  13218. renderStates.set( scene, [ renderState ] );
  13219. } else {
  13220. if ( renderCallDepth >= renderStateArray.length ) {
  13221. renderState = new WebGLRenderState( extensions );
  13222. renderStateArray.push( renderState );
  13223. } else {
  13224. renderState = renderStateArray[ renderCallDepth ];
  13225. }
  13226. }
  13227. return renderState;
  13228. }
  13229. function dispose() {
  13230. renderStates = new WeakMap();
  13231. }
  13232. return {
  13233. get: get,
  13234. dispose: dispose
  13235. };
  13236. }
  13237. class MeshDepthMaterial extends Material {
  13238. constructor( parameters ) {
  13239. super();
  13240. this.isMeshDepthMaterial = true;
  13241. this.type = 'MeshDepthMaterial';
  13242. this.depthPacking = BasicDepthPacking;
  13243. this.map = null;
  13244. this.alphaMap = null;
  13245. this.displacementMap = null;
  13246. this.displacementScale = 1;
  13247. this.displacementBias = 0;
  13248. this.wireframe = false;
  13249. this.wireframeLinewidth = 1;
  13250. this.setValues( parameters );
  13251. }
  13252. copy( source ) {
  13253. super.copy( source );
  13254. this.depthPacking = source.depthPacking;
  13255. this.map = source.map;
  13256. this.alphaMap = source.alphaMap;
  13257. this.displacementMap = source.displacementMap;
  13258. this.displacementScale = source.displacementScale;
  13259. this.displacementBias = source.displacementBias;
  13260. this.wireframe = source.wireframe;
  13261. this.wireframeLinewidth = source.wireframeLinewidth;
  13262. return this;
  13263. }
  13264. }
  13265. class MeshDistanceMaterial extends Material {
  13266. constructor( parameters ) {
  13267. super();
  13268. this.isMeshDistanceMaterial = true;
  13269. this.type = 'MeshDistanceMaterial';
  13270. this.map = null;
  13271. this.alphaMap = null;
  13272. this.displacementMap = null;
  13273. this.displacementScale = 1;
  13274. this.displacementBias = 0;
  13275. this.setValues( parameters );
  13276. }
  13277. copy( source ) {
  13278. super.copy( source );
  13279. this.map = source.map;
  13280. this.alphaMap = source.alphaMap;
  13281. this.displacementMap = source.displacementMap;
  13282. this.displacementScale = source.displacementScale;
  13283. this.displacementBias = source.displacementBias;
  13284. return this;
  13285. }
  13286. }
  13287. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13288. 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}";
  13289. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  13290. let _frustum = new Frustum();
  13291. const _shadowMapSize = new Vector2(),
  13292. _viewportSize = new Vector2(),
  13293. _viewport = new Vector4(),
  13294. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13295. _distanceMaterial = new MeshDistanceMaterial(),
  13296. _materialCache = {},
  13297. _maxTextureSize = _capabilities.maxTextureSize;
  13298. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13299. const shadowMaterialVertical = new ShaderMaterial( {
  13300. defines: {
  13301. VSM_SAMPLES: 8
  13302. },
  13303. uniforms: {
  13304. shadow_pass: { value: null },
  13305. resolution: { value: new Vector2() },
  13306. radius: { value: 4.0 }
  13307. },
  13308. vertexShader: vertex,
  13309. fragmentShader: fragment
  13310. } );
  13311. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13312. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13313. const fullScreenTri = new BufferGeometry();
  13314. fullScreenTri.setAttribute(
  13315. 'position',
  13316. new BufferAttribute(
  13317. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13318. 3
  13319. )
  13320. );
  13321. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13322. const scope = this;
  13323. this.enabled = false;
  13324. this.autoUpdate = true;
  13325. this.needsUpdate = false;
  13326. this.type = PCFShadowMap;
  13327. let _previousType = this.type;
  13328. this.render = function ( lights, scene, camera ) {
  13329. if ( scope.enabled === false ) return;
  13330. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13331. if ( lights.length === 0 ) return;
  13332. const currentRenderTarget = _renderer.getRenderTarget();
  13333. const activeCubeFace = _renderer.getActiveCubeFace();
  13334. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13335. const _state = _renderer.state;
  13336. // Set GL state for depth map.
  13337. _state.setBlending( NoBlending );
  13338. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13339. _state.buffers.depth.setTest( true );
  13340. _state.setScissorTest( false );
  13341. // check for shadow map type changes
  13342. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13343. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13344. // render depth map
  13345. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13346. const light = lights[ i ];
  13347. const shadow = light.shadow;
  13348. if ( shadow === undefined ) {
  13349. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13350. continue;
  13351. }
  13352. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13353. _shadowMapSize.copy( shadow.mapSize );
  13354. const shadowFrameExtents = shadow.getFrameExtents();
  13355. _shadowMapSize.multiply( shadowFrameExtents );
  13356. _viewportSize.copy( shadow.mapSize );
  13357. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13358. if ( _shadowMapSize.x > _maxTextureSize ) {
  13359. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13360. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13361. shadow.mapSize.x = _viewportSize.x;
  13362. }
  13363. if ( _shadowMapSize.y > _maxTextureSize ) {
  13364. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13365. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13366. shadow.mapSize.y = _viewportSize.y;
  13367. }
  13368. }
  13369. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13370. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13371. if ( shadow.map !== null ) {
  13372. shadow.map.dispose();
  13373. }
  13374. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13375. shadow.map.texture.name = light.name + '.shadowMap';
  13376. shadow.camera.updateProjectionMatrix();
  13377. }
  13378. _renderer.setRenderTarget( shadow.map );
  13379. _renderer.clear();
  13380. const viewportCount = shadow.getViewportCount();
  13381. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13382. const viewport = shadow.getViewport( vp );
  13383. _viewport.set(
  13384. _viewportSize.x * viewport.x,
  13385. _viewportSize.y * viewport.y,
  13386. _viewportSize.x * viewport.z,
  13387. _viewportSize.y * viewport.w
  13388. );
  13389. _state.viewport( _viewport );
  13390. shadow.updateMatrices( light, vp );
  13391. _frustum = shadow.getFrustum();
  13392. renderObject( scene, camera, shadow.camera, light, this.type );
  13393. }
  13394. // do blur pass for VSM
  13395. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13396. VSMPass( shadow, camera );
  13397. }
  13398. shadow.needsUpdate = false;
  13399. }
  13400. _previousType = this.type;
  13401. scope.needsUpdate = false;
  13402. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13403. };
  13404. function VSMPass( shadow, camera ) {
  13405. const geometry = _objects.update( fullScreenMesh );
  13406. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13407. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13408. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13409. shadowMaterialVertical.needsUpdate = true;
  13410. shadowMaterialHorizontal.needsUpdate = true;
  13411. }
  13412. if ( shadow.mapPass === null ) {
  13413. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13414. }
  13415. // vertical pass
  13416. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13417. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13418. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13419. _renderer.setRenderTarget( shadow.mapPass );
  13420. _renderer.clear();
  13421. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13422. // horizontal pass
  13423. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13424. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13425. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13426. _renderer.setRenderTarget( shadow.map );
  13427. _renderer.clear();
  13428. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13429. }
  13430. function getDepthMaterial( object, material, light, type ) {
  13431. let result = null;
  13432. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13433. if ( customMaterial !== undefined ) {
  13434. result = customMaterial;
  13435. } else {
  13436. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13437. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13438. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13439. ( material.alphaMap && material.alphaTest > 0 ) ||
  13440. ( material.map && material.alphaTest > 0 ) ) {
  13441. // in this case we need a unique material instance reflecting the
  13442. // appropriate state
  13443. const keyA = result.uuid, keyB = material.uuid;
  13444. let materialsForVariant = _materialCache[ keyA ];
  13445. if ( materialsForVariant === undefined ) {
  13446. materialsForVariant = {};
  13447. _materialCache[ keyA ] = materialsForVariant;
  13448. }
  13449. let cachedMaterial = materialsForVariant[ keyB ];
  13450. if ( cachedMaterial === undefined ) {
  13451. cachedMaterial = result.clone();
  13452. materialsForVariant[ keyB ] = cachedMaterial;
  13453. material.addEventListener( 'dispose', onMaterialDispose );
  13454. }
  13455. result = cachedMaterial;
  13456. }
  13457. }
  13458. result.visible = material.visible;
  13459. result.wireframe = material.wireframe;
  13460. if ( type === VSMShadowMap ) {
  13461. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13462. } else {
  13463. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13464. }
  13465. result.alphaMap = material.alphaMap;
  13466. result.alphaTest = material.alphaTest;
  13467. result.map = material.map;
  13468. result.clipShadows = material.clipShadows;
  13469. result.clippingPlanes = material.clippingPlanes;
  13470. result.clipIntersection = material.clipIntersection;
  13471. result.displacementMap = material.displacementMap;
  13472. result.displacementScale = material.displacementScale;
  13473. result.displacementBias = material.displacementBias;
  13474. result.wireframeLinewidth = material.wireframeLinewidth;
  13475. result.linewidth = material.linewidth;
  13476. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13477. const materialProperties = _renderer.properties.get( result );
  13478. materialProperties.light = light;
  13479. }
  13480. return result;
  13481. }
  13482. function renderObject( object, camera, shadowCamera, light, type ) {
  13483. if ( object.visible === false ) return;
  13484. const visible = object.layers.test( camera.layers );
  13485. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13486. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13487. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13488. const geometry = _objects.update( object );
  13489. const material = object.material;
  13490. if ( Array.isArray( material ) ) {
  13491. const groups = geometry.groups;
  13492. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13493. const group = groups[ k ];
  13494. const groupMaterial = material[ group.materialIndex ];
  13495. if ( groupMaterial && groupMaterial.visible ) {
  13496. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13497. object.onBeforeShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13498. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13499. object.onAfterShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13500. }
  13501. }
  13502. } else if ( material.visible ) {
  13503. const depthMaterial = getDepthMaterial( object, material, light, type );
  13504. object.onBeforeShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13505. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13506. object.onAfterShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13507. }
  13508. }
  13509. }
  13510. const children = object.children;
  13511. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13512. renderObject( children[ i ], camera, shadowCamera, light, type );
  13513. }
  13514. }
  13515. function onMaterialDispose( event ) {
  13516. const material = event.target;
  13517. material.removeEventListener( 'dispose', onMaterialDispose );
  13518. // make sure to remove the unique distance/depth materials used for shadow map rendering
  13519. for ( const id in _materialCache ) {
  13520. const cache = _materialCache[ id ];
  13521. const uuid = event.target.uuid;
  13522. if ( uuid in cache ) {
  13523. const shadowMaterial = cache[ uuid ];
  13524. shadowMaterial.dispose();
  13525. delete cache[ uuid ];
  13526. }
  13527. }
  13528. }
  13529. }
  13530. function WebGLState( gl ) {
  13531. function ColorBuffer() {
  13532. let locked = false;
  13533. const color = new Vector4();
  13534. let currentColorMask = null;
  13535. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13536. return {
  13537. setMask: function ( colorMask ) {
  13538. if ( currentColorMask !== colorMask && ! locked ) {
  13539. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13540. currentColorMask = colorMask;
  13541. }
  13542. },
  13543. setLocked: function ( lock ) {
  13544. locked = lock;
  13545. },
  13546. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13547. if ( premultipliedAlpha === true ) {
  13548. r *= a; g *= a; b *= a;
  13549. }
  13550. color.set( r, g, b, a );
  13551. if ( currentColorClear.equals( color ) === false ) {
  13552. gl.clearColor( r, g, b, a );
  13553. currentColorClear.copy( color );
  13554. }
  13555. },
  13556. reset: function () {
  13557. locked = false;
  13558. currentColorMask = null;
  13559. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13560. }
  13561. };
  13562. }
  13563. function DepthBuffer() {
  13564. let locked = false;
  13565. let currentDepthMask = null;
  13566. let currentDepthFunc = null;
  13567. let currentDepthClear = null;
  13568. return {
  13569. setTest: function ( depthTest ) {
  13570. if ( depthTest ) {
  13571. enable( gl.DEPTH_TEST );
  13572. } else {
  13573. disable( gl.DEPTH_TEST );
  13574. }
  13575. },
  13576. setMask: function ( depthMask ) {
  13577. if ( currentDepthMask !== depthMask && ! locked ) {
  13578. gl.depthMask( depthMask );
  13579. currentDepthMask = depthMask;
  13580. }
  13581. },
  13582. setFunc: function ( depthFunc ) {
  13583. if ( currentDepthFunc !== depthFunc ) {
  13584. switch ( depthFunc ) {
  13585. case NeverDepth:
  13586. gl.depthFunc( gl.NEVER );
  13587. break;
  13588. case AlwaysDepth:
  13589. gl.depthFunc( gl.ALWAYS );
  13590. break;
  13591. case LessDepth:
  13592. gl.depthFunc( gl.LESS );
  13593. break;
  13594. case LessEqualDepth:
  13595. gl.depthFunc( gl.LEQUAL );
  13596. break;
  13597. case EqualDepth:
  13598. gl.depthFunc( gl.EQUAL );
  13599. break;
  13600. case GreaterEqualDepth:
  13601. gl.depthFunc( gl.GEQUAL );
  13602. break;
  13603. case GreaterDepth:
  13604. gl.depthFunc( gl.GREATER );
  13605. break;
  13606. case NotEqualDepth:
  13607. gl.depthFunc( gl.NOTEQUAL );
  13608. break;
  13609. default:
  13610. gl.depthFunc( gl.LEQUAL );
  13611. }
  13612. currentDepthFunc = depthFunc;
  13613. }
  13614. },
  13615. setLocked: function ( lock ) {
  13616. locked = lock;
  13617. },
  13618. setClear: function ( depth ) {
  13619. if ( currentDepthClear !== depth ) {
  13620. gl.clearDepth( depth );
  13621. currentDepthClear = depth;
  13622. }
  13623. },
  13624. reset: function () {
  13625. locked = false;
  13626. currentDepthMask = null;
  13627. currentDepthFunc = null;
  13628. currentDepthClear = null;
  13629. }
  13630. };
  13631. }
  13632. function StencilBuffer() {
  13633. let locked = false;
  13634. let currentStencilMask = null;
  13635. let currentStencilFunc = null;
  13636. let currentStencilRef = null;
  13637. let currentStencilFuncMask = null;
  13638. let currentStencilFail = null;
  13639. let currentStencilZFail = null;
  13640. let currentStencilZPass = null;
  13641. let currentStencilClear = null;
  13642. return {
  13643. setTest: function ( stencilTest ) {
  13644. if ( ! locked ) {
  13645. if ( stencilTest ) {
  13646. enable( gl.STENCIL_TEST );
  13647. } else {
  13648. disable( gl.STENCIL_TEST );
  13649. }
  13650. }
  13651. },
  13652. setMask: function ( stencilMask ) {
  13653. if ( currentStencilMask !== stencilMask && ! locked ) {
  13654. gl.stencilMask( stencilMask );
  13655. currentStencilMask = stencilMask;
  13656. }
  13657. },
  13658. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13659. if ( currentStencilFunc !== stencilFunc ||
  13660. currentStencilRef !== stencilRef ||
  13661. currentStencilFuncMask !== stencilMask ) {
  13662. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13663. currentStencilFunc = stencilFunc;
  13664. currentStencilRef = stencilRef;
  13665. currentStencilFuncMask = stencilMask;
  13666. }
  13667. },
  13668. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13669. if ( currentStencilFail !== stencilFail ||
  13670. currentStencilZFail !== stencilZFail ||
  13671. currentStencilZPass !== stencilZPass ) {
  13672. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13673. currentStencilFail = stencilFail;
  13674. currentStencilZFail = stencilZFail;
  13675. currentStencilZPass = stencilZPass;
  13676. }
  13677. },
  13678. setLocked: function ( lock ) {
  13679. locked = lock;
  13680. },
  13681. setClear: function ( stencil ) {
  13682. if ( currentStencilClear !== stencil ) {
  13683. gl.clearStencil( stencil );
  13684. currentStencilClear = stencil;
  13685. }
  13686. },
  13687. reset: function () {
  13688. locked = false;
  13689. currentStencilMask = null;
  13690. currentStencilFunc = null;
  13691. currentStencilRef = null;
  13692. currentStencilFuncMask = null;
  13693. currentStencilFail = null;
  13694. currentStencilZFail = null;
  13695. currentStencilZPass = null;
  13696. currentStencilClear = null;
  13697. }
  13698. };
  13699. }
  13700. //
  13701. const colorBuffer = new ColorBuffer();
  13702. const depthBuffer = new DepthBuffer();
  13703. const stencilBuffer = new StencilBuffer();
  13704. const uboBindings = new WeakMap();
  13705. const uboProgramMap = new WeakMap();
  13706. let enabledCapabilities = {};
  13707. let currentBoundFramebuffers = {};
  13708. let currentDrawbuffers = new WeakMap();
  13709. let defaultDrawbuffers = [];
  13710. let currentProgram = null;
  13711. let currentBlendingEnabled = false;
  13712. let currentBlending = null;
  13713. let currentBlendEquation = null;
  13714. let currentBlendSrc = null;
  13715. let currentBlendDst = null;
  13716. let currentBlendEquationAlpha = null;
  13717. let currentBlendSrcAlpha = null;
  13718. let currentBlendDstAlpha = null;
  13719. let currentBlendColor = new Color( 0, 0, 0 );
  13720. let currentBlendAlpha = 0;
  13721. let currentPremultipledAlpha = false;
  13722. let currentFlipSided = null;
  13723. let currentCullFace = null;
  13724. let currentLineWidth = null;
  13725. let currentPolygonOffsetFactor = null;
  13726. let currentPolygonOffsetUnits = null;
  13727. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13728. let lineWidthAvailable = false;
  13729. let version = 0;
  13730. const glVersion = gl.getParameter( gl.VERSION );
  13731. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13732. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13733. lineWidthAvailable = ( version >= 1.0 );
  13734. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13735. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13736. lineWidthAvailable = ( version >= 2.0 );
  13737. }
  13738. let currentTextureSlot = null;
  13739. let currentBoundTextures = {};
  13740. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13741. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13742. const currentScissor = new Vector4().fromArray( scissorParam );
  13743. const currentViewport = new Vector4().fromArray( viewportParam );
  13744. function createTexture( type, target, count, dimensions ) {
  13745. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13746. const texture = gl.createTexture();
  13747. gl.bindTexture( type, texture );
  13748. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13749. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13750. for ( let i = 0; i < count; i ++ ) {
  13751. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  13752. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13753. } else {
  13754. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13755. }
  13756. }
  13757. return texture;
  13758. }
  13759. const emptyTextures = {};
  13760. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13761. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13762. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13763. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13764. // init
  13765. colorBuffer.setClear( 0, 0, 0, 1 );
  13766. depthBuffer.setClear( 1 );
  13767. stencilBuffer.setClear( 0 );
  13768. enable( gl.DEPTH_TEST );
  13769. depthBuffer.setFunc( LessEqualDepth );
  13770. setFlipSided( false );
  13771. setCullFace( CullFaceBack );
  13772. enable( gl.CULL_FACE );
  13773. setBlending( NoBlending );
  13774. //
  13775. function enable( id ) {
  13776. if ( enabledCapabilities[ id ] !== true ) {
  13777. gl.enable( id );
  13778. enabledCapabilities[ id ] = true;
  13779. }
  13780. }
  13781. function disable( id ) {
  13782. if ( enabledCapabilities[ id ] !== false ) {
  13783. gl.disable( id );
  13784. enabledCapabilities[ id ] = false;
  13785. }
  13786. }
  13787. function bindFramebuffer( target, framebuffer ) {
  13788. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13789. gl.bindFramebuffer( target, framebuffer );
  13790. currentBoundFramebuffers[ target ] = framebuffer;
  13791. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13792. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13793. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13794. }
  13795. if ( target === gl.FRAMEBUFFER ) {
  13796. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13797. }
  13798. return true;
  13799. }
  13800. return false;
  13801. }
  13802. function drawBuffers( renderTarget, framebuffer ) {
  13803. let drawBuffers = defaultDrawbuffers;
  13804. let needsUpdate = false;
  13805. if ( renderTarget ) {
  13806. drawBuffers = currentDrawbuffers.get( framebuffer );
  13807. if ( drawBuffers === undefined ) {
  13808. drawBuffers = [];
  13809. currentDrawbuffers.set( framebuffer, drawBuffers );
  13810. }
  13811. const textures = renderTarget.textures;
  13812. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13813. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13814. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13815. }
  13816. drawBuffers.length = textures.length;
  13817. needsUpdate = true;
  13818. }
  13819. } else {
  13820. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13821. drawBuffers[ 0 ] = gl.BACK;
  13822. needsUpdate = true;
  13823. }
  13824. }
  13825. if ( needsUpdate ) {
  13826. gl.drawBuffers( drawBuffers );
  13827. }
  13828. }
  13829. function useProgram( program ) {
  13830. if ( currentProgram !== program ) {
  13831. gl.useProgram( program );
  13832. currentProgram = program;
  13833. return true;
  13834. }
  13835. return false;
  13836. }
  13837. const equationToGL = {
  13838. [ AddEquation ]: gl.FUNC_ADD,
  13839. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13840. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13841. };
  13842. equationToGL[ MinEquation ] = gl.MIN;
  13843. equationToGL[ MaxEquation ] = gl.MAX;
  13844. const factorToGL = {
  13845. [ ZeroFactor ]: gl.ZERO,
  13846. [ OneFactor ]: gl.ONE,
  13847. [ SrcColorFactor ]: gl.SRC_COLOR,
  13848. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13849. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13850. [ DstColorFactor ]: gl.DST_COLOR,
  13851. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13852. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13853. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13854. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13855. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  13856. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  13857. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  13858. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  13859. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  13860. };
  13861. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  13862. if ( blending === NoBlending ) {
  13863. if ( currentBlendingEnabled === true ) {
  13864. disable( gl.BLEND );
  13865. currentBlendingEnabled = false;
  13866. }
  13867. return;
  13868. }
  13869. if ( currentBlendingEnabled === false ) {
  13870. enable( gl.BLEND );
  13871. currentBlendingEnabled = true;
  13872. }
  13873. if ( blending !== CustomBlending ) {
  13874. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13875. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13876. gl.blendEquation( gl.FUNC_ADD );
  13877. currentBlendEquation = AddEquation;
  13878. currentBlendEquationAlpha = AddEquation;
  13879. }
  13880. if ( premultipliedAlpha ) {
  13881. switch ( blending ) {
  13882. case NormalBlending:
  13883. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13884. break;
  13885. case AdditiveBlending:
  13886. gl.blendFunc( gl.ONE, gl.ONE );
  13887. break;
  13888. case SubtractiveBlending:
  13889. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13890. break;
  13891. case MultiplyBlending:
  13892. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13893. break;
  13894. default:
  13895. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13896. break;
  13897. }
  13898. } else {
  13899. switch ( blending ) {
  13900. case NormalBlending:
  13901. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13902. break;
  13903. case AdditiveBlending:
  13904. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13905. break;
  13906. case SubtractiveBlending:
  13907. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13908. break;
  13909. case MultiplyBlending:
  13910. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13911. break;
  13912. default:
  13913. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13914. break;
  13915. }
  13916. }
  13917. currentBlendSrc = null;
  13918. currentBlendDst = null;
  13919. currentBlendSrcAlpha = null;
  13920. currentBlendDstAlpha = null;
  13921. currentBlendColor.set( 0, 0, 0 );
  13922. currentBlendAlpha = 0;
  13923. currentBlending = blending;
  13924. currentPremultipledAlpha = premultipliedAlpha;
  13925. }
  13926. return;
  13927. }
  13928. // custom blending
  13929. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13930. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13931. blendDstAlpha = blendDstAlpha || blendDst;
  13932. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13933. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13934. currentBlendEquation = blendEquation;
  13935. currentBlendEquationAlpha = blendEquationAlpha;
  13936. }
  13937. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13938. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13939. currentBlendSrc = blendSrc;
  13940. currentBlendDst = blendDst;
  13941. currentBlendSrcAlpha = blendSrcAlpha;
  13942. currentBlendDstAlpha = blendDstAlpha;
  13943. }
  13944. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  13945. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  13946. currentBlendColor.copy( blendColor );
  13947. currentBlendAlpha = blendAlpha;
  13948. }
  13949. currentBlending = blending;
  13950. currentPremultipledAlpha = false;
  13951. }
  13952. function setMaterial( material, frontFaceCW ) {
  13953. material.side === DoubleSide
  13954. ? disable( gl.CULL_FACE )
  13955. : enable( gl.CULL_FACE );
  13956. let flipSided = ( material.side === BackSide );
  13957. if ( frontFaceCW ) flipSided = ! flipSided;
  13958. setFlipSided( flipSided );
  13959. ( material.blending === NormalBlending && material.transparent === false )
  13960. ? setBlending( NoBlending )
  13961. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  13962. depthBuffer.setFunc( material.depthFunc );
  13963. depthBuffer.setTest( material.depthTest );
  13964. depthBuffer.setMask( material.depthWrite );
  13965. colorBuffer.setMask( material.colorWrite );
  13966. const stencilWrite = material.stencilWrite;
  13967. stencilBuffer.setTest( stencilWrite );
  13968. if ( stencilWrite ) {
  13969. stencilBuffer.setMask( material.stencilWriteMask );
  13970. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13971. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13972. }
  13973. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13974. material.alphaToCoverage === true
  13975. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13976. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13977. }
  13978. //
  13979. function setFlipSided( flipSided ) {
  13980. if ( currentFlipSided !== flipSided ) {
  13981. if ( flipSided ) {
  13982. gl.frontFace( gl.CW );
  13983. } else {
  13984. gl.frontFace( gl.CCW );
  13985. }
  13986. currentFlipSided = flipSided;
  13987. }
  13988. }
  13989. function setCullFace( cullFace ) {
  13990. if ( cullFace !== CullFaceNone ) {
  13991. enable( gl.CULL_FACE );
  13992. if ( cullFace !== currentCullFace ) {
  13993. if ( cullFace === CullFaceBack ) {
  13994. gl.cullFace( gl.BACK );
  13995. } else if ( cullFace === CullFaceFront ) {
  13996. gl.cullFace( gl.FRONT );
  13997. } else {
  13998. gl.cullFace( gl.FRONT_AND_BACK );
  13999. }
  14000. }
  14001. } else {
  14002. disable( gl.CULL_FACE );
  14003. }
  14004. currentCullFace = cullFace;
  14005. }
  14006. function setLineWidth( width ) {
  14007. if ( width !== currentLineWidth ) {
  14008. if ( lineWidthAvailable ) gl.lineWidth( width );
  14009. currentLineWidth = width;
  14010. }
  14011. }
  14012. function setPolygonOffset( polygonOffset, factor, units ) {
  14013. if ( polygonOffset ) {
  14014. enable( gl.POLYGON_OFFSET_FILL );
  14015. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  14016. gl.polygonOffset( factor, units );
  14017. currentPolygonOffsetFactor = factor;
  14018. currentPolygonOffsetUnits = units;
  14019. }
  14020. } else {
  14021. disable( gl.POLYGON_OFFSET_FILL );
  14022. }
  14023. }
  14024. function setScissorTest( scissorTest ) {
  14025. if ( scissorTest ) {
  14026. enable( gl.SCISSOR_TEST );
  14027. } else {
  14028. disable( gl.SCISSOR_TEST );
  14029. }
  14030. }
  14031. // texture
  14032. function activeTexture( webglSlot ) {
  14033. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14034. if ( currentTextureSlot !== webglSlot ) {
  14035. gl.activeTexture( webglSlot );
  14036. currentTextureSlot = webglSlot;
  14037. }
  14038. }
  14039. function bindTexture( webglType, webglTexture, webglSlot ) {
  14040. if ( webglSlot === undefined ) {
  14041. if ( currentTextureSlot === null ) {
  14042. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14043. } else {
  14044. webglSlot = currentTextureSlot;
  14045. }
  14046. }
  14047. let boundTexture = currentBoundTextures[ webglSlot ];
  14048. if ( boundTexture === undefined ) {
  14049. boundTexture = { type: undefined, texture: undefined };
  14050. currentBoundTextures[ webglSlot ] = boundTexture;
  14051. }
  14052. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14053. if ( currentTextureSlot !== webglSlot ) {
  14054. gl.activeTexture( webglSlot );
  14055. currentTextureSlot = webglSlot;
  14056. }
  14057. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14058. boundTexture.type = webglType;
  14059. boundTexture.texture = webglTexture;
  14060. }
  14061. }
  14062. function unbindTexture() {
  14063. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  14064. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  14065. gl.bindTexture( boundTexture.type, null );
  14066. boundTexture.type = undefined;
  14067. boundTexture.texture = undefined;
  14068. }
  14069. }
  14070. function compressedTexImage2D() {
  14071. try {
  14072. gl.compressedTexImage2D.apply( gl, arguments );
  14073. } catch ( error ) {
  14074. console.error( 'THREE.WebGLState:', error );
  14075. }
  14076. }
  14077. function compressedTexImage3D() {
  14078. try {
  14079. gl.compressedTexImage3D.apply( gl, arguments );
  14080. } catch ( error ) {
  14081. console.error( 'THREE.WebGLState:', error );
  14082. }
  14083. }
  14084. function texSubImage2D() {
  14085. try {
  14086. gl.texSubImage2D.apply( gl, arguments );
  14087. } catch ( error ) {
  14088. console.error( 'THREE.WebGLState:', error );
  14089. }
  14090. }
  14091. function texSubImage3D() {
  14092. try {
  14093. gl.texSubImage3D.apply( gl, arguments );
  14094. } catch ( error ) {
  14095. console.error( 'THREE.WebGLState:', error );
  14096. }
  14097. }
  14098. function compressedTexSubImage2D() {
  14099. try {
  14100. gl.compressedTexSubImage2D.apply( gl, arguments );
  14101. } catch ( error ) {
  14102. console.error( 'THREE.WebGLState:', error );
  14103. }
  14104. }
  14105. function compressedTexSubImage3D() {
  14106. try {
  14107. gl.compressedTexSubImage3D.apply( gl, arguments );
  14108. } catch ( error ) {
  14109. console.error( 'THREE.WebGLState:', error );
  14110. }
  14111. }
  14112. function texStorage2D() {
  14113. try {
  14114. gl.texStorage2D.apply( gl, arguments );
  14115. } catch ( error ) {
  14116. console.error( 'THREE.WebGLState:', error );
  14117. }
  14118. }
  14119. function texStorage3D() {
  14120. try {
  14121. gl.texStorage3D.apply( gl, arguments );
  14122. } catch ( error ) {
  14123. console.error( 'THREE.WebGLState:', error );
  14124. }
  14125. }
  14126. function texImage2D() {
  14127. try {
  14128. gl.texImage2D.apply( gl, arguments );
  14129. } catch ( error ) {
  14130. console.error( 'THREE.WebGLState:', error );
  14131. }
  14132. }
  14133. function texImage3D() {
  14134. try {
  14135. gl.texImage3D.apply( gl, arguments );
  14136. } catch ( error ) {
  14137. console.error( 'THREE.WebGLState:', error );
  14138. }
  14139. }
  14140. //
  14141. function scissor( scissor ) {
  14142. if ( currentScissor.equals( scissor ) === false ) {
  14143. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14144. currentScissor.copy( scissor );
  14145. }
  14146. }
  14147. function viewport( viewport ) {
  14148. if ( currentViewport.equals( viewport ) === false ) {
  14149. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14150. currentViewport.copy( viewport );
  14151. }
  14152. }
  14153. function updateUBOMapping( uniformsGroup, program ) {
  14154. let mapping = uboProgramMap.get( program );
  14155. if ( mapping === undefined ) {
  14156. mapping = new WeakMap();
  14157. uboProgramMap.set( program, mapping );
  14158. }
  14159. let blockIndex = mapping.get( uniformsGroup );
  14160. if ( blockIndex === undefined ) {
  14161. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14162. mapping.set( uniformsGroup, blockIndex );
  14163. }
  14164. }
  14165. function uniformBlockBinding( uniformsGroup, program ) {
  14166. const mapping = uboProgramMap.get( program );
  14167. const blockIndex = mapping.get( uniformsGroup );
  14168. if ( uboBindings.get( program ) !== blockIndex ) {
  14169. // bind shader specific block index to global block point
  14170. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14171. uboBindings.set( program, blockIndex );
  14172. }
  14173. }
  14174. //
  14175. function reset() {
  14176. // reset state
  14177. gl.disable( gl.BLEND );
  14178. gl.disable( gl.CULL_FACE );
  14179. gl.disable( gl.DEPTH_TEST );
  14180. gl.disable( gl.POLYGON_OFFSET_FILL );
  14181. gl.disable( gl.SCISSOR_TEST );
  14182. gl.disable( gl.STENCIL_TEST );
  14183. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14184. gl.blendEquation( gl.FUNC_ADD );
  14185. gl.blendFunc( gl.ONE, gl.ZERO );
  14186. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14187. gl.blendColor( 0, 0, 0, 0 );
  14188. gl.colorMask( true, true, true, true );
  14189. gl.clearColor( 0, 0, 0, 0 );
  14190. gl.depthMask( true );
  14191. gl.depthFunc( gl.LESS );
  14192. gl.clearDepth( 1 );
  14193. gl.stencilMask( 0xffffffff );
  14194. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14195. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14196. gl.clearStencil( 0 );
  14197. gl.cullFace( gl.BACK );
  14198. gl.frontFace( gl.CCW );
  14199. gl.polygonOffset( 0, 0 );
  14200. gl.activeTexture( gl.TEXTURE0 );
  14201. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14202. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14203. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14204. gl.useProgram( null );
  14205. gl.lineWidth( 1 );
  14206. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14207. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14208. // reset internals
  14209. enabledCapabilities = {};
  14210. currentTextureSlot = null;
  14211. currentBoundTextures = {};
  14212. currentBoundFramebuffers = {};
  14213. currentDrawbuffers = new WeakMap();
  14214. defaultDrawbuffers = [];
  14215. currentProgram = null;
  14216. currentBlendingEnabled = false;
  14217. currentBlending = null;
  14218. currentBlendEquation = null;
  14219. currentBlendSrc = null;
  14220. currentBlendDst = null;
  14221. currentBlendEquationAlpha = null;
  14222. currentBlendSrcAlpha = null;
  14223. currentBlendDstAlpha = null;
  14224. currentBlendColor = new Color( 0, 0, 0 );
  14225. currentBlendAlpha = 0;
  14226. currentPremultipledAlpha = false;
  14227. currentFlipSided = null;
  14228. currentCullFace = null;
  14229. currentLineWidth = null;
  14230. currentPolygonOffsetFactor = null;
  14231. currentPolygonOffsetUnits = null;
  14232. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14233. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14234. colorBuffer.reset();
  14235. depthBuffer.reset();
  14236. stencilBuffer.reset();
  14237. }
  14238. return {
  14239. buffers: {
  14240. color: colorBuffer,
  14241. depth: depthBuffer,
  14242. stencil: stencilBuffer
  14243. },
  14244. enable: enable,
  14245. disable: disable,
  14246. bindFramebuffer: bindFramebuffer,
  14247. drawBuffers: drawBuffers,
  14248. useProgram: useProgram,
  14249. setBlending: setBlending,
  14250. setMaterial: setMaterial,
  14251. setFlipSided: setFlipSided,
  14252. setCullFace: setCullFace,
  14253. setLineWidth: setLineWidth,
  14254. setPolygonOffset: setPolygonOffset,
  14255. setScissorTest: setScissorTest,
  14256. activeTexture: activeTexture,
  14257. bindTexture: bindTexture,
  14258. unbindTexture: unbindTexture,
  14259. compressedTexImage2D: compressedTexImage2D,
  14260. compressedTexImage3D: compressedTexImage3D,
  14261. texImage2D: texImage2D,
  14262. texImage3D: texImage3D,
  14263. updateUBOMapping: updateUBOMapping,
  14264. uniformBlockBinding: uniformBlockBinding,
  14265. texStorage2D: texStorage2D,
  14266. texStorage3D: texStorage3D,
  14267. texSubImage2D: texSubImage2D,
  14268. texSubImage3D: texSubImage3D,
  14269. compressedTexSubImage2D: compressedTexSubImage2D,
  14270. compressedTexSubImage3D: compressedTexSubImage3D,
  14271. scissor: scissor,
  14272. viewport: viewport,
  14273. reset: reset
  14274. };
  14275. }
  14276. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14277. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14278. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14279. const _imageDimensions = new Vector2();
  14280. const _videoTextures = new WeakMap();
  14281. let _canvas;
  14282. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14283. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14284. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14285. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14286. let useOffscreenCanvas = false;
  14287. try {
  14288. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14289. // eslint-disable-next-line compat/compat
  14290. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14291. } catch ( err ) {
  14292. // Ignore any errors
  14293. }
  14294. function createCanvas( width, height ) {
  14295. // Use OffscreenCanvas when available. Specially needed in web workers
  14296. return useOffscreenCanvas ?
  14297. // eslint-disable-next-line compat/compat
  14298. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14299. }
  14300. function resizeImage( image, needsNewCanvas, maxSize ) {
  14301. let scale = 1;
  14302. const dimensions = getDimensions( image );
  14303. // handle case if texture exceeds max size
  14304. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  14305. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  14306. }
  14307. // only perform resize if necessary
  14308. if ( scale < 1 ) {
  14309. // only perform resize for certain image types
  14310. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14311. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14312. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  14313. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  14314. const width = Math.floor( scale * dimensions.width );
  14315. const height = Math.floor( scale * dimensions.height );
  14316. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14317. // cube textures can't reuse the same canvas
  14318. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14319. canvas.width = width;
  14320. canvas.height = height;
  14321. const context = canvas.getContext( '2d' );
  14322. context.drawImage( image, 0, 0, width, height );
  14323. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  14324. return canvas;
  14325. } else {
  14326. if ( 'data' in image ) {
  14327. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  14328. }
  14329. return image;
  14330. }
  14331. }
  14332. return image;
  14333. }
  14334. function textureNeedsGenerateMipmaps( texture ) {
  14335. return texture.generateMipmaps && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14336. }
  14337. function generateMipmap( target ) {
  14338. _gl.generateMipmap( target );
  14339. }
  14340. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14341. if ( internalFormatName !== null ) {
  14342. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14343. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14344. }
  14345. let internalFormat = glFormat;
  14346. if ( glFormat === _gl.RED ) {
  14347. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14348. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14349. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14350. }
  14351. if ( glFormat === _gl.RED_INTEGER ) {
  14352. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  14353. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  14354. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  14355. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  14356. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  14357. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  14358. }
  14359. if ( glFormat === _gl.RG ) {
  14360. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14361. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14362. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14363. }
  14364. if ( glFormat === _gl.RG_INTEGER ) {
  14365. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  14366. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  14367. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  14368. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  14369. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  14370. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  14371. }
  14372. if ( glFormat === _gl.RGB ) {
  14373. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  14374. }
  14375. if ( glFormat === _gl.RGBA ) {
  14376. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  14377. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14378. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14379. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14380. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14381. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14382. }
  14383. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14384. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14385. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14386. extensions.get( 'EXT_color_buffer_float' );
  14387. }
  14388. return internalFormat;
  14389. }
  14390. function getMipLevels( texture, image ) {
  14391. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14392. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14393. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14394. // user-defined mipmaps
  14395. return texture.mipmaps.length;
  14396. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14397. return image.mipmaps.length;
  14398. } else {
  14399. // texture without mipmaps (only base level)
  14400. return 1;
  14401. }
  14402. }
  14403. //
  14404. function onTextureDispose( event ) {
  14405. const texture = event.target;
  14406. texture.removeEventListener( 'dispose', onTextureDispose );
  14407. deallocateTexture( texture );
  14408. if ( texture.isVideoTexture ) {
  14409. _videoTextures.delete( texture );
  14410. }
  14411. }
  14412. function onRenderTargetDispose( event ) {
  14413. const renderTarget = event.target;
  14414. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14415. deallocateRenderTarget( renderTarget );
  14416. }
  14417. //
  14418. function deallocateTexture( texture ) {
  14419. const textureProperties = properties.get( texture );
  14420. if ( textureProperties.__webglInit === undefined ) return;
  14421. // check if it's necessary to remove the WebGLTexture object
  14422. const source = texture.source;
  14423. const webglTextures = _sources.get( source );
  14424. if ( webglTextures ) {
  14425. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14426. webglTexture.usedTimes --;
  14427. // the WebGLTexture object is not used anymore, remove it
  14428. if ( webglTexture.usedTimes === 0 ) {
  14429. deleteTexture( texture );
  14430. }
  14431. // remove the weak map entry if no WebGLTexture uses the source anymore
  14432. if ( Object.keys( webglTextures ).length === 0 ) {
  14433. _sources.delete( source );
  14434. }
  14435. }
  14436. properties.remove( texture );
  14437. }
  14438. function deleteTexture( texture ) {
  14439. const textureProperties = properties.get( texture );
  14440. _gl.deleteTexture( textureProperties.__webglTexture );
  14441. const source = texture.source;
  14442. const webglTextures = _sources.get( source );
  14443. delete webglTextures[ textureProperties.__cacheKey ];
  14444. info.memory.textures --;
  14445. }
  14446. function deallocateRenderTarget( renderTarget ) {
  14447. const renderTargetProperties = properties.get( renderTarget );
  14448. if ( renderTarget.depthTexture ) {
  14449. renderTarget.depthTexture.dispose();
  14450. }
  14451. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14452. for ( let i = 0; i < 6; i ++ ) {
  14453. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  14454. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  14455. } else {
  14456. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14457. }
  14458. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14459. }
  14460. } else {
  14461. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  14462. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  14463. } else {
  14464. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14465. }
  14466. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14467. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14468. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14469. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14470. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14471. }
  14472. }
  14473. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14474. }
  14475. const textures = renderTarget.textures;
  14476. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14477. const attachmentProperties = properties.get( textures[ i ] );
  14478. if ( attachmentProperties.__webglTexture ) {
  14479. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14480. info.memory.textures --;
  14481. }
  14482. properties.remove( textures[ i ] );
  14483. }
  14484. properties.remove( renderTarget );
  14485. }
  14486. //
  14487. let textureUnits = 0;
  14488. function resetTextureUnits() {
  14489. textureUnits = 0;
  14490. }
  14491. function allocateTextureUnit() {
  14492. const textureUnit = textureUnits;
  14493. if ( textureUnit >= capabilities.maxTextures ) {
  14494. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  14495. }
  14496. textureUnits += 1;
  14497. return textureUnit;
  14498. }
  14499. function getTextureCacheKey( texture ) {
  14500. const array = [];
  14501. array.push( texture.wrapS );
  14502. array.push( texture.wrapT );
  14503. array.push( texture.wrapR || 0 );
  14504. array.push( texture.magFilter );
  14505. array.push( texture.minFilter );
  14506. array.push( texture.anisotropy );
  14507. array.push( texture.internalFormat );
  14508. array.push( texture.format );
  14509. array.push( texture.type );
  14510. array.push( texture.generateMipmaps );
  14511. array.push( texture.premultiplyAlpha );
  14512. array.push( texture.flipY );
  14513. array.push( texture.unpackAlignment );
  14514. array.push( texture.colorSpace );
  14515. return array.join();
  14516. }
  14517. //
  14518. function setTexture2D( texture, slot ) {
  14519. const textureProperties = properties.get( texture );
  14520. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14521. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14522. const image = texture.image;
  14523. if ( image === null ) {
  14524. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14525. } else if ( image.complete === false ) {
  14526. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14527. } else {
  14528. uploadTexture( textureProperties, texture, slot );
  14529. return;
  14530. }
  14531. }
  14532. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14533. }
  14534. function setTexture2DArray( texture, slot ) {
  14535. const textureProperties = properties.get( texture );
  14536. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14537. uploadTexture( textureProperties, texture, slot );
  14538. return;
  14539. }
  14540. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14541. }
  14542. function setTexture3D( texture, slot ) {
  14543. const textureProperties = properties.get( texture );
  14544. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14545. uploadTexture( textureProperties, texture, slot );
  14546. return;
  14547. }
  14548. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14549. }
  14550. function setTextureCube( texture, slot ) {
  14551. const textureProperties = properties.get( texture );
  14552. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14553. uploadCubeTexture( textureProperties, texture, slot );
  14554. return;
  14555. }
  14556. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14557. }
  14558. const wrappingToGL = {
  14559. [ RepeatWrapping ]: _gl.REPEAT,
  14560. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14561. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14562. };
  14563. const filterToGL = {
  14564. [ NearestFilter ]: _gl.NEAREST,
  14565. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14566. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14567. [ LinearFilter ]: _gl.LINEAR,
  14568. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14569. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14570. };
  14571. const compareToGL = {
  14572. [ NeverCompare ]: _gl.NEVER,
  14573. [ AlwaysCompare ]: _gl.ALWAYS,
  14574. [ LessCompare ]: _gl.LESS,
  14575. [ LessEqualCompare ]: _gl.LEQUAL,
  14576. [ EqualCompare ]: _gl.EQUAL,
  14577. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14578. [ GreaterCompare ]: _gl.GREATER,
  14579. [ NotEqualCompare ]: _gl.NOTEQUAL
  14580. };
  14581. function setTextureParameters( textureType, texture ) {
  14582. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  14583. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  14584. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  14585. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  14586. }
  14587. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14588. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14589. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14590. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14591. }
  14592. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14593. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14594. if ( texture.compareFunction ) {
  14595. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14596. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14597. }
  14598. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14599. if ( texture.magFilter === NearestFilter ) return;
  14600. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14601. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  14602. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14603. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14604. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14605. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14606. }
  14607. }
  14608. }
  14609. function initTexture( textureProperties, texture ) {
  14610. let forceUpload = false;
  14611. if ( textureProperties.__webglInit === undefined ) {
  14612. textureProperties.__webglInit = true;
  14613. texture.addEventListener( 'dispose', onTextureDispose );
  14614. }
  14615. // create Source <-> WebGLTextures mapping if necessary
  14616. const source = texture.source;
  14617. let webglTextures = _sources.get( source );
  14618. if ( webglTextures === undefined ) {
  14619. webglTextures = {};
  14620. _sources.set( source, webglTextures );
  14621. }
  14622. // check if there is already a WebGLTexture object for the given texture parameters
  14623. const textureCacheKey = getTextureCacheKey( texture );
  14624. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14625. // if not, create a new instance of WebGLTexture
  14626. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14627. // create new entry
  14628. webglTextures[ textureCacheKey ] = {
  14629. texture: _gl.createTexture(),
  14630. usedTimes: 0
  14631. };
  14632. info.memory.textures ++;
  14633. // when a new instance of WebGLTexture was created, a texture upload is required
  14634. // even if the image contents are identical
  14635. forceUpload = true;
  14636. }
  14637. webglTextures[ textureCacheKey ].usedTimes ++;
  14638. // every time the texture cache key changes, it's necessary to check if an instance of
  14639. // WebGLTexture can be deleted in order to avoid a memory leak.
  14640. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14641. if ( webglTexture !== undefined ) {
  14642. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14643. if ( webglTexture.usedTimes === 0 ) {
  14644. deleteTexture( texture );
  14645. }
  14646. }
  14647. // store references to cache key and WebGLTexture object
  14648. textureProperties.__cacheKey = textureCacheKey;
  14649. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14650. }
  14651. return forceUpload;
  14652. }
  14653. function uploadTexture( textureProperties, texture, slot ) {
  14654. let textureType = _gl.TEXTURE_2D;
  14655. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14656. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14657. const forceUpload = initTexture( textureProperties, texture );
  14658. const source = texture.source;
  14659. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14660. const sourceProperties = properties.get( source );
  14661. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14662. state.activeTexture( _gl.TEXTURE0 + slot );
  14663. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14664. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14665. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14666. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14667. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14668. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14669. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14670. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  14671. image = verifyColorSpace( texture, image );
  14672. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14673. const glType = utils.convert( texture.type );
  14674. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  14675. setTextureParameters( textureType, texture );
  14676. let mipmap;
  14677. const mipmaps = texture.mipmaps;
  14678. const useTexStorage = ( texture.isVideoTexture !== true );
  14679. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14680. const dataReady = source.dataReady;
  14681. const levels = getMipLevels( texture, image );
  14682. if ( texture.isDepthTexture ) {
  14683. // populate depth texture with dummy data
  14684. glInternalFormat = _gl.DEPTH_COMPONENT16;
  14685. if ( texture.type === FloatType ) {
  14686. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14687. } else if ( texture.type === UnsignedIntType ) {
  14688. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14689. } else if ( texture.type === UnsignedInt248Type ) {
  14690. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14691. }
  14692. //
  14693. if ( allocateMemory ) {
  14694. if ( useTexStorage ) {
  14695. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14696. } else {
  14697. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14698. }
  14699. }
  14700. } else if ( texture.isDataTexture ) {
  14701. // use manually created mipmaps if available
  14702. // if there are no manual mipmaps
  14703. // set 0 level mipmap and then use GL to generate other mipmap levels
  14704. if ( mipmaps.length > 0 ) {
  14705. if ( useTexStorage && allocateMemory ) {
  14706. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14707. }
  14708. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14709. mipmap = mipmaps[ i ];
  14710. if ( useTexStorage ) {
  14711. if ( dataReady ) {
  14712. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14713. }
  14714. } else {
  14715. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14716. }
  14717. }
  14718. texture.generateMipmaps = false;
  14719. } else {
  14720. if ( useTexStorage ) {
  14721. if ( allocateMemory ) {
  14722. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14723. }
  14724. if ( dataReady ) {
  14725. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14726. }
  14727. } else {
  14728. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14729. }
  14730. }
  14731. } else if ( texture.isCompressedTexture ) {
  14732. if ( texture.isCompressedArrayTexture ) {
  14733. if ( useTexStorage && allocateMemory ) {
  14734. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14735. }
  14736. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14737. mipmap = mipmaps[ i ];
  14738. if ( texture.format !== RGBAFormat ) {
  14739. if ( glFormat !== null ) {
  14740. if ( useTexStorage ) {
  14741. if ( dataReady ) {
  14742. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14743. }
  14744. } else {
  14745. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14746. }
  14747. } else {
  14748. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14749. }
  14750. } else {
  14751. if ( useTexStorage ) {
  14752. if ( dataReady ) {
  14753. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14754. }
  14755. } else {
  14756. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14757. }
  14758. }
  14759. }
  14760. } else {
  14761. if ( useTexStorage && allocateMemory ) {
  14762. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14763. }
  14764. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14765. mipmap = mipmaps[ i ];
  14766. if ( texture.format !== RGBAFormat ) {
  14767. if ( glFormat !== null ) {
  14768. if ( useTexStorage ) {
  14769. if ( dataReady ) {
  14770. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14771. }
  14772. } else {
  14773. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14774. }
  14775. } else {
  14776. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14777. }
  14778. } else {
  14779. if ( useTexStorage ) {
  14780. if ( dataReady ) {
  14781. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14782. }
  14783. } else {
  14784. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14785. }
  14786. }
  14787. }
  14788. }
  14789. } else if ( texture.isDataArrayTexture ) {
  14790. if ( useTexStorage ) {
  14791. if ( allocateMemory ) {
  14792. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14793. }
  14794. if ( dataReady ) {
  14795. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14796. }
  14797. } else {
  14798. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14799. }
  14800. } else if ( texture.isData3DTexture ) {
  14801. if ( useTexStorage ) {
  14802. if ( allocateMemory ) {
  14803. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14804. }
  14805. if ( dataReady ) {
  14806. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14807. }
  14808. } else {
  14809. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14810. }
  14811. } else if ( texture.isFramebufferTexture ) {
  14812. if ( allocateMemory ) {
  14813. if ( useTexStorage ) {
  14814. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14815. } else {
  14816. let width = image.width, height = image.height;
  14817. for ( let i = 0; i < levels; i ++ ) {
  14818. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14819. width >>= 1;
  14820. height >>= 1;
  14821. }
  14822. }
  14823. }
  14824. } else {
  14825. // regular Texture (image, video, canvas)
  14826. // use manually created mipmaps if available
  14827. // if there are no manual mipmaps
  14828. // set 0 level mipmap and then use GL to generate other mipmap levels
  14829. if ( mipmaps.length > 0 ) {
  14830. if ( useTexStorage && allocateMemory ) {
  14831. const dimensions = getDimensions( mipmaps[ 0 ] );
  14832. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  14833. }
  14834. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14835. mipmap = mipmaps[ i ];
  14836. if ( useTexStorage ) {
  14837. if ( dataReady ) {
  14838. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14839. }
  14840. } else {
  14841. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14842. }
  14843. }
  14844. texture.generateMipmaps = false;
  14845. } else {
  14846. if ( useTexStorage ) {
  14847. if ( allocateMemory ) {
  14848. const dimensions = getDimensions( image );
  14849. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  14850. }
  14851. if ( dataReady ) {
  14852. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14853. }
  14854. } else {
  14855. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14856. }
  14857. }
  14858. }
  14859. if ( textureNeedsGenerateMipmaps( texture ) ) {
  14860. generateMipmap( textureType );
  14861. }
  14862. sourceProperties.__version = source.version;
  14863. if ( texture.onUpdate ) texture.onUpdate( texture );
  14864. }
  14865. textureProperties.__version = texture.version;
  14866. }
  14867. function uploadCubeTexture( textureProperties, texture, slot ) {
  14868. if ( texture.image.length !== 6 ) return;
  14869. const forceUpload = initTexture( textureProperties, texture );
  14870. const source = texture.source;
  14871. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14872. const sourceProperties = properties.get( source );
  14873. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14874. state.activeTexture( _gl.TEXTURE0 + slot );
  14875. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14876. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14877. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14878. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14879. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14880. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14881. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14882. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14883. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14884. const cubeImage = [];
  14885. for ( let i = 0; i < 6; i ++ ) {
  14886. if ( ! isCompressed && ! isDataTexture ) {
  14887. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  14888. } else {
  14889. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14890. }
  14891. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14892. }
  14893. const image = cubeImage[ 0 ],
  14894. glFormat = utils.convert( texture.format, texture.colorSpace ),
  14895. glType = utils.convert( texture.type ),
  14896. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14897. const useTexStorage = ( texture.isVideoTexture !== true );
  14898. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14899. const dataReady = source.dataReady;
  14900. let levels = getMipLevels( texture, image );
  14901. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  14902. let mipmaps;
  14903. if ( isCompressed ) {
  14904. if ( useTexStorage && allocateMemory ) {
  14905. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14906. }
  14907. for ( let i = 0; i < 6; i ++ ) {
  14908. mipmaps = cubeImage[ i ].mipmaps;
  14909. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14910. const mipmap = mipmaps[ j ];
  14911. if ( texture.format !== RGBAFormat ) {
  14912. if ( glFormat !== null ) {
  14913. if ( useTexStorage ) {
  14914. if ( dataReady ) {
  14915. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14916. }
  14917. } else {
  14918. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14919. }
  14920. } else {
  14921. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14922. }
  14923. } else {
  14924. if ( useTexStorage ) {
  14925. if ( dataReady ) {
  14926. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14927. }
  14928. } else {
  14929. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14930. }
  14931. }
  14932. }
  14933. }
  14934. } else {
  14935. mipmaps = texture.mipmaps;
  14936. if ( useTexStorage && allocateMemory ) {
  14937. // TODO: Uniformly handle mipmap definitions
  14938. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14939. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14940. if ( mipmaps.length > 0 ) levels ++;
  14941. const dimensions = getDimensions( cubeImage[ 0 ] );
  14942. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  14943. }
  14944. for ( let i = 0; i < 6; i ++ ) {
  14945. if ( isDataTexture ) {
  14946. if ( useTexStorage ) {
  14947. if ( dataReady ) {
  14948. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14949. }
  14950. } else {
  14951. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14952. }
  14953. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14954. const mipmap = mipmaps[ j ];
  14955. const mipmapImage = mipmap.image[ i ].image;
  14956. if ( useTexStorage ) {
  14957. if ( dataReady ) {
  14958. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14959. }
  14960. } else {
  14961. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14962. }
  14963. }
  14964. } else {
  14965. if ( useTexStorage ) {
  14966. if ( dataReady ) {
  14967. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14968. }
  14969. } else {
  14970. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14971. }
  14972. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14973. const mipmap = mipmaps[ j ];
  14974. if ( useTexStorage ) {
  14975. if ( dataReady ) {
  14976. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14977. }
  14978. } else {
  14979. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14980. }
  14981. }
  14982. }
  14983. }
  14984. }
  14985. if ( textureNeedsGenerateMipmaps( texture ) ) {
  14986. // We assume images for cube map have the same size.
  14987. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14988. }
  14989. sourceProperties.__version = source.version;
  14990. if ( texture.onUpdate ) texture.onUpdate( texture );
  14991. }
  14992. textureProperties.__version = texture.version;
  14993. }
  14994. // Render targets
  14995. // Setup storage for target texture and bind it to correct framebuffer
  14996. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  14997. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14998. const glType = utils.convert( texture.type );
  14999. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15000. const renderTargetProperties = properties.get( renderTarget );
  15001. if ( ! renderTargetProperties.__hasExternalTextures ) {
  15002. const width = Math.max( 1, renderTarget.width >> level );
  15003. const height = Math.max( 1, renderTarget.height >> level );
  15004. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  15005. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  15006. } else {
  15007. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  15008. }
  15009. }
  15010. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15011. if ( useMultisampledRTT( renderTarget ) ) {
  15012. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  15013. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  15014. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, level );
  15015. }
  15016. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15017. }
  15018. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15019. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  15020. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15021. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15022. let glInternalFormat = _gl.DEPTH_COMPONENT24;
  15023. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  15024. const depthTexture = renderTarget.depthTexture;
  15025. if ( depthTexture && depthTexture.isDepthTexture ) {
  15026. if ( depthTexture.type === FloatType ) {
  15027. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  15028. } else if ( depthTexture.type === UnsignedIntType ) {
  15029. glInternalFormat = _gl.DEPTH_COMPONENT24;
  15030. }
  15031. }
  15032. const samples = getRenderTargetSamples( renderTarget );
  15033. if ( useMultisampledRTT( renderTarget ) ) {
  15034. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15035. } else {
  15036. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15037. }
  15038. } else {
  15039. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15040. }
  15041. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15042. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15043. const samples = getRenderTargetSamples( renderTarget );
  15044. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15045. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15046. } else if ( useMultisampledRTT( renderTarget ) ) {
  15047. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15048. } else {
  15049. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15050. }
  15051. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15052. } else {
  15053. const textures = renderTarget.textures;
  15054. for ( let i = 0; i < textures.length; i ++ ) {
  15055. const texture = textures[ i ];
  15056. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15057. const glType = utils.convert( texture.type );
  15058. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15059. const samples = getRenderTargetSamples( renderTarget );
  15060. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15061. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15062. } else if ( useMultisampledRTT( renderTarget ) ) {
  15063. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15064. } else {
  15065. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15066. }
  15067. }
  15068. }
  15069. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15070. }
  15071. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15072. function setupDepthTexture( framebuffer, renderTarget ) {
  15073. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  15074. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15075. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15076. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15077. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15078. }
  15079. // upload an empty depth texture with framebuffer size
  15080. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  15081. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15082. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15083. renderTarget.depthTexture.image.width = renderTarget.width;
  15084. renderTarget.depthTexture.image.height = renderTarget.height;
  15085. renderTarget.depthTexture.needsUpdate = true;
  15086. }
  15087. setTexture2D( renderTarget.depthTexture, 0 );
  15088. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15089. const samples = getRenderTargetSamples( renderTarget );
  15090. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15091. if ( useMultisampledRTT( renderTarget ) ) {
  15092. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15093. } else {
  15094. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15095. }
  15096. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15097. if ( useMultisampledRTT( renderTarget ) ) {
  15098. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15099. } else {
  15100. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15101. }
  15102. } else {
  15103. throw new Error( 'Unknown depthTexture format' );
  15104. }
  15105. }
  15106. // Setup GL resources for a non-texture depth buffer
  15107. function setupDepthRenderbuffer( renderTarget ) {
  15108. const renderTargetProperties = properties.get( renderTarget );
  15109. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15110. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  15111. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15112. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15113. } else {
  15114. if ( isCube ) {
  15115. renderTargetProperties.__webglDepthbuffer = [];
  15116. for ( let i = 0; i < 6; i ++ ) {
  15117. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15118. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15119. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  15120. }
  15121. } else {
  15122. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15123. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15124. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  15125. }
  15126. }
  15127. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15128. }
  15129. // rebind framebuffer with external textures
  15130. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  15131. const renderTargetProperties = properties.get( renderTarget );
  15132. if ( colorTexture !== undefined ) {
  15133. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  15134. }
  15135. if ( depthTexture !== undefined ) {
  15136. setupDepthRenderbuffer( renderTarget );
  15137. }
  15138. }
  15139. // Set up GL resources for the render target
  15140. function setupRenderTarget( renderTarget ) {
  15141. const texture = renderTarget.texture;
  15142. const renderTargetProperties = properties.get( renderTarget );
  15143. const textureProperties = properties.get( texture );
  15144. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15145. const textures = renderTarget.textures;
  15146. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15147. const isMultipleRenderTargets = ( textures.length > 1 );
  15148. if ( ! isMultipleRenderTargets ) {
  15149. if ( textureProperties.__webglTexture === undefined ) {
  15150. textureProperties.__webglTexture = _gl.createTexture();
  15151. }
  15152. textureProperties.__version = texture.version;
  15153. info.memory.textures ++;
  15154. }
  15155. // Setup framebuffer
  15156. if ( isCube ) {
  15157. renderTargetProperties.__webglFramebuffer = [];
  15158. for ( let i = 0; i < 6; i ++ ) {
  15159. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15160. renderTargetProperties.__webglFramebuffer[ i ] = [];
  15161. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15162. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  15163. }
  15164. } else {
  15165. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15166. }
  15167. }
  15168. } else {
  15169. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15170. renderTargetProperties.__webglFramebuffer = [];
  15171. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15172. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  15173. }
  15174. } else {
  15175. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15176. }
  15177. if ( isMultipleRenderTargets ) {
  15178. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15179. const attachmentProperties = properties.get( textures[ i ] );
  15180. if ( attachmentProperties.__webglTexture === undefined ) {
  15181. attachmentProperties.__webglTexture = _gl.createTexture();
  15182. info.memory.textures ++;
  15183. }
  15184. }
  15185. }
  15186. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15187. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15188. renderTargetProperties.__webglColorRenderbuffer = [];
  15189. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15190. for ( let i = 0; i < textures.length; i ++ ) {
  15191. const texture = textures[ i ];
  15192. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15193. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15194. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15195. const glType = utils.convert( texture.type );
  15196. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15197. const samples = getRenderTargetSamples( renderTarget );
  15198. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15199. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15200. }
  15201. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15202. if ( renderTarget.depthBuffer ) {
  15203. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15204. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15205. }
  15206. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15207. }
  15208. }
  15209. // Setup color buffer
  15210. if ( isCube ) {
  15211. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15212. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  15213. for ( let i = 0; i < 6; i ++ ) {
  15214. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15215. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15216. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  15217. }
  15218. } else {
  15219. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  15220. }
  15221. }
  15222. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15223. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15224. }
  15225. state.unbindTexture();
  15226. } else if ( isMultipleRenderTargets ) {
  15227. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15228. const attachment = textures[ i ];
  15229. const attachmentProperties = properties.get( attachment );
  15230. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15231. setTextureParameters( _gl.TEXTURE_2D, attachment );
  15232. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  15233. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  15234. generateMipmap( _gl.TEXTURE_2D );
  15235. }
  15236. }
  15237. state.unbindTexture();
  15238. } else {
  15239. let glTextureType = _gl.TEXTURE_2D;
  15240. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15241. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15242. }
  15243. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15244. setTextureParameters( glTextureType, texture );
  15245. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15246. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15247. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  15248. }
  15249. } else {
  15250. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  15251. }
  15252. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15253. generateMipmap( glTextureType );
  15254. }
  15255. state.unbindTexture();
  15256. }
  15257. // Setup depth and stencil buffers
  15258. if ( renderTarget.depthBuffer ) {
  15259. setupDepthRenderbuffer( renderTarget );
  15260. }
  15261. }
  15262. function updateRenderTargetMipmap( renderTarget ) {
  15263. const textures = renderTarget.textures;
  15264. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15265. const texture = textures[ i ];
  15266. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15267. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15268. const webglTexture = properties.get( texture ).__webglTexture;
  15269. state.bindTexture( target, webglTexture );
  15270. generateMipmap( target );
  15271. state.unbindTexture();
  15272. }
  15273. }
  15274. }
  15275. function updateMultisampleRenderTarget( renderTarget ) {
  15276. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15277. const textures = renderTarget.textures;
  15278. const width = renderTarget.width;
  15279. const height = renderTarget.height;
  15280. let mask = _gl.COLOR_BUFFER_BIT;
  15281. const invalidationArray = [];
  15282. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15283. const renderTargetProperties = properties.get( renderTarget );
  15284. const isMultipleRenderTargets = ( textures.length > 1 );
  15285. // If MRT we need to remove FBO attachments
  15286. if ( isMultipleRenderTargets ) {
  15287. for ( let i = 0; i < textures.length; i ++ ) {
  15288. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15289. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15290. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15291. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15292. }
  15293. }
  15294. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15295. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15296. for ( let i = 0; i < textures.length; i ++ ) {
  15297. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  15298. if ( renderTarget.depthBuffer ) {
  15299. invalidationArray.push( depthStyle );
  15300. }
  15301. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  15302. if ( ignoreDepthValues === false ) {
  15303. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15304. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  15305. if ( renderTarget.stencilBuffer && renderTargetProperties.__isTransmissionRenderTarget !== true ) mask |= _gl.STENCIL_BUFFER_BIT;
  15306. }
  15307. if ( isMultipleRenderTargets ) {
  15308. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15309. }
  15310. if ( ignoreDepthValues === true ) {
  15311. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  15312. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15313. }
  15314. if ( isMultipleRenderTargets ) {
  15315. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15316. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15317. }
  15318. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15319. if ( supportsInvalidateFramebuffer ) {
  15320. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  15321. }
  15322. }
  15323. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15324. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15325. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15326. if ( isMultipleRenderTargets ) {
  15327. for ( let i = 0; i < textures.length; i ++ ) {
  15328. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15329. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15330. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15331. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15332. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15333. }
  15334. }
  15335. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15336. }
  15337. }
  15338. function getRenderTargetSamples( renderTarget ) {
  15339. return Math.min( capabilities.maxSamples, renderTarget.samples );
  15340. }
  15341. function useMultisampledRTT( renderTarget ) {
  15342. const renderTargetProperties = properties.get( renderTarget );
  15343. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15344. }
  15345. function updateVideoTexture( texture ) {
  15346. const frame = info.render.frame;
  15347. // Check the last frame we updated the VideoTexture
  15348. if ( _videoTextures.get( texture ) !== frame ) {
  15349. _videoTextures.set( texture, frame );
  15350. texture.update();
  15351. }
  15352. }
  15353. function verifyColorSpace( texture, image ) {
  15354. const colorSpace = texture.colorSpace;
  15355. const format = texture.format;
  15356. const type = texture.type;
  15357. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  15358. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15359. // sRGB
  15360. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  15361. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15362. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15363. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15364. }
  15365. } else {
  15366. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15367. }
  15368. }
  15369. return image;
  15370. }
  15371. function getDimensions( image ) {
  15372. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  15373. // if intrinsic data are not available, fallback to width/height
  15374. _imageDimensions.width = image.naturalWidth || image.width;
  15375. _imageDimensions.height = image.naturalHeight || image.height;
  15376. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  15377. _imageDimensions.width = image.displayWidth;
  15378. _imageDimensions.height = image.displayHeight;
  15379. } else {
  15380. _imageDimensions.width = image.width;
  15381. _imageDimensions.height = image.height;
  15382. }
  15383. return _imageDimensions;
  15384. }
  15385. //
  15386. this.allocateTextureUnit = allocateTextureUnit;
  15387. this.resetTextureUnits = resetTextureUnits;
  15388. this.setTexture2D = setTexture2D;
  15389. this.setTexture2DArray = setTexture2DArray;
  15390. this.setTexture3D = setTexture3D;
  15391. this.setTextureCube = setTextureCube;
  15392. this.rebindTextures = rebindTextures;
  15393. this.setupRenderTarget = setupRenderTarget;
  15394. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15395. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15396. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15397. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15398. this.useMultisampledRTT = useMultisampledRTT;
  15399. }
  15400. function WebGLUtils( gl, extensions ) {
  15401. function convert( p, colorSpace = NoColorSpace ) {
  15402. let extension;
  15403. const transfer = ColorManagement.getTransfer( colorSpace );
  15404. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15405. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15406. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15407. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  15408. if ( p === ByteType ) return gl.BYTE;
  15409. if ( p === ShortType ) return gl.SHORT;
  15410. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15411. if ( p === IntType ) return gl.INT;
  15412. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15413. if ( p === FloatType ) return gl.FLOAT;
  15414. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  15415. if ( p === AlphaFormat ) return gl.ALPHA;
  15416. if ( p === RGBFormat ) return gl.RGB;
  15417. if ( p === RGBAFormat ) return gl.RGBA;
  15418. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15419. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15420. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15421. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15422. // WebGL2 formats.
  15423. if ( p === RedFormat ) return gl.RED;
  15424. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15425. if ( p === RGFormat ) return gl.RG;
  15426. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15427. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15428. // S3TC
  15429. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15430. if ( transfer === SRGBTransfer ) {
  15431. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15432. if ( extension !== null ) {
  15433. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15434. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15435. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15436. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15437. } else {
  15438. return null;
  15439. }
  15440. } else {
  15441. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15442. if ( extension !== null ) {
  15443. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15444. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15445. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15446. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15447. } else {
  15448. return null;
  15449. }
  15450. }
  15451. }
  15452. // PVRTC
  15453. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15454. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15455. if ( extension !== null ) {
  15456. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15457. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15458. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15459. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15460. } else {
  15461. return null;
  15462. }
  15463. }
  15464. // ETC
  15465. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15466. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15467. if ( extension !== null ) {
  15468. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15469. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15470. } else {
  15471. return null;
  15472. }
  15473. }
  15474. // ASTC
  15475. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15476. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15477. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15478. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15479. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15480. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15481. if ( extension !== null ) {
  15482. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15483. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15484. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15485. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15486. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15487. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15488. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15489. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15490. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15491. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15492. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15493. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15494. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15495. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15496. } else {
  15497. return null;
  15498. }
  15499. }
  15500. // BPTC
  15501. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  15502. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15503. if ( extension !== null ) {
  15504. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15505. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  15506. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  15507. } else {
  15508. return null;
  15509. }
  15510. }
  15511. // RGTC
  15512. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15513. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15514. if ( extension !== null ) {
  15515. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15516. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15517. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15518. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15519. } else {
  15520. return null;
  15521. }
  15522. }
  15523. //
  15524. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  15525. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15526. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15527. }
  15528. return { convert: convert };
  15529. }
  15530. class ArrayCamera extends PerspectiveCamera {
  15531. constructor( array = [] ) {
  15532. super();
  15533. this.isArrayCamera = true;
  15534. this.cameras = array;
  15535. }
  15536. }
  15537. class Group extends Object3D {
  15538. constructor() {
  15539. super();
  15540. this.isGroup = true;
  15541. this.type = 'Group';
  15542. }
  15543. }
  15544. const _moveEvent = { type: 'move' };
  15545. class WebXRController {
  15546. constructor() {
  15547. this._targetRay = null;
  15548. this._grip = null;
  15549. this._hand = null;
  15550. }
  15551. getHandSpace() {
  15552. if ( this._hand === null ) {
  15553. this._hand = new Group();
  15554. this._hand.matrixAutoUpdate = false;
  15555. this._hand.visible = false;
  15556. this._hand.joints = {};
  15557. this._hand.inputState = { pinching: false };
  15558. }
  15559. return this._hand;
  15560. }
  15561. getTargetRaySpace() {
  15562. if ( this._targetRay === null ) {
  15563. this._targetRay = new Group();
  15564. this._targetRay.matrixAutoUpdate = false;
  15565. this._targetRay.visible = false;
  15566. this._targetRay.hasLinearVelocity = false;
  15567. this._targetRay.linearVelocity = new Vector3();
  15568. this._targetRay.hasAngularVelocity = false;
  15569. this._targetRay.angularVelocity = new Vector3();
  15570. }
  15571. return this._targetRay;
  15572. }
  15573. getGripSpace() {
  15574. if ( this._grip === null ) {
  15575. this._grip = new Group();
  15576. this._grip.matrixAutoUpdate = false;
  15577. this._grip.visible = false;
  15578. this._grip.hasLinearVelocity = false;
  15579. this._grip.linearVelocity = new Vector3();
  15580. this._grip.hasAngularVelocity = false;
  15581. this._grip.angularVelocity = new Vector3();
  15582. }
  15583. return this._grip;
  15584. }
  15585. dispatchEvent( event ) {
  15586. if ( this._targetRay !== null ) {
  15587. this._targetRay.dispatchEvent( event );
  15588. }
  15589. if ( this._grip !== null ) {
  15590. this._grip.dispatchEvent( event );
  15591. }
  15592. if ( this._hand !== null ) {
  15593. this._hand.dispatchEvent( event );
  15594. }
  15595. return this;
  15596. }
  15597. connect( inputSource ) {
  15598. if ( inputSource && inputSource.hand ) {
  15599. const hand = this._hand;
  15600. if ( hand ) {
  15601. for ( const inputjoint of inputSource.hand.values() ) {
  15602. // Initialize hand with joints when connected
  15603. this._getHandJoint( hand, inputjoint );
  15604. }
  15605. }
  15606. }
  15607. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15608. return this;
  15609. }
  15610. disconnect( inputSource ) {
  15611. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15612. if ( this._targetRay !== null ) {
  15613. this._targetRay.visible = false;
  15614. }
  15615. if ( this._grip !== null ) {
  15616. this._grip.visible = false;
  15617. }
  15618. if ( this._hand !== null ) {
  15619. this._hand.visible = false;
  15620. }
  15621. return this;
  15622. }
  15623. update( inputSource, frame, referenceSpace ) {
  15624. let inputPose = null;
  15625. let gripPose = null;
  15626. let handPose = null;
  15627. const targetRay = this._targetRay;
  15628. const grip = this._grip;
  15629. const hand = this._hand;
  15630. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15631. if ( hand && inputSource.hand ) {
  15632. handPose = true;
  15633. for ( const inputjoint of inputSource.hand.values() ) {
  15634. // Update the joints groups with the XRJoint poses
  15635. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15636. // The transform of this joint will be updated with the joint pose on each frame
  15637. const joint = this._getHandJoint( hand, inputjoint );
  15638. if ( jointPose !== null ) {
  15639. joint.matrix.fromArray( jointPose.transform.matrix );
  15640. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15641. joint.matrixWorldNeedsUpdate = true;
  15642. joint.jointRadius = jointPose.radius;
  15643. }
  15644. joint.visible = jointPose !== null;
  15645. }
  15646. // Custom events
  15647. // Check pinchz
  15648. const indexTip = hand.joints[ 'index-finger-tip' ];
  15649. const thumbTip = hand.joints[ 'thumb-tip' ];
  15650. const distance = indexTip.position.distanceTo( thumbTip.position );
  15651. const distanceToPinch = 0.02;
  15652. const threshold = 0.005;
  15653. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15654. hand.inputState.pinching = false;
  15655. this.dispatchEvent( {
  15656. type: 'pinchend',
  15657. handedness: inputSource.handedness,
  15658. target: this
  15659. } );
  15660. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15661. hand.inputState.pinching = true;
  15662. this.dispatchEvent( {
  15663. type: 'pinchstart',
  15664. handedness: inputSource.handedness,
  15665. target: this
  15666. } );
  15667. }
  15668. } else {
  15669. if ( grip !== null && inputSource.gripSpace ) {
  15670. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15671. if ( gripPose !== null ) {
  15672. grip.matrix.fromArray( gripPose.transform.matrix );
  15673. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15674. grip.matrixWorldNeedsUpdate = true;
  15675. if ( gripPose.linearVelocity ) {
  15676. grip.hasLinearVelocity = true;
  15677. grip.linearVelocity.copy( gripPose.linearVelocity );
  15678. } else {
  15679. grip.hasLinearVelocity = false;
  15680. }
  15681. if ( gripPose.angularVelocity ) {
  15682. grip.hasAngularVelocity = true;
  15683. grip.angularVelocity.copy( gripPose.angularVelocity );
  15684. } else {
  15685. grip.hasAngularVelocity = false;
  15686. }
  15687. }
  15688. }
  15689. }
  15690. if ( targetRay !== null ) {
  15691. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15692. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15693. if ( inputPose === null && gripPose !== null ) {
  15694. inputPose = gripPose;
  15695. }
  15696. if ( inputPose !== null ) {
  15697. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15698. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15699. targetRay.matrixWorldNeedsUpdate = true;
  15700. if ( inputPose.linearVelocity ) {
  15701. targetRay.hasLinearVelocity = true;
  15702. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15703. } else {
  15704. targetRay.hasLinearVelocity = false;
  15705. }
  15706. if ( inputPose.angularVelocity ) {
  15707. targetRay.hasAngularVelocity = true;
  15708. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15709. } else {
  15710. targetRay.hasAngularVelocity = false;
  15711. }
  15712. this.dispatchEvent( _moveEvent );
  15713. }
  15714. }
  15715. }
  15716. if ( targetRay !== null ) {
  15717. targetRay.visible = ( inputPose !== null );
  15718. }
  15719. if ( grip !== null ) {
  15720. grip.visible = ( gripPose !== null );
  15721. }
  15722. if ( hand !== null ) {
  15723. hand.visible = ( handPose !== null );
  15724. }
  15725. return this;
  15726. }
  15727. // private method
  15728. _getHandJoint( hand, inputjoint ) {
  15729. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15730. const joint = new Group();
  15731. joint.matrixAutoUpdate = false;
  15732. joint.visible = false;
  15733. hand.joints[ inputjoint.jointName ] = joint;
  15734. hand.add( joint );
  15735. }
  15736. return hand.joints[ inputjoint.jointName ];
  15737. }
  15738. }
  15739. const _occlusion_vertex = `
  15740. void main() {
  15741. gl_Position = vec4( position, 1.0 );
  15742. }`;
  15743. const _occlusion_fragment = `
  15744. uniform sampler2DArray depthColor;
  15745. uniform float depthWidth;
  15746. uniform float depthHeight;
  15747. void main() {
  15748. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  15749. if ( coord.x >= 1.0 ) {
  15750. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  15751. } else {
  15752. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  15753. }
  15754. }`;
  15755. class WebXRDepthSensing {
  15756. constructor() {
  15757. this.texture = null;
  15758. this.mesh = null;
  15759. this.depthNear = 0;
  15760. this.depthFar = 0;
  15761. }
  15762. init( renderer, depthData, renderState ) {
  15763. if ( this.texture === null ) {
  15764. const texture = new Texture();
  15765. const texProps = renderer.properties.get( texture );
  15766. texProps.__webglTexture = depthData.texture;
  15767. if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) {
  15768. this.depthNear = depthData.depthNear;
  15769. this.depthFar = depthData.depthFar;
  15770. }
  15771. this.texture = texture;
  15772. }
  15773. }
  15774. render( renderer, cameraXR ) {
  15775. if ( this.texture !== null ) {
  15776. if ( this.mesh === null ) {
  15777. const viewport = cameraXR.cameras[ 0 ].viewport;
  15778. const material = new ShaderMaterial( {
  15779. vertexShader: _occlusion_vertex,
  15780. fragmentShader: _occlusion_fragment,
  15781. uniforms: {
  15782. depthColor: { value: this.texture },
  15783. depthWidth: { value: viewport.z },
  15784. depthHeight: { value: viewport.w }
  15785. }
  15786. } );
  15787. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  15788. }
  15789. renderer.render( this.mesh, cameraXR );
  15790. }
  15791. }
  15792. reset() {
  15793. this.texture = null;
  15794. this.mesh = null;
  15795. }
  15796. }
  15797. class WebXRManager extends EventDispatcher {
  15798. constructor( renderer, gl ) {
  15799. super();
  15800. const scope = this;
  15801. let session = null;
  15802. let framebufferScaleFactor = 1.0;
  15803. let referenceSpace = null;
  15804. let referenceSpaceType = 'local-floor';
  15805. // Set default foveation to maximum.
  15806. let foveation = 1.0;
  15807. let customReferenceSpace = null;
  15808. let pose = null;
  15809. let glBinding = null;
  15810. let glProjLayer = null;
  15811. let glBaseLayer = null;
  15812. let xrFrame = null;
  15813. const depthSensing = new WebXRDepthSensing();
  15814. const attributes = gl.getContextAttributes();
  15815. let initialRenderTarget = null;
  15816. let newRenderTarget = null;
  15817. const controllers = [];
  15818. const controllerInputSources = [];
  15819. const currentSize = new Vector2();
  15820. let currentPixelRatio = null;
  15821. //
  15822. const cameraL = new PerspectiveCamera();
  15823. cameraL.layers.enable( 1 );
  15824. cameraL.viewport = new Vector4();
  15825. const cameraR = new PerspectiveCamera();
  15826. cameraR.layers.enable( 2 );
  15827. cameraR.viewport = new Vector4();
  15828. const cameras = [ cameraL, cameraR ];
  15829. const cameraXR = new ArrayCamera();
  15830. cameraXR.layers.enable( 1 );
  15831. cameraXR.layers.enable( 2 );
  15832. let _currentDepthNear = null;
  15833. let _currentDepthFar = null;
  15834. //
  15835. this.cameraAutoUpdate = true;
  15836. this.enabled = false;
  15837. this.isPresenting = false;
  15838. this.getController = function ( index ) {
  15839. let controller = controllers[ index ];
  15840. if ( controller === undefined ) {
  15841. controller = new WebXRController();
  15842. controllers[ index ] = controller;
  15843. }
  15844. return controller.getTargetRaySpace();
  15845. };
  15846. this.getControllerGrip = function ( index ) {
  15847. let controller = controllers[ index ];
  15848. if ( controller === undefined ) {
  15849. controller = new WebXRController();
  15850. controllers[ index ] = controller;
  15851. }
  15852. return controller.getGripSpace();
  15853. };
  15854. this.getHand = function ( index ) {
  15855. let controller = controllers[ index ];
  15856. if ( controller === undefined ) {
  15857. controller = new WebXRController();
  15858. controllers[ index ] = controller;
  15859. }
  15860. return controller.getHandSpace();
  15861. };
  15862. //
  15863. function onSessionEvent( event ) {
  15864. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15865. if ( controllerIndex === - 1 ) {
  15866. return;
  15867. }
  15868. const controller = controllers[ controllerIndex ];
  15869. if ( controller !== undefined ) {
  15870. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  15871. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15872. }
  15873. }
  15874. function onSessionEnd() {
  15875. session.removeEventListener( 'select', onSessionEvent );
  15876. session.removeEventListener( 'selectstart', onSessionEvent );
  15877. session.removeEventListener( 'selectend', onSessionEvent );
  15878. session.removeEventListener( 'squeeze', onSessionEvent );
  15879. session.removeEventListener( 'squeezestart', onSessionEvent );
  15880. session.removeEventListener( 'squeezeend', onSessionEvent );
  15881. session.removeEventListener( 'end', onSessionEnd );
  15882. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15883. for ( let i = 0; i < controllers.length; i ++ ) {
  15884. const inputSource = controllerInputSources[ i ];
  15885. if ( inputSource === null ) continue;
  15886. controllerInputSources[ i ] = null;
  15887. controllers[ i ].disconnect( inputSource );
  15888. }
  15889. _currentDepthNear = null;
  15890. _currentDepthFar = null;
  15891. depthSensing.reset();
  15892. // restore framebuffer/rendering state
  15893. renderer.setRenderTarget( initialRenderTarget );
  15894. glBaseLayer = null;
  15895. glProjLayer = null;
  15896. glBinding = null;
  15897. session = null;
  15898. newRenderTarget = null;
  15899. //
  15900. animation.stop();
  15901. scope.isPresenting = false;
  15902. renderer.setPixelRatio( currentPixelRatio );
  15903. renderer.setSize( currentSize.width, currentSize.height, false );
  15904. scope.dispatchEvent( { type: 'sessionend' } );
  15905. }
  15906. this.setFramebufferScaleFactor = function ( value ) {
  15907. framebufferScaleFactor = value;
  15908. if ( scope.isPresenting === true ) {
  15909. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15910. }
  15911. };
  15912. this.setReferenceSpaceType = function ( value ) {
  15913. referenceSpaceType = value;
  15914. if ( scope.isPresenting === true ) {
  15915. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15916. }
  15917. };
  15918. this.getReferenceSpace = function () {
  15919. return customReferenceSpace || referenceSpace;
  15920. };
  15921. this.setReferenceSpace = function ( space ) {
  15922. customReferenceSpace = space;
  15923. };
  15924. this.getBaseLayer = function () {
  15925. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15926. };
  15927. this.getBinding = function () {
  15928. return glBinding;
  15929. };
  15930. this.getFrame = function () {
  15931. return xrFrame;
  15932. };
  15933. this.getSession = function () {
  15934. return session;
  15935. };
  15936. this.setSession = async function ( value ) {
  15937. session = value;
  15938. if ( session !== null ) {
  15939. initialRenderTarget = renderer.getRenderTarget();
  15940. session.addEventListener( 'select', onSessionEvent );
  15941. session.addEventListener( 'selectstart', onSessionEvent );
  15942. session.addEventListener( 'selectend', onSessionEvent );
  15943. session.addEventListener( 'squeeze', onSessionEvent );
  15944. session.addEventListener( 'squeezestart', onSessionEvent );
  15945. session.addEventListener( 'squeezeend', onSessionEvent );
  15946. session.addEventListener( 'end', onSessionEnd );
  15947. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15948. if ( attributes.xrCompatible !== true ) {
  15949. await gl.makeXRCompatible();
  15950. }
  15951. currentPixelRatio = renderer.getPixelRatio();
  15952. renderer.getSize( currentSize );
  15953. if ( session.renderState.layers === undefined ) {
  15954. const layerInit = {
  15955. antialias: attributes.antialias,
  15956. alpha: true,
  15957. depth: attributes.depth,
  15958. stencil: attributes.stencil,
  15959. framebufferScaleFactor: framebufferScaleFactor
  15960. };
  15961. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15962. session.updateRenderState( { baseLayer: glBaseLayer } );
  15963. renderer.setPixelRatio( 1 );
  15964. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  15965. newRenderTarget = new WebGLRenderTarget(
  15966. glBaseLayer.framebufferWidth,
  15967. glBaseLayer.framebufferHeight,
  15968. {
  15969. format: RGBAFormat,
  15970. type: UnsignedByteType,
  15971. colorSpace: renderer.outputColorSpace,
  15972. stencilBuffer: attributes.stencil
  15973. }
  15974. );
  15975. } else {
  15976. let depthFormat = null;
  15977. let depthType = null;
  15978. let glDepthFormat = null;
  15979. if ( attributes.depth ) {
  15980. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15981. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15982. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15983. }
  15984. const projectionlayerInit = {
  15985. colorFormat: gl.RGBA8,
  15986. depthFormat: glDepthFormat,
  15987. scaleFactor: framebufferScaleFactor
  15988. };
  15989. glBinding = new XRWebGLBinding( session, gl );
  15990. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15991. session.updateRenderState( { layers: [ glProjLayer ] } );
  15992. renderer.setPixelRatio( 1 );
  15993. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  15994. newRenderTarget = new WebGLRenderTarget(
  15995. glProjLayer.textureWidth,
  15996. glProjLayer.textureHeight,
  15997. {
  15998. format: RGBAFormat,
  15999. type: UnsignedByteType,
  16000. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  16001. stencilBuffer: attributes.stencil,
  16002. colorSpace: renderer.outputColorSpace,
  16003. samples: attributes.antialias ? 4 : 0
  16004. } );
  16005. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  16006. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  16007. }
  16008. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  16009. this.setFoveation( foveation );
  16010. customReferenceSpace = null;
  16011. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  16012. animation.setContext( session );
  16013. animation.start();
  16014. scope.isPresenting = true;
  16015. scope.dispatchEvent( { type: 'sessionstart' } );
  16016. }
  16017. };
  16018. this.getEnvironmentBlendMode = function () {
  16019. if ( session !== null ) {
  16020. return session.environmentBlendMode;
  16021. }
  16022. };
  16023. function onInputSourcesChange( event ) {
  16024. // Notify disconnected
  16025. for ( let i = 0; i < event.removed.length; i ++ ) {
  16026. const inputSource = event.removed[ i ];
  16027. const index = controllerInputSources.indexOf( inputSource );
  16028. if ( index >= 0 ) {
  16029. controllerInputSources[ index ] = null;
  16030. controllers[ index ].disconnect( inputSource );
  16031. }
  16032. }
  16033. // Notify connected
  16034. for ( let i = 0; i < event.added.length; i ++ ) {
  16035. const inputSource = event.added[ i ];
  16036. let controllerIndex = controllerInputSources.indexOf( inputSource );
  16037. if ( controllerIndex === - 1 ) {
  16038. // Assign input source a controller that currently has no input source
  16039. for ( let i = 0; i < controllers.length; i ++ ) {
  16040. if ( i >= controllerInputSources.length ) {
  16041. controllerInputSources.push( inputSource );
  16042. controllerIndex = i;
  16043. break;
  16044. } else if ( controllerInputSources[ i ] === null ) {
  16045. controllerInputSources[ i ] = inputSource;
  16046. controllerIndex = i;
  16047. break;
  16048. }
  16049. }
  16050. // If all controllers do currently receive input we ignore new ones
  16051. if ( controllerIndex === - 1 ) break;
  16052. }
  16053. const controller = controllers[ controllerIndex ];
  16054. if ( controller ) {
  16055. controller.connect( inputSource );
  16056. }
  16057. }
  16058. }
  16059. //
  16060. const cameraLPos = new Vector3();
  16061. const cameraRPos = new Vector3();
  16062. /**
  16063. * Assumes 2 cameras that are parallel and share an X-axis, and that
  16064. * the cameras' projection and world matrices have already been set.
  16065. * And that near and far planes are identical for both cameras.
  16066. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  16067. */
  16068. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  16069. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  16070. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  16071. const ipd = cameraLPos.distanceTo( cameraRPos );
  16072. const projL = cameraL.projectionMatrix.elements;
  16073. const projR = cameraR.projectionMatrix.elements;
  16074. // VR systems will have identical far and near planes, and
  16075. // most likely identical top and bottom frustum extents.
  16076. // Use the left camera for these values.
  16077. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  16078. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  16079. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  16080. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  16081. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  16082. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  16083. const left = near * leftFov;
  16084. const right = near * rightFov;
  16085. // Calculate the new camera's position offset from the
  16086. // left camera. xOffset should be roughly half `ipd`.
  16087. const zOffset = ipd / ( - leftFov + rightFov );
  16088. const xOffset = zOffset * - leftFov;
  16089. // TODO: Better way to apply this offset?
  16090. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  16091. camera.translateX( xOffset );
  16092. camera.translateZ( zOffset );
  16093. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  16094. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16095. // Find the union of the frustum values of the cameras and scale
  16096. // the values so that the near plane's position does not change in world space,
  16097. // although must now be relative to the new union camera.
  16098. const near2 = near + zOffset;
  16099. const far2 = far + zOffset;
  16100. const left2 = left - xOffset;
  16101. const right2 = right + ( ipd - xOffset );
  16102. const top2 = topFov * far / far2 * near2;
  16103. const bottom2 = bottomFov * far / far2 * near2;
  16104. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  16105. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16106. }
  16107. function updateCamera( camera, parent ) {
  16108. if ( parent === null ) {
  16109. camera.matrixWorld.copy( camera.matrix );
  16110. } else {
  16111. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16112. }
  16113. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16114. }
  16115. this.updateCamera = function ( camera ) {
  16116. if ( session === null ) return;
  16117. if ( depthSensing.texture !== null ) {
  16118. camera.near = depthSensing.depthNear;
  16119. camera.far = depthSensing.depthFar;
  16120. }
  16121. cameraXR.near = cameraR.near = cameraL.near = camera.near;
  16122. cameraXR.far = cameraR.far = cameraL.far = camera.far;
  16123. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  16124. // Note that the new renderState won't apply until the next frame. See #18320
  16125. session.updateRenderState( {
  16126. depthNear: cameraXR.near,
  16127. depthFar: cameraXR.far
  16128. } );
  16129. _currentDepthNear = cameraXR.near;
  16130. _currentDepthFar = cameraXR.far;
  16131. cameraL.near = _currentDepthNear;
  16132. cameraL.far = _currentDepthFar;
  16133. cameraR.near = _currentDepthNear;
  16134. cameraR.far = _currentDepthFar;
  16135. cameraL.updateProjectionMatrix();
  16136. cameraR.updateProjectionMatrix();
  16137. camera.updateProjectionMatrix();
  16138. }
  16139. const parent = camera.parent;
  16140. const cameras = cameraXR.cameras;
  16141. updateCamera( cameraXR, parent );
  16142. for ( let i = 0; i < cameras.length; i ++ ) {
  16143. updateCamera( cameras[ i ], parent );
  16144. }
  16145. // update projection matrix for proper view frustum culling
  16146. if ( cameras.length === 2 ) {
  16147. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  16148. } else {
  16149. // assume single camera setup (AR)
  16150. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  16151. }
  16152. // update user camera and its children
  16153. updateUserCamera( camera, cameraXR, parent );
  16154. };
  16155. function updateUserCamera( camera, cameraXR, parent ) {
  16156. if ( parent === null ) {
  16157. camera.matrix.copy( cameraXR.matrixWorld );
  16158. } else {
  16159. camera.matrix.copy( parent.matrixWorld );
  16160. camera.matrix.invert();
  16161. camera.matrix.multiply( cameraXR.matrixWorld );
  16162. }
  16163. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16164. camera.updateMatrixWorld( true );
  16165. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  16166. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  16167. if ( camera.isPerspectiveCamera ) {
  16168. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  16169. camera.zoom = 1;
  16170. }
  16171. }
  16172. this.getCamera = function () {
  16173. return cameraXR;
  16174. };
  16175. this.getFoveation = function () {
  16176. if ( glProjLayer === null && glBaseLayer === null ) {
  16177. return undefined;
  16178. }
  16179. return foveation;
  16180. };
  16181. this.setFoveation = function ( value ) {
  16182. // 0 = no foveation = full resolution
  16183. // 1 = maximum foveation = the edges render at lower resolution
  16184. foveation = value;
  16185. if ( glProjLayer !== null ) {
  16186. glProjLayer.fixedFoveation = value;
  16187. }
  16188. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16189. glBaseLayer.fixedFoveation = value;
  16190. }
  16191. };
  16192. this.hasDepthSensing = function () {
  16193. return depthSensing.texture !== null;
  16194. };
  16195. // Animation Loop
  16196. let onAnimationFrameCallback = null;
  16197. function onAnimationFrame( time, frame ) {
  16198. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16199. xrFrame = frame;
  16200. if ( pose !== null ) {
  16201. const views = pose.views;
  16202. if ( glBaseLayer !== null ) {
  16203. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16204. renderer.setRenderTarget( newRenderTarget );
  16205. }
  16206. let cameraXRNeedsUpdate = false;
  16207. // check if it's necessary to rebuild cameraXR's camera list
  16208. if ( views.length !== cameraXR.cameras.length ) {
  16209. cameraXR.cameras.length = 0;
  16210. cameraXRNeedsUpdate = true;
  16211. }
  16212. for ( let i = 0; i < views.length; i ++ ) {
  16213. const view = views[ i ];
  16214. let viewport = null;
  16215. if ( glBaseLayer !== null ) {
  16216. viewport = glBaseLayer.getViewport( view );
  16217. } else {
  16218. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16219. viewport = glSubImage.viewport;
  16220. // For side-by-side projection, we only produce a single texture for both eyes.
  16221. if ( i === 0 ) {
  16222. renderer.setRenderTargetTextures(
  16223. newRenderTarget,
  16224. glSubImage.colorTexture,
  16225. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16226. renderer.setRenderTarget( newRenderTarget );
  16227. }
  16228. }
  16229. let camera = cameras[ i ];
  16230. if ( camera === undefined ) {
  16231. camera = new PerspectiveCamera();
  16232. camera.layers.enable( i );
  16233. camera.viewport = new Vector4();
  16234. cameras[ i ] = camera;
  16235. }
  16236. camera.matrix.fromArray( view.transform.matrix );
  16237. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16238. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16239. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16240. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16241. if ( i === 0 ) {
  16242. cameraXR.matrix.copy( camera.matrix );
  16243. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16244. }
  16245. if ( cameraXRNeedsUpdate === true ) {
  16246. cameraXR.cameras.push( camera );
  16247. }
  16248. }
  16249. //
  16250. const enabledFeatures = session.enabledFeatures;
  16251. if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) {
  16252. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  16253. if ( depthData && depthData.isValid && depthData.texture ) {
  16254. depthSensing.init( renderer, depthData, session.renderState );
  16255. }
  16256. }
  16257. }
  16258. //
  16259. for ( let i = 0; i < controllers.length; i ++ ) {
  16260. const inputSource = controllerInputSources[ i ];
  16261. const controller = controllers[ i ];
  16262. if ( inputSource !== null && controller !== undefined ) {
  16263. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16264. }
  16265. }
  16266. depthSensing.render( renderer, cameraXR );
  16267. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16268. if ( frame.detectedPlanes ) {
  16269. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16270. }
  16271. xrFrame = null;
  16272. }
  16273. const animation = new WebGLAnimation();
  16274. animation.setAnimationLoop( onAnimationFrame );
  16275. this.setAnimationLoop = function ( callback ) {
  16276. onAnimationFrameCallback = callback;
  16277. };
  16278. this.dispose = function () {};
  16279. }
  16280. }
  16281. const _e1 = /*@__PURE__*/ new Euler();
  16282. const _m1 = /*@__PURE__*/ new Matrix4();
  16283. function WebGLMaterials( renderer, properties ) {
  16284. function refreshTransformUniform( map, uniform ) {
  16285. if ( map.matrixAutoUpdate === true ) {
  16286. map.updateMatrix();
  16287. }
  16288. uniform.value.copy( map.matrix );
  16289. }
  16290. function refreshFogUniforms( uniforms, fog ) {
  16291. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16292. if ( fog.isFog ) {
  16293. uniforms.fogNear.value = fog.near;
  16294. uniforms.fogFar.value = fog.far;
  16295. } else if ( fog.isFogExp2 ) {
  16296. uniforms.fogDensity.value = fog.density;
  16297. }
  16298. }
  16299. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16300. if ( material.isMeshBasicMaterial ) {
  16301. refreshUniformsCommon( uniforms, material );
  16302. } else if ( material.isMeshLambertMaterial ) {
  16303. refreshUniformsCommon( uniforms, material );
  16304. } else if ( material.isMeshToonMaterial ) {
  16305. refreshUniformsCommon( uniforms, material );
  16306. refreshUniformsToon( uniforms, material );
  16307. } else if ( material.isMeshPhongMaterial ) {
  16308. refreshUniformsCommon( uniforms, material );
  16309. refreshUniformsPhong( uniforms, material );
  16310. } else if ( material.isMeshStandardMaterial ) {
  16311. refreshUniformsCommon( uniforms, material );
  16312. refreshUniformsStandard( uniforms, material );
  16313. if ( material.isMeshPhysicalMaterial ) {
  16314. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16315. }
  16316. } else if ( material.isMeshMatcapMaterial ) {
  16317. refreshUniformsCommon( uniforms, material );
  16318. refreshUniformsMatcap( uniforms, material );
  16319. } else if ( material.isMeshDepthMaterial ) {
  16320. refreshUniformsCommon( uniforms, material );
  16321. } else if ( material.isMeshDistanceMaterial ) {
  16322. refreshUniformsCommon( uniforms, material );
  16323. refreshUniformsDistance( uniforms, material );
  16324. } else if ( material.isMeshNormalMaterial ) {
  16325. refreshUniformsCommon( uniforms, material );
  16326. } else if ( material.isLineBasicMaterial ) {
  16327. refreshUniformsLine( uniforms, material );
  16328. if ( material.isLineDashedMaterial ) {
  16329. refreshUniformsDash( uniforms, material );
  16330. }
  16331. } else if ( material.isPointsMaterial ) {
  16332. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16333. } else if ( material.isSpriteMaterial ) {
  16334. refreshUniformsSprites( uniforms, material );
  16335. } else if ( material.isShadowMaterial ) {
  16336. uniforms.color.value.copy( material.color );
  16337. uniforms.opacity.value = material.opacity;
  16338. } else if ( material.isShaderMaterial ) {
  16339. material.uniformsNeedUpdate = false; // #15581
  16340. }
  16341. }
  16342. function refreshUniformsCommon( uniforms, material ) {
  16343. uniforms.opacity.value = material.opacity;
  16344. if ( material.color ) {
  16345. uniforms.diffuse.value.copy( material.color );
  16346. }
  16347. if ( material.emissive ) {
  16348. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16349. }
  16350. if ( material.map ) {
  16351. uniforms.map.value = material.map;
  16352. refreshTransformUniform( material.map, uniforms.mapTransform );
  16353. }
  16354. if ( material.alphaMap ) {
  16355. uniforms.alphaMap.value = material.alphaMap;
  16356. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16357. }
  16358. if ( material.bumpMap ) {
  16359. uniforms.bumpMap.value = material.bumpMap;
  16360. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16361. uniforms.bumpScale.value = material.bumpScale;
  16362. if ( material.side === BackSide ) {
  16363. uniforms.bumpScale.value *= - 1;
  16364. }
  16365. }
  16366. if ( material.normalMap ) {
  16367. uniforms.normalMap.value = material.normalMap;
  16368. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16369. uniforms.normalScale.value.copy( material.normalScale );
  16370. if ( material.side === BackSide ) {
  16371. uniforms.normalScale.value.negate();
  16372. }
  16373. }
  16374. if ( material.displacementMap ) {
  16375. uniforms.displacementMap.value = material.displacementMap;
  16376. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16377. uniforms.displacementScale.value = material.displacementScale;
  16378. uniforms.displacementBias.value = material.displacementBias;
  16379. }
  16380. if ( material.emissiveMap ) {
  16381. uniforms.emissiveMap.value = material.emissiveMap;
  16382. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16383. }
  16384. if ( material.specularMap ) {
  16385. uniforms.specularMap.value = material.specularMap;
  16386. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16387. }
  16388. if ( material.alphaTest > 0 ) {
  16389. uniforms.alphaTest.value = material.alphaTest;
  16390. }
  16391. const materialProperties = properties.get( material );
  16392. const envMap = materialProperties.envMap;
  16393. const envMapRotation = materialProperties.envMapRotation;
  16394. if ( envMap ) {
  16395. uniforms.envMap.value = envMap;
  16396. _e1.copy( envMapRotation );
  16397. // accommodate left-handed frame
  16398. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  16399. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  16400. // environment maps which are not cube render targets or PMREMs follow a different convention
  16401. _e1.y *= - 1;
  16402. _e1.z *= - 1;
  16403. }
  16404. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  16405. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16406. uniforms.reflectivity.value = material.reflectivity;
  16407. uniforms.ior.value = material.ior;
  16408. uniforms.refractionRatio.value = material.refractionRatio;
  16409. }
  16410. if ( material.lightMap ) {
  16411. uniforms.lightMap.value = material.lightMap;
  16412. // artist-friendly light intensity scaling factor
  16413. const scaleFactor = ( renderer._useLegacyLights === true ) ? Math.PI : 1;
  16414. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  16415. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16416. }
  16417. if ( material.aoMap ) {
  16418. uniforms.aoMap.value = material.aoMap;
  16419. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16420. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16421. }
  16422. }
  16423. function refreshUniformsLine( uniforms, material ) {
  16424. uniforms.diffuse.value.copy( material.color );
  16425. uniforms.opacity.value = material.opacity;
  16426. if ( material.map ) {
  16427. uniforms.map.value = material.map;
  16428. refreshTransformUniform( material.map, uniforms.mapTransform );
  16429. }
  16430. }
  16431. function refreshUniformsDash( uniforms, material ) {
  16432. uniforms.dashSize.value = material.dashSize;
  16433. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16434. uniforms.scale.value = material.scale;
  16435. }
  16436. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16437. uniforms.diffuse.value.copy( material.color );
  16438. uniforms.opacity.value = material.opacity;
  16439. uniforms.size.value = material.size * pixelRatio;
  16440. uniforms.scale.value = height * 0.5;
  16441. if ( material.map ) {
  16442. uniforms.map.value = material.map;
  16443. refreshTransformUniform( material.map, uniforms.uvTransform );
  16444. }
  16445. if ( material.alphaMap ) {
  16446. uniforms.alphaMap.value = material.alphaMap;
  16447. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16448. }
  16449. if ( material.alphaTest > 0 ) {
  16450. uniforms.alphaTest.value = material.alphaTest;
  16451. }
  16452. }
  16453. function refreshUniformsSprites( uniforms, material ) {
  16454. uniforms.diffuse.value.copy( material.color );
  16455. uniforms.opacity.value = material.opacity;
  16456. uniforms.rotation.value = material.rotation;
  16457. if ( material.map ) {
  16458. uniforms.map.value = material.map;
  16459. refreshTransformUniform( material.map, uniforms.mapTransform );
  16460. }
  16461. if ( material.alphaMap ) {
  16462. uniforms.alphaMap.value = material.alphaMap;
  16463. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16464. }
  16465. if ( material.alphaTest > 0 ) {
  16466. uniforms.alphaTest.value = material.alphaTest;
  16467. }
  16468. }
  16469. function refreshUniformsPhong( uniforms, material ) {
  16470. uniforms.specular.value.copy( material.specular );
  16471. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16472. }
  16473. function refreshUniformsToon( uniforms, material ) {
  16474. if ( material.gradientMap ) {
  16475. uniforms.gradientMap.value = material.gradientMap;
  16476. }
  16477. }
  16478. function refreshUniformsStandard( uniforms, material ) {
  16479. uniforms.metalness.value = material.metalness;
  16480. if ( material.metalnessMap ) {
  16481. uniforms.metalnessMap.value = material.metalnessMap;
  16482. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16483. }
  16484. uniforms.roughness.value = material.roughness;
  16485. if ( material.roughnessMap ) {
  16486. uniforms.roughnessMap.value = material.roughnessMap;
  16487. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16488. }
  16489. if ( material.envMap ) {
  16490. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16491. uniforms.envMapIntensity.value = material.envMapIntensity;
  16492. }
  16493. }
  16494. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16495. uniforms.ior.value = material.ior; // also part of uniforms common
  16496. if ( material.sheen > 0 ) {
  16497. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16498. uniforms.sheenRoughness.value = material.sheenRoughness;
  16499. if ( material.sheenColorMap ) {
  16500. uniforms.sheenColorMap.value = material.sheenColorMap;
  16501. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16502. }
  16503. if ( material.sheenRoughnessMap ) {
  16504. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16505. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16506. }
  16507. }
  16508. if ( material.clearcoat > 0 ) {
  16509. uniforms.clearcoat.value = material.clearcoat;
  16510. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16511. if ( material.clearcoatMap ) {
  16512. uniforms.clearcoatMap.value = material.clearcoatMap;
  16513. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16514. }
  16515. if ( material.clearcoatRoughnessMap ) {
  16516. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16517. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16518. }
  16519. if ( material.clearcoatNormalMap ) {
  16520. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16521. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16522. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16523. if ( material.side === BackSide ) {
  16524. uniforms.clearcoatNormalScale.value.negate();
  16525. }
  16526. }
  16527. }
  16528. if ( material.dispersion > 0 ) {
  16529. uniforms.dispersion.value = material.dispersion;
  16530. }
  16531. if ( material.iridescence > 0 ) {
  16532. uniforms.iridescence.value = material.iridescence;
  16533. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16534. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16535. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16536. if ( material.iridescenceMap ) {
  16537. uniforms.iridescenceMap.value = material.iridescenceMap;
  16538. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16539. }
  16540. if ( material.iridescenceThicknessMap ) {
  16541. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16542. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16543. }
  16544. }
  16545. if ( material.transmission > 0 ) {
  16546. uniforms.transmission.value = material.transmission;
  16547. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16548. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16549. if ( material.transmissionMap ) {
  16550. uniforms.transmissionMap.value = material.transmissionMap;
  16551. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16552. }
  16553. uniforms.thickness.value = material.thickness;
  16554. if ( material.thicknessMap ) {
  16555. uniforms.thicknessMap.value = material.thicknessMap;
  16556. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16557. }
  16558. uniforms.attenuationDistance.value = material.attenuationDistance;
  16559. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16560. }
  16561. if ( material.anisotropy > 0 ) {
  16562. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16563. if ( material.anisotropyMap ) {
  16564. uniforms.anisotropyMap.value = material.anisotropyMap;
  16565. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16566. }
  16567. }
  16568. uniforms.specularIntensity.value = material.specularIntensity;
  16569. uniforms.specularColor.value.copy( material.specularColor );
  16570. if ( material.specularColorMap ) {
  16571. uniforms.specularColorMap.value = material.specularColorMap;
  16572. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16573. }
  16574. if ( material.specularIntensityMap ) {
  16575. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16576. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16577. }
  16578. }
  16579. function refreshUniformsMatcap( uniforms, material ) {
  16580. if ( material.matcap ) {
  16581. uniforms.matcap.value = material.matcap;
  16582. }
  16583. }
  16584. function refreshUniformsDistance( uniforms, material ) {
  16585. const light = properties.get( material ).light;
  16586. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16587. uniforms.nearDistance.value = light.shadow.camera.near;
  16588. uniforms.farDistance.value = light.shadow.camera.far;
  16589. }
  16590. return {
  16591. refreshFogUniforms: refreshFogUniforms,
  16592. refreshMaterialUniforms: refreshMaterialUniforms
  16593. };
  16594. }
  16595. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16596. let buffers = {};
  16597. let updateList = {};
  16598. let allocatedBindingPoints = [];
  16599. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  16600. function bind( uniformsGroup, program ) {
  16601. const webglProgram = program.program;
  16602. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16603. }
  16604. function update( uniformsGroup, program ) {
  16605. let buffer = buffers[ uniformsGroup.id ];
  16606. if ( buffer === undefined ) {
  16607. prepareUniformsGroup( uniformsGroup );
  16608. buffer = createBuffer( uniformsGroup );
  16609. buffers[ uniformsGroup.id ] = buffer;
  16610. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16611. }
  16612. // ensure to update the binding points/block indices mapping for this program
  16613. const webglProgram = program.program;
  16614. state.updateUBOMapping( uniformsGroup, webglProgram );
  16615. // update UBO once per frame
  16616. const frame = info.render.frame;
  16617. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16618. updateBufferData( uniformsGroup );
  16619. updateList[ uniformsGroup.id ] = frame;
  16620. }
  16621. }
  16622. function createBuffer( uniformsGroup ) {
  16623. // the setup of an UBO is independent of a particular shader program but global
  16624. const bindingPointIndex = allocateBindingPointIndex();
  16625. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16626. const buffer = gl.createBuffer();
  16627. const size = uniformsGroup.__size;
  16628. const usage = uniformsGroup.usage;
  16629. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16630. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16631. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16632. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16633. return buffer;
  16634. }
  16635. function allocateBindingPointIndex() {
  16636. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16637. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16638. allocatedBindingPoints.push( i );
  16639. return i;
  16640. }
  16641. }
  16642. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16643. return 0;
  16644. }
  16645. function updateBufferData( uniformsGroup ) {
  16646. const buffer = buffers[ uniformsGroup.id ];
  16647. const uniforms = uniformsGroup.uniforms;
  16648. const cache = uniformsGroup.__cache;
  16649. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16650. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16651. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16652. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16653. const uniform = uniformArray[ j ];
  16654. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  16655. const offset = uniform.__offset;
  16656. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16657. let arrayOffset = 0;
  16658. for ( let k = 0; k < values.length; k ++ ) {
  16659. const value = values[ k ];
  16660. const info = getUniformSize( value );
  16661. // TODO add integer and struct support
  16662. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16663. uniform.__data[ 0 ] = value;
  16664. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16665. } else if ( value.isMatrix3 ) {
  16666. // manually converting 3x3 to 3x4
  16667. uniform.__data[ 0 ] = value.elements[ 0 ];
  16668. uniform.__data[ 1 ] = value.elements[ 1 ];
  16669. uniform.__data[ 2 ] = value.elements[ 2 ];
  16670. uniform.__data[ 3 ] = 0;
  16671. uniform.__data[ 4 ] = value.elements[ 3 ];
  16672. uniform.__data[ 5 ] = value.elements[ 4 ];
  16673. uniform.__data[ 6 ] = value.elements[ 5 ];
  16674. uniform.__data[ 7 ] = 0;
  16675. uniform.__data[ 8 ] = value.elements[ 6 ];
  16676. uniform.__data[ 9 ] = value.elements[ 7 ];
  16677. uniform.__data[ 10 ] = value.elements[ 8 ];
  16678. uniform.__data[ 11 ] = 0;
  16679. } else {
  16680. value.toArray( uniform.__data, arrayOffset );
  16681. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16682. }
  16683. }
  16684. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16685. }
  16686. }
  16687. }
  16688. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16689. }
  16690. function hasUniformChanged( uniform, index, indexArray, cache ) {
  16691. const value = uniform.value;
  16692. const indexString = index + '_' + indexArray;
  16693. if ( cache[ indexString ] === undefined ) {
  16694. // cache entry does not exist so far
  16695. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16696. cache[ indexString ] = value;
  16697. } else {
  16698. cache[ indexString ] = value.clone();
  16699. }
  16700. return true;
  16701. } else {
  16702. const cachedObject = cache[ indexString ];
  16703. // compare current value with cached entry
  16704. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16705. if ( cachedObject !== value ) {
  16706. cache[ indexString ] = value;
  16707. return true;
  16708. }
  16709. } else {
  16710. if ( cachedObject.equals( value ) === false ) {
  16711. cachedObject.copy( value );
  16712. return true;
  16713. }
  16714. }
  16715. }
  16716. return false;
  16717. }
  16718. function prepareUniformsGroup( uniformsGroup ) {
  16719. // determine total buffer size according to the STD140 layout
  16720. // Hint: STD140 is the only supported layout in WebGL 2
  16721. const uniforms = uniformsGroup.uniforms;
  16722. let offset = 0; // global buffer offset in bytes
  16723. const chunkSize = 16; // size of a chunk in bytes
  16724. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16725. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16726. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16727. const uniform = uniformArray[ j ];
  16728. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16729. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  16730. const value = values[ k ];
  16731. const info = getUniformSize( value );
  16732. // Calculate the chunk offset
  16733. const chunkOffsetUniform = offset % chunkSize;
  16734. // Check for chunk overflow
  16735. if ( chunkOffsetUniform !== 0 && ( chunkSize - chunkOffsetUniform ) < info.boundary ) {
  16736. // Add padding and adjust offset
  16737. offset += ( chunkSize - chunkOffsetUniform );
  16738. }
  16739. // the following two properties will be used for partial buffer updates
  16740. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  16741. uniform.__offset = offset;
  16742. // Update the global offset
  16743. offset += info.storage;
  16744. }
  16745. }
  16746. }
  16747. // ensure correct final padding
  16748. const chunkOffset = offset % chunkSize;
  16749. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16750. //
  16751. uniformsGroup.__size = offset;
  16752. uniformsGroup.__cache = {};
  16753. return this;
  16754. }
  16755. function getUniformSize( value ) {
  16756. const info = {
  16757. boundary: 0, // bytes
  16758. storage: 0 // bytes
  16759. };
  16760. // determine sizes according to STD140
  16761. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16762. // float/int/bool
  16763. info.boundary = 4;
  16764. info.storage = 4;
  16765. } else if ( value.isVector2 ) {
  16766. // vec2
  16767. info.boundary = 8;
  16768. info.storage = 8;
  16769. } else if ( value.isVector3 || value.isColor ) {
  16770. // vec3
  16771. info.boundary = 16;
  16772. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16773. } else if ( value.isVector4 ) {
  16774. // vec4
  16775. info.boundary = 16;
  16776. info.storage = 16;
  16777. } else if ( value.isMatrix3 ) {
  16778. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16779. info.boundary = 48;
  16780. info.storage = 48;
  16781. } else if ( value.isMatrix4 ) {
  16782. // mat4
  16783. info.boundary = 64;
  16784. info.storage = 64;
  16785. } else if ( value.isTexture ) {
  16786. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16787. } else {
  16788. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16789. }
  16790. return info;
  16791. }
  16792. function onUniformsGroupsDispose( event ) {
  16793. const uniformsGroup = event.target;
  16794. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16795. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16796. allocatedBindingPoints.splice( index, 1 );
  16797. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16798. delete buffers[ uniformsGroup.id ];
  16799. delete updateList[ uniformsGroup.id ];
  16800. }
  16801. function dispose() {
  16802. for ( const id in buffers ) {
  16803. gl.deleteBuffer( buffers[ id ] );
  16804. }
  16805. allocatedBindingPoints = [];
  16806. buffers = {};
  16807. updateList = {};
  16808. }
  16809. return {
  16810. bind: bind,
  16811. update: update,
  16812. dispose: dispose
  16813. };
  16814. }
  16815. class WebGLRenderer {
  16816. constructor( parameters = {} ) {
  16817. const {
  16818. canvas = createCanvasElement(),
  16819. context = null,
  16820. depth = true,
  16821. stencil = false,
  16822. alpha = false,
  16823. antialias = false,
  16824. premultipliedAlpha = true,
  16825. preserveDrawingBuffer = false,
  16826. powerPreference = 'default',
  16827. failIfMajorPerformanceCaveat = false,
  16828. } = parameters;
  16829. this.isWebGLRenderer = true;
  16830. let _alpha;
  16831. if ( context !== null ) {
  16832. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  16833. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  16834. }
  16835. _alpha = context.getContextAttributes().alpha;
  16836. } else {
  16837. _alpha = alpha;
  16838. }
  16839. const uintClearColor = new Uint32Array( 4 );
  16840. const intClearColor = new Int32Array( 4 );
  16841. let currentRenderList = null;
  16842. let currentRenderState = null;
  16843. // render() can be called from within a callback triggered by another render.
  16844. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16845. const renderListStack = [];
  16846. const renderStateStack = [];
  16847. // public properties
  16848. this.domElement = canvas;
  16849. // Debug configuration container
  16850. this.debug = {
  16851. /**
  16852. * Enables error checking and reporting when shader programs are being compiled
  16853. * @type {boolean}
  16854. */
  16855. checkShaderErrors: true,
  16856. /**
  16857. * Callback for custom error reporting.
  16858. * @type {?Function}
  16859. */
  16860. onShaderError: null
  16861. };
  16862. // clearing
  16863. this.autoClear = true;
  16864. this.autoClearColor = true;
  16865. this.autoClearDepth = true;
  16866. this.autoClearStencil = true;
  16867. // scene graph
  16868. this.sortObjects = true;
  16869. // user-defined clipping
  16870. this.clippingPlanes = [];
  16871. this.localClippingEnabled = false;
  16872. // physically based shading
  16873. this._outputColorSpace = SRGBColorSpace;
  16874. // physical lights
  16875. this._useLegacyLights = false;
  16876. // tone mapping
  16877. this.toneMapping = NoToneMapping;
  16878. this.toneMappingExposure = 1.0;
  16879. // internal properties
  16880. const _this = this;
  16881. let _isContextLost = false;
  16882. // internal state cache
  16883. let _currentActiveCubeFace = 0;
  16884. let _currentActiveMipmapLevel = 0;
  16885. let _currentRenderTarget = null;
  16886. let _currentMaterialId = - 1;
  16887. let _currentCamera = null;
  16888. const _currentViewport = new Vector4();
  16889. const _currentScissor = new Vector4();
  16890. let _currentScissorTest = null;
  16891. const _currentClearColor = new Color( 0x000000 );
  16892. let _currentClearAlpha = 0;
  16893. //
  16894. let _width = canvas.width;
  16895. let _height = canvas.height;
  16896. let _pixelRatio = 1;
  16897. let _opaqueSort = null;
  16898. let _transparentSort = null;
  16899. const _viewport = new Vector4( 0, 0, _width, _height );
  16900. const _scissor = new Vector4( 0, 0, _width, _height );
  16901. let _scissorTest = false;
  16902. // frustum
  16903. const _frustum = new Frustum();
  16904. // clipping
  16905. let _clippingEnabled = false;
  16906. let _localClippingEnabled = false;
  16907. // camera matrices cache
  16908. const _projScreenMatrix = new Matrix4();
  16909. const _vector2 = new Vector2();
  16910. const _vector3 = new Vector3();
  16911. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16912. function getTargetPixelRatio() {
  16913. return _currentRenderTarget === null ? _pixelRatio : 1;
  16914. }
  16915. // initialize
  16916. let _gl = context;
  16917. function getContext( contextName, contextAttributes ) {
  16918. const context = canvas.getContext( contextName, contextAttributes );
  16919. if ( context !== null ) return context;
  16920. return null;
  16921. }
  16922. try {
  16923. const contextAttributes = {
  16924. alpha: true,
  16925. depth,
  16926. stencil,
  16927. antialias,
  16928. premultipliedAlpha,
  16929. preserveDrawingBuffer,
  16930. powerPreference,
  16931. failIfMajorPerformanceCaveat,
  16932. };
  16933. // OffscreenCanvas does not have setAttribute, see #22811
  16934. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16935. // event listeners must be registered before WebGL context is created, see #12753
  16936. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16937. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16938. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16939. if ( _gl === null ) {
  16940. const contextName = 'webgl2';
  16941. _gl = getContext( contextName, contextAttributes );
  16942. if ( _gl === null ) {
  16943. if ( getContext( contextName ) ) {
  16944. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16945. } else {
  16946. throw new Error( 'Error creating WebGL context.' );
  16947. }
  16948. }
  16949. }
  16950. } catch ( error ) {
  16951. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16952. throw error;
  16953. }
  16954. let extensions, capabilities, state, info;
  16955. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16956. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16957. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16958. let utils, bindingStates, uniformsGroups;
  16959. function initGLContext() {
  16960. extensions = new WebGLExtensions( _gl );
  16961. extensions.init();
  16962. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16963. utils = new WebGLUtils( _gl, extensions );
  16964. state = new WebGLState( _gl );
  16965. info = new WebGLInfo( _gl );
  16966. properties = new WebGLProperties();
  16967. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16968. cubemaps = new WebGLCubeMaps( _this );
  16969. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16970. attributes = new WebGLAttributes( _gl );
  16971. bindingStates = new WebGLBindingStates( _gl, attributes );
  16972. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16973. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16974. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16975. clipping = new WebGLClipping( properties );
  16976. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16977. materials = new WebGLMaterials( _this, properties );
  16978. renderLists = new WebGLRenderLists();
  16979. renderStates = new WebGLRenderStates( extensions );
  16980. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  16981. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16982. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16983. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  16984. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  16985. info.programs = programCache.programs;
  16986. _this.capabilities = capabilities;
  16987. _this.extensions = extensions;
  16988. _this.properties = properties;
  16989. _this.renderLists = renderLists;
  16990. _this.shadowMap = shadowMap;
  16991. _this.state = state;
  16992. _this.info = info;
  16993. }
  16994. initGLContext();
  16995. // xr
  16996. const xr = new WebXRManager( _this, _gl );
  16997. this.xr = xr;
  16998. // API
  16999. this.getContext = function () {
  17000. return _gl;
  17001. };
  17002. this.getContextAttributes = function () {
  17003. return _gl.getContextAttributes();
  17004. };
  17005. this.forceContextLoss = function () {
  17006. const extension = extensions.get( 'WEBGL_lose_context' );
  17007. if ( extension ) extension.loseContext();
  17008. };
  17009. this.forceContextRestore = function () {
  17010. const extension = extensions.get( 'WEBGL_lose_context' );
  17011. if ( extension ) extension.restoreContext();
  17012. };
  17013. this.getPixelRatio = function () {
  17014. return _pixelRatio;
  17015. };
  17016. this.setPixelRatio = function ( value ) {
  17017. if ( value === undefined ) return;
  17018. _pixelRatio = value;
  17019. this.setSize( _width, _height, false );
  17020. };
  17021. this.getSize = function ( target ) {
  17022. return target.set( _width, _height );
  17023. };
  17024. this.setSize = function ( width, height, updateStyle = true ) {
  17025. if ( xr.isPresenting ) {
  17026. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17027. return;
  17028. }
  17029. _width = width;
  17030. _height = height;
  17031. canvas.width = Math.floor( width * _pixelRatio );
  17032. canvas.height = Math.floor( height * _pixelRatio );
  17033. if ( updateStyle === true ) {
  17034. canvas.style.width = width + 'px';
  17035. canvas.style.height = height + 'px';
  17036. }
  17037. this.setViewport( 0, 0, width, height );
  17038. };
  17039. this.getDrawingBufferSize = function ( target ) {
  17040. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  17041. };
  17042. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17043. _width = width;
  17044. _height = height;
  17045. _pixelRatio = pixelRatio;
  17046. canvas.width = Math.floor( width * pixelRatio );
  17047. canvas.height = Math.floor( height * pixelRatio );
  17048. this.setViewport( 0, 0, width, height );
  17049. };
  17050. this.getCurrentViewport = function ( target ) {
  17051. return target.copy( _currentViewport );
  17052. };
  17053. this.getViewport = function ( target ) {
  17054. return target.copy( _viewport );
  17055. };
  17056. this.setViewport = function ( x, y, width, height ) {
  17057. if ( x.isVector4 ) {
  17058. _viewport.set( x.x, x.y, x.z, x.w );
  17059. } else {
  17060. _viewport.set( x, y, width, height );
  17061. }
  17062. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  17063. };
  17064. this.getScissor = function ( target ) {
  17065. return target.copy( _scissor );
  17066. };
  17067. this.setScissor = function ( x, y, width, height ) {
  17068. if ( x.isVector4 ) {
  17069. _scissor.set( x.x, x.y, x.z, x.w );
  17070. } else {
  17071. _scissor.set( x, y, width, height );
  17072. }
  17073. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  17074. };
  17075. this.getScissorTest = function () {
  17076. return _scissorTest;
  17077. };
  17078. this.setScissorTest = function ( boolean ) {
  17079. state.setScissorTest( _scissorTest = boolean );
  17080. };
  17081. this.setOpaqueSort = function ( method ) {
  17082. _opaqueSort = method;
  17083. };
  17084. this.setTransparentSort = function ( method ) {
  17085. _transparentSort = method;
  17086. };
  17087. // Clearing
  17088. this.getClearColor = function ( target ) {
  17089. return target.copy( background.getClearColor() );
  17090. };
  17091. this.setClearColor = function () {
  17092. background.setClearColor.apply( background, arguments );
  17093. };
  17094. this.getClearAlpha = function () {
  17095. return background.getClearAlpha();
  17096. };
  17097. this.setClearAlpha = function () {
  17098. background.setClearAlpha.apply( background, arguments );
  17099. };
  17100. this.clear = function ( color = true, depth = true, stencil = true ) {
  17101. let bits = 0;
  17102. if ( color ) {
  17103. // check if we're trying to clear an integer target
  17104. let isIntegerFormat = false;
  17105. if ( _currentRenderTarget !== null ) {
  17106. const targetFormat = _currentRenderTarget.texture.format;
  17107. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  17108. targetFormat === RGIntegerFormat ||
  17109. targetFormat === RedIntegerFormat;
  17110. }
  17111. // use the appropriate clear functions to clear the target if it's a signed
  17112. // or unsigned integer target
  17113. if ( isIntegerFormat ) {
  17114. const targetType = _currentRenderTarget.texture.type;
  17115. const isUnsignedType = targetType === UnsignedByteType ||
  17116. targetType === UnsignedIntType ||
  17117. targetType === UnsignedShortType ||
  17118. targetType === UnsignedInt248Type ||
  17119. targetType === UnsignedShort4444Type ||
  17120. targetType === UnsignedShort5551Type;
  17121. const clearColor = background.getClearColor();
  17122. const a = background.getClearAlpha();
  17123. const r = clearColor.r;
  17124. const g = clearColor.g;
  17125. const b = clearColor.b;
  17126. if ( isUnsignedType ) {
  17127. uintClearColor[ 0 ] = r;
  17128. uintClearColor[ 1 ] = g;
  17129. uintClearColor[ 2 ] = b;
  17130. uintClearColor[ 3 ] = a;
  17131. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  17132. } else {
  17133. intClearColor[ 0 ] = r;
  17134. intClearColor[ 1 ] = g;
  17135. intClearColor[ 2 ] = b;
  17136. intClearColor[ 3 ] = a;
  17137. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  17138. }
  17139. } else {
  17140. bits |= _gl.COLOR_BUFFER_BIT;
  17141. }
  17142. }
  17143. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17144. if ( stencil ) {
  17145. bits |= _gl.STENCIL_BUFFER_BIT;
  17146. this.state.buffers.stencil.setMask( 0xffffffff );
  17147. }
  17148. _gl.clear( bits );
  17149. };
  17150. this.clearColor = function () {
  17151. this.clear( true, false, false );
  17152. };
  17153. this.clearDepth = function () {
  17154. this.clear( false, true, false );
  17155. };
  17156. this.clearStencil = function () {
  17157. this.clear( false, false, true );
  17158. };
  17159. //
  17160. this.dispose = function () {
  17161. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17162. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17163. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17164. renderLists.dispose();
  17165. renderStates.dispose();
  17166. properties.dispose();
  17167. cubemaps.dispose();
  17168. cubeuvmaps.dispose();
  17169. objects.dispose();
  17170. bindingStates.dispose();
  17171. uniformsGroups.dispose();
  17172. programCache.dispose();
  17173. xr.dispose();
  17174. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  17175. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  17176. animation.stop();
  17177. };
  17178. // Events
  17179. function onContextLost( event ) {
  17180. event.preventDefault();
  17181. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17182. _isContextLost = true;
  17183. }
  17184. function onContextRestore( /* event */ ) {
  17185. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17186. _isContextLost = false;
  17187. const infoAutoReset = info.autoReset;
  17188. const shadowMapEnabled = shadowMap.enabled;
  17189. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17190. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17191. const shadowMapType = shadowMap.type;
  17192. initGLContext();
  17193. info.autoReset = infoAutoReset;
  17194. shadowMap.enabled = shadowMapEnabled;
  17195. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17196. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17197. shadowMap.type = shadowMapType;
  17198. }
  17199. function onContextCreationError( event ) {
  17200. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17201. }
  17202. function onMaterialDispose( event ) {
  17203. const material = event.target;
  17204. material.removeEventListener( 'dispose', onMaterialDispose );
  17205. deallocateMaterial( material );
  17206. }
  17207. // Buffer deallocation
  17208. function deallocateMaterial( material ) {
  17209. releaseMaterialProgramReferences( material );
  17210. properties.remove( material );
  17211. }
  17212. function releaseMaterialProgramReferences( material ) {
  17213. const programs = properties.get( material ).programs;
  17214. if ( programs !== undefined ) {
  17215. programs.forEach( function ( program ) {
  17216. programCache.releaseProgram( program );
  17217. } );
  17218. if ( material.isShaderMaterial ) {
  17219. programCache.releaseShaderCache( material );
  17220. }
  17221. }
  17222. }
  17223. // Buffer rendering
  17224. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17225. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17226. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17227. const program = setProgram( camera, scene, geometry, material, object );
  17228. state.setMaterial( material, frontFaceCW );
  17229. //
  17230. let index = geometry.index;
  17231. let rangeFactor = 1;
  17232. if ( material.wireframe === true ) {
  17233. index = geometries.getWireframeAttribute( geometry );
  17234. if ( index === undefined ) return;
  17235. rangeFactor = 2;
  17236. }
  17237. //
  17238. const drawRange = geometry.drawRange;
  17239. const position = geometry.attributes.position;
  17240. let drawStart = drawRange.start * rangeFactor;
  17241. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17242. if ( group !== null ) {
  17243. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17244. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17245. }
  17246. if ( index !== null ) {
  17247. drawStart = Math.max( drawStart, 0 );
  17248. drawEnd = Math.min( drawEnd, index.count );
  17249. } else if ( position !== undefined && position !== null ) {
  17250. drawStart = Math.max( drawStart, 0 );
  17251. drawEnd = Math.min( drawEnd, position.count );
  17252. }
  17253. const drawCount = drawEnd - drawStart;
  17254. if ( drawCount < 0 || drawCount === Infinity ) return;
  17255. //
  17256. bindingStates.setup( object, material, program, geometry, index );
  17257. let attribute;
  17258. let renderer = bufferRenderer;
  17259. if ( index !== null ) {
  17260. attribute = attributes.get( index );
  17261. renderer = indexedBufferRenderer;
  17262. renderer.setIndex( attribute );
  17263. }
  17264. //
  17265. if ( object.isMesh ) {
  17266. if ( material.wireframe === true ) {
  17267. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17268. renderer.setMode( _gl.LINES );
  17269. } else {
  17270. renderer.setMode( _gl.TRIANGLES );
  17271. }
  17272. } else if ( object.isLine ) {
  17273. let lineWidth = material.linewidth;
  17274. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17275. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17276. if ( object.isLineSegments ) {
  17277. renderer.setMode( _gl.LINES );
  17278. } else if ( object.isLineLoop ) {
  17279. renderer.setMode( _gl.LINE_LOOP );
  17280. } else {
  17281. renderer.setMode( _gl.LINE_STRIP );
  17282. }
  17283. } else if ( object.isPoints ) {
  17284. renderer.setMode( _gl.POINTS );
  17285. } else if ( object.isSprite ) {
  17286. renderer.setMode( _gl.TRIANGLES );
  17287. }
  17288. if ( object.isBatchedMesh ) {
  17289. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  17290. } else if ( object.isInstancedMesh ) {
  17291. renderer.renderInstances( drawStart, drawCount, object.count );
  17292. } else if ( geometry.isInstancedBufferGeometry ) {
  17293. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17294. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17295. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17296. } else {
  17297. renderer.render( drawStart, drawCount );
  17298. }
  17299. };
  17300. // Compile
  17301. function prepareMaterial( material, scene, object ) {
  17302. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17303. material.side = BackSide;
  17304. material.needsUpdate = true;
  17305. getProgram( material, scene, object );
  17306. material.side = FrontSide;
  17307. material.needsUpdate = true;
  17308. getProgram( material, scene, object );
  17309. material.side = DoubleSide;
  17310. } else {
  17311. getProgram( material, scene, object );
  17312. }
  17313. }
  17314. this.compile = function ( scene, camera, targetScene = null ) {
  17315. if ( targetScene === null ) targetScene = scene;
  17316. currentRenderState = renderStates.get( targetScene );
  17317. currentRenderState.init();
  17318. renderStateStack.push( currentRenderState );
  17319. // gather lights from both the target scene and the new object that will be added to the scene.
  17320. targetScene.traverseVisible( function ( object ) {
  17321. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17322. currentRenderState.pushLight( object );
  17323. if ( object.castShadow ) {
  17324. currentRenderState.pushShadow( object );
  17325. }
  17326. }
  17327. } );
  17328. if ( scene !== targetScene ) {
  17329. scene.traverseVisible( function ( object ) {
  17330. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17331. currentRenderState.pushLight( object );
  17332. if ( object.castShadow ) {
  17333. currentRenderState.pushShadow( object );
  17334. }
  17335. }
  17336. } );
  17337. }
  17338. currentRenderState.setupLights( _this._useLegacyLights );
  17339. // Only initialize materials in the new scene, not the targetScene.
  17340. const materials = new Set();
  17341. scene.traverse( function ( object ) {
  17342. const material = object.material;
  17343. if ( material ) {
  17344. if ( Array.isArray( material ) ) {
  17345. for ( let i = 0; i < material.length; i ++ ) {
  17346. const material2 = material[ i ];
  17347. prepareMaterial( material2, targetScene, object );
  17348. materials.add( material2 );
  17349. }
  17350. } else {
  17351. prepareMaterial( material, targetScene, object );
  17352. materials.add( material );
  17353. }
  17354. }
  17355. } );
  17356. renderStateStack.pop();
  17357. currentRenderState = null;
  17358. return materials;
  17359. };
  17360. // compileAsync
  17361. this.compileAsync = function ( scene, camera, targetScene = null ) {
  17362. const materials = this.compile( scene, camera, targetScene );
  17363. // Wait for all the materials in the new object to indicate that they're
  17364. // ready to be used before resolving the promise.
  17365. return new Promise( ( resolve ) => {
  17366. function checkMaterialsReady() {
  17367. materials.forEach( function ( material ) {
  17368. const materialProperties = properties.get( material );
  17369. const program = materialProperties.currentProgram;
  17370. if ( program.isReady() ) {
  17371. // remove any programs that report they're ready to use from the list
  17372. materials.delete( material );
  17373. }
  17374. } );
  17375. // once the list of compiling materials is empty, call the callback
  17376. if ( materials.size === 0 ) {
  17377. resolve( scene );
  17378. return;
  17379. }
  17380. // if some materials are still not ready, wait a bit and check again
  17381. setTimeout( checkMaterialsReady, 10 );
  17382. }
  17383. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  17384. // If we can check the compilation status of the materials without
  17385. // blocking then do so right away.
  17386. checkMaterialsReady();
  17387. } else {
  17388. // Otherwise start by waiting a bit to give the materials we just
  17389. // initialized a chance to finish.
  17390. setTimeout( checkMaterialsReady, 10 );
  17391. }
  17392. } );
  17393. };
  17394. // Animation Loop
  17395. let onAnimationFrameCallback = null;
  17396. function onAnimationFrame( time ) {
  17397. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17398. }
  17399. function onXRSessionStart() {
  17400. animation.stop();
  17401. }
  17402. function onXRSessionEnd() {
  17403. animation.start();
  17404. }
  17405. const animation = new WebGLAnimation();
  17406. animation.setAnimationLoop( onAnimationFrame );
  17407. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17408. this.setAnimationLoop = function ( callback ) {
  17409. onAnimationFrameCallback = callback;
  17410. xr.setAnimationLoop( callback );
  17411. ( callback === null ) ? animation.stop() : animation.start();
  17412. };
  17413. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17414. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17415. // Rendering
  17416. this.render = function ( scene, camera ) {
  17417. if ( camera !== undefined && camera.isCamera !== true ) {
  17418. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17419. return;
  17420. }
  17421. if ( _isContextLost === true ) return;
  17422. // update scene graph
  17423. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17424. // update camera matrices and frustum
  17425. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17426. if ( xr.enabled === true && xr.isPresenting === true ) {
  17427. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  17428. camera = xr.getCamera(); // use XR camera for rendering
  17429. }
  17430. //
  17431. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17432. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17433. currentRenderState.init();
  17434. renderStateStack.push( currentRenderState );
  17435. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17436. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17437. _localClippingEnabled = this.localClippingEnabled;
  17438. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17439. currentRenderList = renderLists.get( scene, renderListStack.length );
  17440. currentRenderList.init();
  17441. renderListStack.push( currentRenderList );
  17442. projectObject( scene, camera, 0, _this.sortObjects );
  17443. currentRenderList.finish();
  17444. if ( _this.sortObjects === true ) {
  17445. currentRenderList.sort( _opaqueSort, _transparentSort );
  17446. }
  17447. //
  17448. this.info.render.frame ++;
  17449. if ( _clippingEnabled === true ) clipping.beginShadows();
  17450. const shadowsArray = currentRenderState.state.shadowsArray;
  17451. shadowMap.render( shadowsArray, scene, camera );
  17452. if ( _clippingEnabled === true ) clipping.endShadows();
  17453. //
  17454. if ( this.info.autoReset === true ) this.info.reset();
  17455. //
  17456. if ( xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false ) {
  17457. background.render( currentRenderList, scene );
  17458. }
  17459. // render scene
  17460. currentRenderState.setupLights( _this._useLegacyLights );
  17461. if ( camera.isArrayCamera ) {
  17462. const cameras = camera.cameras;
  17463. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17464. const camera2 = cameras[ i ];
  17465. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17466. }
  17467. } else {
  17468. renderScene( currentRenderList, scene, camera );
  17469. }
  17470. //
  17471. if ( _currentRenderTarget !== null ) {
  17472. // resolve multisample renderbuffers to a single-sample texture if necessary
  17473. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17474. // Generate mipmap if we're using any kind of mipmap filtering
  17475. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17476. }
  17477. //
  17478. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17479. // _gl.finish();
  17480. bindingStates.resetDefaultState();
  17481. _currentMaterialId = - 1;
  17482. _currentCamera = null;
  17483. renderStateStack.pop();
  17484. if ( renderStateStack.length > 0 ) {
  17485. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17486. } else {
  17487. currentRenderState = null;
  17488. }
  17489. renderListStack.pop();
  17490. if ( renderListStack.length > 0 ) {
  17491. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17492. } else {
  17493. currentRenderList = null;
  17494. }
  17495. };
  17496. function projectObject( object, camera, groupOrder, sortObjects ) {
  17497. if ( object.visible === false ) return;
  17498. const visible = object.layers.test( camera.layers );
  17499. if ( visible ) {
  17500. if ( object.isGroup ) {
  17501. groupOrder = object.renderOrder;
  17502. } else if ( object.isLOD ) {
  17503. if ( object.autoUpdate === true ) object.update( camera );
  17504. } else if ( object.isLight ) {
  17505. currentRenderState.pushLight( object );
  17506. if ( object.castShadow ) {
  17507. currentRenderState.pushShadow( object );
  17508. }
  17509. } else if ( object.isSprite ) {
  17510. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17511. if ( sortObjects ) {
  17512. _vector3.setFromMatrixPosition( object.matrixWorld )
  17513. .applyMatrix4( _projScreenMatrix );
  17514. }
  17515. const geometry = objects.update( object );
  17516. const material = object.material;
  17517. if ( material.visible ) {
  17518. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17519. }
  17520. }
  17521. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17522. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17523. const geometry = objects.update( object );
  17524. const material = object.material;
  17525. if ( sortObjects ) {
  17526. if ( object.boundingSphere !== undefined ) {
  17527. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17528. _vector3.copy( object.boundingSphere.center );
  17529. } else {
  17530. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17531. _vector3.copy( geometry.boundingSphere.center );
  17532. }
  17533. _vector3
  17534. .applyMatrix4( object.matrixWorld )
  17535. .applyMatrix4( _projScreenMatrix );
  17536. }
  17537. if ( Array.isArray( material ) ) {
  17538. const groups = geometry.groups;
  17539. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17540. const group = groups[ i ];
  17541. const groupMaterial = material[ group.materialIndex ];
  17542. if ( groupMaterial && groupMaterial.visible ) {
  17543. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17544. }
  17545. }
  17546. } else if ( material.visible ) {
  17547. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17548. }
  17549. }
  17550. }
  17551. }
  17552. const children = object.children;
  17553. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17554. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17555. }
  17556. }
  17557. function renderScene( currentRenderList, scene, camera, viewport ) {
  17558. const opaqueObjects = currentRenderList.opaque;
  17559. const transmissiveObjects = currentRenderList.transmissive;
  17560. const transparentObjects = currentRenderList.transparent;
  17561. currentRenderState.setupLightsView( camera );
  17562. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17563. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17564. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17565. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17566. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17567. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17568. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17569. state.buffers.depth.setTest( true );
  17570. state.buffers.depth.setMask( true );
  17571. state.buffers.color.setMask( true );
  17572. state.setPolygonOffset( false );
  17573. }
  17574. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17575. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17576. if ( overrideMaterial !== null ) {
  17577. return;
  17578. }
  17579. if ( currentRenderState.state.transmissionRenderTarget === null ) {
  17580. currentRenderState.state.transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  17581. generateMipmaps: true,
  17582. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  17583. minFilter: LinearMipmapLinearFilter,
  17584. samples: 4,
  17585. stencilBuffer: stencil
  17586. } );
  17587. const renderTargetProperties = properties.get( currentRenderState.state.transmissionRenderTarget );
  17588. renderTargetProperties.__isTransmissionRenderTarget = true;
  17589. // debug
  17590. /*
  17591. const geometry = new PlaneGeometry();
  17592. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17593. const mesh = new Mesh( geometry, material );
  17594. scene.add( mesh );
  17595. */
  17596. }
  17597. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget;
  17598. _this.getDrawingBufferSize( _vector2 );
  17599. transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  17600. //
  17601. const currentRenderTarget = _this.getRenderTarget();
  17602. _this.setRenderTarget( transmissionRenderTarget );
  17603. _this.getClearColor( _currentClearColor );
  17604. _currentClearAlpha = _this.getClearAlpha();
  17605. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  17606. _this.clear();
  17607. // Turn off the features which can affect the frag color for opaque objects pass.
  17608. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17609. const currentToneMapping = _this.toneMapping;
  17610. _this.toneMapping = NoToneMapping;
  17611. renderObjects( opaqueObjects, scene, camera );
  17612. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  17613. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  17614. let renderTargetNeedsUpdate = false;
  17615. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17616. const renderItem = transmissiveObjects[ i ];
  17617. const object = renderItem.object;
  17618. const geometry = renderItem.geometry;
  17619. const material = renderItem.material;
  17620. const group = renderItem.group;
  17621. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17622. const currentSide = material.side;
  17623. material.side = BackSide;
  17624. material.needsUpdate = true;
  17625. renderObject( object, scene, camera, geometry, material, group );
  17626. material.side = currentSide;
  17627. material.needsUpdate = true;
  17628. renderTargetNeedsUpdate = true;
  17629. }
  17630. }
  17631. if ( renderTargetNeedsUpdate === true ) {
  17632. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  17633. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  17634. }
  17635. _this.setRenderTarget( currentRenderTarget );
  17636. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  17637. _this.toneMapping = currentToneMapping;
  17638. }
  17639. function renderObjects( renderList, scene, camera ) {
  17640. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17641. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17642. const renderItem = renderList[ i ];
  17643. const object = renderItem.object;
  17644. const geometry = renderItem.geometry;
  17645. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17646. const group = renderItem.group;
  17647. if ( object.layers.test( camera.layers ) ) {
  17648. renderObject( object, scene, camera, geometry, material, group );
  17649. }
  17650. }
  17651. }
  17652. function renderObject( object, scene, camera, geometry, material, group ) {
  17653. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17654. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17655. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17656. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17657. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17658. material.side = BackSide;
  17659. material.needsUpdate = true;
  17660. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17661. material.side = FrontSide;
  17662. material.needsUpdate = true;
  17663. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17664. material.side = DoubleSide;
  17665. } else {
  17666. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17667. }
  17668. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17669. }
  17670. function getProgram( material, scene, object ) {
  17671. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17672. const materialProperties = properties.get( material );
  17673. const lights = currentRenderState.state.lights;
  17674. const shadowsArray = currentRenderState.state.shadowsArray;
  17675. const lightsStateVersion = lights.state.version;
  17676. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17677. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17678. let programs = materialProperties.programs;
  17679. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17680. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17681. materialProperties.fog = scene.fog;
  17682. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17683. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  17684. if ( programs === undefined ) {
  17685. // new material
  17686. material.addEventListener( 'dispose', onMaterialDispose );
  17687. programs = new Map();
  17688. materialProperties.programs = programs;
  17689. }
  17690. let program = programs.get( programCacheKey );
  17691. if ( program !== undefined ) {
  17692. // early out if program and light state is identical
  17693. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17694. updateCommonMaterialProperties( material, parameters );
  17695. return program;
  17696. }
  17697. } else {
  17698. parameters.uniforms = programCache.getUniforms( material );
  17699. material.onBuild( object, parameters, _this );
  17700. material.onBeforeCompile( parameters, _this );
  17701. program = programCache.acquireProgram( parameters, programCacheKey );
  17702. programs.set( programCacheKey, program );
  17703. materialProperties.uniforms = parameters.uniforms;
  17704. }
  17705. const uniforms = materialProperties.uniforms;
  17706. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17707. uniforms.clippingPlanes = clipping.uniform;
  17708. }
  17709. updateCommonMaterialProperties( material, parameters );
  17710. // store the light setup it was created for
  17711. materialProperties.needsLights = materialNeedsLights( material );
  17712. materialProperties.lightsStateVersion = lightsStateVersion;
  17713. if ( materialProperties.needsLights ) {
  17714. // wire up the material to this renderer's lighting state
  17715. uniforms.ambientLightColor.value = lights.state.ambient;
  17716. uniforms.lightProbe.value = lights.state.probe;
  17717. uniforms.directionalLights.value = lights.state.directional;
  17718. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17719. uniforms.spotLights.value = lights.state.spot;
  17720. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17721. uniforms.rectAreaLights.value = lights.state.rectArea;
  17722. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17723. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17724. uniforms.pointLights.value = lights.state.point;
  17725. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17726. uniforms.hemisphereLights.value = lights.state.hemi;
  17727. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17728. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17729. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17730. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17731. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17732. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17733. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17734. // TODO (abelnation): add area lights shadow info to uniforms
  17735. }
  17736. materialProperties.currentProgram = program;
  17737. materialProperties.uniformsList = null;
  17738. return program;
  17739. }
  17740. function getUniformList( materialProperties ) {
  17741. if ( materialProperties.uniformsList === null ) {
  17742. const progUniforms = materialProperties.currentProgram.getUniforms();
  17743. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  17744. }
  17745. return materialProperties.uniformsList;
  17746. }
  17747. function updateCommonMaterialProperties( material, parameters ) {
  17748. const materialProperties = properties.get( material );
  17749. materialProperties.outputColorSpace = parameters.outputColorSpace;
  17750. materialProperties.batching = parameters.batching;
  17751. materialProperties.instancing = parameters.instancing;
  17752. materialProperties.instancingColor = parameters.instancingColor;
  17753. materialProperties.instancingMorph = parameters.instancingMorph;
  17754. materialProperties.skinning = parameters.skinning;
  17755. materialProperties.morphTargets = parameters.morphTargets;
  17756. materialProperties.morphNormals = parameters.morphNormals;
  17757. materialProperties.morphColors = parameters.morphColors;
  17758. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17759. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17760. materialProperties.numIntersection = parameters.numClipIntersection;
  17761. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17762. materialProperties.vertexTangents = parameters.vertexTangents;
  17763. materialProperties.toneMapping = parameters.toneMapping;
  17764. }
  17765. function setProgram( camera, scene, geometry, material, object ) {
  17766. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17767. textures.resetTextureUnits();
  17768. const fog = scene.fog;
  17769. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17770. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  17771. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17772. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17773. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  17774. const morphTargets = !! geometry.morphAttributes.position;
  17775. const morphNormals = !! geometry.morphAttributes.normal;
  17776. const morphColors = !! geometry.morphAttributes.color;
  17777. let toneMapping = NoToneMapping;
  17778. if ( material.toneMapped ) {
  17779. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  17780. toneMapping = _this.toneMapping;
  17781. }
  17782. }
  17783. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17784. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17785. const materialProperties = properties.get( material );
  17786. const lights = currentRenderState.state.lights;
  17787. if ( _clippingEnabled === true ) {
  17788. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17789. const useCache =
  17790. camera === _currentCamera &&
  17791. material.id === _currentMaterialId;
  17792. // we might want to call this function with some ClippingGroup
  17793. // object instead of the material, once it becomes feasible
  17794. // (#8465, #8379)
  17795. clipping.setState( material, camera, useCache );
  17796. }
  17797. }
  17798. //
  17799. let needsProgramChange = false;
  17800. if ( material.version === materialProperties.__version ) {
  17801. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17802. needsProgramChange = true;
  17803. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  17804. needsProgramChange = true;
  17805. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  17806. needsProgramChange = true;
  17807. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  17808. needsProgramChange = true;
  17809. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17810. needsProgramChange = true;
  17811. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17812. needsProgramChange = true;
  17813. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17814. needsProgramChange = true;
  17815. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17816. needsProgramChange = true;
  17817. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  17818. needsProgramChange = true;
  17819. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  17820. needsProgramChange = true;
  17821. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  17822. needsProgramChange = true;
  17823. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  17824. needsProgramChange = true;
  17825. } else if ( materialProperties.envMap !== envMap ) {
  17826. needsProgramChange = true;
  17827. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17828. needsProgramChange = true;
  17829. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17830. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17831. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17832. needsProgramChange = true;
  17833. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17834. needsProgramChange = true;
  17835. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17836. needsProgramChange = true;
  17837. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17838. needsProgramChange = true;
  17839. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17840. needsProgramChange = true;
  17841. } else if ( materialProperties.morphColors !== morphColors ) {
  17842. needsProgramChange = true;
  17843. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17844. needsProgramChange = true;
  17845. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17846. needsProgramChange = true;
  17847. }
  17848. } else {
  17849. needsProgramChange = true;
  17850. materialProperties.__version = material.version;
  17851. }
  17852. //
  17853. let program = materialProperties.currentProgram;
  17854. if ( needsProgramChange === true ) {
  17855. program = getProgram( material, scene, object );
  17856. }
  17857. let refreshProgram = false;
  17858. let refreshMaterial = false;
  17859. let refreshLights = false;
  17860. const p_uniforms = program.getUniforms(),
  17861. m_uniforms = materialProperties.uniforms;
  17862. if ( state.useProgram( program.program ) ) {
  17863. refreshProgram = true;
  17864. refreshMaterial = true;
  17865. refreshLights = true;
  17866. }
  17867. if ( material.id !== _currentMaterialId ) {
  17868. _currentMaterialId = material.id;
  17869. refreshMaterial = true;
  17870. }
  17871. if ( refreshProgram || _currentCamera !== camera ) {
  17872. // common camera uniforms
  17873. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17874. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17875. const uCamPos = p_uniforms.map.cameraPosition;
  17876. if ( uCamPos !== undefined ) {
  17877. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17878. }
  17879. if ( capabilities.logarithmicDepthBuffer ) {
  17880. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17881. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17882. }
  17883. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  17884. if ( material.isMeshPhongMaterial ||
  17885. material.isMeshToonMaterial ||
  17886. material.isMeshLambertMaterial ||
  17887. material.isMeshBasicMaterial ||
  17888. material.isMeshStandardMaterial ||
  17889. material.isShaderMaterial ) {
  17890. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17891. }
  17892. if ( _currentCamera !== camera ) {
  17893. _currentCamera = camera;
  17894. // lighting uniforms depend on the camera so enforce an update
  17895. // now, in case this material supports lights - or later, when
  17896. // the next material that does gets activated:
  17897. refreshMaterial = true; // set to true on material change
  17898. refreshLights = true; // remains set until update done
  17899. }
  17900. }
  17901. // skinning and morph target uniforms must be set even if material didn't change
  17902. // auto-setting of texture unit for bone and morph texture must go before other textures
  17903. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17904. if ( object.isSkinnedMesh ) {
  17905. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17906. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17907. const skeleton = object.skeleton;
  17908. if ( skeleton ) {
  17909. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17910. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17911. }
  17912. }
  17913. if ( object.isBatchedMesh ) {
  17914. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  17915. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  17916. }
  17917. const morphAttributes = geometry.morphAttributes;
  17918. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  17919. morphtargets.update( object, geometry, program );
  17920. }
  17921. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17922. materialProperties.receiveShadow = object.receiveShadow;
  17923. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17924. }
  17925. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17926. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17927. m_uniforms.envMap.value = envMap;
  17928. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17929. }
  17930. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  17931. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  17932. }
  17933. if ( refreshMaterial ) {
  17934. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17935. if ( materialProperties.needsLights ) {
  17936. // the current material requires lighting info
  17937. // note: all lighting uniforms are always set correctly
  17938. // they simply reference the renderer's state for their
  17939. // values
  17940. //
  17941. // use the current material's .needsUpdate flags to set
  17942. // the GL state when required
  17943. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17944. }
  17945. // refresh uniforms common to several materials
  17946. if ( fog && material.fog === true ) {
  17947. materials.refreshFogUniforms( m_uniforms, fog );
  17948. }
  17949. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget );
  17950. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  17951. }
  17952. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17953. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  17954. material.uniformsNeedUpdate = false;
  17955. }
  17956. if ( material.isSpriteMaterial ) {
  17957. p_uniforms.setValue( _gl, 'center', object.center );
  17958. }
  17959. // common matrices
  17960. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17961. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17962. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17963. // UBOs
  17964. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17965. const groups = material.uniformsGroups;
  17966. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17967. const group = groups[ i ];
  17968. uniformsGroups.update( group, program );
  17969. uniformsGroups.bind( group, program );
  17970. }
  17971. }
  17972. return program;
  17973. }
  17974. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17975. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17976. uniforms.ambientLightColor.needsUpdate = value;
  17977. uniforms.lightProbe.needsUpdate = value;
  17978. uniforms.directionalLights.needsUpdate = value;
  17979. uniforms.directionalLightShadows.needsUpdate = value;
  17980. uniforms.pointLights.needsUpdate = value;
  17981. uniforms.pointLightShadows.needsUpdate = value;
  17982. uniforms.spotLights.needsUpdate = value;
  17983. uniforms.spotLightShadows.needsUpdate = value;
  17984. uniforms.rectAreaLights.needsUpdate = value;
  17985. uniforms.hemisphereLights.needsUpdate = value;
  17986. }
  17987. function materialNeedsLights( material ) {
  17988. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17989. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17990. ( material.isShaderMaterial && material.lights === true );
  17991. }
  17992. this.getActiveCubeFace = function () {
  17993. return _currentActiveCubeFace;
  17994. };
  17995. this.getActiveMipmapLevel = function () {
  17996. return _currentActiveMipmapLevel;
  17997. };
  17998. this.getRenderTarget = function () {
  17999. return _currentRenderTarget;
  18000. };
  18001. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  18002. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  18003. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  18004. const renderTargetProperties = properties.get( renderTarget );
  18005. renderTargetProperties.__hasExternalTextures = true;
  18006. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  18007. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  18008. // The multisample_render_to_texture extension doesn't work properly if there
  18009. // are midframe flushes and an external depth buffer. Disable use of the extension.
  18010. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  18011. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  18012. renderTargetProperties.__useRenderToTexture = false;
  18013. }
  18014. }
  18015. };
  18016. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  18017. const renderTargetProperties = properties.get( renderTarget );
  18018. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  18019. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  18020. };
  18021. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  18022. _currentRenderTarget = renderTarget;
  18023. _currentActiveCubeFace = activeCubeFace;
  18024. _currentActiveMipmapLevel = activeMipmapLevel;
  18025. let useDefaultFramebuffer = true;
  18026. let framebuffer = null;
  18027. let isCube = false;
  18028. let isRenderTarget3D = false;
  18029. if ( renderTarget ) {
  18030. const renderTargetProperties = properties.get( renderTarget );
  18031. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  18032. // We need to make sure to rebind the framebuffer.
  18033. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  18034. useDefaultFramebuffer = false;
  18035. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  18036. textures.setupRenderTarget( renderTarget );
  18037. } else if ( renderTargetProperties.__hasExternalTextures ) {
  18038. // Color and depth texture must be rebound in order for the swapchain to update.
  18039. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  18040. }
  18041. const texture = renderTarget.texture;
  18042. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18043. isRenderTarget3D = true;
  18044. }
  18045. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18046. if ( renderTarget.isWebGLCubeRenderTarget ) {
  18047. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  18048. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  18049. } else {
  18050. framebuffer = __webglFramebuffer[ activeCubeFace ];
  18051. }
  18052. isCube = true;
  18053. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  18054. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  18055. } else {
  18056. if ( Array.isArray( __webglFramebuffer ) ) {
  18057. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  18058. } else {
  18059. framebuffer = __webglFramebuffer;
  18060. }
  18061. }
  18062. _currentViewport.copy( renderTarget.viewport );
  18063. _currentScissor.copy( renderTarget.scissor );
  18064. _currentScissorTest = renderTarget.scissorTest;
  18065. } else {
  18066. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  18067. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  18068. _currentScissorTest = _scissorTest;
  18069. }
  18070. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18071. if ( framebufferBound && useDefaultFramebuffer ) {
  18072. state.drawBuffers( renderTarget, framebuffer );
  18073. }
  18074. state.viewport( _currentViewport );
  18075. state.scissor( _currentScissor );
  18076. state.setScissorTest( _currentScissorTest );
  18077. if ( isCube ) {
  18078. const textureProperties = properties.get( renderTarget.texture );
  18079. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  18080. } else if ( isRenderTarget3D ) {
  18081. const textureProperties = properties.get( renderTarget.texture );
  18082. const layer = activeCubeFace || 0;
  18083. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  18084. }
  18085. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  18086. };
  18087. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18088. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18089. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18090. return;
  18091. }
  18092. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18093. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18094. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18095. }
  18096. if ( framebuffer ) {
  18097. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18098. try {
  18099. const texture = renderTarget.texture;
  18100. const textureFormat = texture.format;
  18101. const textureType = texture.type;
  18102. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  18103. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18104. return;
  18105. }
  18106. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  18107. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  18108. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  18109. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18110. return;
  18111. }
  18112. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18113. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18114. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18115. }
  18116. } finally {
  18117. // restore framebuffer of current render target if necessary
  18118. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18119. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18120. }
  18121. }
  18122. };
  18123. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  18124. const levelScale = Math.pow( 2, - level );
  18125. const width = Math.floor( texture.image.width * levelScale );
  18126. const height = Math.floor( texture.image.height * levelScale );
  18127. textures.setTexture2D( texture, 0 );
  18128. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  18129. state.unbindTexture();
  18130. };
  18131. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  18132. const width = srcTexture.image.width;
  18133. const height = srcTexture.image.height;
  18134. const glFormat = utils.convert( dstTexture.format );
  18135. const glType = utils.convert( dstTexture.type );
  18136. textures.setTexture2D( dstTexture, 0 );
  18137. // As another texture upload may have changed pixelStorei
  18138. // parameters, make sure they are correct for the dstTexture
  18139. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18140. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18141. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18142. if ( srcTexture.isDataTexture ) {
  18143. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  18144. } else {
  18145. if ( srcTexture.isCompressedTexture ) {
  18146. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  18147. } else {
  18148. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  18149. }
  18150. }
  18151. // Generate mipmaps only when copying level 0
  18152. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  18153. state.unbindTexture();
  18154. };
  18155. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  18156. const width = Math.round( sourceBox.max.x - sourceBox.min.x );
  18157. const height = Math.round( sourceBox.max.y - sourceBox.min.y );
  18158. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  18159. const glFormat = utils.convert( dstTexture.format );
  18160. const glType = utils.convert( dstTexture.type );
  18161. let glTarget;
  18162. if ( dstTexture.isData3DTexture ) {
  18163. textures.setTexture3D( dstTexture, 0 );
  18164. glTarget = _gl.TEXTURE_3D;
  18165. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  18166. textures.setTexture2DArray( dstTexture, 0 );
  18167. glTarget = _gl.TEXTURE_2D_ARRAY;
  18168. } else {
  18169. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  18170. return;
  18171. }
  18172. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18173. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18174. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18175. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18176. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18177. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18178. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18179. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18180. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18181. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18182. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18183. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  18184. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  18185. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  18186. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  18187. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  18188. } else {
  18189. if ( dstTexture.isCompressedArrayTexture ) {
  18190. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  18191. } else {
  18192. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  18193. }
  18194. }
  18195. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  18196. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  18197. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  18198. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  18199. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  18200. // Generate mipmaps only when copying level 0
  18201. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  18202. state.unbindTexture();
  18203. };
  18204. this.initTexture = function ( texture ) {
  18205. if ( texture.isCubeTexture ) {
  18206. textures.setTextureCube( texture, 0 );
  18207. } else if ( texture.isData3DTexture ) {
  18208. textures.setTexture3D( texture, 0 );
  18209. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18210. textures.setTexture2DArray( texture, 0 );
  18211. } else {
  18212. textures.setTexture2D( texture, 0 );
  18213. }
  18214. state.unbindTexture();
  18215. };
  18216. this.resetState = function () {
  18217. _currentActiveCubeFace = 0;
  18218. _currentActiveMipmapLevel = 0;
  18219. _currentRenderTarget = null;
  18220. state.reset();
  18221. bindingStates.reset();
  18222. };
  18223. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18224. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18225. }
  18226. }
  18227. get coordinateSystem() {
  18228. return WebGLCoordinateSystem;
  18229. }
  18230. get outputColorSpace() {
  18231. return this._outputColorSpace;
  18232. }
  18233. set outputColorSpace( colorSpace ) {
  18234. this._outputColorSpace = colorSpace;
  18235. const gl = this.getContext();
  18236. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18237. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18238. }
  18239. get useLegacyLights() { // @deprecated, r155
  18240. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  18241. return this._useLegacyLights;
  18242. }
  18243. set useLegacyLights( value ) { // @deprecated, r155
  18244. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  18245. this._useLegacyLights = value;
  18246. }
  18247. }
  18248. class FogExp2 {
  18249. constructor( color, density = 0.00025 ) {
  18250. this.isFogExp2 = true;
  18251. this.name = '';
  18252. this.color = new Color( color );
  18253. this.density = density;
  18254. }
  18255. clone() {
  18256. return new FogExp2( this.color, this.density );
  18257. }
  18258. toJSON( /* meta */ ) {
  18259. return {
  18260. type: 'FogExp2',
  18261. name: this.name,
  18262. color: this.color.getHex(),
  18263. density: this.density
  18264. };
  18265. }
  18266. }
  18267. class Fog {
  18268. constructor( color, near = 1, far = 1000 ) {
  18269. this.isFog = true;
  18270. this.name = '';
  18271. this.color = new Color( color );
  18272. this.near = near;
  18273. this.far = far;
  18274. }
  18275. clone() {
  18276. return new Fog( this.color, this.near, this.far );
  18277. }
  18278. toJSON( /* meta */ ) {
  18279. return {
  18280. type: 'Fog',
  18281. name: this.name,
  18282. color: this.color.getHex(),
  18283. near: this.near,
  18284. far: this.far
  18285. };
  18286. }
  18287. }
  18288. class Scene extends Object3D {
  18289. constructor() {
  18290. super();
  18291. this.isScene = true;
  18292. this.type = 'Scene';
  18293. this.background = null;
  18294. this.environment = null;
  18295. this.fog = null;
  18296. this.backgroundBlurriness = 0;
  18297. this.backgroundIntensity = 1;
  18298. this.backgroundRotation = new Euler();
  18299. this.environmentIntensity = 1;
  18300. this.environmentRotation = new Euler();
  18301. this.overrideMaterial = null;
  18302. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18303. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18304. }
  18305. }
  18306. copy( source, recursive ) {
  18307. super.copy( source, recursive );
  18308. if ( source.background !== null ) this.background = source.background.clone();
  18309. if ( source.environment !== null ) this.environment = source.environment.clone();
  18310. if ( source.fog !== null ) this.fog = source.fog.clone();
  18311. this.backgroundBlurriness = source.backgroundBlurriness;
  18312. this.backgroundIntensity = source.backgroundIntensity;
  18313. this.backgroundRotation.copy( source.backgroundRotation );
  18314. this.environmentIntensity = source.environmentIntensity;
  18315. this.environmentRotation.copy( source.environmentRotation );
  18316. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18317. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18318. return this;
  18319. }
  18320. toJSON( meta ) {
  18321. const data = super.toJSON( meta );
  18322. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18323. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18324. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18325. data.object.backgroundRotation = this.backgroundRotation.toArray();
  18326. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  18327. data.object.environmentRotation = this.environmentRotation.toArray();
  18328. return data;
  18329. }
  18330. }
  18331. class InterleavedBuffer {
  18332. constructor( array, stride ) {
  18333. this.isInterleavedBuffer = true;
  18334. this.array = array;
  18335. this.stride = stride;
  18336. this.count = array !== undefined ? array.length / stride : 0;
  18337. this.usage = StaticDrawUsage;
  18338. this._updateRange = { offset: 0, count: - 1 };
  18339. this.updateRanges = [];
  18340. this.version = 0;
  18341. this.uuid = generateUUID();
  18342. }
  18343. onUploadCallback() {}
  18344. set needsUpdate( value ) {
  18345. if ( value === true ) this.version ++;
  18346. }
  18347. get updateRange() {
  18348. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  18349. return this._updateRange;
  18350. }
  18351. setUsage( value ) {
  18352. this.usage = value;
  18353. return this;
  18354. }
  18355. addUpdateRange( start, count ) {
  18356. this.updateRanges.push( { start, count } );
  18357. }
  18358. clearUpdateRanges() {
  18359. this.updateRanges.length = 0;
  18360. }
  18361. copy( source ) {
  18362. this.array = new source.array.constructor( source.array );
  18363. this.count = source.count;
  18364. this.stride = source.stride;
  18365. this.usage = source.usage;
  18366. return this;
  18367. }
  18368. copyAt( index1, attribute, index2 ) {
  18369. index1 *= this.stride;
  18370. index2 *= attribute.stride;
  18371. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18372. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18373. }
  18374. return this;
  18375. }
  18376. set( value, offset = 0 ) {
  18377. this.array.set( value, offset );
  18378. return this;
  18379. }
  18380. clone( data ) {
  18381. if ( data.arrayBuffers === undefined ) {
  18382. data.arrayBuffers = {};
  18383. }
  18384. if ( this.array.buffer._uuid === undefined ) {
  18385. this.array.buffer._uuid = generateUUID();
  18386. }
  18387. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18388. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18389. }
  18390. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18391. const ib = new this.constructor( array, this.stride );
  18392. ib.setUsage( this.usage );
  18393. return ib;
  18394. }
  18395. onUpload( callback ) {
  18396. this.onUploadCallback = callback;
  18397. return this;
  18398. }
  18399. toJSON( data ) {
  18400. if ( data.arrayBuffers === undefined ) {
  18401. data.arrayBuffers = {};
  18402. }
  18403. // generate UUID for array buffer if necessary
  18404. if ( this.array.buffer._uuid === undefined ) {
  18405. this.array.buffer._uuid = generateUUID();
  18406. }
  18407. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18408. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18409. }
  18410. //
  18411. return {
  18412. uuid: this.uuid,
  18413. buffer: this.array.buffer._uuid,
  18414. type: this.array.constructor.name,
  18415. stride: this.stride
  18416. };
  18417. }
  18418. }
  18419. const _vector$6 = /*@__PURE__*/ new Vector3();
  18420. class InterleavedBufferAttribute {
  18421. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18422. this.isInterleavedBufferAttribute = true;
  18423. this.name = '';
  18424. this.data = interleavedBuffer;
  18425. this.itemSize = itemSize;
  18426. this.offset = offset;
  18427. this.normalized = normalized;
  18428. }
  18429. get count() {
  18430. return this.data.count;
  18431. }
  18432. get array() {
  18433. return this.data.array;
  18434. }
  18435. set needsUpdate( value ) {
  18436. this.data.needsUpdate = value;
  18437. }
  18438. applyMatrix4( m ) {
  18439. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18440. _vector$6.fromBufferAttribute( this, i );
  18441. _vector$6.applyMatrix4( m );
  18442. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18443. }
  18444. return this;
  18445. }
  18446. applyNormalMatrix( m ) {
  18447. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18448. _vector$6.fromBufferAttribute( this, i );
  18449. _vector$6.applyNormalMatrix( m );
  18450. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18451. }
  18452. return this;
  18453. }
  18454. transformDirection( m ) {
  18455. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18456. _vector$6.fromBufferAttribute( this, i );
  18457. _vector$6.transformDirection( m );
  18458. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18459. }
  18460. return this;
  18461. }
  18462. getComponent( index, component ) {
  18463. let value = this.array[ index * this.data.stride + this.offset + component ];
  18464. if ( this.normalized ) value = denormalize( value, this.array );
  18465. return value;
  18466. }
  18467. setComponent( index, component, value ) {
  18468. if ( this.normalized ) value = normalize( value, this.array );
  18469. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  18470. return this;
  18471. }
  18472. setX( index, x ) {
  18473. if ( this.normalized ) x = normalize( x, this.array );
  18474. this.data.array[ index * this.data.stride + this.offset ] = x;
  18475. return this;
  18476. }
  18477. setY( index, y ) {
  18478. if ( this.normalized ) y = normalize( y, this.array );
  18479. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18480. return this;
  18481. }
  18482. setZ( index, z ) {
  18483. if ( this.normalized ) z = normalize( z, this.array );
  18484. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18485. return this;
  18486. }
  18487. setW( index, w ) {
  18488. if ( this.normalized ) w = normalize( w, this.array );
  18489. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18490. return this;
  18491. }
  18492. getX( index ) {
  18493. let x = this.data.array[ index * this.data.stride + this.offset ];
  18494. if ( this.normalized ) x = denormalize( x, this.array );
  18495. return x;
  18496. }
  18497. getY( index ) {
  18498. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18499. if ( this.normalized ) y = denormalize( y, this.array );
  18500. return y;
  18501. }
  18502. getZ( index ) {
  18503. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18504. if ( this.normalized ) z = denormalize( z, this.array );
  18505. return z;
  18506. }
  18507. getW( index ) {
  18508. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18509. if ( this.normalized ) w = denormalize( w, this.array );
  18510. return w;
  18511. }
  18512. setXY( index, x, y ) {
  18513. index = index * this.data.stride + this.offset;
  18514. if ( this.normalized ) {
  18515. x = normalize( x, this.array );
  18516. y = normalize( y, this.array );
  18517. }
  18518. this.data.array[ index + 0 ] = x;
  18519. this.data.array[ index + 1 ] = y;
  18520. return this;
  18521. }
  18522. setXYZ( index, x, y, z ) {
  18523. index = index * this.data.stride + this.offset;
  18524. if ( this.normalized ) {
  18525. x = normalize( x, this.array );
  18526. y = normalize( y, this.array );
  18527. z = normalize( z, this.array );
  18528. }
  18529. this.data.array[ index + 0 ] = x;
  18530. this.data.array[ index + 1 ] = y;
  18531. this.data.array[ index + 2 ] = z;
  18532. return this;
  18533. }
  18534. setXYZW( index, x, y, z, w ) {
  18535. index = index * this.data.stride + this.offset;
  18536. if ( this.normalized ) {
  18537. x = normalize( x, this.array );
  18538. y = normalize( y, this.array );
  18539. z = normalize( z, this.array );
  18540. w = normalize( w, this.array );
  18541. }
  18542. this.data.array[ index + 0 ] = x;
  18543. this.data.array[ index + 1 ] = y;
  18544. this.data.array[ index + 2 ] = z;
  18545. this.data.array[ index + 3 ] = w;
  18546. return this;
  18547. }
  18548. clone( data ) {
  18549. if ( data === undefined ) {
  18550. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18551. const array = [];
  18552. for ( let i = 0; i < this.count; i ++ ) {
  18553. const index = i * this.data.stride + this.offset;
  18554. for ( let j = 0; j < this.itemSize; j ++ ) {
  18555. array.push( this.data.array[ index + j ] );
  18556. }
  18557. }
  18558. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18559. } else {
  18560. if ( data.interleavedBuffers === undefined ) {
  18561. data.interleavedBuffers = {};
  18562. }
  18563. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18564. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18565. }
  18566. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18567. }
  18568. }
  18569. toJSON( data ) {
  18570. if ( data === undefined ) {
  18571. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18572. const array = [];
  18573. for ( let i = 0; i < this.count; i ++ ) {
  18574. const index = i * this.data.stride + this.offset;
  18575. for ( let j = 0; j < this.itemSize; j ++ ) {
  18576. array.push( this.data.array[ index + j ] );
  18577. }
  18578. }
  18579. // de-interleave data and save it as an ordinary buffer attribute for now
  18580. return {
  18581. itemSize: this.itemSize,
  18582. type: this.array.constructor.name,
  18583. array: array,
  18584. normalized: this.normalized
  18585. };
  18586. } else {
  18587. // save as true interleaved attribute
  18588. if ( data.interleavedBuffers === undefined ) {
  18589. data.interleavedBuffers = {};
  18590. }
  18591. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18592. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18593. }
  18594. return {
  18595. isInterleavedBufferAttribute: true,
  18596. itemSize: this.itemSize,
  18597. data: this.data.uuid,
  18598. offset: this.offset,
  18599. normalized: this.normalized
  18600. };
  18601. }
  18602. }
  18603. }
  18604. class SpriteMaterial extends Material {
  18605. constructor( parameters ) {
  18606. super();
  18607. this.isSpriteMaterial = true;
  18608. this.type = 'SpriteMaterial';
  18609. this.color = new Color( 0xffffff );
  18610. this.map = null;
  18611. this.alphaMap = null;
  18612. this.rotation = 0;
  18613. this.sizeAttenuation = true;
  18614. this.transparent = true;
  18615. this.fog = true;
  18616. this.setValues( parameters );
  18617. }
  18618. copy( source ) {
  18619. super.copy( source );
  18620. this.color.copy( source.color );
  18621. this.map = source.map;
  18622. this.alphaMap = source.alphaMap;
  18623. this.rotation = source.rotation;
  18624. this.sizeAttenuation = source.sizeAttenuation;
  18625. this.fog = source.fog;
  18626. return this;
  18627. }
  18628. }
  18629. let _geometry;
  18630. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18631. const _worldScale = /*@__PURE__*/ new Vector3();
  18632. const _mvPosition = /*@__PURE__*/ new Vector3();
  18633. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18634. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18635. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18636. const _vA = /*@__PURE__*/ new Vector3();
  18637. const _vB = /*@__PURE__*/ new Vector3();
  18638. const _vC = /*@__PURE__*/ new Vector3();
  18639. const _uvA = /*@__PURE__*/ new Vector2();
  18640. const _uvB = /*@__PURE__*/ new Vector2();
  18641. const _uvC = /*@__PURE__*/ new Vector2();
  18642. class Sprite extends Object3D {
  18643. constructor( material = new SpriteMaterial() ) {
  18644. super();
  18645. this.isSprite = true;
  18646. this.type = 'Sprite';
  18647. if ( _geometry === undefined ) {
  18648. _geometry = new BufferGeometry();
  18649. const float32Array = new Float32Array( [
  18650. - 0.5, - 0.5, 0, 0, 0,
  18651. 0.5, - 0.5, 0, 1, 0,
  18652. 0.5, 0.5, 0, 1, 1,
  18653. - 0.5, 0.5, 0, 0, 1
  18654. ] );
  18655. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18656. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18657. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18658. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18659. }
  18660. this.geometry = _geometry;
  18661. this.material = material;
  18662. this.center = new Vector2( 0.5, 0.5 );
  18663. }
  18664. raycast( raycaster, intersects ) {
  18665. if ( raycaster.camera === null ) {
  18666. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18667. }
  18668. _worldScale.setFromMatrixScale( this.matrixWorld );
  18669. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18670. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18671. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18672. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18673. _worldScale.multiplyScalar( - _mvPosition.z );
  18674. }
  18675. const rotation = this.material.rotation;
  18676. let sin, cos;
  18677. if ( rotation !== 0 ) {
  18678. cos = Math.cos( rotation );
  18679. sin = Math.sin( rotation );
  18680. }
  18681. const center = this.center;
  18682. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18683. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18684. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18685. _uvA.set( 0, 0 );
  18686. _uvB.set( 1, 0 );
  18687. _uvC.set( 1, 1 );
  18688. // check first triangle
  18689. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18690. if ( intersect === null ) {
  18691. // check second triangle
  18692. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18693. _uvB.set( 0, 1 );
  18694. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18695. if ( intersect === null ) {
  18696. return;
  18697. }
  18698. }
  18699. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18700. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18701. intersects.push( {
  18702. distance: distance,
  18703. point: _intersectPoint.clone(),
  18704. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18705. face: null,
  18706. object: this
  18707. } );
  18708. }
  18709. copy( source, recursive ) {
  18710. super.copy( source, recursive );
  18711. if ( source.center !== undefined ) this.center.copy( source.center );
  18712. this.material = source.material;
  18713. return this;
  18714. }
  18715. }
  18716. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18717. // compute position in camera space
  18718. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18719. // to check if rotation is not zero
  18720. if ( sin !== undefined ) {
  18721. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18722. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18723. } else {
  18724. _rotatedPosition.copy( _alignedPosition );
  18725. }
  18726. vertexPosition.copy( mvPosition );
  18727. vertexPosition.x += _rotatedPosition.x;
  18728. vertexPosition.y += _rotatedPosition.y;
  18729. // transform to world space
  18730. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18731. }
  18732. const _v1$2 = /*@__PURE__*/ new Vector3();
  18733. const _v2$1 = /*@__PURE__*/ new Vector3();
  18734. class LOD extends Object3D {
  18735. constructor() {
  18736. super();
  18737. this._currentLevel = 0;
  18738. this.type = 'LOD';
  18739. Object.defineProperties( this, {
  18740. levels: {
  18741. enumerable: true,
  18742. value: []
  18743. },
  18744. isLOD: {
  18745. value: true,
  18746. }
  18747. } );
  18748. this.autoUpdate = true;
  18749. }
  18750. copy( source ) {
  18751. super.copy( source, false );
  18752. const levels = source.levels;
  18753. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18754. const level = levels[ i ];
  18755. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18756. }
  18757. this.autoUpdate = source.autoUpdate;
  18758. return this;
  18759. }
  18760. addLevel( object, distance = 0, hysteresis = 0 ) {
  18761. distance = Math.abs( distance );
  18762. const levels = this.levels;
  18763. let l;
  18764. for ( l = 0; l < levels.length; l ++ ) {
  18765. if ( distance < levels[ l ].distance ) {
  18766. break;
  18767. }
  18768. }
  18769. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18770. this.add( object );
  18771. return this;
  18772. }
  18773. getCurrentLevel() {
  18774. return this._currentLevel;
  18775. }
  18776. getObjectForDistance( distance ) {
  18777. const levels = this.levels;
  18778. if ( levels.length > 0 ) {
  18779. let i, l;
  18780. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18781. let levelDistance = levels[ i ].distance;
  18782. if ( levels[ i ].object.visible ) {
  18783. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18784. }
  18785. if ( distance < levelDistance ) {
  18786. break;
  18787. }
  18788. }
  18789. return levels[ i - 1 ].object;
  18790. }
  18791. return null;
  18792. }
  18793. raycast( raycaster, intersects ) {
  18794. const levels = this.levels;
  18795. if ( levels.length > 0 ) {
  18796. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18797. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18798. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18799. }
  18800. }
  18801. update( camera ) {
  18802. const levels = this.levels;
  18803. if ( levels.length > 1 ) {
  18804. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18805. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18806. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18807. levels[ 0 ].object.visible = true;
  18808. let i, l;
  18809. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18810. let levelDistance = levels[ i ].distance;
  18811. if ( levels[ i ].object.visible ) {
  18812. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18813. }
  18814. if ( distance >= levelDistance ) {
  18815. levels[ i - 1 ].object.visible = false;
  18816. levels[ i ].object.visible = true;
  18817. } else {
  18818. break;
  18819. }
  18820. }
  18821. this._currentLevel = i - 1;
  18822. for ( ; i < l; i ++ ) {
  18823. levels[ i ].object.visible = false;
  18824. }
  18825. }
  18826. }
  18827. toJSON( meta ) {
  18828. const data = super.toJSON( meta );
  18829. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18830. data.object.levels = [];
  18831. const levels = this.levels;
  18832. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18833. const level = levels[ i ];
  18834. data.object.levels.push( {
  18835. object: level.object.uuid,
  18836. distance: level.distance,
  18837. hysteresis: level.hysteresis
  18838. } );
  18839. }
  18840. return data;
  18841. }
  18842. }
  18843. const _basePosition = /*@__PURE__*/ new Vector3();
  18844. const _skinIndex = /*@__PURE__*/ new Vector4();
  18845. const _skinWeight = /*@__PURE__*/ new Vector4();
  18846. const _vector3 = /*@__PURE__*/ new Vector3();
  18847. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18848. const _vertex = /*@__PURE__*/ new Vector3();
  18849. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18850. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18851. const _ray$2 = /*@__PURE__*/ new Ray();
  18852. class SkinnedMesh extends Mesh {
  18853. constructor( geometry, material ) {
  18854. super( geometry, material );
  18855. this.isSkinnedMesh = true;
  18856. this.type = 'SkinnedMesh';
  18857. this.bindMode = AttachedBindMode;
  18858. this.bindMatrix = new Matrix4();
  18859. this.bindMatrixInverse = new Matrix4();
  18860. this.boundingBox = null;
  18861. this.boundingSphere = null;
  18862. }
  18863. computeBoundingBox() {
  18864. const geometry = this.geometry;
  18865. if ( this.boundingBox === null ) {
  18866. this.boundingBox = new Box3();
  18867. }
  18868. this.boundingBox.makeEmpty();
  18869. const positionAttribute = geometry.getAttribute( 'position' );
  18870. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18871. this.getVertexPosition( i, _vertex );
  18872. this.boundingBox.expandByPoint( _vertex );
  18873. }
  18874. }
  18875. computeBoundingSphere() {
  18876. const geometry = this.geometry;
  18877. if ( this.boundingSphere === null ) {
  18878. this.boundingSphere = new Sphere();
  18879. }
  18880. this.boundingSphere.makeEmpty();
  18881. const positionAttribute = geometry.getAttribute( 'position' );
  18882. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18883. this.getVertexPosition( i, _vertex );
  18884. this.boundingSphere.expandByPoint( _vertex );
  18885. }
  18886. }
  18887. copy( source, recursive ) {
  18888. super.copy( source, recursive );
  18889. this.bindMode = source.bindMode;
  18890. this.bindMatrix.copy( source.bindMatrix );
  18891. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18892. this.skeleton = source.skeleton;
  18893. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18894. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18895. return this;
  18896. }
  18897. raycast( raycaster, intersects ) {
  18898. const material = this.material;
  18899. const matrixWorld = this.matrixWorld;
  18900. if ( material === undefined ) return;
  18901. // test with bounding sphere in world space
  18902. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18903. _sphere$4.copy( this.boundingSphere );
  18904. _sphere$4.applyMatrix4( matrixWorld );
  18905. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18906. // convert ray to local space of skinned mesh
  18907. _inverseMatrix$2.copy( matrixWorld ).invert();
  18908. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18909. // test with bounding box in local space
  18910. if ( this.boundingBox !== null ) {
  18911. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18912. }
  18913. // test for intersections with geometry
  18914. this._computeIntersections( raycaster, intersects, _ray$2 );
  18915. }
  18916. getVertexPosition( index, target ) {
  18917. super.getVertexPosition( index, target );
  18918. this.applyBoneTransform( index, target );
  18919. return target;
  18920. }
  18921. bind( skeleton, bindMatrix ) {
  18922. this.skeleton = skeleton;
  18923. if ( bindMatrix === undefined ) {
  18924. this.updateMatrixWorld( true );
  18925. this.skeleton.calculateInverses();
  18926. bindMatrix = this.matrixWorld;
  18927. }
  18928. this.bindMatrix.copy( bindMatrix );
  18929. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18930. }
  18931. pose() {
  18932. this.skeleton.pose();
  18933. }
  18934. normalizeSkinWeights() {
  18935. const vector = new Vector4();
  18936. const skinWeight = this.geometry.attributes.skinWeight;
  18937. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18938. vector.fromBufferAttribute( skinWeight, i );
  18939. const scale = 1.0 / vector.manhattanLength();
  18940. if ( scale !== Infinity ) {
  18941. vector.multiplyScalar( scale );
  18942. } else {
  18943. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18944. }
  18945. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18946. }
  18947. }
  18948. updateMatrixWorld( force ) {
  18949. super.updateMatrixWorld( force );
  18950. if ( this.bindMode === AttachedBindMode ) {
  18951. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18952. } else if ( this.bindMode === DetachedBindMode ) {
  18953. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18954. } else {
  18955. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18956. }
  18957. }
  18958. applyBoneTransform( index, vector ) {
  18959. const skeleton = this.skeleton;
  18960. const geometry = this.geometry;
  18961. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18962. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18963. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  18964. vector.set( 0, 0, 0 );
  18965. for ( let i = 0; i < 4; i ++ ) {
  18966. const weight = _skinWeight.getComponent( i );
  18967. if ( weight !== 0 ) {
  18968. const boneIndex = _skinIndex.getComponent( i );
  18969. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18970. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18971. }
  18972. }
  18973. return vector.applyMatrix4( this.bindMatrixInverse );
  18974. }
  18975. }
  18976. class Bone extends Object3D {
  18977. constructor() {
  18978. super();
  18979. this.isBone = true;
  18980. this.type = 'Bone';
  18981. }
  18982. }
  18983. class DataTexture extends Texture {
  18984. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18985. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18986. this.isDataTexture = true;
  18987. this.image = { data: data, width: width, height: height };
  18988. this.generateMipmaps = false;
  18989. this.flipY = false;
  18990. this.unpackAlignment = 1;
  18991. }
  18992. }
  18993. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18994. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  18995. class Skeleton {
  18996. constructor( bones = [], boneInverses = [] ) {
  18997. this.uuid = generateUUID();
  18998. this.bones = bones.slice( 0 );
  18999. this.boneInverses = boneInverses;
  19000. this.boneMatrices = null;
  19001. this.boneTexture = null;
  19002. this.init();
  19003. }
  19004. init() {
  19005. const bones = this.bones;
  19006. const boneInverses = this.boneInverses;
  19007. this.boneMatrices = new Float32Array( bones.length * 16 );
  19008. // calculate inverse bone matrices if necessary
  19009. if ( boneInverses.length === 0 ) {
  19010. this.calculateInverses();
  19011. } else {
  19012. // handle special case
  19013. if ( bones.length !== boneInverses.length ) {
  19014. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19015. this.boneInverses = [];
  19016. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19017. this.boneInverses.push( new Matrix4() );
  19018. }
  19019. }
  19020. }
  19021. }
  19022. calculateInverses() {
  19023. this.boneInverses.length = 0;
  19024. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19025. const inverse = new Matrix4();
  19026. if ( this.bones[ i ] ) {
  19027. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19028. }
  19029. this.boneInverses.push( inverse );
  19030. }
  19031. }
  19032. pose() {
  19033. // recover the bind-time world matrices
  19034. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19035. const bone = this.bones[ i ];
  19036. if ( bone ) {
  19037. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19038. }
  19039. }
  19040. // compute the local matrices, positions, rotations and scales
  19041. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19042. const bone = this.bones[ i ];
  19043. if ( bone ) {
  19044. if ( bone.parent && bone.parent.isBone ) {
  19045. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19046. bone.matrix.multiply( bone.matrixWorld );
  19047. } else {
  19048. bone.matrix.copy( bone.matrixWorld );
  19049. }
  19050. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19051. }
  19052. }
  19053. }
  19054. update() {
  19055. const bones = this.bones;
  19056. const boneInverses = this.boneInverses;
  19057. const boneMatrices = this.boneMatrices;
  19058. const boneTexture = this.boneTexture;
  19059. // flatten bone matrices to array
  19060. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19061. // compute the offset between the current and the original transform
  19062. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  19063. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19064. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19065. }
  19066. if ( boneTexture !== null ) {
  19067. boneTexture.needsUpdate = true;
  19068. }
  19069. }
  19070. clone() {
  19071. return new Skeleton( this.bones, this.boneInverses );
  19072. }
  19073. computeBoneTexture() {
  19074. // layout (1 matrix = 4 pixels)
  19075. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19076. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19077. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19078. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19079. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19080. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19081. size = Math.ceil( size / 4 ) * 4;
  19082. size = Math.max( size, 4 );
  19083. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19084. boneMatrices.set( this.boneMatrices ); // copy current values
  19085. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19086. boneTexture.needsUpdate = true;
  19087. this.boneMatrices = boneMatrices;
  19088. this.boneTexture = boneTexture;
  19089. return this;
  19090. }
  19091. getBoneByName( name ) {
  19092. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19093. const bone = this.bones[ i ];
  19094. if ( bone.name === name ) {
  19095. return bone;
  19096. }
  19097. }
  19098. return undefined;
  19099. }
  19100. dispose( ) {
  19101. if ( this.boneTexture !== null ) {
  19102. this.boneTexture.dispose();
  19103. this.boneTexture = null;
  19104. }
  19105. }
  19106. fromJSON( json, bones ) {
  19107. this.uuid = json.uuid;
  19108. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19109. const uuid = json.bones[ i ];
  19110. let bone = bones[ uuid ];
  19111. if ( bone === undefined ) {
  19112. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  19113. bone = new Bone();
  19114. }
  19115. this.bones.push( bone );
  19116. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19117. }
  19118. this.init();
  19119. return this;
  19120. }
  19121. toJSON() {
  19122. const data = {
  19123. metadata: {
  19124. version: 4.6,
  19125. type: 'Skeleton',
  19126. generator: 'Skeleton.toJSON'
  19127. },
  19128. bones: [],
  19129. boneInverses: []
  19130. };
  19131. data.uuid = this.uuid;
  19132. const bones = this.bones;
  19133. const boneInverses = this.boneInverses;
  19134. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19135. const bone = bones[ i ];
  19136. data.bones.push( bone.uuid );
  19137. const boneInverse = boneInverses[ i ];
  19138. data.boneInverses.push( boneInverse.toArray() );
  19139. }
  19140. return data;
  19141. }
  19142. }
  19143. class InstancedBufferAttribute extends BufferAttribute {
  19144. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19145. super( array, itemSize, normalized );
  19146. this.isInstancedBufferAttribute = true;
  19147. this.meshPerAttribute = meshPerAttribute;
  19148. }
  19149. copy( source ) {
  19150. super.copy( source );
  19151. this.meshPerAttribute = source.meshPerAttribute;
  19152. return this;
  19153. }
  19154. toJSON() {
  19155. const data = super.toJSON();
  19156. data.meshPerAttribute = this.meshPerAttribute;
  19157. data.isInstancedBufferAttribute = true;
  19158. return data;
  19159. }
  19160. }
  19161. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19162. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19163. const _instanceIntersects = [];
  19164. const _box3 = /*@__PURE__*/ new Box3();
  19165. const _identity = /*@__PURE__*/ new Matrix4();
  19166. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19167. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19168. class InstancedMesh extends Mesh {
  19169. constructor( geometry, material, count ) {
  19170. super( geometry, material );
  19171. this.isInstancedMesh = true;
  19172. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19173. this.instanceColor = null;
  19174. this.morphTexture = null;
  19175. this.count = count;
  19176. this.boundingBox = null;
  19177. this.boundingSphere = null;
  19178. for ( let i = 0; i < count; i ++ ) {
  19179. this.setMatrixAt( i, _identity );
  19180. }
  19181. }
  19182. computeBoundingBox() {
  19183. const geometry = this.geometry;
  19184. const count = this.count;
  19185. if ( this.boundingBox === null ) {
  19186. this.boundingBox = new Box3();
  19187. }
  19188. if ( geometry.boundingBox === null ) {
  19189. geometry.computeBoundingBox();
  19190. }
  19191. this.boundingBox.makeEmpty();
  19192. for ( let i = 0; i < count; i ++ ) {
  19193. this.getMatrixAt( i, _instanceLocalMatrix );
  19194. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19195. this.boundingBox.union( _box3 );
  19196. }
  19197. }
  19198. computeBoundingSphere() {
  19199. const geometry = this.geometry;
  19200. const count = this.count;
  19201. if ( this.boundingSphere === null ) {
  19202. this.boundingSphere = new Sphere();
  19203. }
  19204. if ( geometry.boundingSphere === null ) {
  19205. geometry.computeBoundingSphere();
  19206. }
  19207. this.boundingSphere.makeEmpty();
  19208. for ( let i = 0; i < count; i ++ ) {
  19209. this.getMatrixAt( i, _instanceLocalMatrix );
  19210. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19211. this.boundingSphere.union( _sphere$3 );
  19212. }
  19213. }
  19214. copy( source, recursive ) {
  19215. super.copy( source, recursive );
  19216. this.instanceMatrix.copy( source.instanceMatrix );
  19217. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19218. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19219. this.count = source.count;
  19220. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19221. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19222. return this;
  19223. }
  19224. getColorAt( index, color ) {
  19225. color.fromArray( this.instanceColor.array, index * 3 );
  19226. }
  19227. getMatrixAt( index, matrix ) {
  19228. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19229. }
  19230. getMorphAt( index, object ) {
  19231. const objectInfluences = object.morphTargetInfluences;
  19232. const array = this.morphTexture.source.data.data;
  19233. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19234. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19235. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19236. objectInfluences[ i ] = array[ dataIndex + i ];
  19237. }
  19238. }
  19239. raycast( raycaster, intersects ) {
  19240. const matrixWorld = this.matrixWorld;
  19241. const raycastTimes = this.count;
  19242. _mesh$1.geometry = this.geometry;
  19243. _mesh$1.material = this.material;
  19244. if ( _mesh$1.material === undefined ) return;
  19245. // test with bounding sphere first
  19246. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19247. _sphere$3.copy( this.boundingSphere );
  19248. _sphere$3.applyMatrix4( matrixWorld );
  19249. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  19250. // now test each instance
  19251. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19252. // calculate the world matrix for each instance
  19253. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19254. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19255. // the mesh represents this single instance
  19256. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19257. _mesh$1.raycast( raycaster, _instanceIntersects );
  19258. // process the result of raycast
  19259. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19260. const intersect = _instanceIntersects[ i ];
  19261. intersect.instanceId = instanceId;
  19262. intersect.object = this;
  19263. intersects.push( intersect );
  19264. }
  19265. _instanceIntersects.length = 0;
  19266. }
  19267. }
  19268. setColorAt( index, color ) {
  19269. if ( this.instanceColor === null ) {
  19270. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  19271. }
  19272. color.toArray( this.instanceColor.array, index * 3 );
  19273. }
  19274. setMatrixAt( index, matrix ) {
  19275. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19276. }
  19277. setMorphAt( index, object ) {
  19278. const objectInfluences = object.morphTargetInfluences;
  19279. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19280. if ( this.morphTexture === null ) {
  19281. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19282. }
  19283. const array = this.morphTexture.source.data.data;
  19284. let morphInfluencesSum = 0;
  19285. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19286. morphInfluencesSum += objectInfluences[ i ];
  19287. }
  19288. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19289. const dataIndex = len * index;
  19290. array[ dataIndex ] = morphBaseInfluence;
  19291. array.set( objectInfluences, dataIndex + 1 );
  19292. }
  19293. updateMorphTargets() {
  19294. }
  19295. dispose() {
  19296. this.dispatchEvent( { type: 'dispose' } );
  19297. if ( this.morphTexture !== null ) {
  19298. this.morphTexture.dispose();
  19299. this.morphTexture = null;
  19300. }
  19301. return this;
  19302. }
  19303. }
  19304. function sortOpaque( a, b ) {
  19305. return a.z - b.z;
  19306. }
  19307. function sortTransparent( a, b ) {
  19308. return b.z - a.z;
  19309. }
  19310. class MultiDrawRenderList {
  19311. constructor() {
  19312. this.index = 0;
  19313. this.pool = [];
  19314. this.list = [];
  19315. }
  19316. push( drawRange, z ) {
  19317. const pool = this.pool;
  19318. const list = this.list;
  19319. if ( this.index >= pool.length ) {
  19320. pool.push( {
  19321. start: - 1,
  19322. count: - 1,
  19323. z: - 1,
  19324. } );
  19325. }
  19326. const item = pool[ this.index ];
  19327. list.push( item );
  19328. this.index ++;
  19329. item.start = drawRange.start;
  19330. item.count = drawRange.count;
  19331. item.z = z;
  19332. }
  19333. reset() {
  19334. this.list.length = 0;
  19335. this.index = 0;
  19336. }
  19337. }
  19338. const ID_ATTR_NAME = 'batchId';
  19339. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19340. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  19341. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  19342. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19343. const _frustum = /*@__PURE__*/ new Frustum();
  19344. const _box$1 = /*@__PURE__*/ new Box3();
  19345. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19346. const _vector$5 = /*@__PURE__*/ new Vector3();
  19347. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19348. const _mesh = /*@__PURE__*/ new Mesh();
  19349. const _batchIntersects = [];
  19350. // @TODO: SkinnedMesh support?
  19351. // @TODO: geometry.groups support?
  19352. // @TODO: geometry.drawRange support?
  19353. // @TODO: geometry.morphAttributes support?
  19354. // @TODO: Support uniform parameter per geometry
  19355. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  19356. // copies data from attribute "src" into "target" starting at "targetOffset"
  19357. function copyAttributeData( src, target, targetOffset = 0 ) {
  19358. const itemSize = target.itemSize;
  19359. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19360. // use the component getters and setters if the array data cannot
  19361. // be copied directly
  19362. const vertexCount = src.count;
  19363. for ( let i = 0; i < vertexCount; i ++ ) {
  19364. for ( let c = 0; c < itemSize; c ++ ) {
  19365. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19366. }
  19367. }
  19368. } else {
  19369. // faster copy approach using typed array set function
  19370. target.array.set( src.array, targetOffset * itemSize );
  19371. }
  19372. target.needsUpdate = true;
  19373. }
  19374. class BatchedMesh extends Mesh {
  19375. get maxGeometryCount() {
  19376. return this._maxGeometryCount;
  19377. }
  19378. constructor( maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19379. super( new BufferGeometry(), material );
  19380. this.isBatchedMesh = true;
  19381. this.perObjectFrustumCulled = true;
  19382. this.sortObjects = true;
  19383. this.boundingBox = null;
  19384. this.boundingSphere = null;
  19385. this.customSort = null;
  19386. this._drawRanges = [];
  19387. this._reservedRanges = [];
  19388. this._visibility = [];
  19389. this._active = [];
  19390. this._bounds = [];
  19391. this._maxGeometryCount = maxGeometryCount;
  19392. this._maxVertexCount = maxVertexCount;
  19393. this._maxIndexCount = maxIndexCount;
  19394. this._geometryInitialized = false;
  19395. this._geometryCount = 0;
  19396. this._multiDrawCounts = new Int32Array( maxGeometryCount );
  19397. this._multiDrawStarts = new Int32Array( maxGeometryCount );
  19398. this._multiDrawCount = 0;
  19399. this._visibilityChanged = true;
  19400. // Local matrix per geometry by using data texture
  19401. this._matricesTexture = null;
  19402. this._initMatricesTexture();
  19403. }
  19404. _initMatricesTexture() {
  19405. // layout (1 matrix = 4 pixels)
  19406. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19407. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19408. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19409. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19410. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19411. let size = Math.sqrt( this._maxGeometryCount * 4 ); // 4 pixels needed for 1 matrix
  19412. size = Math.ceil( size / 4 ) * 4;
  19413. size = Math.max( size, 4 );
  19414. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19415. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19416. this._matricesTexture = matricesTexture;
  19417. }
  19418. _initializeGeometry( reference ) {
  19419. const geometry = this.geometry;
  19420. const maxVertexCount = this._maxVertexCount;
  19421. const maxGeometryCount = this._maxGeometryCount;
  19422. const maxIndexCount = this._maxIndexCount;
  19423. if ( this._geometryInitialized === false ) {
  19424. for ( const attributeName in reference.attributes ) {
  19425. const srcAttribute = reference.getAttribute( attributeName );
  19426. const { array, itemSize, normalized } = srcAttribute;
  19427. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19428. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19429. geometry.setAttribute( attributeName, dstAttribute );
  19430. }
  19431. if ( reference.getIndex() !== null ) {
  19432. const indexArray = maxVertexCount > 65536
  19433. ? new Uint32Array( maxIndexCount )
  19434. : new Uint16Array( maxIndexCount );
  19435. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19436. }
  19437. const idArray = maxGeometryCount > 65536
  19438. ? new Uint32Array( maxVertexCount )
  19439. : new Uint16Array( maxVertexCount );
  19440. geometry.setAttribute( ID_ATTR_NAME, new BufferAttribute( idArray, 1 ) );
  19441. this._geometryInitialized = true;
  19442. }
  19443. }
  19444. // Make sure the geometry is compatible with the existing combined geometry attributes
  19445. _validateGeometry( geometry ) {
  19446. // check that the geometry doesn't have a version of our reserved id attribute
  19447. if ( geometry.getAttribute( ID_ATTR_NAME ) ) {
  19448. throw new Error( `BatchedMesh: Geometry cannot use attribute "${ ID_ATTR_NAME }"` );
  19449. }
  19450. // check to ensure the geometries are using consistent attributes and indices
  19451. const batchGeometry = this.geometry;
  19452. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19453. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  19454. }
  19455. for ( const attributeName in batchGeometry.attributes ) {
  19456. if ( attributeName === ID_ATTR_NAME ) {
  19457. continue;
  19458. }
  19459. if ( ! geometry.hasAttribute( attributeName ) ) {
  19460. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19461. }
  19462. const srcAttribute = geometry.getAttribute( attributeName );
  19463. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19464. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19465. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19466. }
  19467. }
  19468. }
  19469. setCustomSort( func ) {
  19470. this.customSort = func;
  19471. return this;
  19472. }
  19473. computeBoundingBox() {
  19474. if ( this.boundingBox === null ) {
  19475. this.boundingBox = new Box3();
  19476. }
  19477. const geometryCount = this._geometryCount;
  19478. const boundingBox = this.boundingBox;
  19479. const active = this._active;
  19480. boundingBox.makeEmpty();
  19481. for ( let i = 0; i < geometryCount; i ++ ) {
  19482. if ( active[ i ] === false ) continue;
  19483. this.getMatrixAt( i, _matrix$1 );
  19484. this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix$1 );
  19485. boundingBox.union( _box$1 );
  19486. }
  19487. }
  19488. computeBoundingSphere() {
  19489. if ( this.boundingSphere === null ) {
  19490. this.boundingSphere = new Sphere();
  19491. }
  19492. const geometryCount = this._geometryCount;
  19493. const boundingSphere = this.boundingSphere;
  19494. const active = this._active;
  19495. boundingSphere.makeEmpty();
  19496. for ( let i = 0; i < geometryCount; i ++ ) {
  19497. if ( active[ i ] === false ) continue;
  19498. this.getMatrixAt( i, _matrix$1 );
  19499. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 );
  19500. boundingSphere.union( _sphere$2 );
  19501. }
  19502. }
  19503. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  19504. this._initializeGeometry( geometry );
  19505. this._validateGeometry( geometry );
  19506. // ensure we're not over geometry
  19507. if ( this._geometryCount >= this._maxGeometryCount ) {
  19508. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19509. }
  19510. // get the necessary range fo the geometry
  19511. const reservedRange = {
  19512. vertexStart: - 1,
  19513. vertexCount: - 1,
  19514. indexStart: - 1,
  19515. indexCount: - 1,
  19516. };
  19517. let lastRange = null;
  19518. const reservedRanges = this._reservedRanges;
  19519. const drawRanges = this._drawRanges;
  19520. const bounds = this._bounds;
  19521. if ( this._geometryCount !== 0 ) {
  19522. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  19523. }
  19524. if ( vertexCount === - 1 ) {
  19525. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  19526. } else {
  19527. reservedRange.vertexCount = vertexCount;
  19528. }
  19529. if ( lastRange === null ) {
  19530. reservedRange.vertexStart = 0;
  19531. } else {
  19532. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  19533. }
  19534. const index = geometry.getIndex();
  19535. const hasIndex = index !== null;
  19536. if ( hasIndex ) {
  19537. if ( indexCount === - 1 ) {
  19538. reservedRange.indexCount = index.count;
  19539. } else {
  19540. reservedRange.indexCount = indexCount;
  19541. }
  19542. if ( lastRange === null ) {
  19543. reservedRange.indexStart = 0;
  19544. } else {
  19545. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  19546. }
  19547. }
  19548. if (
  19549. reservedRange.indexStart !== - 1 &&
  19550. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  19551. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  19552. ) {
  19553. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19554. }
  19555. const visibility = this._visibility;
  19556. const active = this._active;
  19557. const matricesTexture = this._matricesTexture;
  19558. const matricesArray = this._matricesTexture.image.data;
  19559. // push new visibility states
  19560. visibility.push( true );
  19561. active.push( true );
  19562. // update id
  19563. const geometryId = this._geometryCount;
  19564. this._geometryCount ++;
  19565. // initialize matrix information
  19566. _identityMatrix.toArray( matricesArray, geometryId * 16 );
  19567. matricesTexture.needsUpdate = true;
  19568. // add the reserved range and draw range objects
  19569. reservedRanges.push( reservedRange );
  19570. drawRanges.push( {
  19571. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  19572. count: - 1
  19573. } );
  19574. bounds.push( {
  19575. boxInitialized: false,
  19576. box: new Box3(),
  19577. sphereInitialized: false,
  19578. sphere: new Sphere()
  19579. } );
  19580. // set the id for the geometry
  19581. const idAttribute = this.geometry.getAttribute( ID_ATTR_NAME );
  19582. for ( let i = 0; i < reservedRange.vertexCount; i ++ ) {
  19583. idAttribute.setX( reservedRange.vertexStart + i, geometryId );
  19584. }
  19585. idAttribute.needsUpdate = true;
  19586. // update the geometry
  19587. this.setGeometryAt( geometryId, geometry );
  19588. return geometryId;
  19589. }
  19590. setGeometryAt( id, geometry ) {
  19591. if ( id >= this._geometryCount ) {
  19592. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19593. }
  19594. this._validateGeometry( geometry );
  19595. const batchGeometry = this.geometry;
  19596. const hasIndex = batchGeometry.getIndex() !== null;
  19597. const dstIndex = batchGeometry.getIndex();
  19598. const srcIndex = geometry.getIndex();
  19599. const reservedRange = this._reservedRanges[ id ];
  19600. if (
  19601. hasIndex &&
  19602. srcIndex.count > reservedRange.indexCount ||
  19603. geometry.attributes.position.count > reservedRange.vertexCount
  19604. ) {
  19605. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  19606. }
  19607. // copy geometry over
  19608. const vertexStart = reservedRange.vertexStart;
  19609. const vertexCount = reservedRange.vertexCount;
  19610. for ( const attributeName in batchGeometry.attributes ) {
  19611. if ( attributeName === ID_ATTR_NAME ) {
  19612. continue;
  19613. }
  19614. // copy attribute data
  19615. const srcAttribute = geometry.getAttribute( attributeName );
  19616. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19617. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19618. // fill the rest in with zeroes
  19619. const itemSize = srcAttribute.itemSize;
  19620. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  19621. const index = vertexStart + i;
  19622. for ( let c = 0; c < itemSize; c ++ ) {
  19623. dstAttribute.setComponent( index, c, 0 );
  19624. }
  19625. }
  19626. dstAttribute.needsUpdate = true;
  19627. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  19628. }
  19629. // copy index
  19630. if ( hasIndex ) {
  19631. const indexStart = reservedRange.indexStart;
  19632. // copy index data over
  19633. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19634. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19635. }
  19636. // fill the rest in with zeroes
  19637. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  19638. dstIndex.setX( indexStart + i, vertexStart );
  19639. }
  19640. dstIndex.needsUpdate = true;
  19641. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  19642. }
  19643. // store the bounding boxes
  19644. const bound = this._bounds[ id ];
  19645. if ( geometry.boundingBox !== null ) {
  19646. bound.box.copy( geometry.boundingBox );
  19647. bound.boxInitialized = true;
  19648. } else {
  19649. bound.boxInitialized = false;
  19650. }
  19651. if ( geometry.boundingSphere !== null ) {
  19652. bound.sphere.copy( geometry.boundingSphere );
  19653. bound.sphereInitialized = true;
  19654. } else {
  19655. bound.sphereInitialized = false;
  19656. }
  19657. // set drawRange count
  19658. const drawRange = this._drawRanges[ id ];
  19659. const posAttr = geometry.getAttribute( 'position' );
  19660. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  19661. this._visibilityChanged = true;
  19662. return id;
  19663. }
  19664. deleteGeometry( geometryId ) {
  19665. // Note: User needs to call optimize() afterward to pack the data.
  19666. const active = this._active;
  19667. if ( geometryId >= active.length || active[ geometryId ] === false ) {
  19668. return this;
  19669. }
  19670. active[ geometryId ] = false;
  19671. this._visibilityChanged = true;
  19672. return this;
  19673. }
  19674. // get bounding box and compute it if it doesn't exist
  19675. getBoundingBoxAt( id, target ) {
  19676. const active = this._active;
  19677. if ( active[ id ] === false ) {
  19678. return null;
  19679. }
  19680. // compute bounding box
  19681. const bound = this._bounds[ id ];
  19682. const box = bound.box;
  19683. const geometry = this.geometry;
  19684. if ( bound.boxInitialized === false ) {
  19685. box.makeEmpty();
  19686. const index = geometry.index;
  19687. const position = geometry.attributes.position;
  19688. const drawRange = this._drawRanges[ id ];
  19689. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  19690. let iv = i;
  19691. if ( index ) {
  19692. iv = index.getX( iv );
  19693. }
  19694. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19695. }
  19696. bound.boxInitialized = true;
  19697. }
  19698. target.copy( box );
  19699. return target;
  19700. }
  19701. // get bounding sphere and compute it if it doesn't exist
  19702. getBoundingSphereAt( id, target ) {
  19703. const active = this._active;
  19704. if ( active[ id ] === false ) {
  19705. return null;
  19706. }
  19707. // compute bounding sphere
  19708. const bound = this._bounds[ id ];
  19709. const sphere = bound.sphere;
  19710. const geometry = this.geometry;
  19711. if ( bound.sphereInitialized === false ) {
  19712. sphere.makeEmpty();
  19713. this.getBoundingBoxAt( id, _box$1 );
  19714. _box$1.getCenter( sphere.center );
  19715. const index = geometry.index;
  19716. const position = geometry.attributes.position;
  19717. const drawRange = this._drawRanges[ id ];
  19718. let maxRadiusSq = 0;
  19719. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  19720. let iv = i;
  19721. if ( index ) {
  19722. iv = index.getX( iv );
  19723. }
  19724. _vector$5.fromBufferAttribute( position, iv );
  19725. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19726. }
  19727. sphere.radius = Math.sqrt( maxRadiusSq );
  19728. bound.sphereInitialized = true;
  19729. }
  19730. target.copy( sphere );
  19731. return target;
  19732. }
  19733. setMatrixAt( geometryId, matrix ) {
  19734. // @TODO: Map geometryId to index of the arrays because
  19735. // optimize() can make geometryId mismatch the index
  19736. const active = this._active;
  19737. const matricesTexture = this._matricesTexture;
  19738. const matricesArray = this._matricesTexture.image.data;
  19739. const geometryCount = this._geometryCount;
  19740. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  19741. return this;
  19742. }
  19743. matrix.toArray( matricesArray, geometryId * 16 );
  19744. matricesTexture.needsUpdate = true;
  19745. return this;
  19746. }
  19747. getMatrixAt( geometryId, matrix ) {
  19748. const active = this._active;
  19749. const matricesArray = this._matricesTexture.image.data;
  19750. const geometryCount = this._geometryCount;
  19751. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  19752. return null;
  19753. }
  19754. return matrix.fromArray( matricesArray, geometryId * 16 );
  19755. }
  19756. setVisibleAt( geometryId, value ) {
  19757. const visibility = this._visibility;
  19758. const active = this._active;
  19759. const geometryCount = this._geometryCount;
  19760. // if the geometry is out of range, not active, or visibility state
  19761. // does not change then return early
  19762. if (
  19763. geometryId >= geometryCount ||
  19764. active[ geometryId ] === false ||
  19765. visibility[ geometryId ] === value
  19766. ) {
  19767. return this;
  19768. }
  19769. visibility[ geometryId ] = value;
  19770. this._visibilityChanged = true;
  19771. return this;
  19772. }
  19773. getVisibleAt( geometryId ) {
  19774. const visibility = this._visibility;
  19775. const active = this._active;
  19776. const geometryCount = this._geometryCount;
  19777. // return early if the geometry is out of range or not active
  19778. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  19779. return false;
  19780. }
  19781. return visibility[ geometryId ];
  19782. }
  19783. raycast( raycaster, intersects ) {
  19784. const visibility = this._visibility;
  19785. const active = this._active;
  19786. const drawRanges = this._drawRanges;
  19787. const geometryCount = this._geometryCount;
  19788. const matrixWorld = this.matrixWorld;
  19789. const batchGeometry = this.geometry;
  19790. // iterate over each geometry
  19791. _mesh.material = this.material;
  19792. _mesh.geometry.index = batchGeometry.index;
  19793. _mesh.geometry.attributes = batchGeometry.attributes;
  19794. if ( _mesh.geometry.boundingBox === null ) {
  19795. _mesh.geometry.boundingBox = new Box3();
  19796. }
  19797. if ( _mesh.geometry.boundingSphere === null ) {
  19798. _mesh.geometry.boundingSphere = new Sphere();
  19799. }
  19800. for ( let i = 0; i < geometryCount; i ++ ) {
  19801. if ( ! visibility[ i ] || ! active[ i ] ) {
  19802. continue;
  19803. }
  19804. const drawRange = drawRanges[ i ];
  19805. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  19806. // ge the intersects
  19807. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  19808. this.getBoundingBoxAt( i, _mesh.geometry.boundingBox );
  19809. this.getBoundingSphereAt( i, _mesh.geometry.boundingSphere );
  19810. _mesh.raycast( raycaster, _batchIntersects );
  19811. // add batch id to the intersects
  19812. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  19813. const intersect = _batchIntersects[ j ];
  19814. intersect.object = this;
  19815. intersect.batchId = i;
  19816. intersects.push( intersect );
  19817. }
  19818. _batchIntersects.length = 0;
  19819. }
  19820. _mesh.material = null;
  19821. _mesh.geometry.index = null;
  19822. _mesh.geometry.attributes = {};
  19823. _mesh.geometry.setDrawRange( 0, Infinity );
  19824. }
  19825. copy( source ) {
  19826. super.copy( source );
  19827. this.geometry = source.geometry.clone();
  19828. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  19829. this.sortObjects = source.sortObjects;
  19830. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  19831. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  19832. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  19833. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  19834. this._visibility = source._visibility.slice();
  19835. this._active = source._active.slice();
  19836. this._bounds = source._bounds.map( bound => ( {
  19837. boxInitialized: bound.boxInitialized,
  19838. box: bound.box.clone(),
  19839. sphereInitialized: bound.sphereInitialized,
  19840. sphere: bound.sphere.clone()
  19841. } ) );
  19842. this._maxGeometryCount = source._maxGeometryCount;
  19843. this._maxVertexCount = source._maxVertexCount;
  19844. this._maxIndexCount = source._maxIndexCount;
  19845. this._geometryInitialized = source._geometryInitialized;
  19846. this._geometryCount = source._geometryCount;
  19847. this._multiDrawCounts = source._multiDrawCounts.slice();
  19848. this._multiDrawStarts = source._multiDrawStarts.slice();
  19849. this._matricesTexture = source._matricesTexture.clone();
  19850. this._matricesTexture.image.data = this._matricesTexture.image.slice();
  19851. return this;
  19852. }
  19853. dispose() {
  19854. // Assuming the geometry is not shared with other meshes
  19855. this.geometry.dispose();
  19856. this._matricesTexture.dispose();
  19857. this._matricesTexture = null;
  19858. return this;
  19859. }
  19860. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  19861. // if visibility has not changed and frustum culling and object sorting is not required
  19862. // then skip iterating over all items
  19863. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  19864. return;
  19865. }
  19866. // the indexed version of the multi draw function requires specifying the start
  19867. // offset in bytes.
  19868. const index = geometry.getIndex();
  19869. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  19870. const active = this._active;
  19871. const visibility = this._visibility;
  19872. const multiDrawStarts = this._multiDrawStarts;
  19873. const multiDrawCounts = this._multiDrawCounts;
  19874. const drawRanges = this._drawRanges;
  19875. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  19876. // prepare the frustum in the local frame
  19877. if ( perObjectFrustumCulled ) {
  19878. _projScreenMatrix$2
  19879. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  19880. .multiply( this.matrixWorld );
  19881. _frustum.setFromProjectionMatrix(
  19882. _projScreenMatrix$2,
  19883. renderer.coordinateSystem
  19884. );
  19885. }
  19886. let count = 0;
  19887. if ( this.sortObjects ) {
  19888. // get the camera position in the local frame
  19889. _invMatrixWorld.copy( this.matrixWorld ).invert();
  19890. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  19891. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  19892. if ( visibility[ i ] && active[ i ] ) {
  19893. // get the bounds in world space
  19894. this.getMatrixAt( i, _matrix$1 );
  19895. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 );
  19896. // determine whether the batched geometry is within the frustum
  19897. let culled = false;
  19898. if ( perObjectFrustumCulled ) {
  19899. culled = ! _frustum.intersectsSphere( _sphere$2 );
  19900. }
  19901. if ( ! culled ) {
  19902. // get the distance from camera used for sorting
  19903. const z = _vector$5.distanceTo( _sphere$2.center );
  19904. _renderList.push( drawRanges[ i ], z );
  19905. }
  19906. }
  19907. }
  19908. // Sort the draw ranges and prep for rendering
  19909. const list = _renderList.list;
  19910. const customSort = this.customSort;
  19911. if ( customSort === null ) {
  19912. list.sort( material.transparent ? sortTransparent : sortOpaque );
  19913. } else {
  19914. customSort.call( this, list, camera );
  19915. }
  19916. for ( let i = 0, l = list.length; i < l; i ++ ) {
  19917. const item = list[ i ];
  19918. multiDrawStarts[ count ] = item.start * bytesPerElement;
  19919. multiDrawCounts[ count ] = item.count;
  19920. count ++;
  19921. }
  19922. _renderList.reset();
  19923. } else {
  19924. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  19925. if ( visibility[ i ] && active[ i ] ) {
  19926. // determine whether the batched geometry is within the frustum
  19927. let culled = false;
  19928. if ( perObjectFrustumCulled ) {
  19929. // get the bounds in world space
  19930. this.getMatrixAt( i, _matrix$1 );
  19931. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 );
  19932. culled = ! _frustum.intersectsSphere( _sphere$2 );
  19933. }
  19934. if ( ! culled ) {
  19935. const range = drawRanges[ i ];
  19936. multiDrawStarts[ count ] = range.start * bytesPerElement;
  19937. multiDrawCounts[ count ] = range.count;
  19938. count ++;
  19939. }
  19940. }
  19941. }
  19942. }
  19943. this._multiDrawCount = count;
  19944. this._visibilityChanged = false;
  19945. }
  19946. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  19947. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  19948. }
  19949. }
  19950. class LineBasicMaterial extends Material {
  19951. constructor( parameters ) {
  19952. super();
  19953. this.isLineBasicMaterial = true;
  19954. this.type = 'LineBasicMaterial';
  19955. this.color = new Color( 0xffffff );
  19956. this.map = null;
  19957. this.linewidth = 1;
  19958. this.linecap = 'round';
  19959. this.linejoin = 'round';
  19960. this.fog = true;
  19961. this.setValues( parameters );
  19962. }
  19963. copy( source ) {
  19964. super.copy( source );
  19965. this.color.copy( source.color );
  19966. this.map = source.map;
  19967. this.linewidth = source.linewidth;
  19968. this.linecap = source.linecap;
  19969. this.linejoin = source.linejoin;
  19970. this.fog = source.fog;
  19971. return this;
  19972. }
  19973. }
  19974. const _start$1 = /*@__PURE__*/ new Vector3();
  19975. const _end$1 = /*@__PURE__*/ new Vector3();
  19976. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  19977. const _ray$1 = /*@__PURE__*/ new Ray();
  19978. const _sphere$1 = /*@__PURE__*/ new Sphere();
  19979. class Line extends Object3D {
  19980. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  19981. super();
  19982. this.isLine = true;
  19983. this.type = 'Line';
  19984. this.geometry = geometry;
  19985. this.material = material;
  19986. this.updateMorphTargets();
  19987. }
  19988. copy( source, recursive ) {
  19989. super.copy( source, recursive );
  19990. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  19991. this.geometry = source.geometry;
  19992. return this;
  19993. }
  19994. computeLineDistances() {
  19995. const geometry = this.geometry;
  19996. // we assume non-indexed geometry
  19997. if ( geometry.index === null ) {
  19998. const positionAttribute = geometry.attributes.position;
  19999. const lineDistances = [ 0 ];
  20000. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20001. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  20002. _end$1.fromBufferAttribute( positionAttribute, i );
  20003. lineDistances[ i ] = lineDistances[ i - 1 ];
  20004. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  20005. }
  20006. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20007. } else {
  20008. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20009. }
  20010. return this;
  20011. }
  20012. raycast( raycaster, intersects ) {
  20013. const geometry = this.geometry;
  20014. const matrixWorld = this.matrixWorld;
  20015. const threshold = raycaster.params.Line.threshold;
  20016. const drawRange = geometry.drawRange;
  20017. // Checking boundingSphere distance to ray
  20018. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20019. _sphere$1.copy( geometry.boundingSphere );
  20020. _sphere$1.applyMatrix4( matrixWorld );
  20021. _sphere$1.radius += threshold;
  20022. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20023. //
  20024. _inverseMatrix$1.copy( matrixWorld ).invert();
  20025. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20026. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20027. const localThresholdSq = localThreshold * localThreshold;
  20028. const vStart = new Vector3();
  20029. const vEnd = new Vector3();
  20030. const interSegment = new Vector3();
  20031. const interRay = new Vector3();
  20032. const step = this.isLineSegments ? 2 : 1;
  20033. const index = geometry.index;
  20034. const attributes = geometry.attributes;
  20035. const positionAttribute = attributes.position;
  20036. if ( index !== null ) {
  20037. const start = Math.max( 0, drawRange.start );
  20038. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20039. for ( let i = start, l = end - 1; i < l; i += step ) {
  20040. const a = index.getX( i );
  20041. const b = index.getX( i + 1 );
  20042. vStart.fromBufferAttribute( positionAttribute, a );
  20043. vEnd.fromBufferAttribute( positionAttribute, b );
  20044. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20045. if ( distSq > localThresholdSq ) continue;
  20046. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20047. const distance = raycaster.ray.origin.distanceTo( interRay );
  20048. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20049. intersects.push( {
  20050. distance: distance,
  20051. // What do we want? intersection point on the ray or on the segment??
  20052. // point: raycaster.ray.at( distance ),
  20053. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20054. index: i,
  20055. face: null,
  20056. faceIndex: null,
  20057. object: this
  20058. } );
  20059. }
  20060. } else {
  20061. const start = Math.max( 0, drawRange.start );
  20062. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20063. for ( let i = start, l = end - 1; i < l; i += step ) {
  20064. vStart.fromBufferAttribute( positionAttribute, i );
  20065. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  20066. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20067. if ( distSq > localThresholdSq ) continue;
  20068. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20069. const distance = raycaster.ray.origin.distanceTo( interRay );
  20070. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20071. intersects.push( {
  20072. distance: distance,
  20073. // What do we want? intersection point on the ray or on the segment??
  20074. // point: raycaster.ray.at( distance ),
  20075. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20076. index: i,
  20077. face: null,
  20078. faceIndex: null,
  20079. object: this
  20080. } );
  20081. }
  20082. }
  20083. }
  20084. updateMorphTargets() {
  20085. const geometry = this.geometry;
  20086. const morphAttributes = geometry.morphAttributes;
  20087. const keys = Object.keys( morphAttributes );
  20088. if ( keys.length > 0 ) {
  20089. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20090. if ( morphAttribute !== undefined ) {
  20091. this.morphTargetInfluences = [];
  20092. this.morphTargetDictionary = {};
  20093. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20094. const name = morphAttribute[ m ].name || String( m );
  20095. this.morphTargetInfluences.push( 0 );
  20096. this.morphTargetDictionary[ name ] = m;
  20097. }
  20098. }
  20099. }
  20100. }
  20101. }
  20102. const _start = /*@__PURE__*/ new Vector3();
  20103. const _end = /*@__PURE__*/ new Vector3();
  20104. class LineSegments extends Line {
  20105. constructor( geometry, material ) {
  20106. super( geometry, material );
  20107. this.isLineSegments = true;
  20108. this.type = 'LineSegments';
  20109. }
  20110. computeLineDistances() {
  20111. const geometry = this.geometry;
  20112. // we assume non-indexed geometry
  20113. if ( geometry.index === null ) {
  20114. const positionAttribute = geometry.attributes.position;
  20115. const lineDistances = [];
  20116. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20117. _start.fromBufferAttribute( positionAttribute, i );
  20118. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20119. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20120. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20121. }
  20122. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20123. } else {
  20124. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20125. }
  20126. return this;
  20127. }
  20128. }
  20129. class LineLoop extends Line {
  20130. constructor( geometry, material ) {
  20131. super( geometry, material );
  20132. this.isLineLoop = true;
  20133. this.type = 'LineLoop';
  20134. }
  20135. }
  20136. class PointsMaterial extends Material {
  20137. constructor( parameters ) {
  20138. super();
  20139. this.isPointsMaterial = true;
  20140. this.type = 'PointsMaterial';
  20141. this.color = new Color( 0xffffff );
  20142. this.map = null;
  20143. this.alphaMap = null;
  20144. this.size = 1;
  20145. this.sizeAttenuation = true;
  20146. this.fog = true;
  20147. this.setValues( parameters );
  20148. }
  20149. copy( source ) {
  20150. super.copy( source );
  20151. this.color.copy( source.color );
  20152. this.map = source.map;
  20153. this.alphaMap = source.alphaMap;
  20154. this.size = source.size;
  20155. this.sizeAttenuation = source.sizeAttenuation;
  20156. this.fog = source.fog;
  20157. return this;
  20158. }
  20159. }
  20160. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20161. const _ray = /*@__PURE__*/ new Ray();
  20162. const _sphere = /*@__PURE__*/ new Sphere();
  20163. const _position$2 = /*@__PURE__*/ new Vector3();
  20164. class Points extends Object3D {
  20165. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20166. super();
  20167. this.isPoints = true;
  20168. this.type = 'Points';
  20169. this.geometry = geometry;
  20170. this.material = material;
  20171. this.updateMorphTargets();
  20172. }
  20173. copy( source, recursive ) {
  20174. super.copy( source, recursive );
  20175. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20176. this.geometry = source.geometry;
  20177. return this;
  20178. }
  20179. raycast( raycaster, intersects ) {
  20180. const geometry = this.geometry;
  20181. const matrixWorld = this.matrixWorld;
  20182. const threshold = raycaster.params.Points.threshold;
  20183. const drawRange = geometry.drawRange;
  20184. // Checking boundingSphere distance to ray
  20185. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20186. _sphere.copy( geometry.boundingSphere );
  20187. _sphere.applyMatrix4( matrixWorld );
  20188. _sphere.radius += threshold;
  20189. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20190. //
  20191. _inverseMatrix.copy( matrixWorld ).invert();
  20192. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20193. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20194. const localThresholdSq = localThreshold * localThreshold;
  20195. const index = geometry.index;
  20196. const attributes = geometry.attributes;
  20197. const positionAttribute = attributes.position;
  20198. if ( index !== null ) {
  20199. const start = Math.max( 0, drawRange.start );
  20200. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20201. for ( let i = start, il = end; i < il; i ++ ) {
  20202. const a = index.getX( i );
  20203. _position$2.fromBufferAttribute( positionAttribute, a );
  20204. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20205. }
  20206. } else {
  20207. const start = Math.max( 0, drawRange.start );
  20208. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20209. for ( let i = start, l = end; i < l; i ++ ) {
  20210. _position$2.fromBufferAttribute( positionAttribute, i );
  20211. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20212. }
  20213. }
  20214. }
  20215. updateMorphTargets() {
  20216. const geometry = this.geometry;
  20217. const morphAttributes = geometry.morphAttributes;
  20218. const keys = Object.keys( morphAttributes );
  20219. if ( keys.length > 0 ) {
  20220. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20221. if ( morphAttribute !== undefined ) {
  20222. this.morphTargetInfluences = [];
  20223. this.morphTargetDictionary = {};
  20224. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20225. const name = morphAttribute[ m ].name || String( m );
  20226. this.morphTargetInfluences.push( 0 );
  20227. this.morphTargetDictionary[ name ] = m;
  20228. }
  20229. }
  20230. }
  20231. }
  20232. }
  20233. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20234. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20235. if ( rayPointDistanceSq < localThresholdSq ) {
  20236. const intersectPoint = new Vector3();
  20237. _ray.closestPointToPoint( point, intersectPoint );
  20238. intersectPoint.applyMatrix4( matrixWorld );
  20239. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20240. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20241. intersects.push( {
  20242. distance: distance,
  20243. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20244. point: intersectPoint,
  20245. index: index,
  20246. face: null,
  20247. object: object
  20248. } );
  20249. }
  20250. }
  20251. class VideoTexture extends Texture {
  20252. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20253. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20254. this.isVideoTexture = true;
  20255. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  20256. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  20257. this.generateMipmaps = false;
  20258. const scope = this;
  20259. function updateVideo() {
  20260. scope.needsUpdate = true;
  20261. video.requestVideoFrameCallback( updateVideo );
  20262. }
  20263. if ( 'requestVideoFrameCallback' in video ) {
  20264. video.requestVideoFrameCallback( updateVideo );
  20265. }
  20266. }
  20267. clone() {
  20268. return new this.constructor( this.image ).copy( this );
  20269. }
  20270. update() {
  20271. const video = this.image;
  20272. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20273. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20274. this.needsUpdate = true;
  20275. }
  20276. }
  20277. }
  20278. class FramebufferTexture extends Texture {
  20279. constructor( width, height ) {
  20280. super( { width, height } );
  20281. this.isFramebufferTexture = true;
  20282. this.magFilter = NearestFilter;
  20283. this.minFilter = NearestFilter;
  20284. this.generateMipmaps = false;
  20285. this.needsUpdate = true;
  20286. }
  20287. }
  20288. class CompressedTexture extends Texture {
  20289. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  20290. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  20291. this.isCompressedTexture = true;
  20292. this.image = { width: width, height: height };
  20293. this.mipmaps = mipmaps;
  20294. // no flipping for cube textures
  20295. // (also flipping doesn't work for compressed textures )
  20296. this.flipY = false;
  20297. // can't generate mipmaps for compressed textures
  20298. // mips must be embedded in DDS files
  20299. this.generateMipmaps = false;
  20300. }
  20301. }
  20302. class CompressedArrayTexture extends CompressedTexture {
  20303. constructor( mipmaps, width, height, depth, format, type ) {
  20304. super( mipmaps, width, height, format, type );
  20305. this.isCompressedArrayTexture = true;
  20306. this.image.depth = depth;
  20307. this.wrapR = ClampToEdgeWrapping;
  20308. }
  20309. }
  20310. class CompressedCubeTexture extends CompressedTexture {
  20311. constructor( images, format, type ) {
  20312. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  20313. this.isCompressedCubeTexture = true;
  20314. this.isCubeTexture = true;
  20315. this.image = images;
  20316. }
  20317. }
  20318. class CanvasTexture extends Texture {
  20319. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20320. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20321. this.isCanvasTexture = true;
  20322. this.needsUpdate = true;
  20323. }
  20324. }
  20325. /**
  20326. * Extensible curve object.
  20327. *
  20328. * Some common of curve methods:
  20329. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20330. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20331. * .getPoints(), .getSpacedPoints()
  20332. * .getLength()
  20333. * .updateArcLengths()
  20334. *
  20335. * This following curves inherit from THREE.Curve:
  20336. *
  20337. * -- 2D curves --
  20338. * THREE.ArcCurve
  20339. * THREE.CubicBezierCurve
  20340. * THREE.EllipseCurve
  20341. * THREE.LineCurve
  20342. * THREE.QuadraticBezierCurve
  20343. * THREE.SplineCurve
  20344. *
  20345. * -- 3D curves --
  20346. * THREE.CatmullRomCurve3
  20347. * THREE.CubicBezierCurve3
  20348. * THREE.LineCurve3
  20349. * THREE.QuadraticBezierCurve3
  20350. *
  20351. * A series of curves can be represented as a THREE.CurvePath.
  20352. *
  20353. **/
  20354. class Curve {
  20355. constructor() {
  20356. this.type = 'Curve';
  20357. this.arcLengthDivisions = 200;
  20358. }
  20359. // Virtual base class method to overwrite and implement in subclasses
  20360. // - t [0 .. 1]
  20361. getPoint( /* t, optionalTarget */ ) {
  20362. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20363. return null;
  20364. }
  20365. // Get point at relative position in curve according to arc length
  20366. // - u [0 .. 1]
  20367. getPointAt( u, optionalTarget ) {
  20368. const t = this.getUtoTmapping( u );
  20369. return this.getPoint( t, optionalTarget );
  20370. }
  20371. // Get sequence of points using getPoint( t )
  20372. getPoints( divisions = 5 ) {
  20373. const points = [];
  20374. for ( let d = 0; d <= divisions; d ++ ) {
  20375. points.push( this.getPoint( d / divisions ) );
  20376. }
  20377. return points;
  20378. }
  20379. // Get sequence of points using getPointAt( u )
  20380. getSpacedPoints( divisions = 5 ) {
  20381. const points = [];
  20382. for ( let d = 0; d <= divisions; d ++ ) {
  20383. points.push( this.getPointAt( d / divisions ) );
  20384. }
  20385. return points;
  20386. }
  20387. // Get total curve arc length
  20388. getLength() {
  20389. const lengths = this.getLengths();
  20390. return lengths[ lengths.length - 1 ];
  20391. }
  20392. // Get list of cumulative segment lengths
  20393. getLengths( divisions = this.arcLengthDivisions ) {
  20394. if ( this.cacheArcLengths &&
  20395. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20396. ! this.needsUpdate ) {
  20397. return this.cacheArcLengths;
  20398. }
  20399. this.needsUpdate = false;
  20400. const cache = [];
  20401. let current, last = this.getPoint( 0 );
  20402. let sum = 0;
  20403. cache.push( 0 );
  20404. for ( let p = 1; p <= divisions; p ++ ) {
  20405. current = this.getPoint( p / divisions );
  20406. sum += current.distanceTo( last );
  20407. cache.push( sum );
  20408. last = current;
  20409. }
  20410. this.cacheArcLengths = cache;
  20411. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20412. }
  20413. updateArcLengths() {
  20414. this.needsUpdate = true;
  20415. this.getLengths();
  20416. }
  20417. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20418. getUtoTmapping( u, distance ) {
  20419. const arcLengths = this.getLengths();
  20420. let i = 0;
  20421. const il = arcLengths.length;
  20422. let targetArcLength; // The targeted u distance value to get
  20423. if ( distance ) {
  20424. targetArcLength = distance;
  20425. } else {
  20426. targetArcLength = u * arcLengths[ il - 1 ];
  20427. }
  20428. // binary search for the index with largest value smaller than target u distance
  20429. let low = 0, high = il - 1, comparison;
  20430. while ( low <= high ) {
  20431. 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
  20432. comparison = arcLengths[ i ] - targetArcLength;
  20433. if ( comparison < 0 ) {
  20434. low = i + 1;
  20435. } else if ( comparison > 0 ) {
  20436. high = i - 1;
  20437. } else {
  20438. high = i;
  20439. break;
  20440. // DONE
  20441. }
  20442. }
  20443. i = high;
  20444. if ( arcLengths[ i ] === targetArcLength ) {
  20445. return i / ( il - 1 );
  20446. }
  20447. // we could get finer grain at lengths, or use simple interpolation between two points
  20448. const lengthBefore = arcLengths[ i ];
  20449. const lengthAfter = arcLengths[ i + 1 ];
  20450. const segmentLength = lengthAfter - lengthBefore;
  20451. // determine where we are between the 'before' and 'after' points
  20452. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20453. // add that fractional amount to t
  20454. const t = ( i + segmentFraction ) / ( il - 1 );
  20455. return t;
  20456. }
  20457. // Returns a unit vector tangent at t
  20458. // In case any sub curve does not implement its tangent derivation,
  20459. // 2 points a small delta apart will be used to find its gradient
  20460. // which seems to give a reasonable approximation
  20461. getTangent( t, optionalTarget ) {
  20462. const delta = 0.0001;
  20463. let t1 = t - delta;
  20464. let t2 = t + delta;
  20465. // Capping in case of danger
  20466. if ( t1 < 0 ) t1 = 0;
  20467. if ( t2 > 1 ) t2 = 1;
  20468. const pt1 = this.getPoint( t1 );
  20469. const pt2 = this.getPoint( t2 );
  20470. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  20471. tangent.copy( pt2 ).sub( pt1 ).normalize();
  20472. return tangent;
  20473. }
  20474. getTangentAt( u, optionalTarget ) {
  20475. const t = this.getUtoTmapping( u );
  20476. return this.getTangent( t, optionalTarget );
  20477. }
  20478. computeFrenetFrames( segments, closed ) {
  20479. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20480. const normal = new Vector3();
  20481. const tangents = [];
  20482. const normals = [];
  20483. const binormals = [];
  20484. const vec = new Vector3();
  20485. const mat = new Matrix4();
  20486. // compute the tangent vectors for each segment on the curve
  20487. for ( let i = 0; i <= segments; i ++ ) {
  20488. const u = i / segments;
  20489. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  20490. }
  20491. // select an initial normal vector perpendicular to the first tangent vector,
  20492. // and in the direction of the minimum tangent xyz component
  20493. normals[ 0 ] = new Vector3();
  20494. binormals[ 0 ] = new Vector3();
  20495. let min = Number.MAX_VALUE;
  20496. const tx = Math.abs( tangents[ 0 ].x );
  20497. const ty = Math.abs( tangents[ 0 ].y );
  20498. const tz = Math.abs( tangents[ 0 ].z );
  20499. if ( tx <= min ) {
  20500. min = tx;
  20501. normal.set( 1, 0, 0 );
  20502. }
  20503. if ( ty <= min ) {
  20504. min = ty;
  20505. normal.set( 0, 1, 0 );
  20506. }
  20507. if ( tz <= min ) {
  20508. normal.set( 0, 0, 1 );
  20509. }
  20510. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20511. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20512. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20513. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20514. for ( let i = 1; i <= segments; i ++ ) {
  20515. normals[ i ] = normals[ i - 1 ].clone();
  20516. binormals[ i ] = binormals[ i - 1 ].clone();
  20517. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20518. if ( vec.length() > Number.EPSILON ) {
  20519. vec.normalize();
  20520. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20521. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20522. }
  20523. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20524. }
  20525. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20526. if ( closed === true ) {
  20527. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20528. theta /= segments;
  20529. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20530. theta = - theta;
  20531. }
  20532. for ( let i = 1; i <= segments; i ++ ) {
  20533. // twist a little...
  20534. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20535. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20536. }
  20537. }
  20538. return {
  20539. tangents: tangents,
  20540. normals: normals,
  20541. binormals: binormals
  20542. };
  20543. }
  20544. clone() {
  20545. return new this.constructor().copy( this );
  20546. }
  20547. copy( source ) {
  20548. this.arcLengthDivisions = source.arcLengthDivisions;
  20549. return this;
  20550. }
  20551. toJSON() {
  20552. const data = {
  20553. metadata: {
  20554. version: 4.6,
  20555. type: 'Curve',
  20556. generator: 'Curve.toJSON'
  20557. }
  20558. };
  20559. data.arcLengthDivisions = this.arcLengthDivisions;
  20560. data.type = this.type;
  20561. return data;
  20562. }
  20563. fromJSON( json ) {
  20564. this.arcLengthDivisions = json.arcLengthDivisions;
  20565. return this;
  20566. }
  20567. }
  20568. class EllipseCurve extends Curve {
  20569. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  20570. super();
  20571. this.isEllipseCurve = true;
  20572. this.type = 'EllipseCurve';
  20573. this.aX = aX;
  20574. this.aY = aY;
  20575. this.xRadius = xRadius;
  20576. this.yRadius = yRadius;
  20577. this.aStartAngle = aStartAngle;
  20578. this.aEndAngle = aEndAngle;
  20579. this.aClockwise = aClockwise;
  20580. this.aRotation = aRotation;
  20581. }
  20582. getPoint( t, optionalTarget = new Vector2() ) {
  20583. const point = optionalTarget;
  20584. const twoPi = Math.PI * 2;
  20585. let deltaAngle = this.aEndAngle - this.aStartAngle;
  20586. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20587. // ensures that deltaAngle is 0 .. 2 PI
  20588. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20589. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20590. if ( deltaAngle < Number.EPSILON ) {
  20591. if ( samePoints ) {
  20592. deltaAngle = 0;
  20593. } else {
  20594. deltaAngle = twoPi;
  20595. }
  20596. }
  20597. if ( this.aClockwise === true && ! samePoints ) {
  20598. if ( deltaAngle === twoPi ) {
  20599. deltaAngle = - twoPi;
  20600. } else {
  20601. deltaAngle = deltaAngle - twoPi;
  20602. }
  20603. }
  20604. const angle = this.aStartAngle + t * deltaAngle;
  20605. let x = this.aX + this.xRadius * Math.cos( angle );
  20606. let y = this.aY + this.yRadius * Math.sin( angle );
  20607. if ( this.aRotation !== 0 ) {
  20608. const cos = Math.cos( this.aRotation );
  20609. const sin = Math.sin( this.aRotation );
  20610. const tx = x - this.aX;
  20611. const ty = y - this.aY;
  20612. // Rotate the point about the center of the ellipse.
  20613. x = tx * cos - ty * sin + this.aX;
  20614. y = tx * sin + ty * cos + this.aY;
  20615. }
  20616. return point.set( x, y );
  20617. }
  20618. copy( source ) {
  20619. super.copy( source );
  20620. this.aX = source.aX;
  20621. this.aY = source.aY;
  20622. this.xRadius = source.xRadius;
  20623. this.yRadius = source.yRadius;
  20624. this.aStartAngle = source.aStartAngle;
  20625. this.aEndAngle = source.aEndAngle;
  20626. this.aClockwise = source.aClockwise;
  20627. this.aRotation = source.aRotation;
  20628. return this;
  20629. }
  20630. toJSON() {
  20631. const data = super.toJSON();
  20632. data.aX = this.aX;
  20633. data.aY = this.aY;
  20634. data.xRadius = this.xRadius;
  20635. data.yRadius = this.yRadius;
  20636. data.aStartAngle = this.aStartAngle;
  20637. data.aEndAngle = this.aEndAngle;
  20638. data.aClockwise = this.aClockwise;
  20639. data.aRotation = this.aRotation;
  20640. return data;
  20641. }
  20642. fromJSON( json ) {
  20643. super.fromJSON( json );
  20644. this.aX = json.aX;
  20645. this.aY = json.aY;
  20646. this.xRadius = json.xRadius;
  20647. this.yRadius = json.yRadius;
  20648. this.aStartAngle = json.aStartAngle;
  20649. this.aEndAngle = json.aEndAngle;
  20650. this.aClockwise = json.aClockwise;
  20651. this.aRotation = json.aRotation;
  20652. return this;
  20653. }
  20654. }
  20655. class ArcCurve extends EllipseCurve {
  20656. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20657. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20658. this.isArcCurve = true;
  20659. this.type = 'ArcCurve';
  20660. }
  20661. }
  20662. /**
  20663. * Centripetal CatmullRom Curve - which is useful for avoiding
  20664. * cusps and self-intersections in non-uniform catmull rom curves.
  20665. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  20666. *
  20667. * curve.type accepts centripetal(default), chordal and catmullrom
  20668. * curve.tension is used for catmullrom which defaults to 0.5
  20669. */
  20670. /*
  20671. Based on an optimized c++ solution in
  20672. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  20673. - http://ideone.com/NoEbVM
  20674. This CubicPoly class could be used for reusing some variables and calculations,
  20675. but for three.js curve use, it could be possible inlined and flatten into a single function call
  20676. which can be placed in CurveUtils.
  20677. */
  20678. function CubicPoly() {
  20679. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  20680. /*
  20681. * Compute coefficients for a cubic polynomial
  20682. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  20683. * such that
  20684. * p(0) = x0, p(1) = x1
  20685. * and
  20686. * p'(0) = t0, p'(1) = t1.
  20687. */
  20688. function init( x0, x1, t0, t1 ) {
  20689. c0 = x0;
  20690. c1 = t0;
  20691. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  20692. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  20693. }
  20694. return {
  20695. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  20696. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  20697. },
  20698. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  20699. // compute tangents when parameterized in [t1,t2]
  20700. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  20701. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  20702. // rescale tangents for parametrization in [0,1]
  20703. t1 *= dt1;
  20704. t2 *= dt1;
  20705. init( x1, x2, t1, t2 );
  20706. },
  20707. calc: function ( t ) {
  20708. const t2 = t * t;
  20709. const t3 = t2 * t;
  20710. return c0 + c1 * t + c2 * t2 + c3 * t3;
  20711. }
  20712. };
  20713. }
  20714. //
  20715. const tmp = /*@__PURE__*/ new Vector3();
  20716. const px = /*@__PURE__*/ new CubicPoly();
  20717. const py = /*@__PURE__*/ new CubicPoly();
  20718. const pz = /*@__PURE__*/ new CubicPoly();
  20719. class CatmullRomCurve3 extends Curve {
  20720. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  20721. super();
  20722. this.isCatmullRomCurve3 = true;
  20723. this.type = 'CatmullRomCurve3';
  20724. this.points = points;
  20725. this.closed = closed;
  20726. this.curveType = curveType;
  20727. this.tension = tension;
  20728. }
  20729. getPoint( t, optionalTarget = new Vector3() ) {
  20730. const point = optionalTarget;
  20731. const points = this.points;
  20732. const l = points.length;
  20733. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  20734. let intPoint = Math.floor( p );
  20735. let weight = p - intPoint;
  20736. if ( this.closed ) {
  20737. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  20738. } else if ( weight === 0 && intPoint === l - 1 ) {
  20739. intPoint = l - 2;
  20740. weight = 1;
  20741. }
  20742. let p0, p3; // 4 points (p1 & p2 defined below)
  20743. if ( this.closed || intPoint > 0 ) {
  20744. p0 = points[ ( intPoint - 1 ) % l ];
  20745. } else {
  20746. // extrapolate first point
  20747. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  20748. p0 = tmp;
  20749. }
  20750. const p1 = points[ intPoint % l ];
  20751. const p2 = points[ ( intPoint + 1 ) % l ];
  20752. if ( this.closed || intPoint + 2 < l ) {
  20753. p3 = points[ ( intPoint + 2 ) % l ];
  20754. } else {
  20755. // extrapolate last point
  20756. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  20757. p3 = tmp;
  20758. }
  20759. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  20760. // init Centripetal / Chordal Catmull-Rom
  20761. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  20762. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  20763. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  20764. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  20765. // safety check for repeated points
  20766. if ( dt1 < 1e-4 ) dt1 = 1.0;
  20767. if ( dt0 < 1e-4 ) dt0 = dt1;
  20768. if ( dt2 < 1e-4 ) dt2 = dt1;
  20769. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  20770. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  20771. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  20772. } else if ( this.curveType === 'catmullrom' ) {
  20773. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  20774. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  20775. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  20776. }
  20777. point.set(
  20778. px.calc( weight ),
  20779. py.calc( weight ),
  20780. pz.calc( weight )
  20781. );
  20782. return point;
  20783. }
  20784. copy( source ) {
  20785. super.copy( source );
  20786. this.points = [];
  20787. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  20788. const point = source.points[ i ];
  20789. this.points.push( point.clone() );
  20790. }
  20791. this.closed = source.closed;
  20792. this.curveType = source.curveType;
  20793. this.tension = source.tension;
  20794. return this;
  20795. }
  20796. toJSON() {
  20797. const data = super.toJSON();
  20798. data.points = [];
  20799. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  20800. const point = this.points[ i ];
  20801. data.points.push( point.toArray() );
  20802. }
  20803. data.closed = this.closed;
  20804. data.curveType = this.curveType;
  20805. data.tension = this.tension;
  20806. return data;
  20807. }
  20808. fromJSON( json ) {
  20809. super.fromJSON( json );
  20810. this.points = [];
  20811. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20812. const point = json.points[ i ];
  20813. this.points.push( new Vector3().fromArray( point ) );
  20814. }
  20815. this.closed = json.closed;
  20816. this.curveType = json.curveType;
  20817. this.tension = json.tension;
  20818. return this;
  20819. }
  20820. }
  20821. /**
  20822. * Bezier Curves formulas obtained from
  20823. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  20824. */
  20825. function CatmullRom( t, p0, p1, p2, p3 ) {
  20826. const v0 = ( p2 - p0 ) * 0.5;
  20827. const v1 = ( p3 - p1 ) * 0.5;
  20828. const t2 = t * t;
  20829. const t3 = t * t2;
  20830. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20831. }
  20832. //
  20833. function QuadraticBezierP0( t, p ) {
  20834. const k = 1 - t;
  20835. return k * k * p;
  20836. }
  20837. function QuadraticBezierP1( t, p ) {
  20838. return 2 * ( 1 - t ) * t * p;
  20839. }
  20840. function QuadraticBezierP2( t, p ) {
  20841. return t * t * p;
  20842. }
  20843. function QuadraticBezier( t, p0, p1, p2 ) {
  20844. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20845. QuadraticBezierP2( t, p2 );
  20846. }
  20847. //
  20848. function CubicBezierP0( t, p ) {
  20849. const k = 1 - t;
  20850. return k * k * k * p;
  20851. }
  20852. function CubicBezierP1( t, p ) {
  20853. const k = 1 - t;
  20854. return 3 * k * k * t * p;
  20855. }
  20856. function CubicBezierP2( t, p ) {
  20857. return 3 * ( 1 - t ) * t * t * p;
  20858. }
  20859. function CubicBezierP3( t, p ) {
  20860. return t * t * t * p;
  20861. }
  20862. function CubicBezier( t, p0, p1, p2, p3 ) {
  20863. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20864. CubicBezierP3( t, p3 );
  20865. }
  20866. class CubicBezierCurve extends Curve {
  20867. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  20868. super();
  20869. this.isCubicBezierCurve = true;
  20870. this.type = 'CubicBezierCurve';
  20871. this.v0 = v0;
  20872. this.v1 = v1;
  20873. this.v2 = v2;
  20874. this.v3 = v3;
  20875. }
  20876. getPoint( t, optionalTarget = new Vector2() ) {
  20877. const point = optionalTarget;
  20878. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20879. point.set(
  20880. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20881. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  20882. );
  20883. return point;
  20884. }
  20885. copy( source ) {
  20886. super.copy( source );
  20887. this.v0.copy( source.v0 );
  20888. this.v1.copy( source.v1 );
  20889. this.v2.copy( source.v2 );
  20890. this.v3.copy( source.v3 );
  20891. return this;
  20892. }
  20893. toJSON() {
  20894. const data = super.toJSON();
  20895. data.v0 = this.v0.toArray();
  20896. data.v1 = this.v1.toArray();
  20897. data.v2 = this.v2.toArray();
  20898. data.v3 = this.v3.toArray();
  20899. return data;
  20900. }
  20901. fromJSON( json ) {
  20902. super.fromJSON( json );
  20903. this.v0.fromArray( json.v0 );
  20904. this.v1.fromArray( json.v1 );
  20905. this.v2.fromArray( json.v2 );
  20906. this.v3.fromArray( json.v3 );
  20907. return this;
  20908. }
  20909. }
  20910. class CubicBezierCurve3 extends Curve {
  20911. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  20912. super();
  20913. this.isCubicBezierCurve3 = true;
  20914. this.type = 'CubicBezierCurve3';
  20915. this.v0 = v0;
  20916. this.v1 = v1;
  20917. this.v2 = v2;
  20918. this.v3 = v3;
  20919. }
  20920. getPoint( t, optionalTarget = new Vector3() ) {
  20921. const point = optionalTarget;
  20922. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20923. point.set(
  20924. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20925. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  20926. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  20927. );
  20928. return point;
  20929. }
  20930. copy( source ) {
  20931. super.copy( source );
  20932. this.v0.copy( source.v0 );
  20933. this.v1.copy( source.v1 );
  20934. this.v2.copy( source.v2 );
  20935. this.v3.copy( source.v3 );
  20936. return this;
  20937. }
  20938. toJSON() {
  20939. const data = super.toJSON();
  20940. data.v0 = this.v0.toArray();
  20941. data.v1 = this.v1.toArray();
  20942. data.v2 = this.v2.toArray();
  20943. data.v3 = this.v3.toArray();
  20944. return data;
  20945. }
  20946. fromJSON( json ) {
  20947. super.fromJSON( json );
  20948. this.v0.fromArray( json.v0 );
  20949. this.v1.fromArray( json.v1 );
  20950. this.v2.fromArray( json.v2 );
  20951. this.v3.fromArray( json.v3 );
  20952. return this;
  20953. }
  20954. }
  20955. class LineCurve extends Curve {
  20956. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  20957. super();
  20958. this.isLineCurve = true;
  20959. this.type = 'LineCurve';
  20960. this.v1 = v1;
  20961. this.v2 = v2;
  20962. }
  20963. getPoint( t, optionalTarget = new Vector2() ) {
  20964. const point = optionalTarget;
  20965. if ( t === 1 ) {
  20966. point.copy( this.v2 );
  20967. } else {
  20968. point.copy( this.v2 ).sub( this.v1 );
  20969. point.multiplyScalar( t ).add( this.v1 );
  20970. }
  20971. return point;
  20972. }
  20973. // Line curve is linear, so we can overwrite default getPointAt
  20974. getPointAt( u, optionalTarget ) {
  20975. return this.getPoint( u, optionalTarget );
  20976. }
  20977. getTangent( t, optionalTarget = new Vector2() ) {
  20978. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  20979. }
  20980. getTangentAt( u, optionalTarget ) {
  20981. return this.getTangent( u, optionalTarget );
  20982. }
  20983. copy( source ) {
  20984. super.copy( source );
  20985. this.v1.copy( source.v1 );
  20986. this.v2.copy( source.v2 );
  20987. return this;
  20988. }
  20989. toJSON() {
  20990. const data = super.toJSON();
  20991. data.v1 = this.v1.toArray();
  20992. data.v2 = this.v2.toArray();
  20993. return data;
  20994. }
  20995. fromJSON( json ) {
  20996. super.fromJSON( json );
  20997. this.v1.fromArray( json.v1 );
  20998. this.v2.fromArray( json.v2 );
  20999. return this;
  21000. }
  21001. }
  21002. class LineCurve3 extends Curve {
  21003. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  21004. super();
  21005. this.isLineCurve3 = true;
  21006. this.type = 'LineCurve3';
  21007. this.v1 = v1;
  21008. this.v2 = v2;
  21009. }
  21010. getPoint( t, optionalTarget = new Vector3() ) {
  21011. const point = optionalTarget;
  21012. if ( t === 1 ) {
  21013. point.copy( this.v2 );
  21014. } else {
  21015. point.copy( this.v2 ).sub( this.v1 );
  21016. point.multiplyScalar( t ).add( this.v1 );
  21017. }
  21018. return point;
  21019. }
  21020. // Line curve is linear, so we can overwrite default getPointAt
  21021. getPointAt( u, optionalTarget ) {
  21022. return this.getPoint( u, optionalTarget );
  21023. }
  21024. getTangent( t, optionalTarget = new Vector3() ) {
  21025. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21026. }
  21027. getTangentAt( u, optionalTarget ) {
  21028. return this.getTangent( u, optionalTarget );
  21029. }
  21030. copy( source ) {
  21031. super.copy( source );
  21032. this.v1.copy( source.v1 );
  21033. this.v2.copy( source.v2 );
  21034. return this;
  21035. }
  21036. toJSON() {
  21037. const data = super.toJSON();
  21038. data.v1 = this.v1.toArray();
  21039. data.v2 = this.v2.toArray();
  21040. return data;
  21041. }
  21042. fromJSON( json ) {
  21043. super.fromJSON( json );
  21044. this.v1.fromArray( json.v1 );
  21045. this.v2.fromArray( json.v2 );
  21046. return this;
  21047. }
  21048. }
  21049. class QuadraticBezierCurve extends Curve {
  21050. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  21051. super();
  21052. this.isQuadraticBezierCurve = true;
  21053. this.type = 'QuadraticBezierCurve';
  21054. this.v0 = v0;
  21055. this.v1 = v1;
  21056. this.v2 = v2;
  21057. }
  21058. getPoint( t, optionalTarget = new Vector2() ) {
  21059. const point = optionalTarget;
  21060. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21061. point.set(
  21062. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21063. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21064. );
  21065. return point;
  21066. }
  21067. copy( source ) {
  21068. super.copy( source );
  21069. this.v0.copy( source.v0 );
  21070. this.v1.copy( source.v1 );
  21071. this.v2.copy( source.v2 );
  21072. return this;
  21073. }
  21074. toJSON() {
  21075. const data = super.toJSON();
  21076. data.v0 = this.v0.toArray();
  21077. data.v1 = this.v1.toArray();
  21078. data.v2 = this.v2.toArray();
  21079. return data;
  21080. }
  21081. fromJSON( json ) {
  21082. super.fromJSON( json );
  21083. this.v0.fromArray( json.v0 );
  21084. this.v1.fromArray( json.v1 );
  21085. this.v2.fromArray( json.v2 );
  21086. return this;
  21087. }
  21088. }
  21089. class QuadraticBezierCurve3 extends Curve {
  21090. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  21091. super();
  21092. this.isQuadraticBezierCurve3 = true;
  21093. this.type = 'QuadraticBezierCurve3';
  21094. this.v0 = v0;
  21095. this.v1 = v1;
  21096. this.v2 = v2;
  21097. }
  21098. getPoint( t, optionalTarget = new Vector3() ) {
  21099. const point = optionalTarget;
  21100. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21101. point.set(
  21102. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21103. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  21104. QuadraticBezier( t, v0.z, v1.z, v2.z )
  21105. );
  21106. return point;
  21107. }
  21108. copy( source ) {
  21109. super.copy( source );
  21110. this.v0.copy( source.v0 );
  21111. this.v1.copy( source.v1 );
  21112. this.v2.copy( source.v2 );
  21113. return this;
  21114. }
  21115. toJSON() {
  21116. const data = super.toJSON();
  21117. data.v0 = this.v0.toArray();
  21118. data.v1 = this.v1.toArray();
  21119. data.v2 = this.v2.toArray();
  21120. return data;
  21121. }
  21122. fromJSON( json ) {
  21123. super.fromJSON( json );
  21124. this.v0.fromArray( json.v0 );
  21125. this.v1.fromArray( json.v1 );
  21126. this.v2.fromArray( json.v2 );
  21127. return this;
  21128. }
  21129. }
  21130. class SplineCurve extends Curve {
  21131. constructor( points = [] ) {
  21132. super();
  21133. this.isSplineCurve = true;
  21134. this.type = 'SplineCurve';
  21135. this.points = points;
  21136. }
  21137. getPoint( t, optionalTarget = new Vector2() ) {
  21138. const point = optionalTarget;
  21139. const points = this.points;
  21140. const p = ( points.length - 1 ) * t;
  21141. const intPoint = Math.floor( p );
  21142. const weight = p - intPoint;
  21143. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21144. const p1 = points[ intPoint ];
  21145. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21146. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21147. point.set(
  21148. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  21149. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  21150. );
  21151. return point;
  21152. }
  21153. copy( source ) {
  21154. super.copy( source );
  21155. this.points = [];
  21156. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21157. const point = source.points[ i ];
  21158. this.points.push( point.clone() );
  21159. }
  21160. return this;
  21161. }
  21162. toJSON() {
  21163. const data = super.toJSON();
  21164. data.points = [];
  21165. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21166. const point = this.points[ i ];
  21167. data.points.push( point.toArray() );
  21168. }
  21169. return data;
  21170. }
  21171. fromJSON( json ) {
  21172. super.fromJSON( json );
  21173. this.points = [];
  21174. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21175. const point = json.points[ i ];
  21176. this.points.push( new Vector2().fromArray( point ) );
  21177. }
  21178. return this;
  21179. }
  21180. }
  21181. var Curves = /*#__PURE__*/Object.freeze({
  21182. __proto__: null,
  21183. ArcCurve: ArcCurve,
  21184. CatmullRomCurve3: CatmullRomCurve3,
  21185. CubicBezierCurve: CubicBezierCurve,
  21186. CubicBezierCurve3: CubicBezierCurve3,
  21187. EllipseCurve: EllipseCurve,
  21188. LineCurve: LineCurve,
  21189. LineCurve3: LineCurve3,
  21190. QuadraticBezierCurve: QuadraticBezierCurve,
  21191. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21192. SplineCurve: SplineCurve
  21193. });
  21194. /**************************************************************
  21195. * Curved Path - a curve path is simply a array of connected
  21196. * curves, but retains the api of a curve
  21197. **************************************************************/
  21198. class CurvePath extends Curve {
  21199. constructor() {
  21200. super();
  21201. this.type = 'CurvePath';
  21202. this.curves = [];
  21203. this.autoClose = false; // Automatically closes the path
  21204. }
  21205. add( curve ) {
  21206. this.curves.push( curve );
  21207. }
  21208. closePath() {
  21209. // Add a line curve if start and end of lines are not connected
  21210. const startPoint = this.curves[ 0 ].getPoint( 0 );
  21211. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21212. if ( ! startPoint.equals( endPoint ) ) {
  21213. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  21214. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  21215. }
  21216. return this;
  21217. }
  21218. // To get accurate point with reference to
  21219. // entire path distance at time t,
  21220. // following has to be done:
  21221. // 1. Length of each sub path have to be known
  21222. // 2. Locate and identify type of curve
  21223. // 3. Get t for the curve
  21224. // 4. Return curve.getPointAt(t')
  21225. getPoint( t, optionalTarget ) {
  21226. const d = t * this.getLength();
  21227. const curveLengths = this.getCurveLengths();
  21228. let i = 0;
  21229. // To think about boundaries points.
  21230. while ( i < curveLengths.length ) {
  21231. if ( curveLengths[ i ] >= d ) {
  21232. const diff = curveLengths[ i ] - d;
  21233. const curve = this.curves[ i ];
  21234. const segmentLength = curve.getLength();
  21235. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21236. return curve.getPointAt( u, optionalTarget );
  21237. }
  21238. i ++;
  21239. }
  21240. return null;
  21241. // loop where sum != 0, sum > d , sum+1 <d
  21242. }
  21243. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21244. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21245. // getPoint() depends on getLength
  21246. getLength() {
  21247. const lens = this.getCurveLengths();
  21248. return lens[ lens.length - 1 ];
  21249. }
  21250. // cacheLengths must be recalculated.
  21251. updateArcLengths() {
  21252. this.needsUpdate = true;
  21253. this.cacheLengths = null;
  21254. this.getCurveLengths();
  21255. }
  21256. // Compute lengths and cache them
  21257. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21258. getCurveLengths() {
  21259. // We use cache values if curves and cache array are same length
  21260. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21261. return this.cacheLengths;
  21262. }
  21263. // Get length of sub-curve
  21264. // Push sums into cached array
  21265. const lengths = [];
  21266. let sums = 0;
  21267. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21268. sums += this.curves[ i ].getLength();
  21269. lengths.push( sums );
  21270. }
  21271. this.cacheLengths = lengths;
  21272. return lengths;
  21273. }
  21274. getSpacedPoints( divisions = 40 ) {
  21275. const points = [];
  21276. for ( let i = 0; i <= divisions; i ++ ) {
  21277. points.push( this.getPoint( i / divisions ) );
  21278. }
  21279. if ( this.autoClose ) {
  21280. points.push( points[ 0 ] );
  21281. }
  21282. return points;
  21283. }
  21284. getPoints( divisions = 12 ) {
  21285. const points = [];
  21286. let last;
  21287. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21288. const curve = curves[ i ];
  21289. const resolution = curve.isEllipseCurve ? divisions * 2
  21290. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  21291. : curve.isSplineCurve ? divisions * curve.points.length
  21292. : divisions;
  21293. const pts = curve.getPoints( resolution );
  21294. for ( let j = 0; j < pts.length; j ++ ) {
  21295. const point = pts[ j ];
  21296. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21297. points.push( point );
  21298. last = point;
  21299. }
  21300. }
  21301. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21302. points.push( points[ 0 ] );
  21303. }
  21304. return points;
  21305. }
  21306. copy( source ) {
  21307. super.copy( source );
  21308. this.curves = [];
  21309. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  21310. const curve = source.curves[ i ];
  21311. this.curves.push( curve.clone() );
  21312. }
  21313. this.autoClose = source.autoClose;
  21314. return this;
  21315. }
  21316. toJSON() {
  21317. const data = super.toJSON();
  21318. data.autoClose = this.autoClose;
  21319. data.curves = [];
  21320. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21321. const curve = this.curves[ i ];
  21322. data.curves.push( curve.toJSON() );
  21323. }
  21324. return data;
  21325. }
  21326. fromJSON( json ) {
  21327. super.fromJSON( json );
  21328. this.autoClose = json.autoClose;
  21329. this.curves = [];
  21330. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  21331. const curve = json.curves[ i ];
  21332. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  21333. }
  21334. return this;
  21335. }
  21336. }
  21337. class Path extends CurvePath {
  21338. constructor( points ) {
  21339. super();
  21340. this.type = 'Path';
  21341. this.currentPoint = new Vector2();
  21342. if ( points ) {
  21343. this.setFromPoints( points );
  21344. }
  21345. }
  21346. setFromPoints( points ) {
  21347. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  21348. for ( let i = 1, l = points.length; i < l; i ++ ) {
  21349. this.lineTo( points[ i ].x, points[ i ].y );
  21350. }
  21351. return this;
  21352. }
  21353. moveTo( x, y ) {
  21354. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21355. return this;
  21356. }
  21357. lineTo( x, y ) {
  21358. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21359. this.curves.push( curve );
  21360. this.currentPoint.set( x, y );
  21361. return this;
  21362. }
  21363. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21364. const curve = new QuadraticBezierCurve(
  21365. this.currentPoint.clone(),
  21366. new Vector2( aCPx, aCPy ),
  21367. new Vector2( aX, aY )
  21368. );
  21369. this.curves.push( curve );
  21370. this.currentPoint.set( aX, aY );
  21371. return this;
  21372. }
  21373. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21374. const curve = new CubicBezierCurve(
  21375. this.currentPoint.clone(),
  21376. new Vector2( aCP1x, aCP1y ),
  21377. new Vector2( aCP2x, aCP2y ),
  21378. new Vector2( aX, aY )
  21379. );
  21380. this.curves.push( curve );
  21381. this.currentPoint.set( aX, aY );
  21382. return this;
  21383. }
  21384. splineThru( pts /*Array of Vector*/ ) {
  21385. const npts = [ this.currentPoint.clone() ].concat( pts );
  21386. const curve = new SplineCurve( npts );
  21387. this.curves.push( curve );
  21388. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21389. return this;
  21390. }
  21391. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21392. const x0 = this.currentPoint.x;
  21393. const y0 = this.currentPoint.y;
  21394. this.absarc( aX + x0, aY + y0, aRadius,
  21395. aStartAngle, aEndAngle, aClockwise );
  21396. return this;
  21397. }
  21398. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21399. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21400. return this;
  21401. }
  21402. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21403. const x0 = this.currentPoint.x;
  21404. const y0 = this.currentPoint.y;
  21405. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21406. return this;
  21407. }
  21408. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21409. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21410. if ( this.curves.length > 0 ) {
  21411. // if a previous curve is present, attempt to join
  21412. const firstPoint = curve.getPoint( 0 );
  21413. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21414. this.lineTo( firstPoint.x, firstPoint.y );
  21415. }
  21416. }
  21417. this.curves.push( curve );
  21418. const lastPoint = curve.getPoint( 1 );
  21419. this.currentPoint.copy( lastPoint );
  21420. return this;
  21421. }
  21422. copy( source ) {
  21423. super.copy( source );
  21424. this.currentPoint.copy( source.currentPoint );
  21425. return this;
  21426. }
  21427. toJSON() {
  21428. const data = super.toJSON();
  21429. data.currentPoint = this.currentPoint.toArray();
  21430. return data;
  21431. }
  21432. fromJSON( json ) {
  21433. super.fromJSON( json );
  21434. this.currentPoint.fromArray( json.currentPoint );
  21435. return this;
  21436. }
  21437. }
  21438. class LatheGeometry extends BufferGeometry {
  21439. 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 ) {
  21440. super();
  21441. this.type = 'LatheGeometry';
  21442. this.parameters = {
  21443. points: points,
  21444. segments: segments,
  21445. phiStart: phiStart,
  21446. phiLength: phiLength
  21447. };
  21448. segments = Math.floor( segments );
  21449. // clamp phiLength so it's in range of [ 0, 2PI ]
  21450. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  21451. // buffers
  21452. const indices = [];
  21453. const vertices = [];
  21454. const uvs = [];
  21455. const initNormals = [];
  21456. const normals = [];
  21457. // helper variables
  21458. const inverseSegments = 1.0 / segments;
  21459. const vertex = new Vector3();
  21460. const uv = new Vector2();
  21461. const normal = new Vector3();
  21462. const curNormal = new Vector3();
  21463. const prevNormal = new Vector3();
  21464. let dx = 0;
  21465. let dy = 0;
  21466. // pre-compute normals for initial "meridian"
  21467. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21468. switch ( j ) {
  21469. case 0: // special handling for 1st vertex on path
  21470. dx = points[ j + 1 ].x - points[ j ].x;
  21471. dy = points[ j + 1 ].y - points[ j ].y;
  21472. normal.x = dy * 1.0;
  21473. normal.y = - dx;
  21474. normal.z = dy * 0.0;
  21475. prevNormal.copy( normal );
  21476. normal.normalize();
  21477. initNormals.push( normal.x, normal.y, normal.z );
  21478. break;
  21479. case ( points.length - 1 ): // special handling for last Vertex on path
  21480. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  21481. break;
  21482. default: // default handling for all vertices in between
  21483. dx = points[ j + 1 ].x - points[ j ].x;
  21484. dy = points[ j + 1 ].y - points[ j ].y;
  21485. normal.x = dy * 1.0;
  21486. normal.y = - dx;
  21487. normal.z = dy * 0.0;
  21488. curNormal.copy( normal );
  21489. normal.x += prevNormal.x;
  21490. normal.y += prevNormal.y;
  21491. normal.z += prevNormal.z;
  21492. normal.normalize();
  21493. initNormals.push( normal.x, normal.y, normal.z );
  21494. prevNormal.copy( curNormal );
  21495. }
  21496. }
  21497. // generate vertices, uvs and normals
  21498. for ( let i = 0; i <= segments; i ++ ) {
  21499. const phi = phiStart + i * inverseSegments * phiLength;
  21500. const sin = Math.sin( phi );
  21501. const cos = Math.cos( phi );
  21502. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21503. // vertex
  21504. vertex.x = points[ j ].x * sin;
  21505. vertex.y = points[ j ].y;
  21506. vertex.z = points[ j ].x * cos;
  21507. vertices.push( vertex.x, vertex.y, vertex.z );
  21508. // uv
  21509. uv.x = i / segments;
  21510. uv.y = j / ( points.length - 1 );
  21511. uvs.push( uv.x, uv.y );
  21512. // normal
  21513. const x = initNormals[ 3 * j + 0 ] * sin;
  21514. const y = initNormals[ 3 * j + 1 ];
  21515. const z = initNormals[ 3 * j + 0 ] * cos;
  21516. normals.push( x, y, z );
  21517. }
  21518. }
  21519. // indices
  21520. for ( let i = 0; i < segments; i ++ ) {
  21521. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  21522. const base = j + i * points.length;
  21523. const a = base;
  21524. const b = base + points.length;
  21525. const c = base + points.length + 1;
  21526. const d = base + 1;
  21527. // faces
  21528. indices.push( a, b, d );
  21529. indices.push( c, d, b );
  21530. }
  21531. }
  21532. // build geometry
  21533. this.setIndex( indices );
  21534. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21535. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21536. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21537. }
  21538. copy( source ) {
  21539. super.copy( source );
  21540. this.parameters = Object.assign( {}, source.parameters );
  21541. return this;
  21542. }
  21543. static fromJSON( data ) {
  21544. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  21545. }
  21546. }
  21547. class CapsuleGeometry extends LatheGeometry {
  21548. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  21549. const path = new Path();
  21550. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  21551. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  21552. super( path.getPoints( capSegments ), radialSegments );
  21553. this.type = 'CapsuleGeometry';
  21554. this.parameters = {
  21555. radius: radius,
  21556. length: length,
  21557. capSegments: capSegments,
  21558. radialSegments: radialSegments,
  21559. };
  21560. }
  21561. static fromJSON( data ) {
  21562. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  21563. }
  21564. }
  21565. class CircleGeometry extends BufferGeometry {
  21566. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21567. super();
  21568. this.type = 'CircleGeometry';
  21569. this.parameters = {
  21570. radius: radius,
  21571. segments: segments,
  21572. thetaStart: thetaStart,
  21573. thetaLength: thetaLength
  21574. };
  21575. segments = Math.max( 3, segments );
  21576. // buffers
  21577. const indices = [];
  21578. const vertices = [];
  21579. const normals = [];
  21580. const uvs = [];
  21581. // helper variables
  21582. const vertex = new Vector3();
  21583. const uv = new Vector2();
  21584. // center point
  21585. vertices.push( 0, 0, 0 );
  21586. normals.push( 0, 0, 1 );
  21587. uvs.push( 0.5, 0.5 );
  21588. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21589. const segment = thetaStart + s / segments * thetaLength;
  21590. // vertex
  21591. vertex.x = radius * Math.cos( segment );
  21592. vertex.y = radius * Math.sin( segment );
  21593. vertices.push( vertex.x, vertex.y, vertex.z );
  21594. // normal
  21595. normals.push( 0, 0, 1 );
  21596. // uvs
  21597. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21598. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21599. uvs.push( uv.x, uv.y );
  21600. }
  21601. // indices
  21602. for ( let i = 1; i <= segments; i ++ ) {
  21603. indices.push( i, i + 1, 0 );
  21604. }
  21605. // build geometry
  21606. this.setIndex( indices );
  21607. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21608. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21609. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21610. }
  21611. copy( source ) {
  21612. super.copy( source );
  21613. this.parameters = Object.assign( {}, source.parameters );
  21614. return this;
  21615. }
  21616. static fromJSON( data ) {
  21617. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  21618. }
  21619. }
  21620. class CylinderGeometry extends BufferGeometry {
  21621. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21622. super();
  21623. this.type = 'CylinderGeometry';
  21624. this.parameters = {
  21625. radiusTop: radiusTop,
  21626. radiusBottom: radiusBottom,
  21627. height: height,
  21628. radialSegments: radialSegments,
  21629. heightSegments: heightSegments,
  21630. openEnded: openEnded,
  21631. thetaStart: thetaStart,
  21632. thetaLength: thetaLength
  21633. };
  21634. const scope = this;
  21635. radialSegments = Math.floor( radialSegments );
  21636. heightSegments = Math.floor( heightSegments );
  21637. // buffers
  21638. const indices = [];
  21639. const vertices = [];
  21640. const normals = [];
  21641. const uvs = [];
  21642. // helper variables
  21643. let index = 0;
  21644. const indexArray = [];
  21645. const halfHeight = height / 2;
  21646. let groupStart = 0;
  21647. // generate geometry
  21648. generateTorso();
  21649. if ( openEnded === false ) {
  21650. if ( radiusTop > 0 ) generateCap( true );
  21651. if ( radiusBottom > 0 ) generateCap( false );
  21652. }
  21653. // build geometry
  21654. this.setIndex( indices );
  21655. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21656. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21657. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21658. function generateTorso() {
  21659. const normal = new Vector3();
  21660. const vertex = new Vector3();
  21661. let groupCount = 0;
  21662. // this will be used to calculate the normal
  21663. const slope = ( radiusBottom - radiusTop ) / height;
  21664. // generate vertices, normals and uvs
  21665. for ( let y = 0; y <= heightSegments; y ++ ) {
  21666. const indexRow = [];
  21667. const v = y / heightSegments;
  21668. // calculate the radius of the current row
  21669. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21670. for ( let x = 0; x <= radialSegments; x ++ ) {
  21671. const u = x / radialSegments;
  21672. const theta = u * thetaLength + thetaStart;
  21673. const sinTheta = Math.sin( theta );
  21674. const cosTheta = Math.cos( theta );
  21675. // vertex
  21676. vertex.x = radius * sinTheta;
  21677. vertex.y = - v * height + halfHeight;
  21678. vertex.z = radius * cosTheta;
  21679. vertices.push( vertex.x, vertex.y, vertex.z );
  21680. // normal
  21681. normal.set( sinTheta, slope, cosTheta ).normalize();
  21682. normals.push( normal.x, normal.y, normal.z );
  21683. // uv
  21684. uvs.push( u, 1 - v );
  21685. // save index of vertex in respective row
  21686. indexRow.push( index ++ );
  21687. }
  21688. // now save vertices of the row in our index array
  21689. indexArray.push( indexRow );
  21690. }
  21691. // generate indices
  21692. for ( let x = 0; x < radialSegments; x ++ ) {
  21693. for ( let y = 0; y < heightSegments; y ++ ) {
  21694. // we use the index array to access the correct indices
  21695. const a = indexArray[ y ][ x ];
  21696. const b = indexArray[ y + 1 ][ x ];
  21697. const c = indexArray[ y + 1 ][ x + 1 ];
  21698. const d = indexArray[ y ][ x + 1 ];
  21699. // faces
  21700. indices.push( a, b, d );
  21701. indices.push( b, c, d );
  21702. // update group counter
  21703. groupCount += 6;
  21704. }
  21705. }
  21706. // add a group to the geometry. this will ensure multi material support
  21707. scope.addGroup( groupStart, groupCount, 0 );
  21708. // calculate new start value for groups
  21709. groupStart += groupCount;
  21710. }
  21711. function generateCap( top ) {
  21712. // save the index of the first center vertex
  21713. const centerIndexStart = index;
  21714. const uv = new Vector2();
  21715. const vertex = new Vector3();
  21716. let groupCount = 0;
  21717. const radius = ( top === true ) ? radiusTop : radiusBottom;
  21718. const sign = ( top === true ) ? 1 : - 1;
  21719. // first we generate the center vertex data of the cap.
  21720. // because the geometry needs one set of uvs per face,
  21721. // we must generate a center vertex per face/segment
  21722. for ( let x = 1; x <= radialSegments; x ++ ) {
  21723. // vertex
  21724. vertices.push( 0, halfHeight * sign, 0 );
  21725. // normal
  21726. normals.push( 0, sign, 0 );
  21727. // uv
  21728. uvs.push( 0.5, 0.5 );
  21729. // increase index
  21730. index ++;
  21731. }
  21732. // save the index of the last center vertex
  21733. const centerIndexEnd = index;
  21734. // now we generate the surrounding vertices, normals and uvs
  21735. for ( let x = 0; x <= radialSegments; x ++ ) {
  21736. const u = x / radialSegments;
  21737. const theta = u * thetaLength + thetaStart;
  21738. const cosTheta = Math.cos( theta );
  21739. const sinTheta = Math.sin( theta );
  21740. // vertex
  21741. vertex.x = radius * sinTheta;
  21742. vertex.y = halfHeight * sign;
  21743. vertex.z = radius * cosTheta;
  21744. vertices.push( vertex.x, vertex.y, vertex.z );
  21745. // normal
  21746. normals.push( 0, sign, 0 );
  21747. // uv
  21748. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21749. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21750. uvs.push( uv.x, uv.y );
  21751. // increase index
  21752. index ++;
  21753. }
  21754. // generate indices
  21755. for ( let x = 0; x < radialSegments; x ++ ) {
  21756. const c = centerIndexStart + x;
  21757. const i = centerIndexEnd + x;
  21758. if ( top === true ) {
  21759. // face top
  21760. indices.push( i, i + 1, c );
  21761. } else {
  21762. // face bottom
  21763. indices.push( i + 1, i, c );
  21764. }
  21765. groupCount += 3;
  21766. }
  21767. // add a group to the geometry. this will ensure multi material support
  21768. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  21769. // calculate new start value for groups
  21770. groupStart += groupCount;
  21771. }
  21772. }
  21773. copy( source ) {
  21774. super.copy( source );
  21775. this.parameters = Object.assign( {}, source.parameters );
  21776. return this;
  21777. }
  21778. static fromJSON( data ) {
  21779. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  21780. }
  21781. }
  21782. class ConeGeometry extends CylinderGeometry {
  21783. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21784. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21785. this.type = 'ConeGeometry';
  21786. this.parameters = {
  21787. radius: radius,
  21788. height: height,
  21789. radialSegments: radialSegments,
  21790. heightSegments: heightSegments,
  21791. openEnded: openEnded,
  21792. thetaStart: thetaStart,
  21793. thetaLength: thetaLength
  21794. };
  21795. }
  21796. static fromJSON( data ) {
  21797. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  21798. }
  21799. }
  21800. class PolyhedronGeometry extends BufferGeometry {
  21801. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  21802. super();
  21803. this.type = 'PolyhedronGeometry';
  21804. this.parameters = {
  21805. vertices: vertices,
  21806. indices: indices,
  21807. radius: radius,
  21808. detail: detail
  21809. };
  21810. // default buffer data
  21811. const vertexBuffer = [];
  21812. const uvBuffer = [];
  21813. // the subdivision creates the vertex buffer data
  21814. subdivide( detail );
  21815. // all vertices should lie on a conceptual sphere with a given radius
  21816. applyRadius( radius );
  21817. // finally, create the uv data
  21818. generateUVs();
  21819. // build non-indexed geometry
  21820. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  21821. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  21822. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  21823. if ( detail === 0 ) {
  21824. this.computeVertexNormals(); // flat normals
  21825. } else {
  21826. this.normalizeNormals(); // smooth normals
  21827. }
  21828. // helper functions
  21829. function subdivide( detail ) {
  21830. const a = new Vector3();
  21831. const b = new Vector3();
  21832. const c = new Vector3();
  21833. // iterate over all faces and apply a subdivision with the given detail value
  21834. for ( let i = 0; i < indices.length; i += 3 ) {
  21835. // get the vertices of the face
  21836. getVertexByIndex( indices[ i + 0 ], a );
  21837. getVertexByIndex( indices[ i + 1 ], b );
  21838. getVertexByIndex( indices[ i + 2 ], c );
  21839. // perform subdivision
  21840. subdivideFace( a, b, c, detail );
  21841. }
  21842. }
  21843. function subdivideFace( a, b, c, detail ) {
  21844. const cols = detail + 1;
  21845. // we use this multidimensional array as a data structure for creating the subdivision
  21846. const v = [];
  21847. // construct all of the vertices for this subdivision
  21848. for ( let i = 0; i <= cols; i ++ ) {
  21849. v[ i ] = [];
  21850. const aj = a.clone().lerp( c, i / cols );
  21851. const bj = b.clone().lerp( c, i / cols );
  21852. const rows = cols - i;
  21853. for ( let j = 0; j <= rows; j ++ ) {
  21854. if ( j === 0 && i === cols ) {
  21855. v[ i ][ j ] = aj;
  21856. } else {
  21857. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  21858. }
  21859. }
  21860. }
  21861. // construct all of the faces
  21862. for ( let i = 0; i < cols; i ++ ) {
  21863. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  21864. const k = Math.floor( j / 2 );
  21865. if ( j % 2 === 0 ) {
  21866. pushVertex( v[ i ][ k + 1 ] );
  21867. pushVertex( v[ i + 1 ][ k ] );
  21868. pushVertex( v[ i ][ k ] );
  21869. } else {
  21870. pushVertex( v[ i ][ k + 1 ] );
  21871. pushVertex( v[ i + 1 ][ k + 1 ] );
  21872. pushVertex( v[ i + 1 ][ k ] );
  21873. }
  21874. }
  21875. }
  21876. }
  21877. function applyRadius( radius ) {
  21878. const vertex = new Vector3();
  21879. // iterate over the entire buffer and apply the radius to each vertex
  21880. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  21881. vertex.x = vertexBuffer[ i + 0 ];
  21882. vertex.y = vertexBuffer[ i + 1 ];
  21883. vertex.z = vertexBuffer[ i + 2 ];
  21884. vertex.normalize().multiplyScalar( radius );
  21885. vertexBuffer[ i + 0 ] = vertex.x;
  21886. vertexBuffer[ i + 1 ] = vertex.y;
  21887. vertexBuffer[ i + 2 ] = vertex.z;
  21888. }
  21889. }
  21890. function generateUVs() {
  21891. const vertex = new Vector3();
  21892. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  21893. vertex.x = vertexBuffer[ i + 0 ];
  21894. vertex.y = vertexBuffer[ i + 1 ];
  21895. vertex.z = vertexBuffer[ i + 2 ];
  21896. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  21897. const v = inclination( vertex ) / Math.PI + 0.5;
  21898. uvBuffer.push( u, 1 - v );
  21899. }
  21900. correctUVs();
  21901. correctSeam();
  21902. }
  21903. function correctSeam() {
  21904. // handle case when face straddles the seam, see #3269
  21905. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  21906. // uv data of a single face
  21907. const x0 = uvBuffer[ i + 0 ];
  21908. const x1 = uvBuffer[ i + 2 ];
  21909. const x2 = uvBuffer[ i + 4 ];
  21910. const max = Math.max( x0, x1, x2 );
  21911. const min = Math.min( x0, x1, x2 );
  21912. // 0.9 is somewhat arbitrary
  21913. if ( max > 0.9 && min < 0.1 ) {
  21914. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  21915. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  21916. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  21917. }
  21918. }
  21919. }
  21920. function pushVertex( vertex ) {
  21921. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  21922. }
  21923. function getVertexByIndex( index, vertex ) {
  21924. const stride = index * 3;
  21925. vertex.x = vertices[ stride + 0 ];
  21926. vertex.y = vertices[ stride + 1 ];
  21927. vertex.z = vertices[ stride + 2 ];
  21928. }
  21929. function correctUVs() {
  21930. const a = new Vector3();
  21931. const b = new Vector3();
  21932. const c = new Vector3();
  21933. const centroid = new Vector3();
  21934. const uvA = new Vector2();
  21935. const uvB = new Vector2();
  21936. const uvC = new Vector2();
  21937. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  21938. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  21939. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  21940. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  21941. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  21942. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  21943. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  21944. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  21945. const azi = azimuth( centroid );
  21946. correctUV( uvA, j + 0, a, azi );
  21947. correctUV( uvB, j + 2, b, azi );
  21948. correctUV( uvC, j + 4, c, azi );
  21949. }
  21950. }
  21951. function correctUV( uv, stride, vector, azimuth ) {
  21952. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  21953. uvBuffer[ stride ] = uv.x - 1;
  21954. }
  21955. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  21956. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  21957. }
  21958. }
  21959. // Angle around the Y axis, counter-clockwise when looking from above.
  21960. function azimuth( vector ) {
  21961. return Math.atan2( vector.z, - vector.x );
  21962. }
  21963. // Angle above the XZ plane.
  21964. function inclination( vector ) {
  21965. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21966. }
  21967. }
  21968. copy( source ) {
  21969. super.copy( source );
  21970. this.parameters = Object.assign( {}, source.parameters );
  21971. return this;
  21972. }
  21973. static fromJSON( data ) {
  21974. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  21975. }
  21976. }
  21977. class DodecahedronGeometry extends PolyhedronGeometry {
  21978. constructor( radius = 1, detail = 0 ) {
  21979. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21980. const r = 1 / t;
  21981. const vertices = [
  21982. // (±1, ±1, ±1)
  21983. - 1, - 1, - 1, - 1, - 1, 1,
  21984. - 1, 1, - 1, - 1, 1, 1,
  21985. 1, - 1, - 1, 1, - 1, 1,
  21986. 1, 1, - 1, 1, 1, 1,
  21987. // (0, ±1/φ, ±φ)
  21988. 0, - r, - t, 0, - r, t,
  21989. 0, r, - t, 0, r, t,
  21990. // (±1/φ, ±φ, 0)
  21991. - r, - t, 0, - r, t, 0,
  21992. r, - t, 0, r, t, 0,
  21993. // (±φ, 0, ±1/φ)
  21994. - t, 0, - r, t, 0, - r,
  21995. - t, 0, r, t, 0, r
  21996. ];
  21997. const indices = [
  21998. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  21999. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22000. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22001. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22002. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22003. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22004. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22005. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22006. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22007. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22008. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22009. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22010. ];
  22011. super( vertices, indices, radius, detail );
  22012. this.type = 'DodecahedronGeometry';
  22013. this.parameters = {
  22014. radius: radius,
  22015. detail: detail
  22016. };
  22017. }
  22018. static fromJSON( data ) {
  22019. return new DodecahedronGeometry( data.radius, data.detail );
  22020. }
  22021. }
  22022. const _v0 = /*@__PURE__*/ new Vector3();
  22023. const _v1$1 = /*@__PURE__*/ new Vector3();
  22024. const _normal = /*@__PURE__*/ new Vector3();
  22025. const _triangle = /*@__PURE__*/ new Triangle();
  22026. class EdgesGeometry extends BufferGeometry {
  22027. constructor( geometry = null, thresholdAngle = 1 ) {
  22028. super();
  22029. this.type = 'EdgesGeometry';
  22030. this.parameters = {
  22031. geometry: geometry,
  22032. thresholdAngle: thresholdAngle
  22033. };
  22034. if ( geometry !== null ) {
  22035. const precisionPoints = 4;
  22036. const precision = Math.pow( 10, precisionPoints );
  22037. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22038. const indexAttr = geometry.getIndex();
  22039. const positionAttr = geometry.getAttribute( 'position' );
  22040. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22041. const indexArr = [ 0, 0, 0 ];
  22042. const vertKeys = [ 'a', 'b', 'c' ];
  22043. const hashes = new Array( 3 );
  22044. const edgeData = {};
  22045. const vertices = [];
  22046. for ( let i = 0; i < indexCount; i += 3 ) {
  22047. if ( indexAttr ) {
  22048. indexArr[ 0 ] = indexAttr.getX( i );
  22049. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22050. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22051. } else {
  22052. indexArr[ 0 ] = i;
  22053. indexArr[ 1 ] = i + 1;
  22054. indexArr[ 2 ] = i + 2;
  22055. }
  22056. const { a, b, c } = _triangle;
  22057. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22058. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22059. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22060. _triangle.getNormal( _normal );
  22061. // create hashes for the edge from the vertices
  22062. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22063. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22064. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22065. // skip degenerate triangles
  22066. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22067. continue;
  22068. }
  22069. // iterate over every edge
  22070. for ( let j = 0; j < 3; j ++ ) {
  22071. // get the first and next vertex making up the edge
  22072. const jNext = ( j + 1 ) % 3;
  22073. const vecHash0 = hashes[ j ];
  22074. const vecHash1 = hashes[ jNext ];
  22075. const v0 = _triangle[ vertKeys[ j ] ];
  22076. const v1 = _triangle[ vertKeys[ jNext ] ];
  22077. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22078. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22079. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22080. // if we found a sibling edge add it into the vertex array if
  22081. // it meets the angle threshold and delete the edge from the map.
  22082. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22083. vertices.push( v0.x, v0.y, v0.z );
  22084. vertices.push( v1.x, v1.y, v1.z );
  22085. }
  22086. edgeData[ reverseHash ] = null;
  22087. } else if ( ! ( hash in edgeData ) ) {
  22088. // if we've already got an edge here then skip adding a new one
  22089. edgeData[ hash ] = {
  22090. index0: indexArr[ j ],
  22091. index1: indexArr[ jNext ],
  22092. normal: _normal.clone(),
  22093. };
  22094. }
  22095. }
  22096. }
  22097. // iterate over all remaining, unmatched edges and add them to the vertex array
  22098. for ( const key in edgeData ) {
  22099. if ( edgeData[ key ] ) {
  22100. const { index0, index1 } = edgeData[ key ];
  22101. _v0.fromBufferAttribute( positionAttr, index0 );
  22102. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22103. vertices.push( _v0.x, _v0.y, _v0.z );
  22104. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22105. }
  22106. }
  22107. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22108. }
  22109. }
  22110. copy( source ) {
  22111. super.copy( source );
  22112. this.parameters = Object.assign( {}, source.parameters );
  22113. return this;
  22114. }
  22115. }
  22116. class Shape extends Path {
  22117. constructor( points ) {
  22118. super( points );
  22119. this.uuid = generateUUID();
  22120. this.type = 'Shape';
  22121. this.holes = [];
  22122. }
  22123. getPointsHoles( divisions ) {
  22124. const holesPts = [];
  22125. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22126. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  22127. }
  22128. return holesPts;
  22129. }
  22130. // get points of shape and holes (keypoints based on segments parameter)
  22131. extractPoints( divisions ) {
  22132. return {
  22133. shape: this.getPoints( divisions ),
  22134. holes: this.getPointsHoles( divisions )
  22135. };
  22136. }
  22137. copy( source ) {
  22138. super.copy( source );
  22139. this.holes = [];
  22140. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  22141. const hole = source.holes[ i ];
  22142. this.holes.push( hole.clone() );
  22143. }
  22144. return this;
  22145. }
  22146. toJSON() {
  22147. const data = super.toJSON();
  22148. data.uuid = this.uuid;
  22149. data.holes = [];
  22150. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22151. const hole = this.holes[ i ];
  22152. data.holes.push( hole.toJSON() );
  22153. }
  22154. return data;
  22155. }
  22156. fromJSON( json ) {
  22157. super.fromJSON( json );
  22158. this.uuid = json.uuid;
  22159. this.holes = [];
  22160. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  22161. const hole = json.holes[ i ];
  22162. this.holes.push( new Path().fromJSON( hole ) );
  22163. }
  22164. return this;
  22165. }
  22166. }
  22167. /**
  22168. * Port from https://github.com/mapbox/earcut (v2.2.4)
  22169. */
  22170. const Earcut = {
  22171. triangulate: function ( data, holeIndices, dim = 2 ) {
  22172. const hasHoles = holeIndices && holeIndices.length;
  22173. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  22174. let outerNode = linkedList( data, 0, outerLen, dim, true );
  22175. const triangles = [];
  22176. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  22177. let minX, minY, maxX, maxY, x, y, invSize;
  22178. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  22179. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  22180. if ( data.length > 80 * dim ) {
  22181. minX = maxX = data[ 0 ];
  22182. minY = maxY = data[ 1 ];
  22183. for ( let i = dim; i < outerLen; i += dim ) {
  22184. x = data[ i ];
  22185. y = data[ i + 1 ];
  22186. if ( x < minX ) minX = x;
  22187. if ( y < minY ) minY = y;
  22188. if ( x > maxX ) maxX = x;
  22189. if ( y > maxY ) maxY = y;
  22190. }
  22191. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  22192. invSize = Math.max( maxX - minX, maxY - minY );
  22193. invSize = invSize !== 0 ? 32767 / invSize : 0;
  22194. }
  22195. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  22196. return triangles;
  22197. }
  22198. };
  22199. // create a circular doubly linked list from polygon points in the specified winding order
  22200. function linkedList( data, start, end, dim, clockwise ) {
  22201. let i, last;
  22202. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  22203. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22204. } else {
  22205. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22206. }
  22207. if ( last && equals( last, last.next ) ) {
  22208. removeNode( last );
  22209. last = last.next;
  22210. }
  22211. return last;
  22212. }
  22213. // eliminate colinear or duplicate points
  22214. function filterPoints( start, end ) {
  22215. if ( ! start ) return start;
  22216. if ( ! end ) end = start;
  22217. let p = start,
  22218. again;
  22219. do {
  22220. again = false;
  22221. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  22222. removeNode( p );
  22223. p = end = p.prev;
  22224. if ( p === p.next ) break;
  22225. again = true;
  22226. } else {
  22227. p = p.next;
  22228. }
  22229. } while ( again || p !== end );
  22230. return end;
  22231. }
  22232. // main ear slicing loop which triangulates a polygon (given as a linked list)
  22233. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  22234. if ( ! ear ) return;
  22235. // interlink polygon nodes in z-order
  22236. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  22237. let stop = ear,
  22238. prev, next;
  22239. // iterate through ears, slicing them one by one
  22240. while ( ear.prev !== ear.next ) {
  22241. prev = ear.prev;
  22242. next = ear.next;
  22243. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  22244. // cut off the triangle
  22245. triangles.push( prev.i / dim | 0 );
  22246. triangles.push( ear.i / dim | 0 );
  22247. triangles.push( next.i / dim | 0 );
  22248. removeNode( ear );
  22249. // skipping the next vertex leads to less sliver triangles
  22250. ear = next.next;
  22251. stop = next.next;
  22252. continue;
  22253. }
  22254. ear = next;
  22255. // if we looped through the whole remaining polygon and can't find any more ears
  22256. if ( ear === stop ) {
  22257. // try filtering points and slicing again
  22258. if ( ! pass ) {
  22259. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  22260. // if this didn't work, try curing all small self-intersections locally
  22261. } else if ( pass === 1 ) {
  22262. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  22263. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  22264. // as a last resort, try splitting the remaining polygon into two
  22265. } else if ( pass === 2 ) {
  22266. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  22267. }
  22268. break;
  22269. }
  22270. }
  22271. }
  22272. // check whether a polygon node forms a valid ear with adjacent nodes
  22273. function isEar( ear ) {
  22274. const a = ear.prev,
  22275. b = ear,
  22276. c = ear.next;
  22277. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22278. // now make sure we don't have other points inside the potential ear
  22279. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22280. // triangle bbox; min & max are calculated like this for speed
  22281. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22282. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22283. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22284. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22285. let p = c.next;
  22286. while ( p !== a ) {
  22287. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  22288. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  22289. area( p.prev, p, p.next ) >= 0 ) return false;
  22290. p = p.next;
  22291. }
  22292. return true;
  22293. }
  22294. function isEarHashed( ear, minX, minY, invSize ) {
  22295. const a = ear.prev,
  22296. b = ear,
  22297. c = ear.next;
  22298. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22299. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22300. // triangle bbox; min & max are calculated like this for speed
  22301. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22302. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22303. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22304. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22305. // z-order range for the current triangle bbox;
  22306. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  22307. maxZ = zOrder( x1, y1, minX, minY, invSize );
  22308. let p = ear.prevZ,
  22309. n = ear.nextZ;
  22310. // look for points inside the triangle in both directions
  22311. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  22312. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22313. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22314. p = p.prevZ;
  22315. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22316. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22317. n = n.nextZ;
  22318. }
  22319. // look for remaining points in decreasing z-order
  22320. while ( p && p.z >= minZ ) {
  22321. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22322. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22323. p = p.prevZ;
  22324. }
  22325. // look for remaining points in increasing z-order
  22326. while ( n && n.z <= maxZ ) {
  22327. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22328. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22329. n = n.nextZ;
  22330. }
  22331. return true;
  22332. }
  22333. // go through all polygon nodes and cure small local self-intersections
  22334. function cureLocalIntersections( start, triangles, dim ) {
  22335. let p = start;
  22336. do {
  22337. const a = p.prev,
  22338. b = p.next.next;
  22339. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  22340. triangles.push( a.i / dim | 0 );
  22341. triangles.push( p.i / dim | 0 );
  22342. triangles.push( b.i / dim | 0 );
  22343. // remove two nodes involved
  22344. removeNode( p );
  22345. removeNode( p.next );
  22346. p = start = b;
  22347. }
  22348. p = p.next;
  22349. } while ( p !== start );
  22350. return filterPoints( p );
  22351. }
  22352. // try splitting polygon into two and triangulate them independently
  22353. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  22354. // look for a valid diagonal that divides the polygon into two
  22355. let a = start;
  22356. do {
  22357. let b = a.next.next;
  22358. while ( b !== a.prev ) {
  22359. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  22360. // split the polygon in two by the diagonal
  22361. let c = splitPolygon( a, b );
  22362. // filter colinear points around the cuts
  22363. a = filterPoints( a, a.next );
  22364. c = filterPoints( c, c.next );
  22365. // run earcut on each half
  22366. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  22367. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  22368. return;
  22369. }
  22370. b = b.next;
  22371. }
  22372. a = a.next;
  22373. } while ( a !== start );
  22374. }
  22375. // link every hole into the outer loop, producing a single-ring polygon without holes
  22376. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  22377. const queue = [];
  22378. let i, len, start, end, list;
  22379. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  22380. start = holeIndices[ i ] * dim;
  22381. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  22382. list = linkedList( data, start, end, dim, false );
  22383. if ( list === list.next ) list.steiner = true;
  22384. queue.push( getLeftmost( list ) );
  22385. }
  22386. queue.sort( compareX );
  22387. // process holes from left to right
  22388. for ( i = 0; i < queue.length; i ++ ) {
  22389. outerNode = eliminateHole( queue[ i ], outerNode );
  22390. }
  22391. return outerNode;
  22392. }
  22393. function compareX( a, b ) {
  22394. return a.x - b.x;
  22395. }
  22396. // find a bridge between vertices that connects hole with an outer ring and link it
  22397. function eliminateHole( hole, outerNode ) {
  22398. const bridge = findHoleBridge( hole, outerNode );
  22399. if ( ! bridge ) {
  22400. return outerNode;
  22401. }
  22402. const bridgeReverse = splitPolygon( bridge, hole );
  22403. // filter collinear points around the cuts
  22404. filterPoints( bridgeReverse, bridgeReverse.next );
  22405. return filterPoints( bridge, bridge.next );
  22406. }
  22407. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  22408. function findHoleBridge( hole, outerNode ) {
  22409. let p = outerNode,
  22410. qx = - Infinity,
  22411. m;
  22412. const hx = hole.x, hy = hole.y;
  22413. // find a segment intersected by a ray from the hole's leftmost point to the left;
  22414. // segment's endpoint with lesser x will be potential connection point
  22415. do {
  22416. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  22417. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  22418. if ( x <= hx && x > qx ) {
  22419. qx = x;
  22420. m = p.x < p.next.x ? p : p.next;
  22421. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  22422. }
  22423. }
  22424. p = p.next;
  22425. } while ( p !== outerNode );
  22426. if ( ! m ) return null;
  22427. // look for points inside the triangle of hole point, segment intersection and endpoint;
  22428. // if there are no points found, we have a valid connection;
  22429. // otherwise choose the point of the minimum angle with the ray as connection point
  22430. const stop = m,
  22431. mx = m.x,
  22432. my = m.y;
  22433. let tanMin = Infinity, tan;
  22434. p = m;
  22435. do {
  22436. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  22437. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  22438. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  22439. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  22440. m = p;
  22441. tanMin = tan;
  22442. }
  22443. }
  22444. p = p.next;
  22445. } while ( p !== stop );
  22446. return m;
  22447. }
  22448. // whether sector in vertex m contains sector in vertex p in the same coordinates
  22449. function sectorContainsSector( m, p ) {
  22450. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  22451. }
  22452. // interlink polygon nodes in z-order
  22453. function indexCurve( start, minX, minY, invSize ) {
  22454. let p = start;
  22455. do {
  22456. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  22457. p.prevZ = p.prev;
  22458. p.nextZ = p.next;
  22459. p = p.next;
  22460. } while ( p !== start );
  22461. p.prevZ.nextZ = null;
  22462. p.prevZ = null;
  22463. sortLinked( p );
  22464. }
  22465. // Simon Tatham's linked list merge sort algorithm
  22466. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  22467. function sortLinked( list ) {
  22468. let i, p, q, e, tail, numMerges, pSize, qSize,
  22469. inSize = 1;
  22470. do {
  22471. p = list;
  22472. list = null;
  22473. tail = null;
  22474. numMerges = 0;
  22475. while ( p ) {
  22476. numMerges ++;
  22477. q = p;
  22478. pSize = 0;
  22479. for ( i = 0; i < inSize; i ++ ) {
  22480. pSize ++;
  22481. q = q.nextZ;
  22482. if ( ! q ) break;
  22483. }
  22484. qSize = inSize;
  22485. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  22486. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  22487. e = p;
  22488. p = p.nextZ;
  22489. pSize --;
  22490. } else {
  22491. e = q;
  22492. q = q.nextZ;
  22493. qSize --;
  22494. }
  22495. if ( tail ) tail.nextZ = e;
  22496. else list = e;
  22497. e.prevZ = tail;
  22498. tail = e;
  22499. }
  22500. p = q;
  22501. }
  22502. tail.nextZ = null;
  22503. inSize *= 2;
  22504. } while ( numMerges > 1 );
  22505. return list;
  22506. }
  22507. // z-order of a point given coords and inverse of the longer side of data bbox
  22508. function zOrder( x, y, minX, minY, invSize ) {
  22509. // coords are transformed into non-negative 15-bit integer range
  22510. x = ( x - minX ) * invSize | 0;
  22511. y = ( y - minY ) * invSize | 0;
  22512. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  22513. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  22514. x = ( x | ( x << 2 ) ) & 0x33333333;
  22515. x = ( x | ( x << 1 ) ) & 0x55555555;
  22516. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  22517. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  22518. y = ( y | ( y << 2 ) ) & 0x33333333;
  22519. y = ( y | ( y << 1 ) ) & 0x55555555;
  22520. return x | ( y << 1 );
  22521. }
  22522. // find the leftmost node of a polygon ring
  22523. function getLeftmost( start ) {
  22524. let p = start,
  22525. leftmost = start;
  22526. do {
  22527. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  22528. p = p.next;
  22529. } while ( p !== start );
  22530. return leftmost;
  22531. }
  22532. // check if a point lies within a convex triangle
  22533. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  22534. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  22535. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  22536. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  22537. }
  22538. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  22539. function isValidDiagonal( a, b ) {
  22540. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  22541. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  22542. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  22543. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  22544. }
  22545. // signed area of a triangle
  22546. function area( p, q, r ) {
  22547. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  22548. }
  22549. // check if two points are equal
  22550. function equals( p1, p2 ) {
  22551. return p1.x === p2.x && p1.y === p2.y;
  22552. }
  22553. // check if two segments intersect
  22554. function intersects( p1, q1, p2, q2 ) {
  22555. const o1 = sign( area( p1, q1, p2 ) );
  22556. const o2 = sign( area( p1, q1, q2 ) );
  22557. const o3 = sign( area( p2, q2, p1 ) );
  22558. const o4 = sign( area( p2, q2, q1 ) );
  22559. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  22560. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  22561. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  22562. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  22563. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  22564. return false;
  22565. }
  22566. // for collinear points p, q, r, check if point q lies on segment pr
  22567. function onSegment( p, q, r ) {
  22568. 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 );
  22569. }
  22570. function sign( num ) {
  22571. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  22572. }
  22573. // check if a polygon diagonal intersects any polygon segments
  22574. function intersectsPolygon( a, b ) {
  22575. let p = a;
  22576. do {
  22577. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  22578. intersects( p, p.next, a, b ) ) return true;
  22579. p = p.next;
  22580. } while ( p !== a );
  22581. return false;
  22582. }
  22583. // check if a polygon diagonal is locally inside the polygon
  22584. function locallyInside( a, b ) {
  22585. return area( a.prev, a, a.next ) < 0 ?
  22586. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  22587. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  22588. }
  22589. // check if the middle point of a polygon diagonal is inside the polygon
  22590. function middleInside( a, b ) {
  22591. let p = a,
  22592. inside = false;
  22593. const px = ( a.x + b.x ) / 2,
  22594. py = ( a.y + b.y ) / 2;
  22595. do {
  22596. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  22597. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  22598. inside = ! inside;
  22599. p = p.next;
  22600. } while ( p !== a );
  22601. return inside;
  22602. }
  22603. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  22604. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  22605. function splitPolygon( a, b ) {
  22606. const a2 = new Node( a.i, a.x, a.y ),
  22607. b2 = new Node( b.i, b.x, b.y ),
  22608. an = a.next,
  22609. bp = b.prev;
  22610. a.next = b;
  22611. b.prev = a;
  22612. a2.next = an;
  22613. an.prev = a2;
  22614. b2.next = a2;
  22615. a2.prev = b2;
  22616. bp.next = b2;
  22617. b2.prev = bp;
  22618. return b2;
  22619. }
  22620. // create a node and optionally link it with previous one (in a circular doubly linked list)
  22621. function insertNode( i, x, y, last ) {
  22622. const p = new Node( i, x, y );
  22623. if ( ! last ) {
  22624. p.prev = p;
  22625. p.next = p;
  22626. } else {
  22627. p.next = last.next;
  22628. p.prev = last;
  22629. last.next.prev = p;
  22630. last.next = p;
  22631. }
  22632. return p;
  22633. }
  22634. function removeNode( p ) {
  22635. p.next.prev = p.prev;
  22636. p.prev.next = p.next;
  22637. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  22638. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  22639. }
  22640. function Node( i, x, y ) {
  22641. // vertex index in coordinates array
  22642. this.i = i;
  22643. // vertex coordinates
  22644. this.x = x;
  22645. this.y = y;
  22646. // previous and next vertex nodes in a polygon ring
  22647. this.prev = null;
  22648. this.next = null;
  22649. // z-order curve value
  22650. this.z = 0;
  22651. // previous and next nodes in z-order
  22652. this.prevZ = null;
  22653. this.nextZ = null;
  22654. // indicates whether this is a steiner point
  22655. this.steiner = false;
  22656. }
  22657. function signedArea( data, start, end, dim ) {
  22658. let sum = 0;
  22659. for ( let i = start, j = end - dim; i < end; i += dim ) {
  22660. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  22661. j = i;
  22662. }
  22663. return sum;
  22664. }
  22665. class ShapeUtils {
  22666. // calculate area of the contour polygon
  22667. static area( contour ) {
  22668. const n = contour.length;
  22669. let a = 0.0;
  22670. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  22671. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  22672. }
  22673. return a * 0.5;
  22674. }
  22675. static isClockWise( pts ) {
  22676. return ShapeUtils.area( pts ) < 0;
  22677. }
  22678. static triangulateShape( contour, holes ) {
  22679. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  22680. const holeIndices = []; // array of hole indices
  22681. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  22682. removeDupEndPts( contour );
  22683. addContour( vertices, contour );
  22684. //
  22685. let holeIndex = contour.length;
  22686. holes.forEach( removeDupEndPts );
  22687. for ( let i = 0; i < holes.length; i ++ ) {
  22688. holeIndices.push( holeIndex );
  22689. holeIndex += holes[ i ].length;
  22690. addContour( vertices, holes[ i ] );
  22691. }
  22692. //
  22693. const triangles = Earcut.triangulate( vertices, holeIndices );
  22694. //
  22695. for ( let i = 0; i < triangles.length; i += 3 ) {
  22696. faces.push( triangles.slice( i, i + 3 ) );
  22697. }
  22698. return faces;
  22699. }
  22700. }
  22701. function removeDupEndPts( points ) {
  22702. const l = points.length;
  22703. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  22704. points.pop();
  22705. }
  22706. }
  22707. function addContour( vertices, contour ) {
  22708. for ( let i = 0; i < contour.length; i ++ ) {
  22709. vertices.push( contour[ i ].x );
  22710. vertices.push( contour[ i ].y );
  22711. }
  22712. }
  22713. /**
  22714. * Creates extruded geometry from a path shape.
  22715. *
  22716. * parameters = {
  22717. *
  22718. * curveSegments: <int>, // number of points on the curves
  22719. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  22720. * depth: <float>, // Depth to extrude the shape
  22721. *
  22722. * bevelEnabled: <bool>, // turn on bevel
  22723. * bevelThickness: <float>, // how deep into the original shape bevel goes
  22724. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  22725. * bevelOffset: <float>, // how far from shape outline does bevel start
  22726. * bevelSegments: <int>, // number of bevel layers
  22727. *
  22728. * extrudePath: <THREE.Curve> // curve to extrude shape along
  22729. *
  22730. * UVGenerator: <Object> // object that provides UV generator functions
  22731. *
  22732. * }
  22733. */
  22734. class ExtrudeGeometry extends BufferGeometry {
  22735. 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 = {} ) {
  22736. super();
  22737. this.type = 'ExtrudeGeometry';
  22738. this.parameters = {
  22739. shapes: shapes,
  22740. options: options
  22741. };
  22742. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  22743. const scope = this;
  22744. const verticesArray = [];
  22745. const uvArray = [];
  22746. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22747. const shape = shapes[ i ];
  22748. addShape( shape );
  22749. }
  22750. // build geometry
  22751. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  22752. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  22753. this.computeVertexNormals();
  22754. // functions
  22755. function addShape( shape ) {
  22756. const placeholder = [];
  22757. // options
  22758. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  22759. const steps = options.steps !== undefined ? options.steps : 1;
  22760. const depth = options.depth !== undefined ? options.depth : 1;
  22761. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  22762. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  22763. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  22764. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  22765. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  22766. const extrudePath = options.extrudePath;
  22767. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  22768. //
  22769. let extrudePts, extrudeByPath = false;
  22770. let splineTube, binormal, normal, position2;
  22771. if ( extrudePath ) {
  22772. extrudePts = extrudePath.getSpacedPoints( steps );
  22773. extrudeByPath = true;
  22774. bevelEnabled = false; // bevels not supported for path extrusion
  22775. // SETUP TNB variables
  22776. // TODO1 - have a .isClosed in spline?
  22777. splineTube = extrudePath.computeFrenetFrames( steps, false );
  22778. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  22779. binormal = new Vector3();
  22780. normal = new Vector3();
  22781. position2 = new Vector3();
  22782. }
  22783. // Safeguards if bevels are not enabled
  22784. if ( ! bevelEnabled ) {
  22785. bevelSegments = 0;
  22786. bevelThickness = 0;
  22787. bevelSize = 0;
  22788. bevelOffset = 0;
  22789. }
  22790. // Variables initialization
  22791. const shapePoints = shape.extractPoints( curveSegments );
  22792. let vertices = shapePoints.shape;
  22793. const holes = shapePoints.holes;
  22794. const reverse = ! ShapeUtils.isClockWise( vertices );
  22795. if ( reverse ) {
  22796. vertices = vertices.reverse();
  22797. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  22798. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22799. const ahole = holes[ h ];
  22800. if ( ShapeUtils.isClockWise( ahole ) ) {
  22801. holes[ h ] = ahole.reverse();
  22802. }
  22803. }
  22804. }
  22805. const faces = ShapeUtils.triangulateShape( vertices, holes );
  22806. /* Vertices */
  22807. const contour = vertices; // vertices has all points but contour has only points of circumference
  22808. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22809. const ahole = holes[ h ];
  22810. vertices = vertices.concat( ahole );
  22811. }
  22812. function scalePt2( pt, vec, size ) {
  22813. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  22814. return pt.clone().addScaledVector( vec, size );
  22815. }
  22816. const vlen = vertices.length, flen = faces.length;
  22817. // Find directions for point movement
  22818. function getBevelVec( inPt, inPrev, inNext ) {
  22819. // computes for inPt the corresponding point inPt' on a new contour
  22820. // shifted by 1 unit (length of normalized vector) to the left
  22821. // if we walk along contour clockwise, this new contour is outside the old one
  22822. //
  22823. // inPt' is the intersection of the two lines parallel to the two
  22824. // adjacent edges of inPt at a distance of 1 unit on the left side.
  22825. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  22826. // good reading for geometry algorithms (here: line-line intersection)
  22827. // http://geomalgorithms.com/a05-_intersect-1.html
  22828. const v_prev_x = inPt.x - inPrev.x,
  22829. v_prev_y = inPt.y - inPrev.y;
  22830. const v_next_x = inNext.x - inPt.x,
  22831. v_next_y = inNext.y - inPt.y;
  22832. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  22833. // check for collinear edges
  22834. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22835. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  22836. // not collinear
  22837. // length of vectors for normalizing
  22838. const v_prev_len = Math.sqrt( v_prev_lensq );
  22839. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  22840. // shift adjacent points by unit vectors to the left
  22841. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  22842. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  22843. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  22844. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  22845. // scaling factor for v_prev to intersection point
  22846. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  22847. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  22848. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22849. // vector from inPt to intersection point
  22850. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  22851. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  22852. // Don't normalize!, otherwise sharp corners become ugly
  22853. // but prevent crazy spikes
  22854. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  22855. if ( v_trans_lensq <= 2 ) {
  22856. return new Vector2( v_trans_x, v_trans_y );
  22857. } else {
  22858. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  22859. }
  22860. } else {
  22861. // handle special case of collinear edges
  22862. let direction_eq = false; // assumes: opposite
  22863. if ( v_prev_x > Number.EPSILON ) {
  22864. if ( v_next_x > Number.EPSILON ) {
  22865. direction_eq = true;
  22866. }
  22867. } else {
  22868. if ( v_prev_x < - Number.EPSILON ) {
  22869. if ( v_next_x < - Number.EPSILON ) {
  22870. direction_eq = true;
  22871. }
  22872. } else {
  22873. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  22874. direction_eq = true;
  22875. }
  22876. }
  22877. }
  22878. if ( direction_eq ) {
  22879. // console.log("Warning: lines are a straight sequence");
  22880. v_trans_x = - v_prev_y;
  22881. v_trans_y = v_prev_x;
  22882. shrink_by = Math.sqrt( v_prev_lensq );
  22883. } else {
  22884. // console.log("Warning: lines are a straight spike");
  22885. v_trans_x = v_prev_x;
  22886. v_trans_y = v_prev_y;
  22887. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  22888. }
  22889. }
  22890. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  22891. }
  22892. const contourMovements = [];
  22893. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22894. if ( j === il ) j = 0;
  22895. if ( k === il ) k = 0;
  22896. // (j)---(i)---(k)
  22897. // console.log('i,j,k', i, j , k)
  22898. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  22899. }
  22900. const holesMovements = [];
  22901. let oneHoleMovements, verticesMovements = contourMovements.concat();
  22902. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22903. const ahole = holes[ h ];
  22904. oneHoleMovements = [];
  22905. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22906. if ( j === il ) j = 0;
  22907. if ( k === il ) k = 0;
  22908. // (j)---(i)---(k)
  22909. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  22910. }
  22911. holesMovements.push( oneHoleMovements );
  22912. verticesMovements = verticesMovements.concat( oneHoleMovements );
  22913. }
  22914. // Loop bevelSegments, 1 for the front, 1 for the back
  22915. for ( let b = 0; b < bevelSegments; b ++ ) {
  22916. //for ( b = bevelSegments; b > 0; b -- ) {
  22917. const t = b / bevelSegments;
  22918. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22919. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  22920. // contract shape
  22921. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  22922. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22923. v( vert.x, vert.y, - z );
  22924. }
  22925. // expand holes
  22926. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22927. const ahole = holes[ h ];
  22928. oneHoleMovements = holesMovements[ h ];
  22929. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  22930. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22931. v( vert.x, vert.y, - z );
  22932. }
  22933. }
  22934. }
  22935. const bs = bevelSize + bevelOffset;
  22936. // Back facing vertices
  22937. for ( let i = 0; i < vlen; i ++ ) {
  22938. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22939. if ( ! extrudeByPath ) {
  22940. v( vert.x, vert.y, 0 );
  22941. } else {
  22942. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  22943. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  22944. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  22945. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  22946. v( position2.x, position2.y, position2.z );
  22947. }
  22948. }
  22949. // Add stepped vertices...
  22950. // Including front facing vertices
  22951. for ( let s = 1; s <= steps; s ++ ) {
  22952. for ( let i = 0; i < vlen; i ++ ) {
  22953. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22954. if ( ! extrudeByPath ) {
  22955. v( vert.x, vert.y, depth / steps * s );
  22956. } else {
  22957. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  22958. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  22959. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  22960. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  22961. v( position2.x, position2.y, position2.z );
  22962. }
  22963. }
  22964. }
  22965. // Add bevel segments planes
  22966. //for ( b = 1; b <= bevelSegments; b ++ ) {
  22967. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  22968. const t = b / bevelSegments;
  22969. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22970. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  22971. // contract shape
  22972. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  22973. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22974. v( vert.x, vert.y, depth + z );
  22975. }
  22976. // expand holes
  22977. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22978. const ahole = holes[ h ];
  22979. oneHoleMovements = holesMovements[ h ];
  22980. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  22981. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22982. if ( ! extrudeByPath ) {
  22983. v( vert.x, vert.y, depth + z );
  22984. } else {
  22985. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  22986. }
  22987. }
  22988. }
  22989. }
  22990. /* Faces */
  22991. // Top and bottom faces
  22992. buildLidFaces();
  22993. // Sides faces
  22994. buildSideFaces();
  22995. ///// Internal functions
  22996. function buildLidFaces() {
  22997. const start = verticesArray.length / 3;
  22998. if ( bevelEnabled ) {
  22999. let layer = 0; // steps + 1
  23000. let offset = vlen * layer;
  23001. // Bottom faces
  23002. for ( let i = 0; i < flen; i ++ ) {
  23003. const face = faces[ i ];
  23004. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  23005. }
  23006. layer = steps + bevelSegments * 2;
  23007. offset = vlen * layer;
  23008. // Top faces
  23009. for ( let i = 0; i < flen; i ++ ) {
  23010. const face = faces[ i ];
  23011. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  23012. }
  23013. } else {
  23014. // Bottom faces
  23015. for ( let i = 0; i < flen; i ++ ) {
  23016. const face = faces[ i ];
  23017. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  23018. }
  23019. // Top faces
  23020. for ( let i = 0; i < flen; i ++ ) {
  23021. const face = faces[ i ];
  23022. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  23023. }
  23024. }
  23025. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  23026. }
  23027. // Create faces for the z-sides of the shape
  23028. function buildSideFaces() {
  23029. const start = verticesArray.length / 3;
  23030. let layeroffset = 0;
  23031. sidewalls( contour, layeroffset );
  23032. layeroffset += contour.length;
  23033. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23034. const ahole = holes[ h ];
  23035. sidewalls( ahole, layeroffset );
  23036. //, true
  23037. layeroffset += ahole.length;
  23038. }
  23039. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  23040. }
  23041. function sidewalls( contour, layeroffset ) {
  23042. let i = contour.length;
  23043. while ( -- i >= 0 ) {
  23044. const j = i;
  23045. let k = i - 1;
  23046. if ( k < 0 ) k = contour.length - 1;
  23047. //console.log('b', i,j, i-1, k,vertices.length);
  23048. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  23049. const slen1 = vlen * s;
  23050. const slen2 = vlen * ( s + 1 );
  23051. const a = layeroffset + j + slen1,
  23052. b = layeroffset + k + slen1,
  23053. c = layeroffset + k + slen2,
  23054. d = layeroffset + j + slen2;
  23055. f4( a, b, c, d );
  23056. }
  23057. }
  23058. }
  23059. function v( x, y, z ) {
  23060. placeholder.push( x );
  23061. placeholder.push( y );
  23062. placeholder.push( z );
  23063. }
  23064. function f3( a, b, c ) {
  23065. addVertex( a );
  23066. addVertex( b );
  23067. addVertex( c );
  23068. const nextIndex = verticesArray.length / 3;
  23069. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23070. addUV( uvs[ 0 ] );
  23071. addUV( uvs[ 1 ] );
  23072. addUV( uvs[ 2 ] );
  23073. }
  23074. function f4( a, b, c, d ) {
  23075. addVertex( a );
  23076. addVertex( b );
  23077. addVertex( d );
  23078. addVertex( b );
  23079. addVertex( c );
  23080. addVertex( d );
  23081. const nextIndex = verticesArray.length / 3;
  23082. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23083. addUV( uvs[ 0 ] );
  23084. addUV( uvs[ 1 ] );
  23085. addUV( uvs[ 3 ] );
  23086. addUV( uvs[ 1 ] );
  23087. addUV( uvs[ 2 ] );
  23088. addUV( uvs[ 3 ] );
  23089. }
  23090. function addVertex( index ) {
  23091. verticesArray.push( placeholder[ index * 3 + 0 ] );
  23092. verticesArray.push( placeholder[ index * 3 + 1 ] );
  23093. verticesArray.push( placeholder[ index * 3 + 2 ] );
  23094. }
  23095. function addUV( vector2 ) {
  23096. uvArray.push( vector2.x );
  23097. uvArray.push( vector2.y );
  23098. }
  23099. }
  23100. }
  23101. copy( source ) {
  23102. super.copy( source );
  23103. this.parameters = Object.assign( {}, source.parameters );
  23104. return this;
  23105. }
  23106. toJSON() {
  23107. const data = super.toJSON();
  23108. const shapes = this.parameters.shapes;
  23109. const options = this.parameters.options;
  23110. return toJSON$1( shapes, options, data );
  23111. }
  23112. static fromJSON( data, shapes ) {
  23113. const geometryShapes = [];
  23114. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23115. const shape = shapes[ data.shapes[ j ] ];
  23116. geometryShapes.push( shape );
  23117. }
  23118. const extrudePath = data.options.extrudePath;
  23119. if ( extrudePath !== undefined ) {
  23120. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  23121. }
  23122. return new ExtrudeGeometry( geometryShapes, data.options );
  23123. }
  23124. }
  23125. const WorldUVGenerator = {
  23126. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  23127. const a_x = vertices[ indexA * 3 ];
  23128. const a_y = vertices[ indexA * 3 + 1 ];
  23129. const b_x = vertices[ indexB * 3 ];
  23130. const b_y = vertices[ indexB * 3 + 1 ];
  23131. const c_x = vertices[ indexC * 3 ];
  23132. const c_y = vertices[ indexC * 3 + 1 ];
  23133. return [
  23134. new Vector2( a_x, a_y ),
  23135. new Vector2( b_x, b_y ),
  23136. new Vector2( c_x, c_y )
  23137. ];
  23138. },
  23139. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  23140. const a_x = vertices[ indexA * 3 ];
  23141. const a_y = vertices[ indexA * 3 + 1 ];
  23142. const a_z = vertices[ indexA * 3 + 2 ];
  23143. const b_x = vertices[ indexB * 3 ];
  23144. const b_y = vertices[ indexB * 3 + 1 ];
  23145. const b_z = vertices[ indexB * 3 + 2 ];
  23146. const c_x = vertices[ indexC * 3 ];
  23147. const c_y = vertices[ indexC * 3 + 1 ];
  23148. const c_z = vertices[ indexC * 3 + 2 ];
  23149. const d_x = vertices[ indexD * 3 ];
  23150. const d_y = vertices[ indexD * 3 + 1 ];
  23151. const d_z = vertices[ indexD * 3 + 2 ];
  23152. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  23153. return [
  23154. new Vector2( a_x, 1 - a_z ),
  23155. new Vector2( b_x, 1 - b_z ),
  23156. new Vector2( c_x, 1 - c_z ),
  23157. new Vector2( d_x, 1 - d_z )
  23158. ];
  23159. } else {
  23160. return [
  23161. new Vector2( a_y, 1 - a_z ),
  23162. new Vector2( b_y, 1 - b_z ),
  23163. new Vector2( c_y, 1 - c_z ),
  23164. new Vector2( d_y, 1 - d_z )
  23165. ];
  23166. }
  23167. }
  23168. };
  23169. function toJSON$1( shapes, options, data ) {
  23170. data.shapes = [];
  23171. if ( Array.isArray( shapes ) ) {
  23172. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23173. const shape = shapes[ i ];
  23174. data.shapes.push( shape.uuid );
  23175. }
  23176. } else {
  23177. data.shapes.push( shapes.uuid );
  23178. }
  23179. data.options = Object.assign( {}, options );
  23180. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  23181. return data;
  23182. }
  23183. class IcosahedronGeometry extends PolyhedronGeometry {
  23184. constructor( radius = 1, detail = 0 ) {
  23185. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23186. const vertices = [
  23187. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23188. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23189. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23190. ];
  23191. const indices = [
  23192. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23193. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23194. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23195. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23196. ];
  23197. super( vertices, indices, radius, detail );
  23198. this.type = 'IcosahedronGeometry';
  23199. this.parameters = {
  23200. radius: radius,
  23201. detail: detail
  23202. };
  23203. }
  23204. static fromJSON( data ) {
  23205. return new IcosahedronGeometry( data.radius, data.detail );
  23206. }
  23207. }
  23208. class OctahedronGeometry extends PolyhedronGeometry {
  23209. constructor( radius = 1, detail = 0 ) {
  23210. const vertices = [
  23211. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  23212. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23213. ];
  23214. const indices = [
  23215. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  23216. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  23217. 1, 3, 4, 1, 4, 2
  23218. ];
  23219. super( vertices, indices, radius, detail );
  23220. this.type = 'OctahedronGeometry';
  23221. this.parameters = {
  23222. radius: radius,
  23223. detail: detail
  23224. };
  23225. }
  23226. static fromJSON( data ) {
  23227. return new OctahedronGeometry( data.radius, data.detail );
  23228. }
  23229. }
  23230. class RingGeometry extends BufferGeometry {
  23231. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23232. super();
  23233. this.type = 'RingGeometry';
  23234. this.parameters = {
  23235. innerRadius: innerRadius,
  23236. outerRadius: outerRadius,
  23237. thetaSegments: thetaSegments,
  23238. phiSegments: phiSegments,
  23239. thetaStart: thetaStart,
  23240. thetaLength: thetaLength
  23241. };
  23242. thetaSegments = Math.max( 3, thetaSegments );
  23243. phiSegments = Math.max( 1, phiSegments );
  23244. // buffers
  23245. const indices = [];
  23246. const vertices = [];
  23247. const normals = [];
  23248. const uvs = [];
  23249. // some helper variables
  23250. let radius = innerRadius;
  23251. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23252. const vertex = new Vector3();
  23253. const uv = new Vector2();
  23254. // generate vertices, normals and uvs
  23255. for ( let j = 0; j <= phiSegments; j ++ ) {
  23256. for ( let i = 0; i <= thetaSegments; i ++ ) {
  23257. // values are generate from the inside of the ring to the outside
  23258. const segment = thetaStart + i / thetaSegments * thetaLength;
  23259. // vertex
  23260. vertex.x = radius * Math.cos( segment );
  23261. vertex.y = radius * Math.sin( segment );
  23262. vertices.push( vertex.x, vertex.y, vertex.z );
  23263. // normal
  23264. normals.push( 0, 0, 1 );
  23265. // uv
  23266. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23267. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23268. uvs.push( uv.x, uv.y );
  23269. }
  23270. // increase the radius for next row of vertices
  23271. radius += radiusStep;
  23272. }
  23273. // indices
  23274. for ( let j = 0; j < phiSegments; j ++ ) {
  23275. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  23276. for ( let i = 0; i < thetaSegments; i ++ ) {
  23277. const segment = i + thetaSegmentLevel;
  23278. const a = segment;
  23279. const b = segment + thetaSegments + 1;
  23280. const c = segment + thetaSegments + 2;
  23281. const d = segment + 1;
  23282. // faces
  23283. indices.push( a, b, d );
  23284. indices.push( b, c, d );
  23285. }
  23286. }
  23287. // build geometry
  23288. this.setIndex( indices );
  23289. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23290. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23291. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23292. }
  23293. copy( source ) {
  23294. super.copy( source );
  23295. this.parameters = Object.assign( {}, source.parameters );
  23296. return this;
  23297. }
  23298. static fromJSON( data ) {
  23299. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  23300. }
  23301. }
  23302. class ShapeGeometry extends BufferGeometry {
  23303. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  23304. super();
  23305. this.type = 'ShapeGeometry';
  23306. this.parameters = {
  23307. shapes: shapes,
  23308. curveSegments: curveSegments
  23309. };
  23310. // buffers
  23311. const indices = [];
  23312. const vertices = [];
  23313. const normals = [];
  23314. const uvs = [];
  23315. // helper variables
  23316. let groupStart = 0;
  23317. let groupCount = 0;
  23318. // allow single and array values for "shapes" parameter
  23319. if ( Array.isArray( shapes ) === false ) {
  23320. addShape( shapes );
  23321. } else {
  23322. for ( let i = 0; i < shapes.length; i ++ ) {
  23323. addShape( shapes[ i ] );
  23324. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  23325. groupStart += groupCount;
  23326. groupCount = 0;
  23327. }
  23328. }
  23329. // build geometry
  23330. this.setIndex( indices );
  23331. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23332. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23333. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23334. // helper functions
  23335. function addShape( shape ) {
  23336. const indexOffset = vertices.length / 3;
  23337. const points = shape.extractPoints( curveSegments );
  23338. let shapeVertices = points.shape;
  23339. const shapeHoles = points.holes;
  23340. // check direction of vertices
  23341. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  23342. shapeVertices = shapeVertices.reverse();
  23343. }
  23344. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23345. const shapeHole = shapeHoles[ i ];
  23346. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  23347. shapeHoles[ i ] = shapeHole.reverse();
  23348. }
  23349. }
  23350. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  23351. // join vertices of inner and outer paths to a single array
  23352. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23353. const shapeHole = shapeHoles[ i ];
  23354. shapeVertices = shapeVertices.concat( shapeHole );
  23355. }
  23356. // vertices, normals, uvs
  23357. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  23358. const vertex = shapeVertices[ i ];
  23359. vertices.push( vertex.x, vertex.y, 0 );
  23360. normals.push( 0, 0, 1 );
  23361. uvs.push( vertex.x, vertex.y ); // world uvs
  23362. }
  23363. // indices
  23364. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  23365. const face = faces[ i ];
  23366. const a = face[ 0 ] + indexOffset;
  23367. const b = face[ 1 ] + indexOffset;
  23368. const c = face[ 2 ] + indexOffset;
  23369. indices.push( a, b, c );
  23370. groupCount += 3;
  23371. }
  23372. }
  23373. }
  23374. copy( source ) {
  23375. super.copy( source );
  23376. this.parameters = Object.assign( {}, source.parameters );
  23377. return this;
  23378. }
  23379. toJSON() {
  23380. const data = super.toJSON();
  23381. const shapes = this.parameters.shapes;
  23382. return toJSON( shapes, data );
  23383. }
  23384. static fromJSON( data, shapes ) {
  23385. const geometryShapes = [];
  23386. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23387. const shape = shapes[ data.shapes[ j ] ];
  23388. geometryShapes.push( shape );
  23389. }
  23390. return new ShapeGeometry( geometryShapes, data.curveSegments );
  23391. }
  23392. }
  23393. function toJSON( shapes, data ) {
  23394. data.shapes = [];
  23395. if ( Array.isArray( shapes ) ) {
  23396. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23397. const shape = shapes[ i ];
  23398. data.shapes.push( shape.uuid );
  23399. }
  23400. } else {
  23401. data.shapes.push( shapes.uuid );
  23402. }
  23403. return data;
  23404. }
  23405. class SphereGeometry extends BufferGeometry {
  23406. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  23407. super();
  23408. this.type = 'SphereGeometry';
  23409. this.parameters = {
  23410. radius: radius,
  23411. widthSegments: widthSegments,
  23412. heightSegments: heightSegments,
  23413. phiStart: phiStart,
  23414. phiLength: phiLength,
  23415. thetaStart: thetaStart,
  23416. thetaLength: thetaLength
  23417. };
  23418. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  23419. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  23420. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  23421. let index = 0;
  23422. const grid = [];
  23423. const vertex = new Vector3();
  23424. const normal = new Vector3();
  23425. // buffers
  23426. const indices = [];
  23427. const vertices = [];
  23428. const normals = [];
  23429. const uvs = [];
  23430. // generate vertices, normals and uvs
  23431. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  23432. const verticesRow = [];
  23433. const v = iy / heightSegments;
  23434. // special case for the poles
  23435. let uOffset = 0;
  23436. if ( iy === 0 && thetaStart === 0 ) {
  23437. uOffset = 0.5 / widthSegments;
  23438. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  23439. uOffset = - 0.5 / widthSegments;
  23440. }
  23441. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  23442. const u = ix / widthSegments;
  23443. // vertex
  23444. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23445. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  23446. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23447. vertices.push( vertex.x, vertex.y, vertex.z );
  23448. // normal
  23449. normal.copy( vertex ).normalize();
  23450. normals.push( normal.x, normal.y, normal.z );
  23451. // uv
  23452. uvs.push( u + uOffset, 1 - v );
  23453. verticesRow.push( index ++ );
  23454. }
  23455. grid.push( verticesRow );
  23456. }
  23457. // indices
  23458. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  23459. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  23460. const a = grid[ iy ][ ix + 1 ];
  23461. const b = grid[ iy ][ ix ];
  23462. const c = grid[ iy + 1 ][ ix ];
  23463. const d = grid[ iy + 1 ][ ix + 1 ];
  23464. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  23465. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  23466. }
  23467. }
  23468. // build geometry
  23469. this.setIndex( indices );
  23470. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23471. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23472. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23473. }
  23474. copy( source ) {
  23475. super.copy( source );
  23476. this.parameters = Object.assign( {}, source.parameters );
  23477. return this;
  23478. }
  23479. static fromJSON( data ) {
  23480. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  23481. }
  23482. }
  23483. class TetrahedronGeometry extends PolyhedronGeometry {
  23484. constructor( radius = 1, detail = 0 ) {
  23485. const vertices = [
  23486. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23487. ];
  23488. const indices = [
  23489. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23490. ];
  23491. super( vertices, indices, radius, detail );
  23492. this.type = 'TetrahedronGeometry';
  23493. this.parameters = {
  23494. radius: radius,
  23495. detail: detail
  23496. };
  23497. }
  23498. static fromJSON( data ) {
  23499. return new TetrahedronGeometry( data.radius, data.detail );
  23500. }
  23501. }
  23502. class TorusGeometry extends BufferGeometry {
  23503. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  23504. super();
  23505. this.type = 'TorusGeometry';
  23506. this.parameters = {
  23507. radius: radius,
  23508. tube: tube,
  23509. radialSegments: radialSegments,
  23510. tubularSegments: tubularSegments,
  23511. arc: arc
  23512. };
  23513. radialSegments = Math.floor( radialSegments );
  23514. tubularSegments = Math.floor( tubularSegments );
  23515. // buffers
  23516. const indices = [];
  23517. const vertices = [];
  23518. const normals = [];
  23519. const uvs = [];
  23520. // helper variables
  23521. const center = new Vector3();
  23522. const vertex = new Vector3();
  23523. const normal = new Vector3();
  23524. // generate vertices, normals and uvs
  23525. for ( let j = 0; j <= radialSegments; j ++ ) {
  23526. for ( let i = 0; i <= tubularSegments; i ++ ) {
  23527. const u = i / tubularSegments * arc;
  23528. const v = j / radialSegments * Math.PI * 2;
  23529. // vertex
  23530. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23531. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23532. vertex.z = tube * Math.sin( v );
  23533. vertices.push( vertex.x, vertex.y, vertex.z );
  23534. // normal
  23535. center.x = radius * Math.cos( u );
  23536. center.y = radius * Math.sin( u );
  23537. normal.subVectors( vertex, center ).normalize();
  23538. normals.push( normal.x, normal.y, normal.z );
  23539. // uv
  23540. uvs.push( i / tubularSegments );
  23541. uvs.push( j / radialSegments );
  23542. }
  23543. }
  23544. // generate indices
  23545. for ( let j = 1; j <= radialSegments; j ++ ) {
  23546. for ( let i = 1; i <= tubularSegments; i ++ ) {
  23547. // indices
  23548. const a = ( tubularSegments + 1 ) * j + i - 1;
  23549. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23550. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23551. const d = ( tubularSegments + 1 ) * j + i;
  23552. // faces
  23553. indices.push( a, b, d );
  23554. indices.push( b, c, d );
  23555. }
  23556. }
  23557. // build geometry
  23558. this.setIndex( indices );
  23559. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23560. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23561. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23562. }
  23563. copy( source ) {
  23564. super.copy( source );
  23565. this.parameters = Object.assign( {}, source.parameters );
  23566. return this;
  23567. }
  23568. static fromJSON( data ) {
  23569. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  23570. }
  23571. }
  23572. class TorusKnotGeometry extends BufferGeometry {
  23573. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  23574. super();
  23575. this.type = 'TorusKnotGeometry';
  23576. this.parameters = {
  23577. radius: radius,
  23578. tube: tube,
  23579. tubularSegments: tubularSegments,
  23580. radialSegments: radialSegments,
  23581. p: p,
  23582. q: q
  23583. };
  23584. tubularSegments = Math.floor( tubularSegments );
  23585. radialSegments = Math.floor( radialSegments );
  23586. // buffers
  23587. const indices = [];
  23588. const vertices = [];
  23589. const normals = [];
  23590. const uvs = [];
  23591. // helper variables
  23592. const vertex = new Vector3();
  23593. const normal = new Vector3();
  23594. const P1 = new Vector3();
  23595. const P2 = new Vector3();
  23596. const B = new Vector3();
  23597. const T = new Vector3();
  23598. const N = new Vector3();
  23599. // generate vertices, normals and uvs
  23600. for ( let i = 0; i <= tubularSegments; ++ i ) {
  23601. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  23602. const u = i / tubularSegments * p * Math.PI * 2;
  23603. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23604. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23605. calculatePositionOnCurve( u, p, q, radius, P1 );
  23606. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23607. // calculate orthonormal basis
  23608. T.subVectors( P2, P1 );
  23609. N.addVectors( P2, P1 );
  23610. B.crossVectors( T, N );
  23611. N.crossVectors( B, T );
  23612. // normalize B, N. T can be ignored, we don't use it
  23613. B.normalize();
  23614. N.normalize();
  23615. for ( let j = 0; j <= radialSegments; ++ j ) {
  23616. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23617. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23618. const v = j / radialSegments * Math.PI * 2;
  23619. const cx = - tube * Math.cos( v );
  23620. const cy = tube * Math.sin( v );
  23621. // now calculate the final vertex position.
  23622. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  23623. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23624. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23625. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23626. vertices.push( vertex.x, vertex.y, vertex.z );
  23627. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23628. normal.subVectors( vertex, P1 ).normalize();
  23629. normals.push( normal.x, normal.y, normal.z );
  23630. // uv
  23631. uvs.push( i / tubularSegments );
  23632. uvs.push( j / radialSegments );
  23633. }
  23634. }
  23635. // generate indices
  23636. for ( let j = 1; j <= tubularSegments; j ++ ) {
  23637. for ( let i = 1; i <= radialSegments; i ++ ) {
  23638. // indices
  23639. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23640. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  23641. const c = ( radialSegments + 1 ) * j + i;
  23642. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23643. // faces
  23644. indices.push( a, b, d );
  23645. indices.push( b, c, d );
  23646. }
  23647. }
  23648. // build geometry
  23649. this.setIndex( indices );
  23650. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23651. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23652. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23653. // this function calculates the current position on the torus curve
  23654. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23655. const cu = Math.cos( u );
  23656. const su = Math.sin( u );
  23657. const quOverP = q / p * u;
  23658. const cs = Math.cos( quOverP );
  23659. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23660. position.y = radius * ( 2 + cs ) * su * 0.5;
  23661. position.z = radius * Math.sin( quOverP ) * 0.5;
  23662. }
  23663. }
  23664. copy( source ) {
  23665. super.copy( source );
  23666. this.parameters = Object.assign( {}, source.parameters );
  23667. return this;
  23668. }
  23669. static fromJSON( data ) {
  23670. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  23671. }
  23672. }
  23673. class TubeGeometry extends BufferGeometry {
  23674. 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 ) {
  23675. super();
  23676. this.type = 'TubeGeometry';
  23677. this.parameters = {
  23678. path: path,
  23679. tubularSegments: tubularSegments,
  23680. radius: radius,
  23681. radialSegments: radialSegments,
  23682. closed: closed
  23683. };
  23684. const frames = path.computeFrenetFrames( tubularSegments, closed );
  23685. // expose internals
  23686. this.tangents = frames.tangents;
  23687. this.normals = frames.normals;
  23688. this.binormals = frames.binormals;
  23689. // helper variables
  23690. const vertex = new Vector3();
  23691. const normal = new Vector3();
  23692. const uv = new Vector2();
  23693. let P = new Vector3();
  23694. // buffer
  23695. const vertices = [];
  23696. const normals = [];
  23697. const uvs = [];
  23698. const indices = [];
  23699. // create buffer data
  23700. generateBufferData();
  23701. // build geometry
  23702. this.setIndex( indices );
  23703. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23704. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23705. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23706. // functions
  23707. function generateBufferData() {
  23708. for ( let i = 0; i < tubularSegments; i ++ ) {
  23709. generateSegment( i );
  23710. }
  23711. // if the geometry is not closed, generate the last row of vertices and normals
  23712. // at the regular position on the given path
  23713. //
  23714. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  23715. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  23716. // uvs are generated in a separate function.
  23717. // this makes it easy compute correct values for closed geometries
  23718. generateUVs();
  23719. // finally create faces
  23720. generateIndices();
  23721. }
  23722. function generateSegment( i ) {
  23723. // we use getPointAt to sample evenly distributed points from the given path
  23724. P = path.getPointAt( i / tubularSegments, P );
  23725. // retrieve corresponding normal and binormal
  23726. const N = frames.normals[ i ];
  23727. const B = frames.binormals[ i ];
  23728. // generate normals and vertices for the current segment
  23729. for ( let j = 0; j <= radialSegments; j ++ ) {
  23730. const v = j / radialSegments * Math.PI * 2;
  23731. const sin = Math.sin( v );
  23732. const cos = - Math.cos( v );
  23733. // normal
  23734. normal.x = ( cos * N.x + sin * B.x );
  23735. normal.y = ( cos * N.y + sin * B.y );
  23736. normal.z = ( cos * N.z + sin * B.z );
  23737. normal.normalize();
  23738. normals.push( normal.x, normal.y, normal.z );
  23739. // vertex
  23740. vertex.x = P.x + radius * normal.x;
  23741. vertex.y = P.y + radius * normal.y;
  23742. vertex.z = P.z + radius * normal.z;
  23743. vertices.push( vertex.x, vertex.y, vertex.z );
  23744. }
  23745. }
  23746. function generateIndices() {
  23747. for ( let j = 1; j <= tubularSegments; j ++ ) {
  23748. for ( let i = 1; i <= radialSegments; i ++ ) {
  23749. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23750. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  23751. const c = ( radialSegments + 1 ) * j + i;
  23752. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23753. // faces
  23754. indices.push( a, b, d );
  23755. indices.push( b, c, d );
  23756. }
  23757. }
  23758. }
  23759. function generateUVs() {
  23760. for ( let i = 0; i <= tubularSegments; i ++ ) {
  23761. for ( let j = 0; j <= radialSegments; j ++ ) {
  23762. uv.x = i / tubularSegments;
  23763. uv.y = j / radialSegments;
  23764. uvs.push( uv.x, uv.y );
  23765. }
  23766. }
  23767. }
  23768. }
  23769. copy( source ) {
  23770. super.copy( source );
  23771. this.parameters = Object.assign( {}, source.parameters );
  23772. return this;
  23773. }
  23774. toJSON() {
  23775. const data = super.toJSON();
  23776. data.path = this.parameters.path.toJSON();
  23777. return data;
  23778. }
  23779. static fromJSON( data ) {
  23780. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23781. // User defined curves or instances of CurvePath will not be deserialized.
  23782. return new TubeGeometry(
  23783. new Curves[ data.path.type ]().fromJSON( data.path ),
  23784. data.tubularSegments,
  23785. data.radius,
  23786. data.radialSegments,
  23787. data.closed
  23788. );
  23789. }
  23790. }
  23791. class WireframeGeometry extends BufferGeometry {
  23792. constructor( geometry = null ) {
  23793. super();
  23794. this.type = 'WireframeGeometry';
  23795. this.parameters = {
  23796. geometry: geometry
  23797. };
  23798. if ( geometry !== null ) {
  23799. // buffer
  23800. const vertices = [];
  23801. const edges = new Set();
  23802. // helper variables
  23803. const start = new Vector3();
  23804. const end = new Vector3();
  23805. if ( geometry.index !== null ) {
  23806. // indexed BufferGeometry
  23807. const position = geometry.attributes.position;
  23808. const indices = geometry.index;
  23809. let groups = geometry.groups;
  23810. if ( groups.length === 0 ) {
  23811. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  23812. }
  23813. // create a data structure that contains all edges without duplicates
  23814. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  23815. const group = groups[ o ];
  23816. const groupStart = group.start;
  23817. const groupCount = group.count;
  23818. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  23819. for ( let j = 0; j < 3; j ++ ) {
  23820. const index1 = indices.getX( i + j );
  23821. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  23822. start.fromBufferAttribute( position, index1 );
  23823. end.fromBufferAttribute( position, index2 );
  23824. if ( isUniqueEdge( start, end, edges ) === true ) {
  23825. vertices.push( start.x, start.y, start.z );
  23826. vertices.push( end.x, end.y, end.z );
  23827. }
  23828. }
  23829. }
  23830. }
  23831. } else {
  23832. // non-indexed BufferGeometry
  23833. const position = geometry.attributes.position;
  23834. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  23835. for ( let j = 0; j < 3; j ++ ) {
  23836. // three edges per triangle, an edge is represented as (index1, index2)
  23837. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  23838. const index1 = 3 * i + j;
  23839. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  23840. start.fromBufferAttribute( position, index1 );
  23841. end.fromBufferAttribute( position, index2 );
  23842. if ( isUniqueEdge( start, end, edges ) === true ) {
  23843. vertices.push( start.x, start.y, start.z );
  23844. vertices.push( end.x, end.y, end.z );
  23845. }
  23846. }
  23847. }
  23848. }
  23849. // build geometry
  23850. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23851. }
  23852. }
  23853. copy( source ) {
  23854. super.copy( source );
  23855. this.parameters = Object.assign( {}, source.parameters );
  23856. return this;
  23857. }
  23858. }
  23859. function isUniqueEdge( start, end, edges ) {
  23860. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  23861. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  23862. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  23863. return false;
  23864. } else {
  23865. edges.add( hash1 );
  23866. edges.add( hash2 );
  23867. return true;
  23868. }
  23869. }
  23870. var Geometries = /*#__PURE__*/Object.freeze({
  23871. __proto__: null,
  23872. BoxGeometry: BoxGeometry,
  23873. CapsuleGeometry: CapsuleGeometry,
  23874. CircleGeometry: CircleGeometry,
  23875. ConeGeometry: ConeGeometry,
  23876. CylinderGeometry: CylinderGeometry,
  23877. DodecahedronGeometry: DodecahedronGeometry,
  23878. EdgesGeometry: EdgesGeometry,
  23879. ExtrudeGeometry: ExtrudeGeometry,
  23880. IcosahedronGeometry: IcosahedronGeometry,
  23881. LatheGeometry: LatheGeometry,
  23882. OctahedronGeometry: OctahedronGeometry,
  23883. PlaneGeometry: PlaneGeometry,
  23884. PolyhedronGeometry: PolyhedronGeometry,
  23885. RingGeometry: RingGeometry,
  23886. ShapeGeometry: ShapeGeometry,
  23887. SphereGeometry: SphereGeometry,
  23888. TetrahedronGeometry: TetrahedronGeometry,
  23889. TorusGeometry: TorusGeometry,
  23890. TorusKnotGeometry: TorusKnotGeometry,
  23891. TubeGeometry: TubeGeometry,
  23892. WireframeGeometry: WireframeGeometry
  23893. });
  23894. class ShadowMaterial extends Material {
  23895. constructor( parameters ) {
  23896. super();
  23897. this.isShadowMaterial = true;
  23898. this.type = 'ShadowMaterial';
  23899. this.color = new Color( 0x000000 );
  23900. this.transparent = true;
  23901. this.fog = true;
  23902. this.setValues( parameters );
  23903. }
  23904. copy( source ) {
  23905. super.copy( source );
  23906. this.color.copy( source.color );
  23907. this.fog = source.fog;
  23908. return this;
  23909. }
  23910. }
  23911. class RawShaderMaterial extends ShaderMaterial {
  23912. constructor( parameters ) {
  23913. super( parameters );
  23914. this.isRawShaderMaterial = true;
  23915. this.type = 'RawShaderMaterial';
  23916. }
  23917. }
  23918. class MeshStandardMaterial extends Material {
  23919. constructor( parameters ) {
  23920. super();
  23921. this.isMeshStandardMaterial = true;
  23922. this.defines = { 'STANDARD': '' };
  23923. this.type = 'MeshStandardMaterial';
  23924. this.color = new Color( 0xffffff ); // diffuse
  23925. this.roughness = 1.0;
  23926. this.metalness = 0.0;
  23927. this.map = null;
  23928. this.lightMap = null;
  23929. this.lightMapIntensity = 1.0;
  23930. this.aoMap = null;
  23931. this.aoMapIntensity = 1.0;
  23932. this.emissive = new Color( 0x000000 );
  23933. this.emissiveIntensity = 1.0;
  23934. this.emissiveMap = null;
  23935. this.bumpMap = null;
  23936. this.bumpScale = 1;
  23937. this.normalMap = null;
  23938. this.normalMapType = TangentSpaceNormalMap;
  23939. this.normalScale = new Vector2( 1, 1 );
  23940. this.displacementMap = null;
  23941. this.displacementScale = 1;
  23942. this.displacementBias = 0;
  23943. this.roughnessMap = null;
  23944. this.metalnessMap = null;
  23945. this.alphaMap = null;
  23946. this.envMap = null;
  23947. this.envMapRotation = new Euler();
  23948. this.envMapIntensity = 1.0;
  23949. this.wireframe = false;
  23950. this.wireframeLinewidth = 1;
  23951. this.wireframeLinecap = 'round';
  23952. this.wireframeLinejoin = 'round';
  23953. this.flatShading = false;
  23954. this.fog = true;
  23955. this.setValues( parameters );
  23956. }
  23957. copy( source ) {
  23958. super.copy( source );
  23959. this.defines = { 'STANDARD': '' };
  23960. this.color.copy( source.color );
  23961. this.roughness = source.roughness;
  23962. this.metalness = source.metalness;
  23963. this.map = source.map;
  23964. this.lightMap = source.lightMap;
  23965. this.lightMapIntensity = source.lightMapIntensity;
  23966. this.aoMap = source.aoMap;
  23967. this.aoMapIntensity = source.aoMapIntensity;
  23968. this.emissive.copy( source.emissive );
  23969. this.emissiveMap = source.emissiveMap;
  23970. this.emissiveIntensity = source.emissiveIntensity;
  23971. this.bumpMap = source.bumpMap;
  23972. this.bumpScale = source.bumpScale;
  23973. this.normalMap = source.normalMap;
  23974. this.normalMapType = source.normalMapType;
  23975. this.normalScale.copy( source.normalScale );
  23976. this.displacementMap = source.displacementMap;
  23977. this.displacementScale = source.displacementScale;
  23978. this.displacementBias = source.displacementBias;
  23979. this.roughnessMap = source.roughnessMap;
  23980. this.metalnessMap = source.metalnessMap;
  23981. this.alphaMap = source.alphaMap;
  23982. this.envMap = source.envMap;
  23983. this.envMapRotation.copy( source.envMapRotation );
  23984. this.envMapIntensity = source.envMapIntensity;
  23985. this.wireframe = source.wireframe;
  23986. this.wireframeLinewidth = source.wireframeLinewidth;
  23987. this.wireframeLinecap = source.wireframeLinecap;
  23988. this.wireframeLinejoin = source.wireframeLinejoin;
  23989. this.flatShading = source.flatShading;
  23990. this.fog = source.fog;
  23991. return this;
  23992. }
  23993. }
  23994. class MeshPhysicalMaterial extends MeshStandardMaterial {
  23995. constructor( parameters ) {
  23996. super();
  23997. this.isMeshPhysicalMaterial = true;
  23998. this.defines = {
  23999. 'STANDARD': '',
  24000. 'PHYSICAL': ''
  24001. };
  24002. this.type = 'MeshPhysicalMaterial';
  24003. this.anisotropyRotation = 0;
  24004. this.anisotropyMap = null;
  24005. this.clearcoatMap = null;
  24006. this.clearcoatRoughness = 0.0;
  24007. this.clearcoatRoughnessMap = null;
  24008. this.clearcoatNormalScale = new Vector2( 1, 1 );
  24009. this.clearcoatNormalMap = null;
  24010. this.ior = 1.5;
  24011. Object.defineProperty( this, 'reflectivity', {
  24012. get: function () {
  24013. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  24014. },
  24015. set: function ( reflectivity ) {
  24016. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  24017. }
  24018. } );
  24019. this.iridescenceMap = null;
  24020. this.iridescenceIOR = 1.3;
  24021. this.iridescenceThicknessRange = [ 100, 400 ];
  24022. this.iridescenceThicknessMap = null;
  24023. this.sheenColor = new Color( 0x000000 );
  24024. this.sheenColorMap = null;
  24025. this.sheenRoughness = 1.0;
  24026. this.sheenRoughnessMap = null;
  24027. this.transmissionMap = null;
  24028. this.thickness = 0;
  24029. this.thicknessMap = null;
  24030. this.attenuationDistance = Infinity;
  24031. this.attenuationColor = new Color( 1, 1, 1 );
  24032. this.specularIntensity = 1.0;
  24033. this.specularIntensityMap = null;
  24034. this.specularColor = new Color( 1, 1, 1 );
  24035. this.specularColorMap = null;
  24036. this._anisotropy = 0;
  24037. this._clearcoat = 0;
  24038. this._dispersion = 0;
  24039. this._iridescence = 0;
  24040. this._sheen = 0.0;
  24041. this._transmission = 0;
  24042. this.setValues( parameters );
  24043. }
  24044. get anisotropy() {
  24045. return this._anisotropy;
  24046. }
  24047. set anisotropy( value ) {
  24048. if ( this._anisotropy > 0 !== value > 0 ) {
  24049. this.version ++;
  24050. }
  24051. this._anisotropy = value;
  24052. }
  24053. get clearcoat() {
  24054. return this._clearcoat;
  24055. }
  24056. set clearcoat( value ) {
  24057. if ( this._clearcoat > 0 !== value > 0 ) {
  24058. this.version ++;
  24059. }
  24060. this._clearcoat = value;
  24061. }
  24062. get iridescence() {
  24063. return this._iridescence;
  24064. }
  24065. set iridescence( value ) {
  24066. if ( this._iridescence > 0 !== value > 0 ) {
  24067. this.version ++;
  24068. }
  24069. this._iridescence = value;
  24070. }
  24071. get dispersion() {
  24072. return this._dispersion;
  24073. }
  24074. set dispersion( value ) {
  24075. if ( this._dispersion > 0 !== value > 0 ) {
  24076. this.version ++;
  24077. }
  24078. this._dispersion = value;
  24079. }
  24080. get sheen() {
  24081. return this._sheen;
  24082. }
  24083. set sheen( value ) {
  24084. if ( this._sheen > 0 !== value > 0 ) {
  24085. this.version ++;
  24086. }
  24087. this._sheen = value;
  24088. }
  24089. get transmission() {
  24090. return this._transmission;
  24091. }
  24092. set transmission( value ) {
  24093. if ( this._transmission > 0 !== value > 0 ) {
  24094. this.version ++;
  24095. }
  24096. this._transmission = value;
  24097. }
  24098. copy( source ) {
  24099. super.copy( source );
  24100. this.defines = {
  24101. 'STANDARD': '',
  24102. 'PHYSICAL': ''
  24103. };
  24104. this.anisotropy = source.anisotropy;
  24105. this.anisotropyRotation = source.anisotropyRotation;
  24106. this.anisotropyMap = source.anisotropyMap;
  24107. this.clearcoat = source.clearcoat;
  24108. this.clearcoatMap = source.clearcoatMap;
  24109. this.clearcoatRoughness = source.clearcoatRoughness;
  24110. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  24111. this.clearcoatNormalMap = source.clearcoatNormalMap;
  24112. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  24113. this.dispersion = source.dispersion;
  24114. this.ior = source.ior;
  24115. this.iridescence = source.iridescence;
  24116. this.iridescenceMap = source.iridescenceMap;
  24117. this.iridescenceIOR = source.iridescenceIOR;
  24118. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  24119. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  24120. this.sheen = source.sheen;
  24121. this.sheenColor.copy( source.sheenColor );
  24122. this.sheenColorMap = source.sheenColorMap;
  24123. this.sheenRoughness = source.sheenRoughness;
  24124. this.sheenRoughnessMap = source.sheenRoughnessMap;
  24125. this.transmission = source.transmission;
  24126. this.transmissionMap = source.transmissionMap;
  24127. this.thickness = source.thickness;
  24128. this.thicknessMap = source.thicknessMap;
  24129. this.attenuationDistance = source.attenuationDistance;
  24130. this.attenuationColor.copy( source.attenuationColor );
  24131. this.specularIntensity = source.specularIntensity;
  24132. this.specularIntensityMap = source.specularIntensityMap;
  24133. this.specularColor.copy( source.specularColor );
  24134. this.specularColorMap = source.specularColorMap;
  24135. return this;
  24136. }
  24137. }
  24138. class MeshPhongMaterial extends Material {
  24139. constructor( parameters ) {
  24140. super();
  24141. this.isMeshPhongMaterial = true;
  24142. this.type = 'MeshPhongMaterial';
  24143. this.color = new Color( 0xffffff ); // diffuse
  24144. this.specular = new Color( 0x111111 );
  24145. this.shininess = 30;
  24146. this.map = null;
  24147. this.lightMap = null;
  24148. this.lightMapIntensity = 1.0;
  24149. this.aoMap = null;
  24150. this.aoMapIntensity = 1.0;
  24151. this.emissive = new Color( 0x000000 );
  24152. this.emissiveIntensity = 1.0;
  24153. this.emissiveMap = null;
  24154. this.bumpMap = null;
  24155. this.bumpScale = 1;
  24156. this.normalMap = null;
  24157. this.normalMapType = TangentSpaceNormalMap;
  24158. this.normalScale = new Vector2( 1, 1 );
  24159. this.displacementMap = null;
  24160. this.displacementScale = 1;
  24161. this.displacementBias = 0;
  24162. this.specularMap = null;
  24163. this.alphaMap = null;
  24164. this.envMap = null;
  24165. this.envMapRotation = new Euler();
  24166. this.combine = MultiplyOperation;
  24167. this.reflectivity = 1;
  24168. this.refractionRatio = 0.98;
  24169. this.wireframe = false;
  24170. this.wireframeLinewidth = 1;
  24171. this.wireframeLinecap = 'round';
  24172. this.wireframeLinejoin = 'round';
  24173. this.flatShading = false;
  24174. this.fog = true;
  24175. this.setValues( parameters );
  24176. }
  24177. copy( source ) {
  24178. super.copy( source );
  24179. this.color.copy( source.color );
  24180. this.specular.copy( source.specular );
  24181. this.shininess = source.shininess;
  24182. this.map = source.map;
  24183. this.lightMap = source.lightMap;
  24184. this.lightMapIntensity = source.lightMapIntensity;
  24185. this.aoMap = source.aoMap;
  24186. this.aoMapIntensity = source.aoMapIntensity;
  24187. this.emissive.copy( source.emissive );
  24188. this.emissiveMap = source.emissiveMap;
  24189. this.emissiveIntensity = source.emissiveIntensity;
  24190. this.bumpMap = source.bumpMap;
  24191. this.bumpScale = source.bumpScale;
  24192. this.normalMap = source.normalMap;
  24193. this.normalMapType = source.normalMapType;
  24194. this.normalScale.copy( source.normalScale );
  24195. this.displacementMap = source.displacementMap;
  24196. this.displacementScale = source.displacementScale;
  24197. this.displacementBias = source.displacementBias;
  24198. this.specularMap = source.specularMap;
  24199. this.alphaMap = source.alphaMap;
  24200. this.envMap = source.envMap;
  24201. this.envMapRotation.copy( source.envMapRotation );
  24202. this.combine = source.combine;
  24203. this.reflectivity = source.reflectivity;
  24204. this.refractionRatio = source.refractionRatio;
  24205. this.wireframe = source.wireframe;
  24206. this.wireframeLinewidth = source.wireframeLinewidth;
  24207. this.wireframeLinecap = source.wireframeLinecap;
  24208. this.wireframeLinejoin = source.wireframeLinejoin;
  24209. this.flatShading = source.flatShading;
  24210. this.fog = source.fog;
  24211. return this;
  24212. }
  24213. }
  24214. class MeshToonMaterial extends Material {
  24215. constructor( parameters ) {
  24216. super();
  24217. this.isMeshToonMaterial = true;
  24218. this.defines = { 'TOON': '' };
  24219. this.type = 'MeshToonMaterial';
  24220. this.color = new Color( 0xffffff );
  24221. this.map = null;
  24222. this.gradientMap = null;
  24223. this.lightMap = null;
  24224. this.lightMapIntensity = 1.0;
  24225. this.aoMap = null;
  24226. this.aoMapIntensity = 1.0;
  24227. this.emissive = new Color( 0x000000 );
  24228. this.emissiveIntensity = 1.0;
  24229. this.emissiveMap = null;
  24230. this.bumpMap = null;
  24231. this.bumpScale = 1;
  24232. this.normalMap = null;
  24233. this.normalMapType = TangentSpaceNormalMap;
  24234. this.normalScale = new Vector2( 1, 1 );
  24235. this.displacementMap = null;
  24236. this.displacementScale = 1;
  24237. this.displacementBias = 0;
  24238. this.alphaMap = null;
  24239. this.wireframe = false;
  24240. this.wireframeLinewidth = 1;
  24241. this.wireframeLinecap = 'round';
  24242. this.wireframeLinejoin = 'round';
  24243. this.fog = true;
  24244. this.setValues( parameters );
  24245. }
  24246. copy( source ) {
  24247. super.copy( source );
  24248. this.color.copy( source.color );
  24249. this.map = source.map;
  24250. this.gradientMap = source.gradientMap;
  24251. this.lightMap = source.lightMap;
  24252. this.lightMapIntensity = source.lightMapIntensity;
  24253. this.aoMap = source.aoMap;
  24254. this.aoMapIntensity = source.aoMapIntensity;
  24255. this.emissive.copy( source.emissive );
  24256. this.emissiveMap = source.emissiveMap;
  24257. this.emissiveIntensity = source.emissiveIntensity;
  24258. this.bumpMap = source.bumpMap;
  24259. this.bumpScale = source.bumpScale;
  24260. this.normalMap = source.normalMap;
  24261. this.normalMapType = source.normalMapType;
  24262. this.normalScale.copy( source.normalScale );
  24263. this.displacementMap = source.displacementMap;
  24264. this.displacementScale = source.displacementScale;
  24265. this.displacementBias = source.displacementBias;
  24266. this.alphaMap = source.alphaMap;
  24267. this.wireframe = source.wireframe;
  24268. this.wireframeLinewidth = source.wireframeLinewidth;
  24269. this.wireframeLinecap = source.wireframeLinecap;
  24270. this.wireframeLinejoin = source.wireframeLinejoin;
  24271. this.fog = source.fog;
  24272. return this;
  24273. }
  24274. }
  24275. class MeshNormalMaterial extends Material {
  24276. constructor( parameters ) {
  24277. super();
  24278. this.isMeshNormalMaterial = true;
  24279. this.type = 'MeshNormalMaterial';
  24280. this.bumpMap = null;
  24281. this.bumpScale = 1;
  24282. this.normalMap = null;
  24283. this.normalMapType = TangentSpaceNormalMap;
  24284. this.normalScale = new Vector2( 1, 1 );
  24285. this.displacementMap = null;
  24286. this.displacementScale = 1;
  24287. this.displacementBias = 0;
  24288. this.wireframe = false;
  24289. this.wireframeLinewidth = 1;
  24290. this.flatShading = false;
  24291. this.setValues( parameters );
  24292. }
  24293. copy( source ) {
  24294. super.copy( source );
  24295. this.bumpMap = source.bumpMap;
  24296. this.bumpScale = source.bumpScale;
  24297. this.normalMap = source.normalMap;
  24298. this.normalMapType = source.normalMapType;
  24299. this.normalScale.copy( source.normalScale );
  24300. this.displacementMap = source.displacementMap;
  24301. this.displacementScale = source.displacementScale;
  24302. this.displacementBias = source.displacementBias;
  24303. this.wireframe = source.wireframe;
  24304. this.wireframeLinewidth = source.wireframeLinewidth;
  24305. this.flatShading = source.flatShading;
  24306. return this;
  24307. }
  24308. }
  24309. class MeshLambertMaterial extends Material {
  24310. constructor( parameters ) {
  24311. super();
  24312. this.isMeshLambertMaterial = true;
  24313. this.type = 'MeshLambertMaterial';
  24314. this.color = new Color( 0xffffff ); // diffuse
  24315. this.map = null;
  24316. this.lightMap = null;
  24317. this.lightMapIntensity = 1.0;
  24318. this.aoMap = null;
  24319. this.aoMapIntensity = 1.0;
  24320. this.emissive = new Color( 0x000000 );
  24321. this.emissiveIntensity = 1.0;
  24322. this.emissiveMap = null;
  24323. this.bumpMap = null;
  24324. this.bumpScale = 1;
  24325. this.normalMap = null;
  24326. this.normalMapType = TangentSpaceNormalMap;
  24327. this.normalScale = new Vector2( 1, 1 );
  24328. this.displacementMap = null;
  24329. this.displacementScale = 1;
  24330. this.displacementBias = 0;
  24331. this.specularMap = null;
  24332. this.alphaMap = null;
  24333. this.envMap = null;
  24334. this.envMapRotation = new Euler();
  24335. this.combine = MultiplyOperation;
  24336. this.reflectivity = 1;
  24337. this.refractionRatio = 0.98;
  24338. this.wireframe = false;
  24339. this.wireframeLinewidth = 1;
  24340. this.wireframeLinecap = 'round';
  24341. this.wireframeLinejoin = 'round';
  24342. this.flatShading = false;
  24343. this.fog = true;
  24344. this.setValues( parameters );
  24345. }
  24346. copy( source ) {
  24347. super.copy( source );
  24348. this.color.copy( source.color );
  24349. this.map = source.map;
  24350. this.lightMap = source.lightMap;
  24351. this.lightMapIntensity = source.lightMapIntensity;
  24352. this.aoMap = source.aoMap;
  24353. this.aoMapIntensity = source.aoMapIntensity;
  24354. this.emissive.copy( source.emissive );
  24355. this.emissiveMap = source.emissiveMap;
  24356. this.emissiveIntensity = source.emissiveIntensity;
  24357. this.bumpMap = source.bumpMap;
  24358. this.bumpScale = source.bumpScale;
  24359. this.normalMap = source.normalMap;
  24360. this.normalMapType = source.normalMapType;
  24361. this.normalScale.copy( source.normalScale );
  24362. this.displacementMap = source.displacementMap;
  24363. this.displacementScale = source.displacementScale;
  24364. this.displacementBias = source.displacementBias;
  24365. this.specularMap = source.specularMap;
  24366. this.alphaMap = source.alphaMap;
  24367. this.envMap = source.envMap;
  24368. this.envMapRotation.copy( source.envMapRotation );
  24369. this.combine = source.combine;
  24370. this.reflectivity = source.reflectivity;
  24371. this.refractionRatio = source.refractionRatio;
  24372. this.wireframe = source.wireframe;
  24373. this.wireframeLinewidth = source.wireframeLinewidth;
  24374. this.wireframeLinecap = source.wireframeLinecap;
  24375. this.wireframeLinejoin = source.wireframeLinejoin;
  24376. this.flatShading = source.flatShading;
  24377. this.fog = source.fog;
  24378. return this;
  24379. }
  24380. }
  24381. class MeshMatcapMaterial extends Material {
  24382. constructor( parameters ) {
  24383. super();
  24384. this.isMeshMatcapMaterial = true;
  24385. this.defines = { 'MATCAP': '' };
  24386. this.type = 'MeshMatcapMaterial';
  24387. this.color = new Color( 0xffffff ); // diffuse
  24388. this.matcap = null;
  24389. this.map = null;
  24390. this.bumpMap = null;
  24391. this.bumpScale = 1;
  24392. this.normalMap = null;
  24393. this.normalMapType = TangentSpaceNormalMap;
  24394. this.normalScale = new Vector2( 1, 1 );
  24395. this.displacementMap = null;
  24396. this.displacementScale = 1;
  24397. this.displacementBias = 0;
  24398. this.alphaMap = null;
  24399. this.flatShading = false;
  24400. this.fog = true;
  24401. this.setValues( parameters );
  24402. }
  24403. copy( source ) {
  24404. super.copy( source );
  24405. this.defines = { 'MATCAP': '' };
  24406. this.color.copy( source.color );
  24407. this.matcap = source.matcap;
  24408. this.map = source.map;
  24409. this.bumpMap = source.bumpMap;
  24410. this.bumpScale = source.bumpScale;
  24411. this.normalMap = source.normalMap;
  24412. this.normalMapType = source.normalMapType;
  24413. this.normalScale.copy( source.normalScale );
  24414. this.displacementMap = source.displacementMap;
  24415. this.displacementScale = source.displacementScale;
  24416. this.displacementBias = source.displacementBias;
  24417. this.alphaMap = source.alphaMap;
  24418. this.flatShading = source.flatShading;
  24419. this.fog = source.fog;
  24420. return this;
  24421. }
  24422. }
  24423. class LineDashedMaterial extends LineBasicMaterial {
  24424. constructor( parameters ) {
  24425. super();
  24426. this.isLineDashedMaterial = true;
  24427. this.type = 'LineDashedMaterial';
  24428. this.scale = 1;
  24429. this.dashSize = 3;
  24430. this.gapSize = 1;
  24431. this.setValues( parameters );
  24432. }
  24433. copy( source ) {
  24434. super.copy( source );
  24435. this.scale = source.scale;
  24436. this.dashSize = source.dashSize;
  24437. this.gapSize = source.gapSize;
  24438. return this;
  24439. }
  24440. }
  24441. // converts an array to a specific type
  24442. function convertArray( array, type, forceClone ) {
  24443. if ( ! array || // let 'undefined' and 'null' pass
  24444. ! forceClone && array.constructor === type ) return array;
  24445. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  24446. return new type( array ); // create typed array
  24447. }
  24448. return Array.prototype.slice.call( array ); // create Array
  24449. }
  24450. function isTypedArray( object ) {
  24451. return ArrayBuffer.isView( object ) &&
  24452. ! ( object instanceof DataView );
  24453. }
  24454. // returns an array by which times and values can be sorted
  24455. function getKeyframeOrder( times ) {
  24456. function compareTime( i, j ) {
  24457. return times[ i ] - times[ j ];
  24458. }
  24459. const n = times.length;
  24460. const result = new Array( n );
  24461. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  24462. result.sort( compareTime );
  24463. return result;
  24464. }
  24465. // uses the array previously returned by 'getKeyframeOrder' to sort data
  24466. function sortedArray( values, stride, order ) {
  24467. const nValues = values.length;
  24468. const result = new values.constructor( nValues );
  24469. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  24470. const srcOffset = order[ i ] * stride;
  24471. for ( let j = 0; j !== stride; ++ j ) {
  24472. result[ dstOffset ++ ] = values[ srcOffset + j ];
  24473. }
  24474. }
  24475. return result;
  24476. }
  24477. // function for parsing AOS keyframe formats
  24478. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  24479. let i = 1, key = jsonKeys[ 0 ];
  24480. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  24481. key = jsonKeys[ i ++ ];
  24482. }
  24483. if ( key === undefined ) return; // no data
  24484. let value = key[ valuePropertyName ];
  24485. if ( value === undefined ) return; // no data
  24486. if ( Array.isArray( value ) ) {
  24487. do {
  24488. value = key[ valuePropertyName ];
  24489. if ( value !== undefined ) {
  24490. times.push( key.time );
  24491. values.push.apply( values, value ); // push all elements
  24492. }
  24493. key = jsonKeys[ i ++ ];
  24494. } while ( key !== undefined );
  24495. } else if ( value.toArray !== undefined ) {
  24496. // ...assume THREE.Math-ish
  24497. do {
  24498. value = key[ valuePropertyName ];
  24499. if ( value !== undefined ) {
  24500. times.push( key.time );
  24501. value.toArray( values, values.length );
  24502. }
  24503. key = jsonKeys[ i ++ ];
  24504. } while ( key !== undefined );
  24505. } else {
  24506. // otherwise push as-is
  24507. do {
  24508. value = key[ valuePropertyName ];
  24509. if ( value !== undefined ) {
  24510. times.push( key.time );
  24511. values.push( value );
  24512. }
  24513. key = jsonKeys[ i ++ ];
  24514. } while ( key !== undefined );
  24515. }
  24516. }
  24517. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  24518. const clip = sourceClip.clone();
  24519. clip.name = name;
  24520. const tracks = [];
  24521. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24522. const track = clip.tracks[ i ];
  24523. const valueSize = track.getValueSize();
  24524. const times = [];
  24525. const values = [];
  24526. for ( let j = 0; j < track.times.length; ++ j ) {
  24527. const frame = track.times[ j ] * fps;
  24528. if ( frame < startFrame || frame >= endFrame ) continue;
  24529. times.push( track.times[ j ] );
  24530. for ( let k = 0; k < valueSize; ++ k ) {
  24531. values.push( track.values[ j * valueSize + k ] );
  24532. }
  24533. }
  24534. if ( times.length === 0 ) continue;
  24535. track.times = convertArray( times, track.times.constructor );
  24536. track.values = convertArray( values, track.values.constructor );
  24537. tracks.push( track );
  24538. }
  24539. clip.tracks = tracks;
  24540. // find minimum .times value across all tracks in the trimmed clip
  24541. let minStartTime = Infinity;
  24542. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24543. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  24544. minStartTime = clip.tracks[ i ].times[ 0 ];
  24545. }
  24546. }
  24547. // shift all tracks such that clip begins at t=0
  24548. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24549. clip.tracks[ i ].shift( - 1 * minStartTime );
  24550. }
  24551. clip.resetDuration();
  24552. return clip;
  24553. }
  24554. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  24555. if ( fps <= 0 ) fps = 30;
  24556. const numTracks = referenceClip.tracks.length;
  24557. const referenceTime = referenceFrame / fps;
  24558. // Make each track's values relative to the values at the reference frame
  24559. for ( let i = 0; i < numTracks; ++ i ) {
  24560. const referenceTrack = referenceClip.tracks[ i ];
  24561. const referenceTrackType = referenceTrack.ValueTypeName;
  24562. // Skip this track if it's non-numeric
  24563. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  24564. // Find the track in the target clip whose name and type matches the reference track
  24565. const targetTrack = targetClip.tracks.find( function ( track ) {
  24566. return track.name === referenceTrack.name
  24567. && track.ValueTypeName === referenceTrackType;
  24568. } );
  24569. if ( targetTrack === undefined ) continue;
  24570. let referenceOffset = 0;
  24571. const referenceValueSize = referenceTrack.getValueSize();
  24572. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24573. referenceOffset = referenceValueSize / 3;
  24574. }
  24575. let targetOffset = 0;
  24576. const targetValueSize = targetTrack.getValueSize();
  24577. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24578. targetOffset = targetValueSize / 3;
  24579. }
  24580. const lastIndex = referenceTrack.times.length - 1;
  24581. let referenceValue;
  24582. // Find the value to subtract out of the track
  24583. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  24584. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  24585. const startIndex = referenceOffset;
  24586. const endIndex = referenceValueSize - referenceOffset;
  24587. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24588. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  24589. // Reference frame is after the last keyframe, so just use the last keyframe
  24590. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  24591. const endIndex = startIndex + referenceValueSize - referenceOffset;
  24592. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24593. } else {
  24594. // Interpolate to the reference value
  24595. const interpolant = referenceTrack.createInterpolant();
  24596. const startIndex = referenceOffset;
  24597. const endIndex = referenceValueSize - referenceOffset;
  24598. interpolant.evaluate( referenceTime );
  24599. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  24600. }
  24601. // Conjugate the quaternion
  24602. if ( referenceTrackType === 'quaternion' ) {
  24603. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  24604. referenceQuat.toArray( referenceValue );
  24605. }
  24606. // Subtract the reference value from all of the track values
  24607. const numTimes = targetTrack.times.length;
  24608. for ( let j = 0; j < numTimes; ++ j ) {
  24609. const valueStart = j * targetValueSize + targetOffset;
  24610. if ( referenceTrackType === 'quaternion' ) {
  24611. // Multiply the conjugate for quaternion track types
  24612. Quaternion.multiplyQuaternionsFlat(
  24613. targetTrack.values,
  24614. valueStart,
  24615. referenceValue,
  24616. 0,
  24617. targetTrack.values,
  24618. valueStart
  24619. );
  24620. } else {
  24621. const valueEnd = targetValueSize - targetOffset * 2;
  24622. // Subtract each value for all other numeric track types
  24623. for ( let k = 0; k < valueEnd; ++ k ) {
  24624. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  24625. }
  24626. }
  24627. }
  24628. }
  24629. targetClip.blendMode = AdditiveAnimationBlendMode;
  24630. return targetClip;
  24631. }
  24632. const AnimationUtils = {
  24633. convertArray: convertArray,
  24634. isTypedArray: isTypedArray,
  24635. getKeyframeOrder: getKeyframeOrder,
  24636. sortedArray: sortedArray,
  24637. flattenJSON: flattenJSON,
  24638. subclip: subclip,
  24639. makeClipAdditive: makeClipAdditive
  24640. };
  24641. /**
  24642. * Abstract base class of interpolants over parametric samples.
  24643. *
  24644. * The parameter domain is one dimensional, typically the time or a path
  24645. * along a curve defined by the data.
  24646. *
  24647. * The sample values can have any dimensionality and derived classes may
  24648. * apply special interpretations to the data.
  24649. *
  24650. * This class provides the interval seek in a Template Method, deferring
  24651. * the actual interpolation to derived classes.
  24652. *
  24653. * Time complexity is O(1) for linear access crossing at most two points
  24654. * and O(log N) for random access, where N is the number of positions.
  24655. *
  24656. * References:
  24657. *
  24658. * http://www.oodesign.com/template-method-pattern.html
  24659. *
  24660. */
  24661. class Interpolant {
  24662. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24663. this.parameterPositions = parameterPositions;
  24664. this._cachedIndex = 0;
  24665. this.resultBuffer = resultBuffer !== undefined ?
  24666. resultBuffer : new sampleValues.constructor( sampleSize );
  24667. this.sampleValues = sampleValues;
  24668. this.valueSize = sampleSize;
  24669. this.settings = null;
  24670. this.DefaultSettings_ = {};
  24671. }
  24672. evaluate( t ) {
  24673. const pp = this.parameterPositions;
  24674. let i1 = this._cachedIndex,
  24675. t1 = pp[ i1 ],
  24676. t0 = pp[ i1 - 1 ];
  24677. validate_interval: {
  24678. seek: {
  24679. let right;
  24680. linear_scan: {
  24681. //- See http://jsperf.com/comparison-to-undefined/3
  24682. //- slower code:
  24683. //-
  24684. //- if ( t >= t1 || t1 === undefined ) {
  24685. forward_scan: if ( ! ( t < t1 ) ) {
  24686. for ( let giveUpAt = i1 + 2; ; ) {
  24687. if ( t1 === undefined ) {
  24688. if ( t < t0 ) break forward_scan;
  24689. // after end
  24690. i1 = pp.length;
  24691. this._cachedIndex = i1;
  24692. return this.copySampleValue_( i1 - 1 );
  24693. }
  24694. if ( i1 === giveUpAt ) break; // this loop
  24695. t0 = t1;
  24696. t1 = pp[ ++ i1 ];
  24697. if ( t < t1 ) {
  24698. // we have arrived at the sought interval
  24699. break seek;
  24700. }
  24701. }
  24702. // prepare binary search on the right side of the index
  24703. right = pp.length;
  24704. break linear_scan;
  24705. }
  24706. //- slower code:
  24707. //- if ( t < t0 || t0 === undefined ) {
  24708. if ( ! ( t >= t0 ) ) {
  24709. // looping?
  24710. const t1global = pp[ 1 ];
  24711. if ( t < t1global ) {
  24712. i1 = 2; // + 1, using the scan for the details
  24713. t0 = t1global;
  24714. }
  24715. // linear reverse scan
  24716. for ( let giveUpAt = i1 - 2; ; ) {
  24717. if ( t0 === undefined ) {
  24718. // before start
  24719. this._cachedIndex = 0;
  24720. return this.copySampleValue_( 0 );
  24721. }
  24722. if ( i1 === giveUpAt ) break; // this loop
  24723. t1 = t0;
  24724. t0 = pp[ -- i1 - 1 ];
  24725. if ( t >= t0 ) {
  24726. // we have arrived at the sought interval
  24727. break seek;
  24728. }
  24729. }
  24730. // prepare binary search on the left side of the index
  24731. right = i1;
  24732. i1 = 0;
  24733. break linear_scan;
  24734. }
  24735. // the interval is valid
  24736. break validate_interval;
  24737. } // linear scan
  24738. // binary search
  24739. while ( i1 < right ) {
  24740. const mid = ( i1 + right ) >>> 1;
  24741. if ( t < pp[ mid ] ) {
  24742. right = mid;
  24743. } else {
  24744. i1 = mid + 1;
  24745. }
  24746. }
  24747. t1 = pp[ i1 ];
  24748. t0 = pp[ i1 - 1 ];
  24749. // check boundary cases, again
  24750. if ( t0 === undefined ) {
  24751. this._cachedIndex = 0;
  24752. return this.copySampleValue_( 0 );
  24753. }
  24754. if ( t1 === undefined ) {
  24755. i1 = pp.length;
  24756. this._cachedIndex = i1;
  24757. return this.copySampleValue_( i1 - 1 );
  24758. }
  24759. } // seek
  24760. this._cachedIndex = i1;
  24761. this.intervalChanged_( i1, t0, t1 );
  24762. } // validate_interval
  24763. return this.interpolate_( i1, t0, t, t1 );
  24764. }
  24765. getSettings_() {
  24766. return this.settings || this.DefaultSettings_;
  24767. }
  24768. copySampleValue_( index ) {
  24769. // copies a sample value to the result buffer
  24770. const result = this.resultBuffer,
  24771. values = this.sampleValues,
  24772. stride = this.valueSize,
  24773. offset = index * stride;
  24774. for ( let i = 0; i !== stride; ++ i ) {
  24775. result[ i ] = values[ offset + i ];
  24776. }
  24777. return result;
  24778. }
  24779. // Template methods for derived classes:
  24780. interpolate_( /* i1, t0, t, t1 */ ) {
  24781. throw new Error( 'call to abstract method' );
  24782. // implementations shall return this.resultBuffer
  24783. }
  24784. intervalChanged_( /* i1, t0, t1 */ ) {
  24785. // empty
  24786. }
  24787. }
  24788. /**
  24789. * Fast and simple cubic spline interpolant.
  24790. *
  24791. * It was derived from a Hermitian construction setting the first derivative
  24792. * at each sample position to the linear slope between neighboring positions
  24793. * over their parameter interval.
  24794. */
  24795. class CubicInterpolant extends Interpolant {
  24796. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24797. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24798. this._weightPrev = - 0;
  24799. this._offsetPrev = - 0;
  24800. this._weightNext = - 0;
  24801. this._offsetNext = - 0;
  24802. this.DefaultSettings_ = {
  24803. endingStart: ZeroCurvatureEnding,
  24804. endingEnd: ZeroCurvatureEnding
  24805. };
  24806. }
  24807. intervalChanged_( i1, t0, t1 ) {
  24808. const pp = this.parameterPositions;
  24809. let iPrev = i1 - 2,
  24810. iNext = i1 + 1,
  24811. tPrev = pp[ iPrev ],
  24812. tNext = pp[ iNext ];
  24813. if ( tPrev === undefined ) {
  24814. switch ( this.getSettings_().endingStart ) {
  24815. case ZeroSlopeEnding:
  24816. // f'(t0) = 0
  24817. iPrev = i1;
  24818. tPrev = 2 * t0 - t1;
  24819. break;
  24820. case WrapAroundEnding:
  24821. // use the other end of the curve
  24822. iPrev = pp.length - 2;
  24823. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  24824. break;
  24825. default: // ZeroCurvatureEnding
  24826. // f''(t0) = 0 a.k.a. Natural Spline
  24827. iPrev = i1;
  24828. tPrev = t1;
  24829. }
  24830. }
  24831. if ( tNext === undefined ) {
  24832. switch ( this.getSettings_().endingEnd ) {
  24833. case ZeroSlopeEnding:
  24834. // f'(tN) = 0
  24835. iNext = i1;
  24836. tNext = 2 * t1 - t0;
  24837. break;
  24838. case WrapAroundEnding:
  24839. // use the other end of the curve
  24840. iNext = 1;
  24841. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  24842. break;
  24843. default: // ZeroCurvatureEnding
  24844. // f''(tN) = 0, a.k.a. Natural Spline
  24845. iNext = i1 - 1;
  24846. tNext = t0;
  24847. }
  24848. }
  24849. const halfDt = ( t1 - t0 ) * 0.5,
  24850. stride = this.valueSize;
  24851. this._weightPrev = halfDt / ( t0 - tPrev );
  24852. this._weightNext = halfDt / ( tNext - t1 );
  24853. this._offsetPrev = iPrev * stride;
  24854. this._offsetNext = iNext * stride;
  24855. }
  24856. interpolate_( i1, t0, t, t1 ) {
  24857. const result = this.resultBuffer,
  24858. values = this.sampleValues,
  24859. stride = this.valueSize,
  24860. o1 = i1 * stride, o0 = o1 - stride,
  24861. oP = this._offsetPrev, oN = this._offsetNext,
  24862. wP = this._weightPrev, wN = this._weightNext,
  24863. p = ( t - t0 ) / ( t1 - t0 ),
  24864. pp = p * p,
  24865. ppp = pp * p;
  24866. // evaluate polynomials
  24867. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  24868. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  24869. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  24870. const sN = wN * ppp - wN * pp;
  24871. // combine data linearly
  24872. for ( let i = 0; i !== stride; ++ i ) {
  24873. result[ i ] =
  24874. sP * values[ oP + i ] +
  24875. s0 * values[ o0 + i ] +
  24876. s1 * values[ o1 + i ] +
  24877. sN * values[ oN + i ];
  24878. }
  24879. return result;
  24880. }
  24881. }
  24882. class LinearInterpolant extends Interpolant {
  24883. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24884. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24885. }
  24886. interpolate_( i1, t0, t, t1 ) {
  24887. const result = this.resultBuffer,
  24888. values = this.sampleValues,
  24889. stride = this.valueSize,
  24890. offset1 = i1 * stride,
  24891. offset0 = offset1 - stride,
  24892. weight1 = ( t - t0 ) / ( t1 - t0 ),
  24893. weight0 = 1 - weight1;
  24894. for ( let i = 0; i !== stride; ++ i ) {
  24895. result[ i ] =
  24896. values[ offset0 + i ] * weight0 +
  24897. values[ offset1 + i ] * weight1;
  24898. }
  24899. return result;
  24900. }
  24901. }
  24902. /**
  24903. *
  24904. * Interpolant that evaluates to the sample value at the position preceding
  24905. * the parameter.
  24906. */
  24907. class DiscreteInterpolant extends Interpolant {
  24908. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24909. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24910. }
  24911. interpolate_( i1 /*, t0, t, t1 */ ) {
  24912. return this.copySampleValue_( i1 - 1 );
  24913. }
  24914. }
  24915. class KeyframeTrack {
  24916. constructor( name, times, values, interpolation ) {
  24917. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  24918. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  24919. this.name = name;
  24920. this.times = convertArray( times, this.TimeBufferType );
  24921. this.values = convertArray( values, this.ValueBufferType );
  24922. this.setInterpolation( interpolation || this.DefaultInterpolation );
  24923. }
  24924. // Serialization (in static context, because of constructor invocation
  24925. // and automatic invocation of .toJSON):
  24926. static toJSON( track ) {
  24927. const trackType = track.constructor;
  24928. let json;
  24929. // derived classes can define a static toJSON method
  24930. if ( trackType.toJSON !== this.toJSON ) {
  24931. json = trackType.toJSON( track );
  24932. } else {
  24933. // by default, we assume the data can be serialized as-is
  24934. json = {
  24935. 'name': track.name,
  24936. 'times': convertArray( track.times, Array ),
  24937. 'values': convertArray( track.values, Array )
  24938. };
  24939. const interpolation = track.getInterpolation();
  24940. if ( interpolation !== track.DefaultInterpolation ) {
  24941. json.interpolation = interpolation;
  24942. }
  24943. }
  24944. json.type = track.ValueTypeName; // mandatory
  24945. return json;
  24946. }
  24947. InterpolantFactoryMethodDiscrete( result ) {
  24948. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  24949. }
  24950. InterpolantFactoryMethodLinear( result ) {
  24951. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24952. }
  24953. InterpolantFactoryMethodSmooth( result ) {
  24954. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  24955. }
  24956. setInterpolation( interpolation ) {
  24957. let factoryMethod;
  24958. switch ( interpolation ) {
  24959. case InterpolateDiscrete:
  24960. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  24961. break;
  24962. case InterpolateLinear:
  24963. factoryMethod = this.InterpolantFactoryMethodLinear;
  24964. break;
  24965. case InterpolateSmooth:
  24966. factoryMethod = this.InterpolantFactoryMethodSmooth;
  24967. break;
  24968. }
  24969. if ( factoryMethod === undefined ) {
  24970. const message = 'unsupported interpolation for ' +
  24971. this.ValueTypeName + ' keyframe track named ' + this.name;
  24972. if ( this.createInterpolant === undefined ) {
  24973. // fall back to default, unless the default itself is messed up
  24974. if ( interpolation !== this.DefaultInterpolation ) {
  24975. this.setInterpolation( this.DefaultInterpolation );
  24976. } else {
  24977. throw new Error( message ); // fatal, in this case
  24978. }
  24979. }
  24980. console.warn( 'THREE.KeyframeTrack:', message );
  24981. return this;
  24982. }
  24983. this.createInterpolant = factoryMethod;
  24984. return this;
  24985. }
  24986. getInterpolation() {
  24987. switch ( this.createInterpolant ) {
  24988. case this.InterpolantFactoryMethodDiscrete:
  24989. return InterpolateDiscrete;
  24990. case this.InterpolantFactoryMethodLinear:
  24991. return InterpolateLinear;
  24992. case this.InterpolantFactoryMethodSmooth:
  24993. return InterpolateSmooth;
  24994. }
  24995. }
  24996. getValueSize() {
  24997. return this.values.length / this.times.length;
  24998. }
  24999. // move all keyframes either forwards or backwards in time
  25000. shift( timeOffset ) {
  25001. if ( timeOffset !== 0.0 ) {
  25002. const times = this.times;
  25003. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25004. times[ i ] += timeOffset;
  25005. }
  25006. }
  25007. return this;
  25008. }
  25009. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25010. scale( timeScale ) {
  25011. if ( timeScale !== 1.0 ) {
  25012. const times = this.times;
  25013. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25014. times[ i ] *= timeScale;
  25015. }
  25016. }
  25017. return this;
  25018. }
  25019. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25020. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25021. trim( startTime, endTime ) {
  25022. const times = this.times,
  25023. nKeys = times.length;
  25024. let from = 0,
  25025. to = nKeys - 1;
  25026. while ( from !== nKeys && times[ from ] < startTime ) {
  25027. ++ from;
  25028. }
  25029. while ( to !== - 1 && times[ to ] > endTime ) {
  25030. -- to;
  25031. }
  25032. ++ to; // inclusive -> exclusive bound
  25033. if ( from !== 0 || to !== nKeys ) {
  25034. // empty tracks are forbidden, so keep at least one keyframe
  25035. if ( from >= to ) {
  25036. to = Math.max( to, 1 );
  25037. from = to - 1;
  25038. }
  25039. const stride = this.getValueSize();
  25040. this.times = times.slice( from, to );
  25041. this.values = this.values.slice( from * stride, to * stride );
  25042. }
  25043. return this;
  25044. }
  25045. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25046. validate() {
  25047. let valid = true;
  25048. const valueSize = this.getValueSize();
  25049. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25050. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25051. valid = false;
  25052. }
  25053. const times = this.times,
  25054. values = this.values,
  25055. nKeys = times.length;
  25056. if ( nKeys === 0 ) {
  25057. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25058. valid = false;
  25059. }
  25060. let prevTime = null;
  25061. for ( let i = 0; i !== nKeys; i ++ ) {
  25062. const currTime = times[ i ];
  25063. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25064. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25065. valid = false;
  25066. break;
  25067. }
  25068. if ( prevTime !== null && prevTime > currTime ) {
  25069. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25070. valid = false;
  25071. break;
  25072. }
  25073. prevTime = currTime;
  25074. }
  25075. if ( values !== undefined ) {
  25076. if ( isTypedArray( values ) ) {
  25077. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  25078. const value = values[ i ];
  25079. if ( isNaN( value ) ) {
  25080. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25081. valid = false;
  25082. break;
  25083. }
  25084. }
  25085. }
  25086. }
  25087. return valid;
  25088. }
  25089. // removes equivalent sequential keys as common in morph target sequences
  25090. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25091. optimize() {
  25092. // times or values may be shared with other tracks, so overwriting is unsafe
  25093. const times = this.times.slice(),
  25094. values = this.values.slice(),
  25095. stride = this.getValueSize(),
  25096. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25097. lastIndex = times.length - 1;
  25098. let writeIndex = 1;
  25099. for ( let i = 1; i < lastIndex; ++ i ) {
  25100. let keep = false;
  25101. const time = times[ i ];
  25102. const timeNext = times[ i + 1 ];
  25103. // remove adjacent keyframes scheduled at the same time
  25104. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  25105. if ( ! smoothInterpolation ) {
  25106. // remove unnecessary keyframes same as their neighbors
  25107. const offset = i * stride,
  25108. offsetP = offset - stride,
  25109. offsetN = offset + stride;
  25110. for ( let j = 0; j !== stride; ++ j ) {
  25111. const value = values[ offset + j ];
  25112. if ( value !== values[ offsetP + j ] ||
  25113. value !== values[ offsetN + j ] ) {
  25114. keep = true;
  25115. break;
  25116. }
  25117. }
  25118. } else {
  25119. keep = true;
  25120. }
  25121. }
  25122. // in-place compaction
  25123. if ( keep ) {
  25124. if ( i !== writeIndex ) {
  25125. times[ writeIndex ] = times[ i ];
  25126. const readOffset = i * stride,
  25127. writeOffset = writeIndex * stride;
  25128. for ( let j = 0; j !== stride; ++ j ) {
  25129. values[ writeOffset + j ] = values[ readOffset + j ];
  25130. }
  25131. }
  25132. ++ writeIndex;
  25133. }
  25134. }
  25135. // flush last keyframe (compaction looks ahead)
  25136. if ( lastIndex > 0 ) {
  25137. times[ writeIndex ] = times[ lastIndex ];
  25138. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25139. values[ writeOffset + j ] = values[ readOffset + j ];
  25140. }
  25141. ++ writeIndex;
  25142. }
  25143. if ( writeIndex !== times.length ) {
  25144. this.times = times.slice( 0, writeIndex );
  25145. this.values = values.slice( 0, writeIndex * stride );
  25146. } else {
  25147. this.times = times;
  25148. this.values = values;
  25149. }
  25150. return this;
  25151. }
  25152. clone() {
  25153. const times = this.times.slice();
  25154. const values = this.values.slice();
  25155. const TypedKeyframeTrack = this.constructor;
  25156. const track = new TypedKeyframeTrack( this.name, times, values );
  25157. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  25158. track.createInterpolant = this.createInterpolant;
  25159. return track;
  25160. }
  25161. }
  25162. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  25163. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  25164. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25165. /**
  25166. * A Track of Boolean keyframe values.
  25167. */
  25168. class BooleanKeyframeTrack extends KeyframeTrack {}
  25169. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  25170. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  25171. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25172. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25173. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25174. /**
  25175. * A Track of keyframe values that represent color.
  25176. */
  25177. class ColorKeyframeTrack extends KeyframeTrack {}
  25178. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  25179. /**
  25180. * A Track of numeric keyframe values.
  25181. */
  25182. class NumberKeyframeTrack extends KeyframeTrack {}
  25183. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  25184. /**
  25185. * Spherical linear unit quaternion interpolant.
  25186. */
  25187. class QuaternionLinearInterpolant extends Interpolant {
  25188. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25189. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25190. }
  25191. interpolate_( i1, t0, t, t1 ) {
  25192. const result = this.resultBuffer,
  25193. values = this.sampleValues,
  25194. stride = this.valueSize,
  25195. alpha = ( t - t0 ) / ( t1 - t0 );
  25196. let offset = i1 * stride;
  25197. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  25198. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  25199. }
  25200. return result;
  25201. }
  25202. }
  25203. /**
  25204. * A Track of quaternion keyframe values.
  25205. */
  25206. class QuaternionKeyframeTrack extends KeyframeTrack {
  25207. InterpolantFactoryMethodLinear( result ) {
  25208. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25209. }
  25210. }
  25211. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  25212. // ValueBufferType is inherited
  25213. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25214. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25215. /**
  25216. * A Track that interpolates Strings
  25217. */
  25218. class StringKeyframeTrack extends KeyframeTrack {}
  25219. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  25220. StringKeyframeTrack.prototype.ValueBufferType = Array;
  25221. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25222. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25223. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25224. /**
  25225. * A Track of vectored keyframe values.
  25226. */
  25227. class VectorKeyframeTrack extends KeyframeTrack {}
  25228. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  25229. class AnimationClip {
  25230. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  25231. this.name = name;
  25232. this.tracks = tracks;
  25233. this.duration = duration;
  25234. this.blendMode = blendMode;
  25235. this.uuid = generateUUID();
  25236. // this means it should figure out its duration by scanning the tracks
  25237. if ( this.duration < 0 ) {
  25238. this.resetDuration();
  25239. }
  25240. }
  25241. static parse( json ) {
  25242. const tracks = [],
  25243. jsonTracks = json.tracks,
  25244. frameTime = 1.0 / ( json.fps || 1.0 );
  25245. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25246. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25247. }
  25248. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  25249. clip.uuid = json.uuid;
  25250. return clip;
  25251. }
  25252. static toJSON( clip ) {
  25253. const tracks = [],
  25254. clipTracks = clip.tracks;
  25255. const json = {
  25256. 'name': clip.name,
  25257. 'duration': clip.duration,
  25258. 'tracks': tracks,
  25259. 'uuid': clip.uuid,
  25260. 'blendMode': clip.blendMode
  25261. };
  25262. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25263. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25264. }
  25265. return json;
  25266. }
  25267. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  25268. const numMorphTargets = morphTargetSequence.length;
  25269. const tracks = [];
  25270. for ( let i = 0; i < numMorphTargets; i ++ ) {
  25271. let times = [];
  25272. let values = [];
  25273. times.push(
  25274. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25275. i,
  25276. ( i + 1 ) % numMorphTargets );
  25277. values.push( 0, 1, 0 );
  25278. const order = getKeyframeOrder( times );
  25279. times = sortedArray( times, 1, order );
  25280. values = sortedArray( values, 1, order );
  25281. // if there is a key at the first frame, duplicate it as the
  25282. // last frame as well for perfect loop.
  25283. if ( ! noLoop && times[ 0 ] === 0 ) {
  25284. times.push( numMorphTargets );
  25285. values.push( values[ 0 ] );
  25286. }
  25287. tracks.push(
  25288. new NumberKeyframeTrack(
  25289. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25290. times, values
  25291. ).scale( 1.0 / fps ) );
  25292. }
  25293. return new this( name, - 1, tracks );
  25294. }
  25295. static findByName( objectOrClipArray, name ) {
  25296. let clipArray = objectOrClipArray;
  25297. if ( ! Array.isArray( objectOrClipArray ) ) {
  25298. const o = objectOrClipArray;
  25299. clipArray = o.geometry && o.geometry.animations || o.animations;
  25300. }
  25301. for ( let i = 0; i < clipArray.length; i ++ ) {
  25302. if ( clipArray[ i ].name === name ) {
  25303. return clipArray[ i ];
  25304. }
  25305. }
  25306. return null;
  25307. }
  25308. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  25309. const animationToMorphTargets = {};
  25310. // tested with https://regex101.com/ on trick sequences
  25311. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25312. const pattern = /^([\w-]*?)([\d]+)$/;
  25313. // sort morph target names into animation groups based
  25314. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25315. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  25316. const morphTarget = morphTargets[ i ];
  25317. const parts = morphTarget.name.match( pattern );
  25318. if ( parts && parts.length > 1 ) {
  25319. const name = parts[ 1 ];
  25320. let animationMorphTargets = animationToMorphTargets[ name ];
  25321. if ( ! animationMorphTargets ) {
  25322. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25323. }
  25324. animationMorphTargets.push( morphTarget );
  25325. }
  25326. }
  25327. const clips = [];
  25328. for ( const name in animationToMorphTargets ) {
  25329. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25330. }
  25331. return clips;
  25332. }
  25333. // parse the animation.hierarchy format
  25334. static parseAnimation( animation, bones ) {
  25335. if ( ! animation ) {
  25336. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25337. return null;
  25338. }
  25339. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25340. // only return track if there are actually keys.
  25341. if ( animationKeys.length !== 0 ) {
  25342. const times = [];
  25343. const values = [];
  25344. flattenJSON( animationKeys, times, values, propertyName );
  25345. // empty keys are filtered out, so check again
  25346. if ( times.length !== 0 ) {
  25347. destTracks.push( new trackType( trackName, times, values ) );
  25348. }
  25349. }
  25350. };
  25351. const tracks = [];
  25352. const clipName = animation.name || 'default';
  25353. const fps = animation.fps || 30;
  25354. const blendMode = animation.blendMode;
  25355. // automatic length determination in AnimationClip.
  25356. let duration = animation.length || - 1;
  25357. const hierarchyTracks = animation.hierarchy || [];
  25358. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  25359. const animationKeys = hierarchyTracks[ h ].keys;
  25360. // skip empty tracks
  25361. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25362. // process morph targets
  25363. if ( animationKeys[ 0 ].morphTargets ) {
  25364. // figure out all morph targets used in this track
  25365. const morphTargetNames = {};
  25366. let k;
  25367. for ( k = 0; k < animationKeys.length; k ++ ) {
  25368. if ( animationKeys[ k ].morphTargets ) {
  25369. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25370. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25371. }
  25372. }
  25373. }
  25374. // create a track for each morph target with all zero
  25375. // morphTargetInfluences except for the keys in which
  25376. // the morphTarget is named.
  25377. for ( const morphTargetName in morphTargetNames ) {
  25378. const times = [];
  25379. const values = [];
  25380. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25381. const animationKey = animationKeys[ k ];
  25382. times.push( animationKey.time );
  25383. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25384. }
  25385. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25386. }
  25387. duration = morphTargetNames.length * fps;
  25388. } else {
  25389. // ...assume skeletal animation
  25390. const boneName = '.bones[' + bones[ h ].name + ']';
  25391. addNonemptyTrack(
  25392. VectorKeyframeTrack, boneName + '.position',
  25393. animationKeys, 'pos', tracks );
  25394. addNonemptyTrack(
  25395. QuaternionKeyframeTrack, boneName + '.quaternion',
  25396. animationKeys, 'rot', tracks );
  25397. addNonemptyTrack(
  25398. VectorKeyframeTrack, boneName + '.scale',
  25399. animationKeys, 'scl', tracks );
  25400. }
  25401. }
  25402. if ( tracks.length === 0 ) {
  25403. return null;
  25404. }
  25405. const clip = new this( clipName, duration, tracks, blendMode );
  25406. return clip;
  25407. }
  25408. resetDuration() {
  25409. const tracks = this.tracks;
  25410. let duration = 0;
  25411. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  25412. const track = this.tracks[ i ];
  25413. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25414. }
  25415. this.duration = duration;
  25416. return this;
  25417. }
  25418. trim() {
  25419. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25420. this.tracks[ i ].trim( 0, this.duration );
  25421. }
  25422. return this;
  25423. }
  25424. validate() {
  25425. let valid = true;
  25426. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25427. valid = valid && this.tracks[ i ].validate();
  25428. }
  25429. return valid;
  25430. }
  25431. optimize() {
  25432. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25433. this.tracks[ i ].optimize();
  25434. }
  25435. return this;
  25436. }
  25437. clone() {
  25438. const tracks = [];
  25439. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25440. tracks.push( this.tracks[ i ].clone() );
  25441. }
  25442. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  25443. }
  25444. toJSON() {
  25445. return this.constructor.toJSON( this );
  25446. }
  25447. }
  25448. function getTrackTypeForValueTypeName( typeName ) {
  25449. switch ( typeName.toLowerCase() ) {
  25450. case 'scalar':
  25451. case 'double':
  25452. case 'float':
  25453. case 'number':
  25454. case 'integer':
  25455. return NumberKeyframeTrack;
  25456. case 'vector':
  25457. case 'vector2':
  25458. case 'vector3':
  25459. case 'vector4':
  25460. return VectorKeyframeTrack;
  25461. case 'color':
  25462. return ColorKeyframeTrack;
  25463. case 'quaternion':
  25464. return QuaternionKeyframeTrack;
  25465. case 'bool':
  25466. case 'boolean':
  25467. return BooleanKeyframeTrack;
  25468. case 'string':
  25469. return StringKeyframeTrack;
  25470. }
  25471. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  25472. }
  25473. function parseKeyframeTrack( json ) {
  25474. if ( json.type === undefined ) {
  25475. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  25476. }
  25477. const trackType = getTrackTypeForValueTypeName( json.type );
  25478. if ( json.times === undefined ) {
  25479. const times = [], values = [];
  25480. flattenJSON( json.keys, times, values, 'value' );
  25481. json.times = times;
  25482. json.values = values;
  25483. }
  25484. // derived classes can define a static parse method
  25485. if ( trackType.parse !== undefined ) {
  25486. return trackType.parse( json );
  25487. } else {
  25488. // by default, we assume a constructor compatible with the base
  25489. return new trackType( json.name, json.times, json.values, json.interpolation );
  25490. }
  25491. }
  25492. const Cache = {
  25493. enabled: false,
  25494. files: {},
  25495. add: function ( key, file ) {
  25496. if ( this.enabled === false ) return;
  25497. // console.log( 'THREE.Cache', 'Adding key:', key );
  25498. this.files[ key ] = file;
  25499. },
  25500. get: function ( key ) {
  25501. if ( this.enabled === false ) return;
  25502. // console.log( 'THREE.Cache', 'Checking key:', key );
  25503. return this.files[ key ];
  25504. },
  25505. remove: function ( key ) {
  25506. delete this.files[ key ];
  25507. },
  25508. clear: function () {
  25509. this.files = {};
  25510. }
  25511. };
  25512. class LoadingManager {
  25513. constructor( onLoad, onProgress, onError ) {
  25514. const scope = this;
  25515. let isLoading = false;
  25516. let itemsLoaded = 0;
  25517. let itemsTotal = 0;
  25518. let urlModifier = undefined;
  25519. const handlers = [];
  25520. // Refer to #5689 for the reason why we don't set .onStart
  25521. // in the constructor
  25522. this.onStart = undefined;
  25523. this.onLoad = onLoad;
  25524. this.onProgress = onProgress;
  25525. this.onError = onError;
  25526. this.itemStart = function ( url ) {
  25527. itemsTotal ++;
  25528. if ( isLoading === false ) {
  25529. if ( scope.onStart !== undefined ) {
  25530. scope.onStart( url, itemsLoaded, itemsTotal );
  25531. }
  25532. }
  25533. isLoading = true;
  25534. };
  25535. this.itemEnd = function ( url ) {
  25536. itemsLoaded ++;
  25537. if ( scope.onProgress !== undefined ) {
  25538. scope.onProgress( url, itemsLoaded, itemsTotal );
  25539. }
  25540. if ( itemsLoaded === itemsTotal ) {
  25541. isLoading = false;
  25542. if ( scope.onLoad !== undefined ) {
  25543. scope.onLoad();
  25544. }
  25545. }
  25546. };
  25547. this.itemError = function ( url ) {
  25548. if ( scope.onError !== undefined ) {
  25549. scope.onError( url );
  25550. }
  25551. };
  25552. this.resolveURL = function ( url ) {
  25553. if ( urlModifier ) {
  25554. return urlModifier( url );
  25555. }
  25556. return url;
  25557. };
  25558. this.setURLModifier = function ( transform ) {
  25559. urlModifier = transform;
  25560. return this;
  25561. };
  25562. this.addHandler = function ( regex, loader ) {
  25563. handlers.push( regex, loader );
  25564. return this;
  25565. };
  25566. this.removeHandler = function ( regex ) {
  25567. const index = handlers.indexOf( regex );
  25568. if ( index !== - 1 ) {
  25569. handlers.splice( index, 2 );
  25570. }
  25571. return this;
  25572. };
  25573. this.getHandler = function ( file ) {
  25574. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  25575. const regex = handlers[ i ];
  25576. const loader = handlers[ i + 1 ];
  25577. if ( regex.global ) regex.lastIndex = 0; // see #17920
  25578. if ( regex.test( file ) ) {
  25579. return loader;
  25580. }
  25581. }
  25582. return null;
  25583. };
  25584. }
  25585. }
  25586. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  25587. class Loader {
  25588. constructor( manager ) {
  25589. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25590. this.crossOrigin = 'anonymous';
  25591. this.withCredentials = false;
  25592. this.path = '';
  25593. this.resourcePath = '';
  25594. this.requestHeader = {};
  25595. }
  25596. load( /* url, onLoad, onProgress, onError */ ) {}
  25597. loadAsync( url, onProgress ) {
  25598. const scope = this;
  25599. return new Promise( function ( resolve, reject ) {
  25600. scope.load( url, resolve, onProgress, reject );
  25601. } );
  25602. }
  25603. parse( /* data */ ) {}
  25604. setCrossOrigin( crossOrigin ) {
  25605. this.crossOrigin = crossOrigin;
  25606. return this;
  25607. }
  25608. setWithCredentials( value ) {
  25609. this.withCredentials = value;
  25610. return this;
  25611. }
  25612. setPath( path ) {
  25613. this.path = path;
  25614. return this;
  25615. }
  25616. setResourcePath( resourcePath ) {
  25617. this.resourcePath = resourcePath;
  25618. return this;
  25619. }
  25620. setRequestHeader( requestHeader ) {
  25621. this.requestHeader = requestHeader;
  25622. return this;
  25623. }
  25624. }
  25625. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  25626. const loading = {};
  25627. class HttpError extends Error {
  25628. constructor( message, response ) {
  25629. super( message );
  25630. this.response = response;
  25631. }
  25632. }
  25633. class FileLoader extends Loader {
  25634. constructor( manager ) {
  25635. super( manager );
  25636. }
  25637. load( url, onLoad, onProgress, onError ) {
  25638. if ( url === undefined ) url = '';
  25639. if ( this.path !== undefined ) url = this.path + url;
  25640. url = this.manager.resolveURL( url );
  25641. const cached = Cache.get( url );
  25642. if ( cached !== undefined ) {
  25643. this.manager.itemStart( url );
  25644. setTimeout( () => {
  25645. if ( onLoad ) onLoad( cached );
  25646. this.manager.itemEnd( url );
  25647. }, 0 );
  25648. return cached;
  25649. }
  25650. // Check if request is duplicate
  25651. if ( loading[ url ] !== undefined ) {
  25652. loading[ url ].push( {
  25653. onLoad: onLoad,
  25654. onProgress: onProgress,
  25655. onError: onError
  25656. } );
  25657. return;
  25658. }
  25659. // Initialise array for duplicate requests
  25660. loading[ url ] = [];
  25661. loading[ url ].push( {
  25662. onLoad: onLoad,
  25663. onProgress: onProgress,
  25664. onError: onError,
  25665. } );
  25666. // create request
  25667. const req = new Request( url, {
  25668. headers: new Headers( this.requestHeader ),
  25669. credentials: this.withCredentials ? 'include' : 'same-origin',
  25670. // An abort controller could be added within a future PR
  25671. } );
  25672. // record states ( avoid data race )
  25673. const mimeType = this.mimeType;
  25674. const responseType = this.responseType;
  25675. // start the fetch
  25676. fetch( req )
  25677. .then( response => {
  25678. if ( response.status === 200 || response.status === 0 ) {
  25679. // Some browsers return HTTP Status 0 when using non-http protocol
  25680. // e.g. 'file://' or 'data://'. Handle as success.
  25681. if ( response.status === 0 ) {
  25682. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  25683. }
  25684. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  25685. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  25686. return response;
  25687. }
  25688. const callbacks = loading[ url ];
  25689. const reader = response.body.getReader();
  25690. // Nginx needs X-File-Size check
  25691. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  25692. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  25693. const total = contentLength ? parseInt( contentLength ) : 0;
  25694. const lengthComputable = total !== 0;
  25695. let loaded = 0;
  25696. // periodically read data into the new stream tracking while download progress
  25697. const stream = new ReadableStream( {
  25698. start( controller ) {
  25699. readData();
  25700. function readData() {
  25701. reader.read().then( ( { done, value } ) => {
  25702. if ( done ) {
  25703. controller.close();
  25704. } else {
  25705. loaded += value.byteLength;
  25706. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  25707. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25708. const callback = callbacks[ i ];
  25709. if ( callback.onProgress ) callback.onProgress( event );
  25710. }
  25711. controller.enqueue( value );
  25712. readData();
  25713. }
  25714. } );
  25715. }
  25716. }
  25717. } );
  25718. return new Response( stream );
  25719. } else {
  25720. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  25721. }
  25722. } )
  25723. .then( response => {
  25724. switch ( responseType ) {
  25725. case 'arraybuffer':
  25726. return response.arrayBuffer();
  25727. case 'blob':
  25728. return response.blob();
  25729. case 'document':
  25730. return response.text()
  25731. .then( text => {
  25732. const parser = new DOMParser();
  25733. return parser.parseFromString( text, mimeType );
  25734. } );
  25735. case 'json':
  25736. return response.json();
  25737. default:
  25738. if ( mimeType === undefined ) {
  25739. return response.text();
  25740. } else {
  25741. // sniff encoding
  25742. const re = /charset="?([^;"\s]*)"?/i;
  25743. const exec = re.exec( mimeType );
  25744. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  25745. const decoder = new TextDecoder( label );
  25746. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  25747. }
  25748. }
  25749. } )
  25750. .then( data => {
  25751. // Add to cache only on HTTP success, so that we do not cache
  25752. // error response bodies as proper responses to requests.
  25753. Cache.add( url, data );
  25754. const callbacks = loading[ url ];
  25755. delete loading[ url ];
  25756. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25757. const callback = callbacks[ i ];
  25758. if ( callback.onLoad ) callback.onLoad( data );
  25759. }
  25760. } )
  25761. .catch( err => {
  25762. // Abort errors and other errors are handled the same
  25763. const callbacks = loading[ url ];
  25764. if ( callbacks === undefined ) {
  25765. // When onLoad was called and url was deleted in `loading`
  25766. this.manager.itemError( url );
  25767. throw err;
  25768. }
  25769. delete loading[ url ];
  25770. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25771. const callback = callbacks[ i ];
  25772. if ( callback.onError ) callback.onError( err );
  25773. }
  25774. this.manager.itemError( url );
  25775. } )
  25776. .finally( () => {
  25777. this.manager.itemEnd( url );
  25778. } );
  25779. this.manager.itemStart( url );
  25780. }
  25781. setResponseType( value ) {
  25782. this.responseType = value;
  25783. return this;
  25784. }
  25785. setMimeType( value ) {
  25786. this.mimeType = value;
  25787. return this;
  25788. }
  25789. }
  25790. class AnimationLoader extends Loader {
  25791. constructor( manager ) {
  25792. super( manager );
  25793. }
  25794. load( url, onLoad, onProgress, onError ) {
  25795. const scope = this;
  25796. const loader = new FileLoader( this.manager );
  25797. loader.setPath( this.path );
  25798. loader.setRequestHeader( this.requestHeader );
  25799. loader.setWithCredentials( this.withCredentials );
  25800. loader.load( url, function ( text ) {
  25801. try {
  25802. onLoad( scope.parse( JSON.parse( text ) ) );
  25803. } catch ( e ) {
  25804. if ( onError ) {
  25805. onError( e );
  25806. } else {
  25807. console.error( e );
  25808. }
  25809. scope.manager.itemError( url );
  25810. }
  25811. }, onProgress, onError );
  25812. }
  25813. parse( json ) {
  25814. const animations = [];
  25815. for ( let i = 0; i < json.length; i ++ ) {
  25816. const clip = AnimationClip.parse( json[ i ] );
  25817. animations.push( clip );
  25818. }
  25819. return animations;
  25820. }
  25821. }
  25822. /**
  25823. * Abstract Base class to block based textures loader (dds, pvr, ...)
  25824. *
  25825. * Sub classes have to implement the parse() method which will be used in load().
  25826. */
  25827. class CompressedTextureLoader extends Loader {
  25828. constructor( manager ) {
  25829. super( manager );
  25830. }
  25831. load( url, onLoad, onProgress, onError ) {
  25832. const scope = this;
  25833. const images = [];
  25834. const texture = new CompressedTexture();
  25835. const loader = new FileLoader( this.manager );
  25836. loader.setPath( this.path );
  25837. loader.setResponseType( 'arraybuffer' );
  25838. loader.setRequestHeader( this.requestHeader );
  25839. loader.setWithCredentials( scope.withCredentials );
  25840. let loaded = 0;
  25841. function loadTexture( i ) {
  25842. loader.load( url[ i ], function ( buffer ) {
  25843. const texDatas = scope.parse( buffer, true );
  25844. images[ i ] = {
  25845. width: texDatas.width,
  25846. height: texDatas.height,
  25847. format: texDatas.format,
  25848. mipmaps: texDatas.mipmaps
  25849. };
  25850. loaded += 1;
  25851. if ( loaded === 6 ) {
  25852. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  25853. texture.image = images;
  25854. texture.format = texDatas.format;
  25855. texture.needsUpdate = true;
  25856. if ( onLoad ) onLoad( texture );
  25857. }
  25858. }, onProgress, onError );
  25859. }
  25860. if ( Array.isArray( url ) ) {
  25861. for ( let i = 0, il = url.length; i < il; ++ i ) {
  25862. loadTexture( i );
  25863. }
  25864. } else {
  25865. // compressed cubemap texture stored in a single DDS file
  25866. loader.load( url, function ( buffer ) {
  25867. const texDatas = scope.parse( buffer, true );
  25868. if ( texDatas.isCubemap ) {
  25869. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  25870. for ( let f = 0; f < faces; f ++ ) {
  25871. images[ f ] = { mipmaps: [] };
  25872. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  25873. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  25874. images[ f ].format = texDatas.format;
  25875. images[ f ].width = texDatas.width;
  25876. images[ f ].height = texDatas.height;
  25877. }
  25878. }
  25879. texture.image = images;
  25880. } else {
  25881. texture.image.width = texDatas.width;
  25882. texture.image.height = texDatas.height;
  25883. texture.mipmaps = texDatas.mipmaps;
  25884. }
  25885. if ( texDatas.mipmapCount === 1 ) {
  25886. texture.minFilter = LinearFilter;
  25887. }
  25888. texture.format = texDatas.format;
  25889. texture.needsUpdate = true;
  25890. if ( onLoad ) onLoad( texture );
  25891. }, onProgress, onError );
  25892. }
  25893. return texture;
  25894. }
  25895. }
  25896. class ImageLoader extends Loader {
  25897. constructor( manager ) {
  25898. super( manager );
  25899. }
  25900. load( url, onLoad, onProgress, onError ) {
  25901. if ( this.path !== undefined ) url = this.path + url;
  25902. url = this.manager.resolveURL( url );
  25903. const scope = this;
  25904. const cached = Cache.get( url );
  25905. if ( cached !== undefined ) {
  25906. scope.manager.itemStart( url );
  25907. setTimeout( function () {
  25908. if ( onLoad ) onLoad( cached );
  25909. scope.manager.itemEnd( url );
  25910. }, 0 );
  25911. return cached;
  25912. }
  25913. const image = createElementNS( 'img' );
  25914. function onImageLoad() {
  25915. removeEventListeners();
  25916. Cache.add( url, this );
  25917. if ( onLoad ) onLoad( this );
  25918. scope.manager.itemEnd( url );
  25919. }
  25920. function onImageError( event ) {
  25921. removeEventListeners();
  25922. if ( onError ) onError( event );
  25923. scope.manager.itemError( url );
  25924. scope.manager.itemEnd( url );
  25925. }
  25926. function removeEventListeners() {
  25927. image.removeEventListener( 'load', onImageLoad, false );
  25928. image.removeEventListener( 'error', onImageError, false );
  25929. }
  25930. image.addEventListener( 'load', onImageLoad, false );
  25931. image.addEventListener( 'error', onImageError, false );
  25932. if ( url.slice( 0, 5 ) !== 'data:' ) {
  25933. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  25934. }
  25935. scope.manager.itemStart( url );
  25936. image.src = url;
  25937. return image;
  25938. }
  25939. }
  25940. class CubeTextureLoader extends Loader {
  25941. constructor( manager ) {
  25942. super( manager );
  25943. }
  25944. load( urls, onLoad, onProgress, onError ) {
  25945. const texture = new CubeTexture();
  25946. texture.colorSpace = SRGBColorSpace;
  25947. const loader = new ImageLoader( this.manager );
  25948. loader.setCrossOrigin( this.crossOrigin );
  25949. loader.setPath( this.path );
  25950. let loaded = 0;
  25951. function loadTexture( i ) {
  25952. loader.load( urls[ i ], function ( image ) {
  25953. texture.images[ i ] = image;
  25954. loaded ++;
  25955. if ( loaded === 6 ) {
  25956. texture.needsUpdate = true;
  25957. if ( onLoad ) onLoad( texture );
  25958. }
  25959. }, undefined, onError );
  25960. }
  25961. for ( let i = 0; i < urls.length; ++ i ) {
  25962. loadTexture( i );
  25963. }
  25964. return texture;
  25965. }
  25966. }
  25967. /**
  25968. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  25969. *
  25970. * Sub classes have to implement the parse() method which will be used in load().
  25971. */
  25972. class DataTextureLoader extends Loader {
  25973. constructor( manager ) {
  25974. super( manager );
  25975. }
  25976. load( url, onLoad, onProgress, onError ) {
  25977. const scope = this;
  25978. const texture = new DataTexture();
  25979. const loader = new FileLoader( this.manager );
  25980. loader.setResponseType( 'arraybuffer' );
  25981. loader.setRequestHeader( this.requestHeader );
  25982. loader.setPath( this.path );
  25983. loader.setWithCredentials( scope.withCredentials );
  25984. loader.load( url, function ( buffer ) {
  25985. let texData;
  25986. try {
  25987. texData = scope.parse( buffer );
  25988. } catch ( error ) {
  25989. if ( onError !== undefined ) {
  25990. onError( error );
  25991. } else {
  25992. console.error( error );
  25993. return;
  25994. }
  25995. }
  25996. if ( texData.image !== undefined ) {
  25997. texture.image = texData.image;
  25998. } else if ( texData.data !== undefined ) {
  25999. texture.image.width = texData.width;
  26000. texture.image.height = texData.height;
  26001. texture.image.data = texData.data;
  26002. }
  26003. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  26004. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  26005. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  26006. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  26007. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  26008. if ( texData.colorSpace !== undefined ) {
  26009. texture.colorSpace = texData.colorSpace;
  26010. }
  26011. if ( texData.flipY !== undefined ) {
  26012. texture.flipY = texData.flipY;
  26013. }
  26014. if ( texData.format !== undefined ) {
  26015. texture.format = texData.format;
  26016. }
  26017. if ( texData.type !== undefined ) {
  26018. texture.type = texData.type;
  26019. }
  26020. if ( texData.mipmaps !== undefined ) {
  26021. texture.mipmaps = texData.mipmaps;
  26022. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  26023. }
  26024. if ( texData.mipmapCount === 1 ) {
  26025. texture.minFilter = LinearFilter;
  26026. }
  26027. if ( texData.generateMipmaps !== undefined ) {
  26028. texture.generateMipmaps = texData.generateMipmaps;
  26029. }
  26030. texture.needsUpdate = true;
  26031. if ( onLoad ) onLoad( texture, texData );
  26032. }, onProgress, onError );
  26033. return texture;
  26034. }
  26035. }
  26036. class TextureLoader extends Loader {
  26037. constructor( manager ) {
  26038. super( manager );
  26039. }
  26040. load( url, onLoad, onProgress, onError ) {
  26041. const texture = new Texture();
  26042. const loader = new ImageLoader( this.manager );
  26043. loader.setCrossOrigin( this.crossOrigin );
  26044. loader.setPath( this.path );
  26045. loader.load( url, function ( image ) {
  26046. texture.image = image;
  26047. texture.needsUpdate = true;
  26048. if ( onLoad !== undefined ) {
  26049. onLoad( texture );
  26050. }
  26051. }, onProgress, onError );
  26052. return texture;
  26053. }
  26054. }
  26055. class Light extends Object3D {
  26056. constructor( color, intensity = 1 ) {
  26057. super();
  26058. this.isLight = true;
  26059. this.type = 'Light';
  26060. this.color = new Color( color );
  26061. this.intensity = intensity;
  26062. }
  26063. dispose() {
  26064. // Empty here in base class; some subclasses override.
  26065. }
  26066. copy( source, recursive ) {
  26067. super.copy( source, recursive );
  26068. this.color.copy( source.color );
  26069. this.intensity = source.intensity;
  26070. return this;
  26071. }
  26072. toJSON( meta ) {
  26073. const data = super.toJSON( meta );
  26074. data.object.color = this.color.getHex();
  26075. data.object.intensity = this.intensity;
  26076. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  26077. if ( this.distance !== undefined ) data.object.distance = this.distance;
  26078. if ( this.angle !== undefined ) data.object.angle = this.angle;
  26079. if ( this.decay !== undefined ) data.object.decay = this.decay;
  26080. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  26081. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  26082. return data;
  26083. }
  26084. }
  26085. class HemisphereLight extends Light {
  26086. constructor( skyColor, groundColor, intensity ) {
  26087. super( skyColor, intensity );
  26088. this.isHemisphereLight = true;
  26089. this.type = 'HemisphereLight';
  26090. this.position.copy( Object3D.DEFAULT_UP );
  26091. this.updateMatrix();
  26092. this.groundColor = new Color( groundColor );
  26093. }
  26094. copy( source, recursive ) {
  26095. super.copy( source, recursive );
  26096. this.groundColor.copy( source.groundColor );
  26097. return this;
  26098. }
  26099. }
  26100. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  26101. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  26102. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  26103. class LightShadow {
  26104. constructor( camera ) {
  26105. this.camera = camera;
  26106. this.bias = 0;
  26107. this.normalBias = 0;
  26108. this.radius = 1;
  26109. this.blurSamples = 8;
  26110. this.mapSize = new Vector2( 512, 512 );
  26111. this.map = null;
  26112. this.mapPass = null;
  26113. this.matrix = new Matrix4();
  26114. this.autoUpdate = true;
  26115. this.needsUpdate = false;
  26116. this._frustum = new Frustum();
  26117. this._frameExtents = new Vector2( 1, 1 );
  26118. this._viewportCount = 1;
  26119. this._viewports = [
  26120. new Vector4( 0, 0, 1, 1 )
  26121. ];
  26122. }
  26123. getViewportCount() {
  26124. return this._viewportCount;
  26125. }
  26126. getFrustum() {
  26127. return this._frustum;
  26128. }
  26129. updateMatrices( light ) {
  26130. const shadowCamera = this.camera;
  26131. const shadowMatrix = this.matrix;
  26132. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  26133. shadowCamera.position.copy( _lightPositionWorld$1 );
  26134. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  26135. shadowCamera.lookAt( _lookTarget$1 );
  26136. shadowCamera.updateMatrixWorld();
  26137. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  26138. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  26139. shadowMatrix.set(
  26140. 0.5, 0.0, 0.0, 0.5,
  26141. 0.0, 0.5, 0.0, 0.5,
  26142. 0.0, 0.0, 0.5, 0.5,
  26143. 0.0, 0.0, 0.0, 1.0
  26144. );
  26145. shadowMatrix.multiply( _projScreenMatrix$1 );
  26146. }
  26147. getViewport( viewportIndex ) {
  26148. return this._viewports[ viewportIndex ];
  26149. }
  26150. getFrameExtents() {
  26151. return this._frameExtents;
  26152. }
  26153. dispose() {
  26154. if ( this.map ) {
  26155. this.map.dispose();
  26156. }
  26157. if ( this.mapPass ) {
  26158. this.mapPass.dispose();
  26159. }
  26160. }
  26161. copy( source ) {
  26162. this.camera = source.camera.clone();
  26163. this.bias = source.bias;
  26164. this.radius = source.radius;
  26165. this.mapSize.copy( source.mapSize );
  26166. return this;
  26167. }
  26168. clone() {
  26169. return new this.constructor().copy( this );
  26170. }
  26171. toJSON() {
  26172. const object = {};
  26173. if ( this.bias !== 0 ) object.bias = this.bias;
  26174. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  26175. if ( this.radius !== 1 ) object.radius = this.radius;
  26176. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  26177. object.camera = this.camera.toJSON( false ).object;
  26178. delete object.camera.matrix;
  26179. return object;
  26180. }
  26181. }
  26182. class SpotLightShadow extends LightShadow {
  26183. constructor() {
  26184. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  26185. this.isSpotLightShadow = true;
  26186. this.focus = 1;
  26187. }
  26188. updateMatrices( light ) {
  26189. const camera = this.camera;
  26190. const fov = RAD2DEG * 2 * light.angle * this.focus;
  26191. const aspect = this.mapSize.width / this.mapSize.height;
  26192. const far = light.distance || camera.far;
  26193. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  26194. camera.fov = fov;
  26195. camera.aspect = aspect;
  26196. camera.far = far;
  26197. camera.updateProjectionMatrix();
  26198. }
  26199. super.updateMatrices( light );
  26200. }
  26201. copy( source ) {
  26202. super.copy( source );
  26203. this.focus = source.focus;
  26204. return this;
  26205. }
  26206. }
  26207. class SpotLight extends Light {
  26208. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  26209. super( color, intensity );
  26210. this.isSpotLight = true;
  26211. this.type = 'SpotLight';
  26212. this.position.copy( Object3D.DEFAULT_UP );
  26213. this.updateMatrix();
  26214. this.target = new Object3D();
  26215. this.distance = distance;
  26216. this.angle = angle;
  26217. this.penumbra = penumbra;
  26218. this.decay = decay;
  26219. this.map = null;
  26220. this.shadow = new SpotLightShadow();
  26221. }
  26222. get power() {
  26223. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26224. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  26225. return this.intensity * Math.PI;
  26226. }
  26227. set power( power ) {
  26228. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26229. this.intensity = power / Math.PI;
  26230. }
  26231. dispose() {
  26232. this.shadow.dispose();
  26233. }
  26234. copy( source, recursive ) {
  26235. super.copy( source, recursive );
  26236. this.distance = source.distance;
  26237. this.angle = source.angle;
  26238. this.penumbra = source.penumbra;
  26239. this.decay = source.decay;
  26240. this.target = source.target.clone();
  26241. this.shadow = source.shadow.clone();
  26242. return this;
  26243. }
  26244. }
  26245. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  26246. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  26247. const _lookTarget = /*@__PURE__*/ new Vector3();
  26248. class PointLightShadow extends LightShadow {
  26249. constructor() {
  26250. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  26251. this.isPointLightShadow = true;
  26252. this._frameExtents = new Vector2( 4, 2 );
  26253. this._viewportCount = 6;
  26254. this._viewports = [
  26255. // These viewports map a cube-map onto a 2D texture with the
  26256. // following orientation:
  26257. //
  26258. // xzXZ
  26259. // y Y
  26260. //
  26261. // X - Positive x direction
  26262. // x - Negative x direction
  26263. // Y - Positive y direction
  26264. // y - Negative y direction
  26265. // Z - Positive z direction
  26266. // z - Negative z direction
  26267. // positive X
  26268. new Vector4( 2, 1, 1, 1 ),
  26269. // negative X
  26270. new Vector4( 0, 1, 1, 1 ),
  26271. // positive Z
  26272. new Vector4( 3, 1, 1, 1 ),
  26273. // negative Z
  26274. new Vector4( 1, 1, 1, 1 ),
  26275. // positive Y
  26276. new Vector4( 3, 0, 1, 1 ),
  26277. // negative Y
  26278. new Vector4( 1, 0, 1, 1 )
  26279. ];
  26280. this._cubeDirections = [
  26281. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  26282. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  26283. ];
  26284. this._cubeUps = [
  26285. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  26286. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  26287. ];
  26288. }
  26289. updateMatrices( light, viewportIndex = 0 ) {
  26290. const camera = this.camera;
  26291. const shadowMatrix = this.matrix;
  26292. const far = light.distance || camera.far;
  26293. if ( far !== camera.far ) {
  26294. camera.far = far;
  26295. camera.updateProjectionMatrix();
  26296. }
  26297. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  26298. camera.position.copy( _lightPositionWorld );
  26299. _lookTarget.copy( camera.position );
  26300. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  26301. camera.up.copy( this._cubeUps[ viewportIndex ] );
  26302. camera.lookAt( _lookTarget );
  26303. camera.updateMatrixWorld();
  26304. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  26305. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  26306. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  26307. }
  26308. }
  26309. class PointLight extends Light {
  26310. constructor( color, intensity, distance = 0, decay = 2 ) {
  26311. super( color, intensity );
  26312. this.isPointLight = true;
  26313. this.type = 'PointLight';
  26314. this.distance = distance;
  26315. this.decay = decay;
  26316. this.shadow = new PointLightShadow();
  26317. }
  26318. get power() {
  26319. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26320. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  26321. return this.intensity * 4 * Math.PI;
  26322. }
  26323. set power( power ) {
  26324. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26325. this.intensity = power / ( 4 * Math.PI );
  26326. }
  26327. dispose() {
  26328. this.shadow.dispose();
  26329. }
  26330. copy( source, recursive ) {
  26331. super.copy( source, recursive );
  26332. this.distance = source.distance;
  26333. this.decay = source.decay;
  26334. this.shadow = source.shadow.clone();
  26335. return this;
  26336. }
  26337. }
  26338. class DirectionalLightShadow extends LightShadow {
  26339. constructor() {
  26340. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  26341. this.isDirectionalLightShadow = true;
  26342. }
  26343. }
  26344. class DirectionalLight extends Light {
  26345. constructor( color, intensity ) {
  26346. super( color, intensity );
  26347. this.isDirectionalLight = true;
  26348. this.type = 'DirectionalLight';
  26349. this.position.copy( Object3D.DEFAULT_UP );
  26350. this.updateMatrix();
  26351. this.target = new Object3D();
  26352. this.shadow = new DirectionalLightShadow();
  26353. }
  26354. dispose() {
  26355. this.shadow.dispose();
  26356. }
  26357. copy( source ) {
  26358. super.copy( source );
  26359. this.target = source.target.clone();
  26360. this.shadow = source.shadow.clone();
  26361. return this;
  26362. }
  26363. }
  26364. class AmbientLight extends Light {
  26365. constructor( color, intensity ) {
  26366. super( color, intensity );
  26367. this.isAmbientLight = true;
  26368. this.type = 'AmbientLight';
  26369. }
  26370. }
  26371. class RectAreaLight extends Light {
  26372. constructor( color, intensity, width = 10, height = 10 ) {
  26373. super( color, intensity );
  26374. this.isRectAreaLight = true;
  26375. this.type = 'RectAreaLight';
  26376. this.width = width;
  26377. this.height = height;
  26378. }
  26379. get power() {
  26380. // compute the light's luminous power (in lumens) from its intensity (in nits)
  26381. return this.intensity * this.width * this.height * Math.PI;
  26382. }
  26383. set power( power ) {
  26384. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  26385. this.intensity = power / ( this.width * this.height * Math.PI );
  26386. }
  26387. copy( source ) {
  26388. super.copy( source );
  26389. this.width = source.width;
  26390. this.height = source.height;
  26391. return this;
  26392. }
  26393. toJSON( meta ) {
  26394. const data = super.toJSON( meta );
  26395. data.object.width = this.width;
  26396. data.object.height = this.height;
  26397. return data;
  26398. }
  26399. }
  26400. /**
  26401. * Primary reference:
  26402. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26403. *
  26404. * Secondary reference:
  26405. * https://www.ppsloan.org/publications/StupidSH36.pdf
  26406. */
  26407. // 3-band SH defined by 9 coefficients
  26408. class SphericalHarmonics3 {
  26409. constructor() {
  26410. this.isSphericalHarmonics3 = true;
  26411. this.coefficients = [];
  26412. for ( let i = 0; i < 9; i ++ ) {
  26413. this.coefficients.push( new Vector3() );
  26414. }
  26415. }
  26416. set( coefficients ) {
  26417. for ( let i = 0; i < 9; i ++ ) {
  26418. this.coefficients[ i ].copy( coefficients[ i ] );
  26419. }
  26420. return this;
  26421. }
  26422. zero() {
  26423. for ( let i = 0; i < 9; i ++ ) {
  26424. this.coefficients[ i ].set( 0, 0, 0 );
  26425. }
  26426. return this;
  26427. }
  26428. // get the radiance in the direction of the normal
  26429. // target is a Vector3
  26430. getAt( normal, target ) {
  26431. // normal is assumed to be unit length
  26432. const x = normal.x, y = normal.y, z = normal.z;
  26433. const coeff = this.coefficients;
  26434. // band 0
  26435. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  26436. // band 1
  26437. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  26438. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  26439. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  26440. // band 2
  26441. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  26442. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  26443. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  26444. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  26445. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  26446. return target;
  26447. }
  26448. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  26449. // target is a Vector3
  26450. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26451. getIrradianceAt( normal, target ) {
  26452. // normal is assumed to be unit length
  26453. const x = normal.x, y = normal.y, z = normal.z;
  26454. const coeff = this.coefficients;
  26455. // band 0
  26456. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  26457. // band 1
  26458. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  26459. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  26460. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  26461. // band 2
  26462. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  26463. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  26464. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  26465. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  26466. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  26467. return target;
  26468. }
  26469. add( sh ) {
  26470. for ( let i = 0; i < 9; i ++ ) {
  26471. this.coefficients[ i ].add( sh.coefficients[ i ] );
  26472. }
  26473. return this;
  26474. }
  26475. addScaledSH( sh, s ) {
  26476. for ( let i = 0; i < 9; i ++ ) {
  26477. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  26478. }
  26479. return this;
  26480. }
  26481. scale( s ) {
  26482. for ( let i = 0; i < 9; i ++ ) {
  26483. this.coefficients[ i ].multiplyScalar( s );
  26484. }
  26485. return this;
  26486. }
  26487. lerp( sh, alpha ) {
  26488. for ( let i = 0; i < 9; i ++ ) {
  26489. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  26490. }
  26491. return this;
  26492. }
  26493. equals( sh ) {
  26494. for ( let i = 0; i < 9; i ++ ) {
  26495. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  26496. return false;
  26497. }
  26498. }
  26499. return true;
  26500. }
  26501. copy( sh ) {
  26502. return this.set( sh.coefficients );
  26503. }
  26504. clone() {
  26505. return new this.constructor().copy( this );
  26506. }
  26507. fromArray( array, offset = 0 ) {
  26508. const coefficients = this.coefficients;
  26509. for ( let i = 0; i < 9; i ++ ) {
  26510. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  26511. }
  26512. return this;
  26513. }
  26514. toArray( array = [], offset = 0 ) {
  26515. const coefficients = this.coefficients;
  26516. for ( let i = 0; i < 9; i ++ ) {
  26517. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  26518. }
  26519. return array;
  26520. }
  26521. // evaluate the basis functions
  26522. // shBasis is an Array[ 9 ]
  26523. static getBasisAt( normal, shBasis ) {
  26524. // normal is assumed to be unit length
  26525. const x = normal.x, y = normal.y, z = normal.z;
  26526. // band 0
  26527. shBasis[ 0 ] = 0.282095;
  26528. // band 1
  26529. shBasis[ 1 ] = 0.488603 * y;
  26530. shBasis[ 2 ] = 0.488603 * z;
  26531. shBasis[ 3 ] = 0.488603 * x;
  26532. // band 2
  26533. shBasis[ 4 ] = 1.092548 * x * y;
  26534. shBasis[ 5 ] = 1.092548 * y * z;
  26535. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  26536. shBasis[ 7 ] = 1.092548 * x * z;
  26537. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  26538. }
  26539. }
  26540. class LightProbe extends Light {
  26541. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  26542. super( undefined, intensity );
  26543. this.isLightProbe = true;
  26544. this.sh = sh;
  26545. }
  26546. copy( source ) {
  26547. super.copy( source );
  26548. this.sh.copy( source.sh );
  26549. return this;
  26550. }
  26551. fromJSON( json ) {
  26552. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  26553. this.sh.fromArray( json.sh );
  26554. return this;
  26555. }
  26556. toJSON( meta ) {
  26557. const data = super.toJSON( meta );
  26558. data.object.sh = this.sh.toArray();
  26559. return data;
  26560. }
  26561. }
  26562. class MaterialLoader extends Loader {
  26563. constructor( manager ) {
  26564. super( manager );
  26565. this.textures = {};
  26566. }
  26567. load( url, onLoad, onProgress, onError ) {
  26568. const scope = this;
  26569. const loader = new FileLoader( scope.manager );
  26570. loader.setPath( scope.path );
  26571. loader.setRequestHeader( scope.requestHeader );
  26572. loader.setWithCredentials( scope.withCredentials );
  26573. loader.load( url, function ( text ) {
  26574. try {
  26575. onLoad( scope.parse( JSON.parse( text ) ) );
  26576. } catch ( e ) {
  26577. if ( onError ) {
  26578. onError( e );
  26579. } else {
  26580. console.error( e );
  26581. }
  26582. scope.manager.itemError( url );
  26583. }
  26584. }, onProgress, onError );
  26585. }
  26586. parse( json ) {
  26587. const textures = this.textures;
  26588. function getTexture( name ) {
  26589. if ( textures[ name ] === undefined ) {
  26590. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  26591. }
  26592. return textures[ name ];
  26593. }
  26594. const material = MaterialLoader.createMaterialFromType( json.type );
  26595. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  26596. if ( json.name !== undefined ) material.name = json.name;
  26597. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  26598. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  26599. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  26600. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  26601. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  26602. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  26603. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  26604. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  26605. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  26606. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  26607. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  26608. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  26609. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  26610. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  26611. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  26612. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  26613. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  26614. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  26615. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  26616. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  26617. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  26618. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  26619. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  26620. if ( json.fog !== undefined ) material.fog = json.fog;
  26621. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  26622. if ( json.blending !== undefined ) material.blending = json.blending;
  26623. if ( json.combine !== undefined ) material.combine = json.combine;
  26624. if ( json.side !== undefined ) material.side = json.side;
  26625. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  26626. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  26627. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  26628. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  26629. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  26630. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  26631. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  26632. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  26633. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  26634. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  26635. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  26636. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  26637. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  26638. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  26639. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  26640. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  26641. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  26642. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  26643. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  26644. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  26645. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  26646. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  26647. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  26648. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  26649. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  26650. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  26651. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  26652. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  26653. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  26654. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  26655. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  26656. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  26657. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  26658. if ( json.scale !== undefined ) material.scale = json.scale;
  26659. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  26660. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  26661. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  26662. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  26663. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  26664. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  26665. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  26666. if ( json.visible !== undefined ) material.visible = json.visible;
  26667. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  26668. if ( json.userData !== undefined ) material.userData = json.userData;
  26669. if ( json.vertexColors !== undefined ) {
  26670. if ( typeof json.vertexColors === 'number' ) {
  26671. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  26672. } else {
  26673. material.vertexColors = json.vertexColors;
  26674. }
  26675. }
  26676. // Shader Material
  26677. if ( json.uniforms !== undefined ) {
  26678. for ( const name in json.uniforms ) {
  26679. const uniform = json.uniforms[ name ];
  26680. material.uniforms[ name ] = {};
  26681. switch ( uniform.type ) {
  26682. case 't':
  26683. material.uniforms[ name ].value = getTexture( uniform.value );
  26684. break;
  26685. case 'c':
  26686. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  26687. break;
  26688. case 'v2':
  26689. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  26690. break;
  26691. case 'v3':
  26692. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  26693. break;
  26694. case 'v4':
  26695. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  26696. break;
  26697. case 'm3':
  26698. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  26699. break;
  26700. case 'm4':
  26701. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  26702. break;
  26703. default:
  26704. material.uniforms[ name ].value = uniform.value;
  26705. }
  26706. }
  26707. }
  26708. if ( json.defines !== undefined ) material.defines = json.defines;
  26709. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  26710. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  26711. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  26712. if ( json.extensions !== undefined ) {
  26713. for ( const key in json.extensions ) {
  26714. material.extensions[ key ] = json.extensions[ key ];
  26715. }
  26716. }
  26717. if ( json.lights !== undefined ) material.lights = json.lights;
  26718. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  26719. // for PointsMaterial
  26720. if ( json.size !== undefined ) material.size = json.size;
  26721. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  26722. // maps
  26723. if ( json.map !== undefined ) material.map = getTexture( json.map );
  26724. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  26725. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  26726. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  26727. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  26728. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  26729. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  26730. if ( json.normalScale !== undefined ) {
  26731. let normalScale = json.normalScale;
  26732. if ( Array.isArray( normalScale ) === false ) {
  26733. // Blender exporter used to export a scalar. See #7459
  26734. normalScale = [ normalScale, normalScale ];
  26735. }
  26736. material.normalScale = new Vector2().fromArray( normalScale );
  26737. }
  26738. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  26739. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  26740. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  26741. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  26742. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  26743. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  26744. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  26745. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  26746. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  26747. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  26748. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  26749. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  26750. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  26751. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  26752. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  26753. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  26754. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  26755. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  26756. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  26757. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  26758. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  26759. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  26760. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  26761. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  26762. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  26763. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  26764. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  26765. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  26766. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  26767. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  26768. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  26769. return material;
  26770. }
  26771. setTextures( value ) {
  26772. this.textures = value;
  26773. return this;
  26774. }
  26775. static createMaterialFromType( type ) {
  26776. const materialLib = {
  26777. ShadowMaterial,
  26778. SpriteMaterial,
  26779. RawShaderMaterial,
  26780. ShaderMaterial,
  26781. PointsMaterial,
  26782. MeshPhysicalMaterial,
  26783. MeshStandardMaterial,
  26784. MeshPhongMaterial,
  26785. MeshToonMaterial,
  26786. MeshNormalMaterial,
  26787. MeshLambertMaterial,
  26788. MeshDepthMaterial,
  26789. MeshDistanceMaterial,
  26790. MeshBasicMaterial,
  26791. MeshMatcapMaterial,
  26792. LineDashedMaterial,
  26793. LineBasicMaterial,
  26794. Material
  26795. };
  26796. return new materialLib[ type ]();
  26797. }
  26798. }
  26799. class LoaderUtils {
  26800. static decodeText( array ) {
  26801. if ( typeof TextDecoder !== 'undefined' ) {
  26802. return new TextDecoder().decode( array );
  26803. }
  26804. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  26805. // throws a "maximum call stack size exceeded" error for large arrays.
  26806. let s = '';
  26807. for ( let i = 0, il = array.length; i < il; i ++ ) {
  26808. // Implicitly assumes little-endian.
  26809. s += String.fromCharCode( array[ i ] );
  26810. }
  26811. try {
  26812. // merges multi-byte utf-8 characters.
  26813. return decodeURIComponent( escape( s ) );
  26814. } catch ( e ) { // see #16358
  26815. return s;
  26816. }
  26817. }
  26818. static extractUrlBase( url ) {
  26819. const index = url.lastIndexOf( '/' );
  26820. if ( index === - 1 ) return './';
  26821. return url.slice( 0, index + 1 );
  26822. }
  26823. static resolveURL( url, path ) {
  26824. // Invalid URL
  26825. if ( typeof url !== 'string' || url === '' ) return '';
  26826. // Host Relative URL
  26827. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  26828. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  26829. }
  26830. // Absolute URL http://,https://,//
  26831. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  26832. // Data URI
  26833. if ( /^data:.*,.*$/i.test( url ) ) return url;
  26834. // Blob URL
  26835. if ( /^blob:.*$/i.test( url ) ) return url;
  26836. // Relative URL
  26837. return path + url;
  26838. }
  26839. }
  26840. class InstancedBufferGeometry extends BufferGeometry {
  26841. constructor() {
  26842. super();
  26843. this.isInstancedBufferGeometry = true;
  26844. this.type = 'InstancedBufferGeometry';
  26845. this.instanceCount = Infinity;
  26846. }
  26847. copy( source ) {
  26848. super.copy( source );
  26849. this.instanceCount = source.instanceCount;
  26850. return this;
  26851. }
  26852. toJSON() {
  26853. const data = super.toJSON();
  26854. data.instanceCount = this.instanceCount;
  26855. data.isInstancedBufferGeometry = true;
  26856. return data;
  26857. }
  26858. }
  26859. class BufferGeometryLoader extends Loader {
  26860. constructor( manager ) {
  26861. super( manager );
  26862. }
  26863. load( url, onLoad, onProgress, onError ) {
  26864. const scope = this;
  26865. const loader = new FileLoader( scope.manager );
  26866. loader.setPath( scope.path );
  26867. loader.setRequestHeader( scope.requestHeader );
  26868. loader.setWithCredentials( scope.withCredentials );
  26869. loader.load( url, function ( text ) {
  26870. try {
  26871. onLoad( scope.parse( JSON.parse( text ) ) );
  26872. } catch ( e ) {
  26873. if ( onError ) {
  26874. onError( e );
  26875. } else {
  26876. console.error( e );
  26877. }
  26878. scope.manager.itemError( url );
  26879. }
  26880. }, onProgress, onError );
  26881. }
  26882. parse( json ) {
  26883. const interleavedBufferMap = {};
  26884. const arrayBufferMap = {};
  26885. function getInterleavedBuffer( json, uuid ) {
  26886. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  26887. const interleavedBuffers = json.interleavedBuffers;
  26888. const interleavedBuffer = interleavedBuffers[ uuid ];
  26889. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  26890. const array = getTypedArray( interleavedBuffer.type, buffer );
  26891. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  26892. ib.uuid = interleavedBuffer.uuid;
  26893. interleavedBufferMap[ uuid ] = ib;
  26894. return ib;
  26895. }
  26896. function getArrayBuffer( json, uuid ) {
  26897. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  26898. const arrayBuffers = json.arrayBuffers;
  26899. const arrayBuffer = arrayBuffers[ uuid ];
  26900. const ab = new Uint32Array( arrayBuffer ).buffer;
  26901. arrayBufferMap[ uuid ] = ab;
  26902. return ab;
  26903. }
  26904. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  26905. const index = json.data.index;
  26906. if ( index !== undefined ) {
  26907. const typedArray = getTypedArray( index.type, index.array );
  26908. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  26909. }
  26910. const attributes = json.data.attributes;
  26911. for ( const key in attributes ) {
  26912. const attribute = attributes[ key ];
  26913. let bufferAttribute;
  26914. if ( attribute.isInterleavedBufferAttribute ) {
  26915. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26916. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26917. } else {
  26918. const typedArray = getTypedArray( attribute.type, attribute.array );
  26919. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  26920. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  26921. }
  26922. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26923. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  26924. geometry.setAttribute( key, bufferAttribute );
  26925. }
  26926. const morphAttributes = json.data.morphAttributes;
  26927. if ( morphAttributes ) {
  26928. for ( const key in morphAttributes ) {
  26929. const attributeArray = morphAttributes[ key ];
  26930. const array = [];
  26931. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  26932. const attribute = attributeArray[ i ];
  26933. let bufferAttribute;
  26934. if ( attribute.isInterleavedBufferAttribute ) {
  26935. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26936. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26937. } else {
  26938. const typedArray = getTypedArray( attribute.type, attribute.array );
  26939. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  26940. }
  26941. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26942. array.push( bufferAttribute );
  26943. }
  26944. geometry.morphAttributes[ key ] = array;
  26945. }
  26946. }
  26947. const morphTargetsRelative = json.data.morphTargetsRelative;
  26948. if ( morphTargetsRelative ) {
  26949. geometry.morphTargetsRelative = true;
  26950. }
  26951. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  26952. if ( groups !== undefined ) {
  26953. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  26954. const group = groups[ i ];
  26955. geometry.addGroup( group.start, group.count, group.materialIndex );
  26956. }
  26957. }
  26958. const boundingSphere = json.data.boundingSphere;
  26959. if ( boundingSphere !== undefined ) {
  26960. const center = new Vector3();
  26961. if ( boundingSphere.center !== undefined ) {
  26962. center.fromArray( boundingSphere.center );
  26963. }
  26964. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  26965. }
  26966. if ( json.name ) geometry.name = json.name;
  26967. if ( json.userData ) geometry.userData = json.userData;
  26968. return geometry;
  26969. }
  26970. }
  26971. class ObjectLoader extends Loader {
  26972. constructor( manager ) {
  26973. super( manager );
  26974. }
  26975. load( url, onLoad, onProgress, onError ) {
  26976. const scope = this;
  26977. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26978. this.resourcePath = this.resourcePath || path;
  26979. const loader = new FileLoader( this.manager );
  26980. loader.setPath( this.path );
  26981. loader.setRequestHeader( this.requestHeader );
  26982. loader.setWithCredentials( this.withCredentials );
  26983. loader.load( url, function ( text ) {
  26984. let json = null;
  26985. try {
  26986. json = JSON.parse( text );
  26987. } catch ( error ) {
  26988. if ( onError !== undefined ) onError( error );
  26989. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26990. return;
  26991. }
  26992. const metadata = json.metadata;
  26993. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26994. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  26995. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26996. return;
  26997. }
  26998. scope.parse( json, onLoad );
  26999. }, onProgress, onError );
  27000. }
  27001. async loadAsync( url, onProgress ) {
  27002. const scope = this;
  27003. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27004. this.resourcePath = this.resourcePath || path;
  27005. const loader = new FileLoader( this.manager );
  27006. loader.setPath( this.path );
  27007. loader.setRequestHeader( this.requestHeader );
  27008. loader.setWithCredentials( this.withCredentials );
  27009. const text = await loader.loadAsync( url, onProgress );
  27010. const json = JSON.parse( text );
  27011. const metadata = json.metadata;
  27012. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27013. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27014. }
  27015. return await scope.parseAsync( json );
  27016. }
  27017. parse( json, onLoad ) {
  27018. const animations = this.parseAnimations( json.animations );
  27019. const shapes = this.parseShapes( json.shapes );
  27020. const geometries = this.parseGeometries( json.geometries, shapes );
  27021. const images = this.parseImages( json.images, function () {
  27022. if ( onLoad !== undefined ) onLoad( object );
  27023. } );
  27024. const textures = this.parseTextures( json.textures, images );
  27025. const materials = this.parseMaterials( json.materials, textures );
  27026. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27027. const skeletons = this.parseSkeletons( json.skeletons, object );
  27028. this.bindSkeletons( object, skeletons );
  27029. //
  27030. if ( onLoad !== undefined ) {
  27031. let hasImages = false;
  27032. for ( const uuid in images ) {
  27033. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  27034. hasImages = true;
  27035. break;
  27036. }
  27037. }
  27038. if ( hasImages === false ) onLoad( object );
  27039. }
  27040. return object;
  27041. }
  27042. async parseAsync( json ) {
  27043. const animations = this.parseAnimations( json.animations );
  27044. const shapes = this.parseShapes( json.shapes );
  27045. const geometries = this.parseGeometries( json.geometries, shapes );
  27046. const images = await this.parseImagesAsync( json.images );
  27047. const textures = this.parseTextures( json.textures, images );
  27048. const materials = this.parseMaterials( json.materials, textures );
  27049. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27050. const skeletons = this.parseSkeletons( json.skeletons, object );
  27051. this.bindSkeletons( object, skeletons );
  27052. return object;
  27053. }
  27054. parseShapes( json ) {
  27055. const shapes = {};
  27056. if ( json !== undefined ) {
  27057. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27058. const shape = new Shape().fromJSON( json[ i ] );
  27059. shapes[ shape.uuid ] = shape;
  27060. }
  27061. }
  27062. return shapes;
  27063. }
  27064. parseSkeletons( json, object ) {
  27065. const skeletons = {};
  27066. const bones = {};
  27067. // generate bone lookup table
  27068. object.traverse( function ( child ) {
  27069. if ( child.isBone ) bones[ child.uuid ] = child;
  27070. } );
  27071. // create skeletons
  27072. if ( json !== undefined ) {
  27073. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27074. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  27075. skeletons[ skeleton.uuid ] = skeleton;
  27076. }
  27077. }
  27078. return skeletons;
  27079. }
  27080. parseGeometries( json, shapes ) {
  27081. const geometries = {};
  27082. if ( json !== undefined ) {
  27083. const bufferGeometryLoader = new BufferGeometryLoader();
  27084. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27085. let geometry;
  27086. const data = json[ i ];
  27087. switch ( data.type ) {
  27088. case 'BufferGeometry':
  27089. case 'InstancedBufferGeometry':
  27090. geometry = bufferGeometryLoader.parse( data );
  27091. break;
  27092. default:
  27093. if ( data.type in Geometries ) {
  27094. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  27095. } else {
  27096. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  27097. }
  27098. }
  27099. geometry.uuid = data.uuid;
  27100. if ( data.name !== undefined ) geometry.name = data.name;
  27101. if ( data.userData !== undefined ) geometry.userData = data.userData;
  27102. geometries[ data.uuid ] = geometry;
  27103. }
  27104. }
  27105. return geometries;
  27106. }
  27107. parseMaterials( json, textures ) {
  27108. const cache = {}; // MultiMaterial
  27109. const materials = {};
  27110. if ( json !== undefined ) {
  27111. const loader = new MaterialLoader();
  27112. loader.setTextures( textures );
  27113. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27114. const data = json[ i ];
  27115. if ( cache[ data.uuid ] === undefined ) {
  27116. cache[ data.uuid ] = loader.parse( data );
  27117. }
  27118. materials[ data.uuid ] = cache[ data.uuid ];
  27119. }
  27120. }
  27121. return materials;
  27122. }
  27123. parseAnimations( json ) {
  27124. const animations = {};
  27125. if ( json !== undefined ) {
  27126. for ( let i = 0; i < json.length; i ++ ) {
  27127. const data = json[ i ];
  27128. const clip = AnimationClip.parse( data );
  27129. animations[ clip.uuid ] = clip;
  27130. }
  27131. }
  27132. return animations;
  27133. }
  27134. parseImages( json, onLoad ) {
  27135. const scope = this;
  27136. const images = {};
  27137. let loader;
  27138. function loadImage( url ) {
  27139. scope.manager.itemStart( url );
  27140. return loader.load( url, function () {
  27141. scope.manager.itemEnd( url );
  27142. }, undefined, function () {
  27143. scope.manager.itemError( url );
  27144. scope.manager.itemEnd( url );
  27145. } );
  27146. }
  27147. function deserializeImage( image ) {
  27148. if ( typeof image === 'string' ) {
  27149. const url = image;
  27150. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27151. return loadImage( path );
  27152. } else {
  27153. if ( image.data ) {
  27154. return {
  27155. data: getTypedArray( image.type, image.data ),
  27156. width: image.width,
  27157. height: image.height
  27158. };
  27159. } else {
  27160. return null;
  27161. }
  27162. }
  27163. }
  27164. if ( json !== undefined && json.length > 0 ) {
  27165. const manager = new LoadingManager( onLoad );
  27166. loader = new ImageLoader( manager );
  27167. loader.setCrossOrigin( this.crossOrigin );
  27168. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27169. const image = json[ i ];
  27170. const url = image.url;
  27171. if ( Array.isArray( url ) ) {
  27172. // load array of images e.g CubeTexture
  27173. const imageArray = [];
  27174. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27175. const currentUrl = url[ j ];
  27176. const deserializedImage = deserializeImage( currentUrl );
  27177. if ( deserializedImage !== null ) {
  27178. if ( deserializedImage instanceof HTMLImageElement ) {
  27179. imageArray.push( deserializedImage );
  27180. } else {
  27181. // special case: handle array of data textures for cube textures
  27182. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27183. }
  27184. }
  27185. }
  27186. images[ image.uuid ] = new Source( imageArray );
  27187. } else {
  27188. // load single image
  27189. const deserializedImage = deserializeImage( image.url );
  27190. images[ image.uuid ] = new Source( deserializedImage );
  27191. }
  27192. }
  27193. }
  27194. return images;
  27195. }
  27196. async parseImagesAsync( json ) {
  27197. const scope = this;
  27198. const images = {};
  27199. let loader;
  27200. async function deserializeImage( image ) {
  27201. if ( typeof image === 'string' ) {
  27202. const url = image;
  27203. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27204. return await loader.loadAsync( path );
  27205. } else {
  27206. if ( image.data ) {
  27207. return {
  27208. data: getTypedArray( image.type, image.data ),
  27209. width: image.width,
  27210. height: image.height
  27211. };
  27212. } else {
  27213. return null;
  27214. }
  27215. }
  27216. }
  27217. if ( json !== undefined && json.length > 0 ) {
  27218. loader = new ImageLoader( this.manager );
  27219. loader.setCrossOrigin( this.crossOrigin );
  27220. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27221. const image = json[ i ];
  27222. const url = image.url;
  27223. if ( Array.isArray( url ) ) {
  27224. // load array of images e.g CubeTexture
  27225. const imageArray = [];
  27226. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27227. const currentUrl = url[ j ];
  27228. const deserializedImage = await deserializeImage( currentUrl );
  27229. if ( deserializedImage !== null ) {
  27230. if ( deserializedImage instanceof HTMLImageElement ) {
  27231. imageArray.push( deserializedImage );
  27232. } else {
  27233. // special case: handle array of data textures for cube textures
  27234. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27235. }
  27236. }
  27237. }
  27238. images[ image.uuid ] = new Source( imageArray );
  27239. } else {
  27240. // load single image
  27241. const deserializedImage = await deserializeImage( image.url );
  27242. images[ image.uuid ] = new Source( deserializedImage );
  27243. }
  27244. }
  27245. }
  27246. return images;
  27247. }
  27248. parseTextures( json, images ) {
  27249. function parseConstant( value, type ) {
  27250. if ( typeof value === 'number' ) return value;
  27251. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27252. return type[ value ];
  27253. }
  27254. const textures = {};
  27255. if ( json !== undefined ) {
  27256. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27257. const data = json[ i ];
  27258. if ( data.image === undefined ) {
  27259. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27260. }
  27261. if ( images[ data.image ] === undefined ) {
  27262. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27263. }
  27264. const source = images[ data.image ];
  27265. const image = source.data;
  27266. let texture;
  27267. if ( Array.isArray( image ) ) {
  27268. texture = new CubeTexture();
  27269. if ( image.length === 6 ) texture.needsUpdate = true;
  27270. } else {
  27271. if ( image && image.data ) {
  27272. texture = new DataTexture();
  27273. } else {
  27274. texture = new Texture();
  27275. }
  27276. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  27277. }
  27278. texture.source = source;
  27279. texture.uuid = data.uuid;
  27280. if ( data.name !== undefined ) texture.name = data.name;
  27281. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27282. if ( data.channel !== undefined ) texture.channel = data.channel;
  27283. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27284. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27285. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27286. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27287. if ( data.wrap !== undefined ) {
  27288. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27289. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27290. }
  27291. if ( data.format !== undefined ) texture.format = data.format;
  27292. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  27293. if ( data.type !== undefined ) texture.type = data.type;
  27294. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  27295. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27296. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27297. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27298. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27299. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  27300. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27301. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27302. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  27303. if ( data.userData !== undefined ) texture.userData = data.userData;
  27304. textures[ data.uuid ] = texture;
  27305. }
  27306. }
  27307. return textures;
  27308. }
  27309. parseObject( data, geometries, materials, textures, animations ) {
  27310. let object;
  27311. function getGeometry( name ) {
  27312. if ( geometries[ name ] === undefined ) {
  27313. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27314. }
  27315. return geometries[ name ];
  27316. }
  27317. function getMaterial( name ) {
  27318. if ( name === undefined ) return undefined;
  27319. if ( Array.isArray( name ) ) {
  27320. const array = [];
  27321. for ( let i = 0, l = name.length; i < l; i ++ ) {
  27322. const uuid = name[ i ];
  27323. if ( materials[ uuid ] === undefined ) {
  27324. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27325. }
  27326. array.push( materials[ uuid ] );
  27327. }
  27328. return array;
  27329. }
  27330. if ( materials[ name ] === undefined ) {
  27331. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27332. }
  27333. return materials[ name ];
  27334. }
  27335. function getTexture( uuid ) {
  27336. if ( textures[ uuid ] === undefined ) {
  27337. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  27338. }
  27339. return textures[ uuid ];
  27340. }
  27341. let geometry, material;
  27342. switch ( data.type ) {
  27343. case 'Scene':
  27344. object = new Scene();
  27345. if ( data.background !== undefined ) {
  27346. if ( Number.isInteger( data.background ) ) {
  27347. object.background = new Color( data.background );
  27348. } else {
  27349. object.background = getTexture( data.background );
  27350. }
  27351. }
  27352. if ( data.environment !== undefined ) {
  27353. object.environment = getTexture( data.environment );
  27354. }
  27355. if ( data.fog !== undefined ) {
  27356. if ( data.fog.type === 'Fog' ) {
  27357. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27358. } else if ( data.fog.type === 'FogExp2' ) {
  27359. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27360. }
  27361. if ( data.fog.name !== '' ) {
  27362. object.fog.name = data.fog.name;
  27363. }
  27364. }
  27365. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  27366. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  27367. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  27368. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  27369. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  27370. break;
  27371. case 'PerspectiveCamera':
  27372. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27373. if ( data.focus !== undefined ) object.focus = data.focus;
  27374. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27375. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27376. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27377. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27378. break;
  27379. case 'OrthographicCamera':
  27380. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27381. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27382. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27383. break;
  27384. case 'AmbientLight':
  27385. object = new AmbientLight( data.color, data.intensity );
  27386. break;
  27387. case 'DirectionalLight':
  27388. object = new DirectionalLight( data.color, data.intensity );
  27389. break;
  27390. case 'PointLight':
  27391. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27392. break;
  27393. case 'RectAreaLight':
  27394. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27395. break;
  27396. case 'SpotLight':
  27397. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27398. break;
  27399. case 'HemisphereLight':
  27400. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27401. break;
  27402. case 'LightProbe':
  27403. object = new LightProbe().fromJSON( data );
  27404. break;
  27405. case 'SkinnedMesh':
  27406. geometry = getGeometry( data.geometry );
  27407. material = getMaterial( data.material );
  27408. object = new SkinnedMesh( geometry, material );
  27409. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  27410. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  27411. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  27412. break;
  27413. case 'Mesh':
  27414. geometry = getGeometry( data.geometry );
  27415. material = getMaterial( data.material );
  27416. object = new Mesh( geometry, material );
  27417. break;
  27418. case 'InstancedMesh':
  27419. geometry = getGeometry( data.geometry );
  27420. material = getMaterial( data.material );
  27421. const count = data.count;
  27422. const instanceMatrix = data.instanceMatrix;
  27423. const instanceColor = data.instanceColor;
  27424. object = new InstancedMesh( geometry, material, count );
  27425. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  27426. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  27427. break;
  27428. case 'BatchedMesh':
  27429. geometry = getGeometry( data.geometry );
  27430. material = getMaterial( data.material );
  27431. object = new BatchedMesh( data.maxGeometryCount, data.maxVertexCount, data.maxIndexCount, material );
  27432. object.geometry = geometry;
  27433. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  27434. object.sortObjects = data.sortObjects;
  27435. object._drawRanges = data.drawRanges;
  27436. object._reservedRanges = data.reservedRanges;
  27437. object._visibility = data.visibility;
  27438. object._active = data.active;
  27439. object._bounds = data.bounds.map( bound => {
  27440. const box = new Box3();
  27441. box.min.fromArray( bound.boxMin );
  27442. box.max.fromArray( bound.boxMax );
  27443. const sphere = new Sphere();
  27444. sphere.radius = bound.sphereRadius;
  27445. sphere.center.fromArray( bound.sphereCenter );
  27446. return {
  27447. boxInitialized: bound.boxInitialized,
  27448. box: box,
  27449. sphereInitialized: bound.sphereInitialized,
  27450. sphere: sphere
  27451. };
  27452. } );
  27453. object._maxGeometryCount = data.maxGeometryCount;
  27454. object._maxVertexCount = data.maxVertexCount;
  27455. object._maxIndexCount = data.maxIndexCount;
  27456. object._geometryInitialized = data.geometryInitialized;
  27457. object._geometryCount = data.geometryCount;
  27458. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  27459. break;
  27460. case 'LOD':
  27461. object = new LOD();
  27462. break;
  27463. case 'Line':
  27464. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  27465. break;
  27466. case 'LineLoop':
  27467. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  27468. break;
  27469. case 'LineSegments':
  27470. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  27471. break;
  27472. case 'PointCloud':
  27473. case 'Points':
  27474. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  27475. break;
  27476. case 'Sprite':
  27477. object = new Sprite( getMaterial( data.material ) );
  27478. break;
  27479. case 'Group':
  27480. object = new Group();
  27481. break;
  27482. case 'Bone':
  27483. object = new Bone();
  27484. break;
  27485. default:
  27486. object = new Object3D();
  27487. }
  27488. object.uuid = data.uuid;
  27489. if ( data.name !== undefined ) object.name = data.name;
  27490. if ( data.matrix !== undefined ) {
  27491. object.matrix.fromArray( data.matrix );
  27492. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  27493. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  27494. } else {
  27495. if ( data.position !== undefined ) object.position.fromArray( data.position );
  27496. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  27497. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  27498. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  27499. }
  27500. if ( data.up !== undefined ) object.up.fromArray( data.up );
  27501. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  27502. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  27503. if ( data.shadow ) {
  27504. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  27505. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  27506. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  27507. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  27508. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  27509. }
  27510. if ( data.visible !== undefined ) object.visible = data.visible;
  27511. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  27512. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  27513. if ( data.userData !== undefined ) object.userData = data.userData;
  27514. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  27515. if ( data.children !== undefined ) {
  27516. const children = data.children;
  27517. for ( let i = 0; i < children.length; i ++ ) {
  27518. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  27519. }
  27520. }
  27521. if ( data.animations !== undefined ) {
  27522. const objectAnimations = data.animations;
  27523. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  27524. const uuid = objectAnimations[ i ];
  27525. object.animations.push( animations[ uuid ] );
  27526. }
  27527. }
  27528. if ( data.type === 'LOD' ) {
  27529. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  27530. const levels = data.levels;
  27531. for ( let l = 0; l < levels.length; l ++ ) {
  27532. const level = levels[ l ];
  27533. const child = object.getObjectByProperty( 'uuid', level.object );
  27534. if ( child !== undefined ) {
  27535. object.addLevel( child, level.distance, level.hysteresis );
  27536. }
  27537. }
  27538. }
  27539. return object;
  27540. }
  27541. bindSkeletons( object, skeletons ) {
  27542. if ( Object.keys( skeletons ).length === 0 ) return;
  27543. object.traverse( function ( child ) {
  27544. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  27545. const skeleton = skeletons[ child.skeleton ];
  27546. if ( skeleton === undefined ) {
  27547. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  27548. } else {
  27549. child.bind( skeleton, child.bindMatrix );
  27550. }
  27551. }
  27552. } );
  27553. }
  27554. }
  27555. const TEXTURE_MAPPING = {
  27556. UVMapping: UVMapping,
  27557. CubeReflectionMapping: CubeReflectionMapping,
  27558. CubeRefractionMapping: CubeRefractionMapping,
  27559. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  27560. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  27561. CubeUVReflectionMapping: CubeUVReflectionMapping
  27562. };
  27563. const TEXTURE_WRAPPING = {
  27564. RepeatWrapping: RepeatWrapping,
  27565. ClampToEdgeWrapping: ClampToEdgeWrapping,
  27566. MirroredRepeatWrapping: MirroredRepeatWrapping
  27567. };
  27568. const TEXTURE_FILTER = {
  27569. NearestFilter: NearestFilter,
  27570. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  27571. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  27572. LinearFilter: LinearFilter,
  27573. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  27574. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  27575. };
  27576. class ImageBitmapLoader extends Loader {
  27577. constructor( manager ) {
  27578. super( manager );
  27579. this.isImageBitmapLoader = true;
  27580. if ( typeof createImageBitmap === 'undefined' ) {
  27581. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  27582. }
  27583. if ( typeof fetch === 'undefined' ) {
  27584. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  27585. }
  27586. this.options = { premultiplyAlpha: 'none' };
  27587. }
  27588. setOptions( options ) {
  27589. this.options = options;
  27590. return this;
  27591. }
  27592. load( url, onLoad, onProgress, onError ) {
  27593. if ( url === undefined ) url = '';
  27594. if ( this.path !== undefined ) url = this.path + url;
  27595. url = this.manager.resolveURL( url );
  27596. const scope = this;
  27597. const cached = Cache.get( url );
  27598. if ( cached !== undefined ) {
  27599. scope.manager.itemStart( url );
  27600. // If cached is a promise, wait for it to resolve
  27601. if ( cached.then ) {
  27602. cached.then( imageBitmap => {
  27603. if ( onLoad ) onLoad( imageBitmap );
  27604. scope.manager.itemEnd( url );
  27605. } ).catch( e => {
  27606. if ( onError ) onError( e );
  27607. } );
  27608. return;
  27609. }
  27610. // If cached is not a promise (i.e., it's already an imageBitmap)
  27611. setTimeout( function () {
  27612. if ( onLoad ) onLoad( cached );
  27613. scope.manager.itemEnd( url );
  27614. }, 0 );
  27615. return cached;
  27616. }
  27617. const fetchOptions = {};
  27618. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  27619. fetchOptions.headers = this.requestHeader;
  27620. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  27621. return res.blob();
  27622. } ).then( function ( blob ) {
  27623. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  27624. } ).then( function ( imageBitmap ) {
  27625. Cache.add( url, imageBitmap );
  27626. if ( onLoad ) onLoad( imageBitmap );
  27627. scope.manager.itemEnd( url );
  27628. return imageBitmap;
  27629. } ).catch( function ( e ) {
  27630. if ( onError ) onError( e );
  27631. Cache.remove( url );
  27632. scope.manager.itemError( url );
  27633. scope.manager.itemEnd( url );
  27634. } );
  27635. Cache.add( url, promise );
  27636. scope.manager.itemStart( url );
  27637. }
  27638. }
  27639. let _context;
  27640. class AudioContext {
  27641. static getContext() {
  27642. if ( _context === undefined ) {
  27643. _context = new ( window.AudioContext || window.webkitAudioContext )();
  27644. }
  27645. return _context;
  27646. }
  27647. static setContext( value ) {
  27648. _context = value;
  27649. }
  27650. }
  27651. class AudioLoader extends Loader {
  27652. constructor( manager ) {
  27653. super( manager );
  27654. }
  27655. load( url, onLoad, onProgress, onError ) {
  27656. const scope = this;
  27657. const loader = new FileLoader( this.manager );
  27658. loader.setResponseType( 'arraybuffer' );
  27659. loader.setPath( this.path );
  27660. loader.setRequestHeader( this.requestHeader );
  27661. loader.setWithCredentials( this.withCredentials );
  27662. loader.load( url, function ( buffer ) {
  27663. try {
  27664. // Create a copy of the buffer. The `decodeAudioData` method
  27665. // detaches the buffer when complete, preventing reuse.
  27666. const bufferCopy = buffer.slice( 0 );
  27667. const context = AudioContext.getContext();
  27668. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  27669. onLoad( audioBuffer );
  27670. } ).catch( handleError );
  27671. } catch ( e ) {
  27672. handleError( e );
  27673. }
  27674. }, onProgress, onError );
  27675. function handleError( e ) {
  27676. if ( onError ) {
  27677. onError( e );
  27678. } else {
  27679. console.error( e );
  27680. }
  27681. scope.manager.itemError( url );
  27682. }
  27683. }
  27684. }
  27685. const _eyeRight = /*@__PURE__*/ new Matrix4();
  27686. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  27687. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  27688. class StereoCamera {
  27689. constructor() {
  27690. this.type = 'StereoCamera';
  27691. this.aspect = 1;
  27692. this.eyeSep = 0.064;
  27693. this.cameraL = new PerspectiveCamera();
  27694. this.cameraL.layers.enable( 1 );
  27695. this.cameraL.matrixAutoUpdate = false;
  27696. this.cameraR = new PerspectiveCamera();
  27697. this.cameraR.layers.enable( 2 );
  27698. this.cameraR.matrixAutoUpdate = false;
  27699. this._cache = {
  27700. focus: null,
  27701. fov: null,
  27702. aspect: null,
  27703. near: null,
  27704. far: null,
  27705. zoom: null,
  27706. eyeSep: null
  27707. };
  27708. }
  27709. update( camera ) {
  27710. const cache = this._cache;
  27711. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  27712. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  27713. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  27714. if ( needsUpdate ) {
  27715. cache.focus = camera.focus;
  27716. cache.fov = camera.fov;
  27717. cache.aspect = camera.aspect * this.aspect;
  27718. cache.near = camera.near;
  27719. cache.far = camera.far;
  27720. cache.zoom = camera.zoom;
  27721. cache.eyeSep = this.eyeSep;
  27722. // Off-axis stereoscopic effect based on
  27723. // http://paulbourke.net/stereographics/stereorender/
  27724. _projectionMatrix.copy( camera.projectionMatrix );
  27725. const eyeSepHalf = cache.eyeSep / 2;
  27726. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  27727. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  27728. let xmin, xmax;
  27729. // translate xOffset
  27730. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  27731. _eyeRight.elements[ 12 ] = eyeSepHalf;
  27732. // for left eye
  27733. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  27734. xmax = ymax * cache.aspect + eyeSepOnProjection;
  27735. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27736. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27737. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  27738. // for right eye
  27739. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  27740. xmax = ymax * cache.aspect - eyeSepOnProjection;
  27741. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27742. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27743. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  27744. }
  27745. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  27746. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  27747. }
  27748. }
  27749. class Clock {
  27750. constructor( autoStart = true ) {
  27751. this.autoStart = autoStart;
  27752. this.startTime = 0;
  27753. this.oldTime = 0;
  27754. this.elapsedTime = 0;
  27755. this.running = false;
  27756. }
  27757. start() {
  27758. this.startTime = now();
  27759. this.oldTime = this.startTime;
  27760. this.elapsedTime = 0;
  27761. this.running = true;
  27762. }
  27763. stop() {
  27764. this.getElapsedTime();
  27765. this.running = false;
  27766. this.autoStart = false;
  27767. }
  27768. getElapsedTime() {
  27769. this.getDelta();
  27770. return this.elapsedTime;
  27771. }
  27772. getDelta() {
  27773. let diff = 0;
  27774. if ( this.autoStart && ! this.running ) {
  27775. this.start();
  27776. return 0;
  27777. }
  27778. if ( this.running ) {
  27779. const newTime = now();
  27780. diff = ( newTime - this.oldTime ) / 1000;
  27781. this.oldTime = newTime;
  27782. this.elapsedTime += diff;
  27783. }
  27784. return diff;
  27785. }
  27786. }
  27787. function now() {
  27788. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  27789. }
  27790. const _position$1 = /*@__PURE__*/ new Vector3();
  27791. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  27792. const _scale$1 = /*@__PURE__*/ new Vector3();
  27793. const _orientation$1 = /*@__PURE__*/ new Vector3();
  27794. class AudioListener extends Object3D {
  27795. constructor() {
  27796. super();
  27797. this.type = 'AudioListener';
  27798. this.context = AudioContext.getContext();
  27799. this.gain = this.context.createGain();
  27800. this.gain.connect( this.context.destination );
  27801. this.filter = null;
  27802. this.timeDelta = 0;
  27803. // private
  27804. this._clock = new Clock();
  27805. }
  27806. getInput() {
  27807. return this.gain;
  27808. }
  27809. removeFilter() {
  27810. if ( this.filter !== null ) {
  27811. this.gain.disconnect( this.filter );
  27812. this.filter.disconnect( this.context.destination );
  27813. this.gain.connect( this.context.destination );
  27814. this.filter = null;
  27815. }
  27816. return this;
  27817. }
  27818. getFilter() {
  27819. return this.filter;
  27820. }
  27821. setFilter( value ) {
  27822. if ( this.filter !== null ) {
  27823. this.gain.disconnect( this.filter );
  27824. this.filter.disconnect( this.context.destination );
  27825. } else {
  27826. this.gain.disconnect( this.context.destination );
  27827. }
  27828. this.filter = value;
  27829. this.gain.connect( this.filter );
  27830. this.filter.connect( this.context.destination );
  27831. return this;
  27832. }
  27833. getMasterVolume() {
  27834. return this.gain.gain.value;
  27835. }
  27836. setMasterVolume( value ) {
  27837. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27838. return this;
  27839. }
  27840. updateMatrixWorld( force ) {
  27841. super.updateMatrixWorld( force );
  27842. const listener = this.context.listener;
  27843. const up = this.up;
  27844. this.timeDelta = this._clock.getDelta();
  27845. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  27846. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  27847. if ( listener.positionX ) {
  27848. // code path for Chrome (see #14393)
  27849. const endTime = this.context.currentTime + this.timeDelta;
  27850. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  27851. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  27852. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  27853. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  27854. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  27855. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  27856. listener.upX.linearRampToValueAtTime( up.x, endTime );
  27857. listener.upY.linearRampToValueAtTime( up.y, endTime );
  27858. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  27859. } else {
  27860. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  27861. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  27862. }
  27863. }
  27864. }
  27865. class Audio extends Object3D {
  27866. constructor( listener ) {
  27867. super();
  27868. this.type = 'Audio';
  27869. this.listener = listener;
  27870. this.context = listener.context;
  27871. this.gain = this.context.createGain();
  27872. this.gain.connect( listener.getInput() );
  27873. this.autoplay = false;
  27874. this.buffer = null;
  27875. this.detune = 0;
  27876. this.loop = false;
  27877. this.loopStart = 0;
  27878. this.loopEnd = 0;
  27879. this.offset = 0;
  27880. this.duration = undefined;
  27881. this.playbackRate = 1;
  27882. this.isPlaying = false;
  27883. this.hasPlaybackControl = true;
  27884. this.source = null;
  27885. this.sourceType = 'empty';
  27886. this._startedAt = 0;
  27887. this._progress = 0;
  27888. this._connected = false;
  27889. this.filters = [];
  27890. }
  27891. getOutput() {
  27892. return this.gain;
  27893. }
  27894. setNodeSource( audioNode ) {
  27895. this.hasPlaybackControl = false;
  27896. this.sourceType = 'audioNode';
  27897. this.source = audioNode;
  27898. this.connect();
  27899. return this;
  27900. }
  27901. setMediaElementSource( mediaElement ) {
  27902. this.hasPlaybackControl = false;
  27903. this.sourceType = 'mediaNode';
  27904. this.source = this.context.createMediaElementSource( mediaElement );
  27905. this.connect();
  27906. return this;
  27907. }
  27908. setMediaStreamSource( mediaStream ) {
  27909. this.hasPlaybackControl = false;
  27910. this.sourceType = 'mediaStreamNode';
  27911. this.source = this.context.createMediaStreamSource( mediaStream );
  27912. this.connect();
  27913. return this;
  27914. }
  27915. setBuffer( audioBuffer ) {
  27916. this.buffer = audioBuffer;
  27917. this.sourceType = 'buffer';
  27918. if ( this.autoplay ) this.play();
  27919. return this;
  27920. }
  27921. play( delay = 0 ) {
  27922. if ( this.isPlaying === true ) {
  27923. console.warn( 'THREE.Audio: Audio is already playing.' );
  27924. return;
  27925. }
  27926. if ( this.hasPlaybackControl === false ) {
  27927. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27928. return;
  27929. }
  27930. this._startedAt = this.context.currentTime + delay;
  27931. const source = this.context.createBufferSource();
  27932. source.buffer = this.buffer;
  27933. source.loop = this.loop;
  27934. source.loopStart = this.loopStart;
  27935. source.loopEnd = this.loopEnd;
  27936. source.onended = this.onEnded.bind( this );
  27937. source.start( this._startedAt, this._progress + this.offset, this.duration );
  27938. this.isPlaying = true;
  27939. this.source = source;
  27940. this.setDetune( this.detune );
  27941. this.setPlaybackRate( this.playbackRate );
  27942. return this.connect();
  27943. }
  27944. pause() {
  27945. if ( this.hasPlaybackControl === false ) {
  27946. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27947. return;
  27948. }
  27949. if ( this.isPlaying === true ) {
  27950. // update current progress
  27951. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  27952. if ( this.loop === true ) {
  27953. // ensure _progress does not exceed duration with looped audios
  27954. this._progress = this._progress % ( this.duration || this.buffer.duration );
  27955. }
  27956. this.source.stop();
  27957. this.source.onended = null;
  27958. this.isPlaying = false;
  27959. }
  27960. return this;
  27961. }
  27962. stop() {
  27963. if ( this.hasPlaybackControl === false ) {
  27964. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27965. return;
  27966. }
  27967. this._progress = 0;
  27968. if ( this.source !== null ) {
  27969. this.source.stop();
  27970. this.source.onended = null;
  27971. }
  27972. this.isPlaying = false;
  27973. return this;
  27974. }
  27975. connect() {
  27976. if ( this.filters.length > 0 ) {
  27977. this.source.connect( this.filters[ 0 ] );
  27978. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  27979. this.filters[ i - 1 ].connect( this.filters[ i ] );
  27980. }
  27981. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  27982. } else {
  27983. this.source.connect( this.getOutput() );
  27984. }
  27985. this._connected = true;
  27986. return this;
  27987. }
  27988. disconnect() {
  27989. if ( this._connected === false ) {
  27990. return;
  27991. }
  27992. if ( this.filters.length > 0 ) {
  27993. this.source.disconnect( this.filters[ 0 ] );
  27994. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  27995. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  27996. }
  27997. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  27998. } else {
  27999. this.source.disconnect( this.getOutput() );
  28000. }
  28001. this._connected = false;
  28002. return this;
  28003. }
  28004. getFilters() {
  28005. return this.filters;
  28006. }
  28007. setFilters( value ) {
  28008. if ( ! value ) value = [];
  28009. if ( this._connected === true ) {
  28010. this.disconnect();
  28011. this.filters = value.slice();
  28012. this.connect();
  28013. } else {
  28014. this.filters = value.slice();
  28015. }
  28016. return this;
  28017. }
  28018. setDetune( value ) {
  28019. this.detune = value;
  28020. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  28021. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  28022. }
  28023. return this;
  28024. }
  28025. getDetune() {
  28026. return this.detune;
  28027. }
  28028. getFilter() {
  28029. return this.getFilters()[ 0 ];
  28030. }
  28031. setFilter( filter ) {
  28032. return this.setFilters( filter ? [ filter ] : [] );
  28033. }
  28034. setPlaybackRate( value ) {
  28035. if ( this.hasPlaybackControl === false ) {
  28036. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28037. return;
  28038. }
  28039. this.playbackRate = value;
  28040. if ( this.isPlaying === true ) {
  28041. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  28042. }
  28043. return this;
  28044. }
  28045. getPlaybackRate() {
  28046. return this.playbackRate;
  28047. }
  28048. onEnded() {
  28049. this.isPlaying = false;
  28050. }
  28051. getLoop() {
  28052. if ( this.hasPlaybackControl === false ) {
  28053. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28054. return false;
  28055. }
  28056. return this.loop;
  28057. }
  28058. setLoop( value ) {
  28059. if ( this.hasPlaybackControl === false ) {
  28060. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28061. return;
  28062. }
  28063. this.loop = value;
  28064. if ( this.isPlaying === true ) {
  28065. this.source.loop = this.loop;
  28066. }
  28067. return this;
  28068. }
  28069. setLoopStart( value ) {
  28070. this.loopStart = value;
  28071. return this;
  28072. }
  28073. setLoopEnd( value ) {
  28074. this.loopEnd = value;
  28075. return this;
  28076. }
  28077. getVolume() {
  28078. return this.gain.gain.value;
  28079. }
  28080. setVolume( value ) {
  28081. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28082. return this;
  28083. }
  28084. }
  28085. const _position = /*@__PURE__*/ new Vector3();
  28086. const _quaternion = /*@__PURE__*/ new Quaternion();
  28087. const _scale = /*@__PURE__*/ new Vector3();
  28088. const _orientation = /*@__PURE__*/ new Vector3();
  28089. class PositionalAudio extends Audio {
  28090. constructor( listener ) {
  28091. super( listener );
  28092. this.panner = this.context.createPanner();
  28093. this.panner.panningModel = 'HRTF';
  28094. this.panner.connect( this.gain );
  28095. }
  28096. connect() {
  28097. super.connect();
  28098. this.panner.connect( this.gain );
  28099. }
  28100. disconnect() {
  28101. super.disconnect();
  28102. this.panner.disconnect( this.gain );
  28103. }
  28104. getOutput() {
  28105. return this.panner;
  28106. }
  28107. getRefDistance() {
  28108. return this.panner.refDistance;
  28109. }
  28110. setRefDistance( value ) {
  28111. this.panner.refDistance = value;
  28112. return this;
  28113. }
  28114. getRolloffFactor() {
  28115. return this.panner.rolloffFactor;
  28116. }
  28117. setRolloffFactor( value ) {
  28118. this.panner.rolloffFactor = value;
  28119. return this;
  28120. }
  28121. getDistanceModel() {
  28122. return this.panner.distanceModel;
  28123. }
  28124. setDistanceModel( value ) {
  28125. this.panner.distanceModel = value;
  28126. return this;
  28127. }
  28128. getMaxDistance() {
  28129. return this.panner.maxDistance;
  28130. }
  28131. setMaxDistance( value ) {
  28132. this.panner.maxDistance = value;
  28133. return this;
  28134. }
  28135. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28136. this.panner.coneInnerAngle = coneInnerAngle;
  28137. this.panner.coneOuterAngle = coneOuterAngle;
  28138. this.panner.coneOuterGain = coneOuterGain;
  28139. return this;
  28140. }
  28141. updateMatrixWorld( force ) {
  28142. super.updateMatrixWorld( force );
  28143. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  28144. this.matrixWorld.decompose( _position, _quaternion, _scale );
  28145. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  28146. const panner = this.panner;
  28147. if ( panner.positionX ) {
  28148. // code path for Chrome and Firefox (see #14393)
  28149. const endTime = this.context.currentTime + this.listener.timeDelta;
  28150. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  28151. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  28152. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  28153. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  28154. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  28155. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  28156. } else {
  28157. panner.setPosition( _position.x, _position.y, _position.z );
  28158. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  28159. }
  28160. }
  28161. }
  28162. class AudioAnalyser {
  28163. constructor( audio, fftSize = 2048 ) {
  28164. this.analyser = audio.context.createAnalyser();
  28165. this.analyser.fftSize = fftSize;
  28166. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28167. audio.getOutput().connect( this.analyser );
  28168. }
  28169. getFrequencyData() {
  28170. this.analyser.getByteFrequencyData( this.data );
  28171. return this.data;
  28172. }
  28173. getAverageFrequency() {
  28174. let value = 0;
  28175. const data = this.getFrequencyData();
  28176. for ( let i = 0; i < data.length; i ++ ) {
  28177. value += data[ i ];
  28178. }
  28179. return value / data.length;
  28180. }
  28181. }
  28182. class PropertyMixer {
  28183. constructor( binding, typeName, valueSize ) {
  28184. this.binding = binding;
  28185. this.valueSize = valueSize;
  28186. let mixFunction,
  28187. mixFunctionAdditive,
  28188. setIdentity;
  28189. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  28190. //
  28191. // interpolators can use .buffer as their .result
  28192. // the data then goes to 'incoming'
  28193. //
  28194. // 'accu0' and 'accu1' are used frame-interleaved for
  28195. // the cumulative result and are compared to detect
  28196. // changes
  28197. //
  28198. // 'orig' stores the original state of the property
  28199. //
  28200. // 'add' is used for additive cumulative results
  28201. //
  28202. // 'work' is optional and is only present for quaternion types. It is used
  28203. // to store intermediate quaternion multiplication results
  28204. switch ( typeName ) {
  28205. case 'quaternion':
  28206. mixFunction = this._slerp;
  28207. mixFunctionAdditive = this._slerpAdditive;
  28208. setIdentity = this._setAdditiveIdentityQuaternion;
  28209. this.buffer = new Float64Array( valueSize * 6 );
  28210. this._workIndex = 5;
  28211. break;
  28212. case 'string':
  28213. case 'bool':
  28214. mixFunction = this._select;
  28215. // Use the regular mix function and for additive on these types,
  28216. // additive is not relevant for non-numeric types
  28217. mixFunctionAdditive = this._select;
  28218. setIdentity = this._setAdditiveIdentityOther;
  28219. this.buffer = new Array( valueSize * 5 );
  28220. break;
  28221. default:
  28222. mixFunction = this._lerp;
  28223. mixFunctionAdditive = this._lerpAdditive;
  28224. setIdentity = this._setAdditiveIdentityNumeric;
  28225. this.buffer = new Float64Array( valueSize * 5 );
  28226. }
  28227. this._mixBufferRegion = mixFunction;
  28228. this._mixBufferRegionAdditive = mixFunctionAdditive;
  28229. this._setIdentity = setIdentity;
  28230. this._origIndex = 3;
  28231. this._addIndex = 4;
  28232. this.cumulativeWeight = 0;
  28233. this.cumulativeWeightAdditive = 0;
  28234. this.useCount = 0;
  28235. this.referenceCount = 0;
  28236. }
  28237. // accumulate data in the 'incoming' region into 'accu<i>'
  28238. accumulate( accuIndex, weight ) {
  28239. // note: happily accumulating nothing when weight = 0, the caller knows
  28240. // the weight and shouldn't have made the call in the first place
  28241. const buffer = this.buffer,
  28242. stride = this.valueSize,
  28243. offset = accuIndex * stride + stride;
  28244. let currentWeight = this.cumulativeWeight;
  28245. if ( currentWeight === 0 ) {
  28246. // accuN := incoming * weight
  28247. for ( let i = 0; i !== stride; ++ i ) {
  28248. buffer[ offset + i ] = buffer[ i ];
  28249. }
  28250. currentWeight = weight;
  28251. } else {
  28252. // accuN := accuN + incoming * weight
  28253. currentWeight += weight;
  28254. const mix = weight / currentWeight;
  28255. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28256. }
  28257. this.cumulativeWeight = currentWeight;
  28258. }
  28259. // accumulate data in the 'incoming' region into 'add'
  28260. accumulateAdditive( weight ) {
  28261. const buffer = this.buffer,
  28262. stride = this.valueSize,
  28263. offset = stride * this._addIndex;
  28264. if ( this.cumulativeWeightAdditive === 0 ) {
  28265. // add = identity
  28266. this._setIdentity();
  28267. }
  28268. // add := add + incoming * weight
  28269. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  28270. this.cumulativeWeightAdditive += weight;
  28271. }
  28272. // apply the state of 'accu<i>' to the binding when accus differ
  28273. apply( accuIndex ) {
  28274. const stride = this.valueSize,
  28275. buffer = this.buffer,
  28276. offset = accuIndex * stride + stride,
  28277. weight = this.cumulativeWeight,
  28278. weightAdditive = this.cumulativeWeightAdditive,
  28279. binding = this.binding;
  28280. this.cumulativeWeight = 0;
  28281. this.cumulativeWeightAdditive = 0;
  28282. if ( weight < 1 ) {
  28283. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28284. const originalValueOffset = stride * this._origIndex;
  28285. this._mixBufferRegion(
  28286. buffer, offset, originalValueOffset, 1 - weight, stride );
  28287. }
  28288. if ( weightAdditive > 0 ) {
  28289. // accuN := accuN + additive accuN
  28290. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  28291. }
  28292. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  28293. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28294. // value has changed -> update scene graph
  28295. binding.setValue( buffer, offset );
  28296. break;
  28297. }
  28298. }
  28299. }
  28300. // remember the state of the bound property and copy it to both accus
  28301. saveOriginalState() {
  28302. const binding = this.binding;
  28303. const buffer = this.buffer,
  28304. stride = this.valueSize,
  28305. originalValueOffset = stride * this._origIndex;
  28306. binding.getValue( buffer, originalValueOffset );
  28307. // accu[0..1] := orig -- initially detect changes against the original
  28308. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  28309. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  28310. }
  28311. // Add to identity for additive
  28312. this._setIdentity();
  28313. this.cumulativeWeight = 0;
  28314. this.cumulativeWeightAdditive = 0;
  28315. }
  28316. // apply the state previously taken via 'saveOriginalState' to the binding
  28317. restoreOriginalState() {
  28318. const originalValueOffset = this.valueSize * 3;
  28319. this.binding.setValue( this.buffer, originalValueOffset );
  28320. }
  28321. _setAdditiveIdentityNumeric() {
  28322. const startIndex = this._addIndex * this.valueSize;
  28323. const endIndex = startIndex + this.valueSize;
  28324. for ( let i = startIndex; i < endIndex; i ++ ) {
  28325. this.buffer[ i ] = 0;
  28326. }
  28327. }
  28328. _setAdditiveIdentityQuaternion() {
  28329. this._setAdditiveIdentityNumeric();
  28330. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  28331. }
  28332. _setAdditiveIdentityOther() {
  28333. const startIndex = this._origIndex * this.valueSize;
  28334. const targetIndex = this._addIndex * this.valueSize;
  28335. for ( let i = 0; i < this.valueSize; i ++ ) {
  28336. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  28337. }
  28338. }
  28339. // mix functions
  28340. _select( buffer, dstOffset, srcOffset, t, stride ) {
  28341. if ( t >= 0.5 ) {
  28342. for ( let i = 0; i !== stride; ++ i ) {
  28343. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  28344. }
  28345. }
  28346. }
  28347. _slerp( buffer, dstOffset, srcOffset, t ) {
  28348. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  28349. }
  28350. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28351. const workOffset = this._workIndex * stride;
  28352. // Store result in intermediate buffer offset
  28353. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  28354. // Slerp to the intermediate result
  28355. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  28356. }
  28357. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  28358. const s = 1 - t;
  28359. for ( let i = 0; i !== stride; ++ i ) {
  28360. const j = dstOffset + i;
  28361. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  28362. }
  28363. }
  28364. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28365. for ( let i = 0; i !== stride; ++ i ) {
  28366. const j = dstOffset + i;
  28367. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  28368. }
  28369. }
  28370. }
  28371. // Characters [].:/ are reserved for track binding syntax.
  28372. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  28373. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  28374. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  28375. // only latin characters, and the unicode \p{L} is not yet supported. So
  28376. // instead, we exclude reserved characters and match everything else.
  28377. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  28378. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  28379. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  28380. // be matched to parse the rest of the track name.
  28381. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  28382. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  28383. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  28384. // Object on target node, and accessor. May not contain reserved
  28385. // characters. Accessor may contain any character except closing bracket.
  28386. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  28387. // Property and accessor. May not contain reserved characters. Accessor may
  28388. // contain any non-bracket characters.
  28389. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  28390. const _trackRe = new RegExp( ''
  28391. + '^'
  28392. + _directoryRe
  28393. + _nodeRe
  28394. + _objectRe
  28395. + _propertyRe
  28396. + '$'
  28397. );
  28398. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  28399. class Composite {
  28400. constructor( targetGroup, path, optionalParsedPath ) {
  28401. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  28402. this._targetGroup = targetGroup;
  28403. this._bindings = targetGroup.subscribe_( path, parsedPath );
  28404. }
  28405. getValue( array, offset ) {
  28406. this.bind(); // bind all binding
  28407. const firstValidIndex = this._targetGroup.nCachedObjects_,
  28408. binding = this._bindings[ firstValidIndex ];
  28409. // and only call .getValue on the first
  28410. if ( binding !== undefined ) binding.getValue( array, offset );
  28411. }
  28412. setValue( array, offset ) {
  28413. const bindings = this._bindings;
  28414. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28415. bindings[ i ].setValue( array, offset );
  28416. }
  28417. }
  28418. bind() {
  28419. const bindings = this._bindings;
  28420. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28421. bindings[ i ].bind();
  28422. }
  28423. }
  28424. unbind() {
  28425. const bindings = this._bindings;
  28426. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28427. bindings[ i ].unbind();
  28428. }
  28429. }
  28430. }
  28431. // Note: This class uses a State pattern on a per-method basis:
  28432. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  28433. // prototype version of these methods with one that represents
  28434. // the bound state. When the property is not found, the methods
  28435. // become no-ops.
  28436. class PropertyBinding {
  28437. constructor( rootNode, path, parsedPath ) {
  28438. this.path = path;
  28439. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  28440. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  28441. this.rootNode = rootNode;
  28442. // initial state of these methods that calls 'bind'
  28443. this.getValue = this._getValue_unbound;
  28444. this.setValue = this._setValue_unbound;
  28445. }
  28446. static create( root, path, parsedPath ) {
  28447. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  28448. return new PropertyBinding( root, path, parsedPath );
  28449. } else {
  28450. return new PropertyBinding.Composite( root, path, parsedPath );
  28451. }
  28452. }
  28453. /**
  28454. * Replaces spaces with underscores and removes unsupported characters from
  28455. * node names, to ensure compatibility with parseTrackName().
  28456. *
  28457. * @param {string} name Node name to be sanitized.
  28458. * @return {string}
  28459. */
  28460. static sanitizeNodeName( name ) {
  28461. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  28462. }
  28463. static parseTrackName( trackName ) {
  28464. const matches = _trackRe.exec( trackName );
  28465. if ( matches === null ) {
  28466. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  28467. }
  28468. const results = {
  28469. // directoryName: matches[ 1 ], // (tschw) currently unused
  28470. nodeName: matches[ 2 ],
  28471. objectName: matches[ 3 ],
  28472. objectIndex: matches[ 4 ],
  28473. propertyName: matches[ 5 ], // required
  28474. propertyIndex: matches[ 6 ]
  28475. };
  28476. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  28477. if ( lastDot !== undefined && lastDot !== - 1 ) {
  28478. const objectName = results.nodeName.substring( lastDot + 1 );
  28479. // Object names must be checked against an allowlist. Otherwise, there
  28480. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  28481. // 'bar' could be the objectName, or part of a nodeName (which can
  28482. // include '.' characters).
  28483. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  28484. results.nodeName = results.nodeName.substring( 0, lastDot );
  28485. results.objectName = objectName;
  28486. }
  28487. }
  28488. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  28489. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  28490. }
  28491. return results;
  28492. }
  28493. static findNode( root, nodeName ) {
  28494. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  28495. return root;
  28496. }
  28497. // search into skeleton bones.
  28498. if ( root.skeleton ) {
  28499. const bone = root.skeleton.getBoneByName( nodeName );
  28500. if ( bone !== undefined ) {
  28501. return bone;
  28502. }
  28503. }
  28504. // search into node subtree.
  28505. if ( root.children ) {
  28506. const searchNodeSubtree = function ( children ) {
  28507. for ( let i = 0; i < children.length; i ++ ) {
  28508. const childNode = children[ i ];
  28509. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  28510. return childNode;
  28511. }
  28512. const result = searchNodeSubtree( childNode.children );
  28513. if ( result ) return result;
  28514. }
  28515. return null;
  28516. };
  28517. const subTreeNode = searchNodeSubtree( root.children );
  28518. if ( subTreeNode ) {
  28519. return subTreeNode;
  28520. }
  28521. }
  28522. return null;
  28523. }
  28524. // these are used to "bind" a nonexistent property
  28525. _getValue_unavailable() {}
  28526. _setValue_unavailable() {}
  28527. // Getters
  28528. _getValue_direct( buffer, offset ) {
  28529. buffer[ offset ] = this.targetObject[ this.propertyName ];
  28530. }
  28531. _getValue_array( buffer, offset ) {
  28532. const source = this.resolvedProperty;
  28533. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  28534. buffer[ offset ++ ] = source[ i ];
  28535. }
  28536. }
  28537. _getValue_arrayElement( buffer, offset ) {
  28538. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  28539. }
  28540. _getValue_toArray( buffer, offset ) {
  28541. this.resolvedProperty.toArray( buffer, offset );
  28542. }
  28543. // Direct
  28544. _setValue_direct( buffer, offset ) {
  28545. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28546. }
  28547. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  28548. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28549. this.targetObject.needsUpdate = true;
  28550. }
  28551. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28552. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28553. this.targetObject.matrixWorldNeedsUpdate = true;
  28554. }
  28555. // EntireArray
  28556. _setValue_array( buffer, offset ) {
  28557. const dest = this.resolvedProperty;
  28558. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28559. dest[ i ] = buffer[ offset ++ ];
  28560. }
  28561. }
  28562. _setValue_array_setNeedsUpdate( buffer, offset ) {
  28563. const dest = this.resolvedProperty;
  28564. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28565. dest[ i ] = buffer[ offset ++ ];
  28566. }
  28567. this.targetObject.needsUpdate = true;
  28568. }
  28569. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28570. const dest = this.resolvedProperty;
  28571. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28572. dest[ i ] = buffer[ offset ++ ];
  28573. }
  28574. this.targetObject.matrixWorldNeedsUpdate = true;
  28575. }
  28576. // ArrayElement
  28577. _setValue_arrayElement( buffer, offset ) {
  28578. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28579. }
  28580. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  28581. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28582. this.targetObject.needsUpdate = true;
  28583. }
  28584. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28585. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28586. this.targetObject.matrixWorldNeedsUpdate = true;
  28587. }
  28588. // HasToFromArray
  28589. _setValue_fromArray( buffer, offset ) {
  28590. this.resolvedProperty.fromArray( buffer, offset );
  28591. }
  28592. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  28593. this.resolvedProperty.fromArray( buffer, offset );
  28594. this.targetObject.needsUpdate = true;
  28595. }
  28596. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28597. this.resolvedProperty.fromArray( buffer, offset );
  28598. this.targetObject.matrixWorldNeedsUpdate = true;
  28599. }
  28600. _getValue_unbound( targetArray, offset ) {
  28601. this.bind();
  28602. this.getValue( targetArray, offset );
  28603. }
  28604. _setValue_unbound( sourceArray, offset ) {
  28605. this.bind();
  28606. this.setValue( sourceArray, offset );
  28607. }
  28608. // create getter / setter pair for a property in the scene graph
  28609. bind() {
  28610. let targetObject = this.node;
  28611. const parsedPath = this.parsedPath;
  28612. const objectName = parsedPath.objectName;
  28613. const propertyName = parsedPath.propertyName;
  28614. let propertyIndex = parsedPath.propertyIndex;
  28615. if ( ! targetObject ) {
  28616. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  28617. this.node = targetObject;
  28618. }
  28619. // set fail state so we can just 'return' on error
  28620. this.getValue = this._getValue_unavailable;
  28621. this.setValue = this._setValue_unavailable;
  28622. // ensure there is a value node
  28623. if ( ! targetObject ) {
  28624. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  28625. return;
  28626. }
  28627. if ( objectName ) {
  28628. let objectIndex = parsedPath.objectIndex;
  28629. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  28630. switch ( objectName ) {
  28631. case 'materials':
  28632. if ( ! targetObject.material ) {
  28633. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28634. return;
  28635. }
  28636. if ( ! targetObject.material.materials ) {
  28637. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  28638. return;
  28639. }
  28640. targetObject = targetObject.material.materials;
  28641. break;
  28642. case 'bones':
  28643. if ( ! targetObject.skeleton ) {
  28644. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  28645. return;
  28646. }
  28647. // potential future optimization: skip this if propertyIndex is already an integer
  28648. // and convert the integer string to a true integer.
  28649. targetObject = targetObject.skeleton.bones;
  28650. // support resolving morphTarget names into indices.
  28651. for ( let i = 0; i < targetObject.length; i ++ ) {
  28652. if ( targetObject[ i ].name === objectIndex ) {
  28653. objectIndex = i;
  28654. break;
  28655. }
  28656. }
  28657. break;
  28658. case 'map':
  28659. if ( 'map' in targetObject ) {
  28660. targetObject = targetObject.map;
  28661. break;
  28662. }
  28663. if ( ! targetObject.material ) {
  28664. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28665. return;
  28666. }
  28667. if ( ! targetObject.material.map ) {
  28668. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  28669. return;
  28670. }
  28671. targetObject = targetObject.material.map;
  28672. break;
  28673. default:
  28674. if ( targetObject[ objectName ] === undefined ) {
  28675. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  28676. return;
  28677. }
  28678. targetObject = targetObject[ objectName ];
  28679. }
  28680. if ( objectIndex !== undefined ) {
  28681. if ( targetObject[ objectIndex ] === undefined ) {
  28682. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  28683. return;
  28684. }
  28685. targetObject = targetObject[ objectIndex ];
  28686. }
  28687. }
  28688. // resolve property
  28689. const nodeProperty = targetObject[ propertyName ];
  28690. if ( nodeProperty === undefined ) {
  28691. const nodeName = parsedPath.nodeName;
  28692. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  28693. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  28694. return;
  28695. }
  28696. // determine versioning scheme
  28697. let versioning = this.Versioning.None;
  28698. this.targetObject = targetObject;
  28699. if ( targetObject.needsUpdate !== undefined ) { // material
  28700. versioning = this.Versioning.NeedsUpdate;
  28701. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  28702. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  28703. }
  28704. // determine how the property gets bound
  28705. let bindingType = this.BindingType.Direct;
  28706. if ( propertyIndex !== undefined ) {
  28707. // access a sub element of the property array (only primitives are supported right now)
  28708. if ( propertyName === 'morphTargetInfluences' ) {
  28709. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  28710. // support resolving morphTarget names into indices.
  28711. if ( ! targetObject.geometry ) {
  28712. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  28713. return;
  28714. }
  28715. if ( ! targetObject.geometry.morphAttributes ) {
  28716. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  28717. return;
  28718. }
  28719. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  28720. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  28721. }
  28722. }
  28723. bindingType = this.BindingType.ArrayElement;
  28724. this.resolvedProperty = nodeProperty;
  28725. this.propertyIndex = propertyIndex;
  28726. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  28727. // must use copy for Object3D.Euler/Quaternion
  28728. bindingType = this.BindingType.HasFromToArray;
  28729. this.resolvedProperty = nodeProperty;
  28730. } else if ( Array.isArray( nodeProperty ) ) {
  28731. bindingType = this.BindingType.EntireArray;
  28732. this.resolvedProperty = nodeProperty;
  28733. } else {
  28734. this.propertyName = propertyName;
  28735. }
  28736. // select getter / setter
  28737. this.getValue = this.GetterByBindingType[ bindingType ];
  28738. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  28739. }
  28740. unbind() {
  28741. this.node = null;
  28742. // back to the prototype version of getValue / setValue
  28743. // note: avoiding to mutate the shape of 'this' via 'delete'
  28744. this.getValue = this._getValue_unbound;
  28745. this.setValue = this._setValue_unbound;
  28746. }
  28747. }
  28748. PropertyBinding.Composite = Composite;
  28749. PropertyBinding.prototype.BindingType = {
  28750. Direct: 0,
  28751. EntireArray: 1,
  28752. ArrayElement: 2,
  28753. HasFromToArray: 3
  28754. };
  28755. PropertyBinding.prototype.Versioning = {
  28756. None: 0,
  28757. NeedsUpdate: 1,
  28758. MatrixWorldNeedsUpdate: 2
  28759. };
  28760. PropertyBinding.prototype.GetterByBindingType = [
  28761. PropertyBinding.prototype._getValue_direct,
  28762. PropertyBinding.prototype._getValue_array,
  28763. PropertyBinding.prototype._getValue_arrayElement,
  28764. PropertyBinding.prototype._getValue_toArray,
  28765. ];
  28766. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  28767. [
  28768. // Direct
  28769. PropertyBinding.prototype._setValue_direct,
  28770. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  28771. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  28772. ], [
  28773. // EntireArray
  28774. PropertyBinding.prototype._setValue_array,
  28775. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  28776. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  28777. ], [
  28778. // ArrayElement
  28779. PropertyBinding.prototype._setValue_arrayElement,
  28780. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  28781. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  28782. ], [
  28783. // HasToFromArray
  28784. PropertyBinding.prototype._setValue_fromArray,
  28785. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  28786. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  28787. ]
  28788. ];
  28789. /**
  28790. *
  28791. * A group of objects that receives a shared animation state.
  28792. *
  28793. * Usage:
  28794. *
  28795. * - Add objects you would otherwise pass as 'root' to the
  28796. * constructor or the .clipAction method of AnimationMixer.
  28797. *
  28798. * - Instead pass this object as 'root'.
  28799. *
  28800. * - You can also add and remove objects later when the mixer
  28801. * is running.
  28802. *
  28803. * Note:
  28804. *
  28805. * Objects of this class appear as one object to the mixer,
  28806. * so cache control of the individual objects must be done
  28807. * on the group.
  28808. *
  28809. * Limitation:
  28810. *
  28811. * - The animated properties must be compatible among the
  28812. * all objects in the group.
  28813. *
  28814. * - A single property can either be controlled through a
  28815. * target group or directly, but not both.
  28816. */
  28817. class AnimationObjectGroup {
  28818. constructor() {
  28819. this.isAnimationObjectGroup = true;
  28820. this.uuid = generateUUID();
  28821. // cached objects followed by the active ones
  28822. this._objects = Array.prototype.slice.call( arguments );
  28823. this.nCachedObjects_ = 0; // threshold
  28824. // note: read by PropertyBinding.Composite
  28825. const indices = {};
  28826. this._indicesByUUID = indices; // for bookkeeping
  28827. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28828. indices[ arguments[ i ].uuid ] = i;
  28829. }
  28830. this._paths = []; // inside: string
  28831. this._parsedPaths = []; // inside: { we don't care, here }
  28832. this._bindings = []; // inside: Array< PropertyBinding >
  28833. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  28834. const scope = this;
  28835. this.stats = {
  28836. objects: {
  28837. get total() {
  28838. return scope._objects.length;
  28839. },
  28840. get inUse() {
  28841. return this.total - scope.nCachedObjects_;
  28842. }
  28843. },
  28844. get bindingsPerObject() {
  28845. return scope._bindings.length;
  28846. }
  28847. };
  28848. }
  28849. add() {
  28850. const objects = this._objects,
  28851. indicesByUUID = this._indicesByUUID,
  28852. paths = this._paths,
  28853. parsedPaths = this._parsedPaths,
  28854. bindings = this._bindings,
  28855. nBindings = bindings.length;
  28856. let knownObject = undefined,
  28857. nObjects = objects.length,
  28858. nCachedObjects = this.nCachedObjects_;
  28859. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28860. const object = arguments[ i ],
  28861. uuid = object.uuid;
  28862. let index = indicesByUUID[ uuid ];
  28863. if ( index === undefined ) {
  28864. // unknown object -> add it to the ACTIVE region
  28865. index = nObjects ++;
  28866. indicesByUUID[ uuid ] = index;
  28867. objects.push( object );
  28868. // accounting is done, now do the same for all bindings
  28869. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28870. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  28871. }
  28872. } else if ( index < nCachedObjects ) {
  28873. knownObject = objects[ index ];
  28874. // move existing object to the ACTIVE region
  28875. const firstActiveIndex = -- nCachedObjects,
  28876. lastCachedObject = objects[ firstActiveIndex ];
  28877. indicesByUUID[ lastCachedObject.uuid ] = index;
  28878. objects[ index ] = lastCachedObject;
  28879. indicesByUUID[ uuid ] = firstActiveIndex;
  28880. objects[ firstActiveIndex ] = object;
  28881. // accounting is done, now do the same for all bindings
  28882. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28883. const bindingsForPath = bindings[ j ],
  28884. lastCached = bindingsForPath[ firstActiveIndex ];
  28885. let binding = bindingsForPath[ index ];
  28886. bindingsForPath[ index ] = lastCached;
  28887. if ( binding === undefined ) {
  28888. // since we do not bother to create new bindings
  28889. // for objects that are cached, the binding may
  28890. // or may not exist
  28891. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  28892. }
  28893. bindingsForPath[ firstActiveIndex ] = binding;
  28894. }
  28895. } else if ( objects[ index ] !== knownObject ) {
  28896. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  28897. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  28898. } // else the object is already where we want it to be
  28899. } // for arguments
  28900. this.nCachedObjects_ = nCachedObjects;
  28901. }
  28902. remove() {
  28903. const objects = this._objects,
  28904. indicesByUUID = this._indicesByUUID,
  28905. bindings = this._bindings,
  28906. nBindings = bindings.length;
  28907. let nCachedObjects = this.nCachedObjects_;
  28908. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28909. const object = arguments[ i ],
  28910. uuid = object.uuid,
  28911. index = indicesByUUID[ uuid ];
  28912. if ( index !== undefined && index >= nCachedObjects ) {
  28913. // move existing object into the CACHED region
  28914. const lastCachedIndex = nCachedObjects ++,
  28915. firstActiveObject = objects[ lastCachedIndex ];
  28916. indicesByUUID[ firstActiveObject.uuid ] = index;
  28917. objects[ index ] = firstActiveObject;
  28918. indicesByUUID[ uuid ] = lastCachedIndex;
  28919. objects[ lastCachedIndex ] = object;
  28920. // accounting is done, now do the same for all bindings
  28921. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28922. const bindingsForPath = bindings[ j ],
  28923. firstActive = bindingsForPath[ lastCachedIndex ],
  28924. binding = bindingsForPath[ index ];
  28925. bindingsForPath[ index ] = firstActive;
  28926. bindingsForPath[ lastCachedIndex ] = binding;
  28927. }
  28928. }
  28929. } // for arguments
  28930. this.nCachedObjects_ = nCachedObjects;
  28931. }
  28932. // remove & forget
  28933. uncache() {
  28934. const objects = this._objects,
  28935. indicesByUUID = this._indicesByUUID,
  28936. bindings = this._bindings,
  28937. nBindings = bindings.length;
  28938. let nCachedObjects = this.nCachedObjects_,
  28939. nObjects = objects.length;
  28940. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28941. const object = arguments[ i ],
  28942. uuid = object.uuid,
  28943. index = indicesByUUID[ uuid ];
  28944. if ( index !== undefined ) {
  28945. delete indicesByUUID[ uuid ];
  28946. if ( index < nCachedObjects ) {
  28947. // object is cached, shrink the CACHED region
  28948. const firstActiveIndex = -- nCachedObjects,
  28949. lastCachedObject = objects[ firstActiveIndex ],
  28950. lastIndex = -- nObjects,
  28951. lastObject = objects[ lastIndex ];
  28952. // last cached object takes this object's place
  28953. indicesByUUID[ lastCachedObject.uuid ] = index;
  28954. objects[ index ] = lastCachedObject;
  28955. // last object goes to the activated slot and pop
  28956. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  28957. objects[ firstActiveIndex ] = lastObject;
  28958. objects.pop();
  28959. // accounting is done, now do the same for all bindings
  28960. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28961. const bindingsForPath = bindings[ j ],
  28962. lastCached = bindingsForPath[ firstActiveIndex ],
  28963. last = bindingsForPath[ lastIndex ];
  28964. bindingsForPath[ index ] = lastCached;
  28965. bindingsForPath[ firstActiveIndex ] = last;
  28966. bindingsForPath.pop();
  28967. }
  28968. } else {
  28969. // object is active, just swap with the last and pop
  28970. const lastIndex = -- nObjects,
  28971. lastObject = objects[ lastIndex ];
  28972. if ( lastIndex > 0 ) {
  28973. indicesByUUID[ lastObject.uuid ] = index;
  28974. }
  28975. objects[ index ] = lastObject;
  28976. objects.pop();
  28977. // accounting is done, now do the same for all bindings
  28978. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28979. const bindingsForPath = bindings[ j ];
  28980. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  28981. bindingsForPath.pop();
  28982. }
  28983. } // cached or active
  28984. } // if object is known
  28985. } // for arguments
  28986. this.nCachedObjects_ = nCachedObjects;
  28987. }
  28988. // Internal interface used by befriended PropertyBinding.Composite:
  28989. subscribe_( path, parsedPath ) {
  28990. // returns an array of bindings for the given path that is changed
  28991. // according to the contained objects in the group
  28992. const indicesByPath = this._bindingsIndicesByPath;
  28993. let index = indicesByPath[ path ];
  28994. const bindings = this._bindings;
  28995. if ( index !== undefined ) return bindings[ index ];
  28996. const paths = this._paths,
  28997. parsedPaths = this._parsedPaths,
  28998. objects = this._objects,
  28999. nObjects = objects.length,
  29000. nCachedObjects = this.nCachedObjects_,
  29001. bindingsForPath = new Array( nObjects );
  29002. index = bindings.length;
  29003. indicesByPath[ path ] = index;
  29004. paths.push( path );
  29005. parsedPaths.push( parsedPath );
  29006. bindings.push( bindingsForPath );
  29007. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29008. const object = objects[ i ];
  29009. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29010. }
  29011. return bindingsForPath;
  29012. }
  29013. unsubscribe_( path ) {
  29014. // tells the group to forget about a property path and no longer
  29015. // update the array previously obtained with 'subscribe_'
  29016. const indicesByPath = this._bindingsIndicesByPath,
  29017. index = indicesByPath[ path ];
  29018. if ( index !== undefined ) {
  29019. const paths = this._paths,
  29020. parsedPaths = this._parsedPaths,
  29021. bindings = this._bindings,
  29022. lastBindingsIndex = bindings.length - 1,
  29023. lastBindings = bindings[ lastBindingsIndex ],
  29024. lastBindingsPath = path[ lastBindingsIndex ];
  29025. indicesByPath[ lastBindingsPath ] = index;
  29026. bindings[ index ] = lastBindings;
  29027. bindings.pop();
  29028. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29029. parsedPaths.pop();
  29030. paths[ index ] = paths[ lastBindingsIndex ];
  29031. paths.pop();
  29032. }
  29033. }
  29034. }
  29035. class AnimationAction {
  29036. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  29037. this._mixer = mixer;
  29038. this._clip = clip;
  29039. this._localRoot = localRoot;
  29040. this.blendMode = blendMode;
  29041. const tracks = clip.tracks,
  29042. nTracks = tracks.length,
  29043. interpolants = new Array( nTracks );
  29044. const interpolantSettings = {
  29045. endingStart: ZeroCurvatureEnding,
  29046. endingEnd: ZeroCurvatureEnding
  29047. };
  29048. for ( let i = 0; i !== nTracks; ++ i ) {
  29049. const interpolant = tracks[ i ].createInterpolant( null );
  29050. interpolants[ i ] = interpolant;
  29051. interpolant.settings = interpolantSettings;
  29052. }
  29053. this._interpolantSettings = interpolantSettings;
  29054. this._interpolants = interpolants; // bound by the mixer
  29055. // inside: PropertyMixer (managed by the mixer)
  29056. this._propertyBindings = new Array( nTracks );
  29057. this._cacheIndex = null; // for the memory manager
  29058. this._byClipCacheIndex = null; // for the memory manager
  29059. this._timeScaleInterpolant = null;
  29060. this._weightInterpolant = null;
  29061. this.loop = LoopRepeat;
  29062. this._loopCount = - 1;
  29063. // global mixer time when the action is to be started
  29064. // it's set back to 'null' upon start of the action
  29065. this._startTime = null;
  29066. // scaled local time of the action
  29067. // gets clamped or wrapped to 0..clip.duration according to loop
  29068. this.time = 0;
  29069. this.timeScale = 1;
  29070. this._effectiveTimeScale = 1;
  29071. this.weight = 1;
  29072. this._effectiveWeight = 1;
  29073. this.repetitions = Infinity; // no. of repetitions when looping
  29074. this.paused = false; // true -> zero effective time scale
  29075. this.enabled = true; // false -> zero effective weight
  29076. this.clampWhenFinished = false;// keep feeding the last frame?
  29077. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29078. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29079. }
  29080. // State & Scheduling
  29081. play() {
  29082. this._mixer._activateAction( this );
  29083. return this;
  29084. }
  29085. stop() {
  29086. this._mixer._deactivateAction( this );
  29087. return this.reset();
  29088. }
  29089. reset() {
  29090. this.paused = false;
  29091. this.enabled = true;
  29092. this.time = 0; // restart clip
  29093. this._loopCount = - 1;// forget previous loops
  29094. this._startTime = null;// forget scheduling
  29095. return this.stopFading().stopWarping();
  29096. }
  29097. isRunning() {
  29098. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29099. this._startTime === null && this._mixer._isActiveAction( this );
  29100. }
  29101. // return true when play has been called
  29102. isScheduled() {
  29103. return this._mixer._isActiveAction( this );
  29104. }
  29105. startAt( time ) {
  29106. this._startTime = time;
  29107. return this;
  29108. }
  29109. setLoop( mode, repetitions ) {
  29110. this.loop = mode;
  29111. this.repetitions = repetitions;
  29112. return this;
  29113. }
  29114. // Weight
  29115. // set the weight stopping any scheduled fading
  29116. // although .enabled = false yields an effective weight of zero, this
  29117. // method does *not* change .enabled, because it would be confusing
  29118. setEffectiveWeight( weight ) {
  29119. this.weight = weight;
  29120. // note: same logic as when updated at runtime
  29121. this._effectiveWeight = this.enabled ? weight : 0;
  29122. return this.stopFading();
  29123. }
  29124. // return the weight considering fading and .enabled
  29125. getEffectiveWeight() {
  29126. return this._effectiveWeight;
  29127. }
  29128. fadeIn( duration ) {
  29129. return this._scheduleFading( duration, 0, 1 );
  29130. }
  29131. fadeOut( duration ) {
  29132. return this._scheduleFading( duration, 1, 0 );
  29133. }
  29134. crossFadeFrom( fadeOutAction, duration, warp ) {
  29135. fadeOutAction.fadeOut( duration );
  29136. this.fadeIn( duration );
  29137. if ( warp ) {
  29138. const fadeInDuration = this._clip.duration,
  29139. fadeOutDuration = fadeOutAction._clip.duration,
  29140. startEndRatio = fadeOutDuration / fadeInDuration,
  29141. endStartRatio = fadeInDuration / fadeOutDuration;
  29142. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29143. this.warp( endStartRatio, 1.0, duration );
  29144. }
  29145. return this;
  29146. }
  29147. crossFadeTo( fadeInAction, duration, warp ) {
  29148. return fadeInAction.crossFadeFrom( this, duration, warp );
  29149. }
  29150. stopFading() {
  29151. const weightInterpolant = this._weightInterpolant;
  29152. if ( weightInterpolant !== null ) {
  29153. this._weightInterpolant = null;
  29154. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29155. }
  29156. return this;
  29157. }
  29158. // Time Scale Control
  29159. // set the time scale stopping any scheduled warping
  29160. // although .paused = true yields an effective time scale of zero, this
  29161. // method does *not* change .paused, because it would be confusing
  29162. setEffectiveTimeScale( timeScale ) {
  29163. this.timeScale = timeScale;
  29164. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29165. return this.stopWarping();
  29166. }
  29167. // return the time scale considering warping and .paused
  29168. getEffectiveTimeScale() {
  29169. return this._effectiveTimeScale;
  29170. }
  29171. setDuration( duration ) {
  29172. this.timeScale = this._clip.duration / duration;
  29173. return this.stopWarping();
  29174. }
  29175. syncWith( action ) {
  29176. this.time = action.time;
  29177. this.timeScale = action.timeScale;
  29178. return this.stopWarping();
  29179. }
  29180. halt( duration ) {
  29181. return this.warp( this._effectiveTimeScale, 0, duration );
  29182. }
  29183. warp( startTimeScale, endTimeScale, duration ) {
  29184. const mixer = this._mixer,
  29185. now = mixer.time,
  29186. timeScale = this.timeScale;
  29187. let interpolant = this._timeScaleInterpolant;
  29188. if ( interpolant === null ) {
  29189. interpolant = mixer._lendControlInterpolant();
  29190. this._timeScaleInterpolant = interpolant;
  29191. }
  29192. const times = interpolant.parameterPositions,
  29193. values = interpolant.sampleValues;
  29194. times[ 0 ] = now;
  29195. times[ 1 ] = now + duration;
  29196. values[ 0 ] = startTimeScale / timeScale;
  29197. values[ 1 ] = endTimeScale / timeScale;
  29198. return this;
  29199. }
  29200. stopWarping() {
  29201. const timeScaleInterpolant = this._timeScaleInterpolant;
  29202. if ( timeScaleInterpolant !== null ) {
  29203. this._timeScaleInterpolant = null;
  29204. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29205. }
  29206. return this;
  29207. }
  29208. // Object Accessors
  29209. getMixer() {
  29210. return this._mixer;
  29211. }
  29212. getClip() {
  29213. return this._clip;
  29214. }
  29215. getRoot() {
  29216. return this._localRoot || this._mixer._root;
  29217. }
  29218. // Interna
  29219. _update( time, deltaTime, timeDirection, accuIndex ) {
  29220. // called by the mixer
  29221. if ( ! this.enabled ) {
  29222. // call ._updateWeight() to update ._effectiveWeight
  29223. this._updateWeight( time );
  29224. return;
  29225. }
  29226. const startTime = this._startTime;
  29227. if ( startTime !== null ) {
  29228. // check for scheduled start of action
  29229. const timeRunning = ( time - startTime ) * timeDirection;
  29230. if ( timeRunning < 0 || timeDirection === 0 ) {
  29231. deltaTime = 0;
  29232. } else {
  29233. this._startTime = null; // unschedule
  29234. deltaTime = timeDirection * timeRunning;
  29235. }
  29236. }
  29237. // apply time scale and advance time
  29238. deltaTime *= this._updateTimeScale( time );
  29239. const clipTime = this._updateTime( deltaTime );
  29240. // note: _updateTime may disable the action resulting in
  29241. // an effective weight of 0
  29242. const weight = this._updateWeight( time );
  29243. if ( weight > 0 ) {
  29244. const interpolants = this._interpolants;
  29245. const propertyMixers = this._propertyBindings;
  29246. switch ( this.blendMode ) {
  29247. case AdditiveAnimationBlendMode:
  29248. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29249. interpolants[ j ].evaluate( clipTime );
  29250. propertyMixers[ j ].accumulateAdditive( weight );
  29251. }
  29252. break;
  29253. case NormalAnimationBlendMode:
  29254. default:
  29255. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29256. interpolants[ j ].evaluate( clipTime );
  29257. propertyMixers[ j ].accumulate( accuIndex, weight );
  29258. }
  29259. }
  29260. }
  29261. }
  29262. _updateWeight( time ) {
  29263. let weight = 0;
  29264. if ( this.enabled ) {
  29265. weight = this.weight;
  29266. const interpolant = this._weightInterpolant;
  29267. if ( interpolant !== null ) {
  29268. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29269. weight *= interpolantValue;
  29270. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29271. this.stopFading();
  29272. if ( interpolantValue === 0 ) {
  29273. // faded out, disable
  29274. this.enabled = false;
  29275. }
  29276. }
  29277. }
  29278. }
  29279. this._effectiveWeight = weight;
  29280. return weight;
  29281. }
  29282. _updateTimeScale( time ) {
  29283. let timeScale = 0;
  29284. if ( ! this.paused ) {
  29285. timeScale = this.timeScale;
  29286. const interpolant = this._timeScaleInterpolant;
  29287. if ( interpolant !== null ) {
  29288. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29289. timeScale *= interpolantValue;
  29290. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29291. this.stopWarping();
  29292. if ( timeScale === 0 ) {
  29293. // motion has halted, pause
  29294. this.paused = true;
  29295. } else {
  29296. // warp done - apply final time scale
  29297. this.timeScale = timeScale;
  29298. }
  29299. }
  29300. }
  29301. }
  29302. this._effectiveTimeScale = timeScale;
  29303. return timeScale;
  29304. }
  29305. _updateTime( deltaTime ) {
  29306. const duration = this._clip.duration;
  29307. const loop = this.loop;
  29308. let time = this.time + deltaTime;
  29309. let loopCount = this._loopCount;
  29310. const pingPong = ( loop === LoopPingPong );
  29311. if ( deltaTime === 0 ) {
  29312. if ( loopCount === - 1 ) return time;
  29313. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  29314. }
  29315. if ( loop === LoopOnce ) {
  29316. if ( loopCount === - 1 ) {
  29317. // just started
  29318. this._loopCount = 0;
  29319. this._setEndings( true, true, false );
  29320. }
  29321. handle_stop: {
  29322. if ( time >= duration ) {
  29323. time = duration;
  29324. } else if ( time < 0 ) {
  29325. time = 0;
  29326. } else {
  29327. this.time = time;
  29328. break handle_stop;
  29329. }
  29330. if ( this.clampWhenFinished ) this.paused = true;
  29331. else this.enabled = false;
  29332. this.time = time;
  29333. this._mixer.dispatchEvent( {
  29334. type: 'finished', action: this,
  29335. direction: deltaTime < 0 ? - 1 : 1
  29336. } );
  29337. }
  29338. } else { // repetitive Repeat or PingPong
  29339. if ( loopCount === - 1 ) {
  29340. // just started
  29341. if ( deltaTime >= 0 ) {
  29342. loopCount = 0;
  29343. this._setEndings( true, this.repetitions === 0, pingPong );
  29344. } else {
  29345. // when looping in reverse direction, the initial
  29346. // transition through zero counts as a repetition,
  29347. // so leave loopCount at -1
  29348. this._setEndings( this.repetitions === 0, true, pingPong );
  29349. }
  29350. }
  29351. if ( time >= duration || time < 0 ) {
  29352. // wrap around
  29353. const loopDelta = Math.floor( time / duration ); // signed
  29354. time -= duration * loopDelta;
  29355. loopCount += Math.abs( loopDelta );
  29356. const pending = this.repetitions - loopCount;
  29357. if ( pending <= 0 ) {
  29358. // have to stop (switch state, clamp time, fire event)
  29359. if ( this.clampWhenFinished ) this.paused = true;
  29360. else this.enabled = false;
  29361. time = deltaTime > 0 ? duration : 0;
  29362. this.time = time;
  29363. this._mixer.dispatchEvent( {
  29364. type: 'finished', action: this,
  29365. direction: deltaTime > 0 ? 1 : - 1
  29366. } );
  29367. } else {
  29368. // keep running
  29369. if ( pending === 1 ) {
  29370. // entering the last round
  29371. const atStart = deltaTime < 0;
  29372. this._setEndings( atStart, ! atStart, pingPong );
  29373. } else {
  29374. this._setEndings( false, false, pingPong );
  29375. }
  29376. this._loopCount = loopCount;
  29377. this.time = time;
  29378. this._mixer.dispatchEvent( {
  29379. type: 'loop', action: this, loopDelta: loopDelta
  29380. } );
  29381. }
  29382. } else {
  29383. this.time = time;
  29384. }
  29385. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  29386. // invert time for the "pong round"
  29387. return duration - time;
  29388. }
  29389. }
  29390. return time;
  29391. }
  29392. _setEndings( atStart, atEnd, pingPong ) {
  29393. const settings = this._interpolantSettings;
  29394. if ( pingPong ) {
  29395. settings.endingStart = ZeroSlopeEnding;
  29396. settings.endingEnd = ZeroSlopeEnding;
  29397. } else {
  29398. // assuming for LoopOnce atStart == atEnd == true
  29399. if ( atStart ) {
  29400. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29401. } else {
  29402. settings.endingStart = WrapAroundEnding;
  29403. }
  29404. if ( atEnd ) {
  29405. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29406. } else {
  29407. settings.endingEnd = WrapAroundEnding;
  29408. }
  29409. }
  29410. }
  29411. _scheduleFading( duration, weightNow, weightThen ) {
  29412. const mixer = this._mixer, now = mixer.time;
  29413. let interpolant = this._weightInterpolant;
  29414. if ( interpolant === null ) {
  29415. interpolant = mixer._lendControlInterpolant();
  29416. this._weightInterpolant = interpolant;
  29417. }
  29418. const times = interpolant.parameterPositions,
  29419. values = interpolant.sampleValues;
  29420. times[ 0 ] = now;
  29421. values[ 0 ] = weightNow;
  29422. times[ 1 ] = now + duration;
  29423. values[ 1 ] = weightThen;
  29424. return this;
  29425. }
  29426. }
  29427. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  29428. class AnimationMixer extends EventDispatcher {
  29429. constructor( root ) {
  29430. super();
  29431. this._root = root;
  29432. this._initMemoryManager();
  29433. this._accuIndex = 0;
  29434. this.time = 0;
  29435. this.timeScale = 1.0;
  29436. }
  29437. _bindAction( action, prototypeAction ) {
  29438. const root = action._localRoot || this._root,
  29439. tracks = action._clip.tracks,
  29440. nTracks = tracks.length,
  29441. bindings = action._propertyBindings,
  29442. interpolants = action._interpolants,
  29443. rootUuid = root.uuid,
  29444. bindingsByRoot = this._bindingsByRootAndName;
  29445. let bindingsByName = bindingsByRoot[ rootUuid ];
  29446. if ( bindingsByName === undefined ) {
  29447. bindingsByName = {};
  29448. bindingsByRoot[ rootUuid ] = bindingsByName;
  29449. }
  29450. for ( let i = 0; i !== nTracks; ++ i ) {
  29451. const track = tracks[ i ],
  29452. trackName = track.name;
  29453. let binding = bindingsByName[ trackName ];
  29454. if ( binding !== undefined ) {
  29455. ++ binding.referenceCount;
  29456. bindings[ i ] = binding;
  29457. } else {
  29458. binding = bindings[ i ];
  29459. if ( binding !== undefined ) {
  29460. // existing binding, make sure the cache knows
  29461. if ( binding._cacheIndex === null ) {
  29462. ++ binding.referenceCount;
  29463. this._addInactiveBinding( binding, rootUuid, trackName );
  29464. }
  29465. continue;
  29466. }
  29467. const path = prototypeAction && prototypeAction.
  29468. _propertyBindings[ i ].binding.parsedPath;
  29469. binding = new PropertyMixer(
  29470. PropertyBinding.create( root, trackName, path ),
  29471. track.ValueTypeName, track.getValueSize() );
  29472. ++ binding.referenceCount;
  29473. this._addInactiveBinding( binding, rootUuid, trackName );
  29474. bindings[ i ] = binding;
  29475. }
  29476. interpolants[ i ].resultBuffer = binding.buffer;
  29477. }
  29478. }
  29479. _activateAction( action ) {
  29480. if ( ! this._isActiveAction( action ) ) {
  29481. if ( action._cacheIndex === null ) {
  29482. // this action has been forgotten by the cache, but the user
  29483. // appears to be still using it -> rebind
  29484. const rootUuid = ( action._localRoot || this._root ).uuid,
  29485. clipUuid = action._clip.uuid,
  29486. actionsForClip = this._actionsByClip[ clipUuid ];
  29487. this._bindAction( action,
  29488. actionsForClip && actionsForClip.knownActions[ 0 ] );
  29489. this._addInactiveAction( action, clipUuid, rootUuid );
  29490. }
  29491. const bindings = action._propertyBindings;
  29492. // increment reference counts / sort out state
  29493. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29494. const binding = bindings[ i ];
  29495. if ( binding.useCount ++ === 0 ) {
  29496. this._lendBinding( binding );
  29497. binding.saveOriginalState();
  29498. }
  29499. }
  29500. this._lendAction( action );
  29501. }
  29502. }
  29503. _deactivateAction( action ) {
  29504. if ( this._isActiveAction( action ) ) {
  29505. const bindings = action._propertyBindings;
  29506. // decrement reference counts / sort out state
  29507. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29508. const binding = bindings[ i ];
  29509. if ( -- binding.useCount === 0 ) {
  29510. binding.restoreOriginalState();
  29511. this._takeBackBinding( binding );
  29512. }
  29513. }
  29514. this._takeBackAction( action );
  29515. }
  29516. }
  29517. // Memory manager
  29518. _initMemoryManager() {
  29519. this._actions = []; // 'nActiveActions' followed by inactive ones
  29520. this._nActiveActions = 0;
  29521. this._actionsByClip = {};
  29522. // inside:
  29523. // {
  29524. // knownActions: Array< AnimationAction > - used as prototypes
  29525. // actionByRoot: AnimationAction - lookup
  29526. // }
  29527. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  29528. this._nActiveBindings = 0;
  29529. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  29530. this._controlInterpolants = []; // same game as above
  29531. this._nActiveControlInterpolants = 0;
  29532. const scope = this;
  29533. this.stats = {
  29534. actions: {
  29535. get total() {
  29536. return scope._actions.length;
  29537. },
  29538. get inUse() {
  29539. return scope._nActiveActions;
  29540. }
  29541. },
  29542. bindings: {
  29543. get total() {
  29544. return scope._bindings.length;
  29545. },
  29546. get inUse() {
  29547. return scope._nActiveBindings;
  29548. }
  29549. },
  29550. controlInterpolants: {
  29551. get total() {
  29552. return scope._controlInterpolants.length;
  29553. },
  29554. get inUse() {
  29555. return scope._nActiveControlInterpolants;
  29556. }
  29557. }
  29558. };
  29559. }
  29560. // Memory management for AnimationAction objects
  29561. _isActiveAction( action ) {
  29562. const index = action._cacheIndex;
  29563. return index !== null && index < this._nActiveActions;
  29564. }
  29565. _addInactiveAction( action, clipUuid, rootUuid ) {
  29566. const actions = this._actions,
  29567. actionsByClip = this._actionsByClip;
  29568. let actionsForClip = actionsByClip[ clipUuid ];
  29569. if ( actionsForClip === undefined ) {
  29570. actionsForClip = {
  29571. knownActions: [ action ],
  29572. actionByRoot: {}
  29573. };
  29574. action._byClipCacheIndex = 0;
  29575. actionsByClip[ clipUuid ] = actionsForClip;
  29576. } else {
  29577. const knownActions = actionsForClip.knownActions;
  29578. action._byClipCacheIndex = knownActions.length;
  29579. knownActions.push( action );
  29580. }
  29581. action._cacheIndex = actions.length;
  29582. actions.push( action );
  29583. actionsForClip.actionByRoot[ rootUuid ] = action;
  29584. }
  29585. _removeInactiveAction( action ) {
  29586. const actions = this._actions,
  29587. lastInactiveAction = actions[ actions.length - 1 ],
  29588. cacheIndex = action._cacheIndex;
  29589. lastInactiveAction._cacheIndex = cacheIndex;
  29590. actions[ cacheIndex ] = lastInactiveAction;
  29591. actions.pop();
  29592. action._cacheIndex = null;
  29593. const clipUuid = action._clip.uuid,
  29594. actionsByClip = this._actionsByClip,
  29595. actionsForClip = actionsByClip[ clipUuid ],
  29596. knownActionsForClip = actionsForClip.knownActions,
  29597. lastKnownAction =
  29598. knownActionsForClip[ knownActionsForClip.length - 1 ],
  29599. byClipCacheIndex = action._byClipCacheIndex;
  29600. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  29601. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  29602. knownActionsForClip.pop();
  29603. action._byClipCacheIndex = null;
  29604. const actionByRoot = actionsForClip.actionByRoot,
  29605. rootUuid = ( action._localRoot || this._root ).uuid;
  29606. delete actionByRoot[ rootUuid ];
  29607. if ( knownActionsForClip.length === 0 ) {
  29608. delete actionsByClip[ clipUuid ];
  29609. }
  29610. this._removeInactiveBindingsForAction( action );
  29611. }
  29612. _removeInactiveBindingsForAction( action ) {
  29613. const bindings = action._propertyBindings;
  29614. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29615. const binding = bindings[ i ];
  29616. if ( -- binding.referenceCount === 0 ) {
  29617. this._removeInactiveBinding( binding );
  29618. }
  29619. }
  29620. }
  29621. _lendAction( action ) {
  29622. // [ active actions | inactive actions ]
  29623. // [ active actions >| inactive actions ]
  29624. // s a
  29625. // <-swap->
  29626. // a s
  29627. const actions = this._actions,
  29628. prevIndex = action._cacheIndex,
  29629. lastActiveIndex = this._nActiveActions ++,
  29630. firstInactiveAction = actions[ lastActiveIndex ];
  29631. action._cacheIndex = lastActiveIndex;
  29632. actions[ lastActiveIndex ] = action;
  29633. firstInactiveAction._cacheIndex = prevIndex;
  29634. actions[ prevIndex ] = firstInactiveAction;
  29635. }
  29636. _takeBackAction( action ) {
  29637. // [ active actions | inactive actions ]
  29638. // [ active actions |< inactive actions ]
  29639. // a s
  29640. // <-swap->
  29641. // s a
  29642. const actions = this._actions,
  29643. prevIndex = action._cacheIndex,
  29644. firstInactiveIndex = -- this._nActiveActions,
  29645. lastActiveAction = actions[ firstInactiveIndex ];
  29646. action._cacheIndex = firstInactiveIndex;
  29647. actions[ firstInactiveIndex ] = action;
  29648. lastActiveAction._cacheIndex = prevIndex;
  29649. actions[ prevIndex ] = lastActiveAction;
  29650. }
  29651. // Memory management for PropertyMixer objects
  29652. _addInactiveBinding( binding, rootUuid, trackName ) {
  29653. const bindingsByRoot = this._bindingsByRootAndName,
  29654. bindings = this._bindings;
  29655. let bindingByName = bindingsByRoot[ rootUuid ];
  29656. if ( bindingByName === undefined ) {
  29657. bindingByName = {};
  29658. bindingsByRoot[ rootUuid ] = bindingByName;
  29659. }
  29660. bindingByName[ trackName ] = binding;
  29661. binding._cacheIndex = bindings.length;
  29662. bindings.push( binding );
  29663. }
  29664. _removeInactiveBinding( binding ) {
  29665. const bindings = this._bindings,
  29666. propBinding = binding.binding,
  29667. rootUuid = propBinding.rootNode.uuid,
  29668. trackName = propBinding.path,
  29669. bindingsByRoot = this._bindingsByRootAndName,
  29670. bindingByName = bindingsByRoot[ rootUuid ],
  29671. lastInactiveBinding = bindings[ bindings.length - 1 ],
  29672. cacheIndex = binding._cacheIndex;
  29673. lastInactiveBinding._cacheIndex = cacheIndex;
  29674. bindings[ cacheIndex ] = lastInactiveBinding;
  29675. bindings.pop();
  29676. delete bindingByName[ trackName ];
  29677. if ( Object.keys( bindingByName ).length === 0 ) {
  29678. delete bindingsByRoot[ rootUuid ];
  29679. }
  29680. }
  29681. _lendBinding( binding ) {
  29682. const bindings = this._bindings,
  29683. prevIndex = binding._cacheIndex,
  29684. lastActiveIndex = this._nActiveBindings ++,
  29685. firstInactiveBinding = bindings[ lastActiveIndex ];
  29686. binding._cacheIndex = lastActiveIndex;
  29687. bindings[ lastActiveIndex ] = binding;
  29688. firstInactiveBinding._cacheIndex = prevIndex;
  29689. bindings[ prevIndex ] = firstInactiveBinding;
  29690. }
  29691. _takeBackBinding( binding ) {
  29692. const bindings = this._bindings,
  29693. prevIndex = binding._cacheIndex,
  29694. firstInactiveIndex = -- this._nActiveBindings,
  29695. lastActiveBinding = bindings[ firstInactiveIndex ];
  29696. binding._cacheIndex = firstInactiveIndex;
  29697. bindings[ firstInactiveIndex ] = binding;
  29698. lastActiveBinding._cacheIndex = prevIndex;
  29699. bindings[ prevIndex ] = lastActiveBinding;
  29700. }
  29701. // Memory management of Interpolants for weight and time scale
  29702. _lendControlInterpolant() {
  29703. const interpolants = this._controlInterpolants,
  29704. lastActiveIndex = this._nActiveControlInterpolants ++;
  29705. let interpolant = interpolants[ lastActiveIndex ];
  29706. if ( interpolant === undefined ) {
  29707. interpolant = new LinearInterpolant(
  29708. new Float32Array( 2 ), new Float32Array( 2 ),
  29709. 1, _controlInterpolantsResultBuffer );
  29710. interpolant.__cacheIndex = lastActiveIndex;
  29711. interpolants[ lastActiveIndex ] = interpolant;
  29712. }
  29713. return interpolant;
  29714. }
  29715. _takeBackControlInterpolant( interpolant ) {
  29716. const interpolants = this._controlInterpolants,
  29717. prevIndex = interpolant.__cacheIndex,
  29718. firstInactiveIndex = -- this._nActiveControlInterpolants,
  29719. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  29720. interpolant.__cacheIndex = firstInactiveIndex;
  29721. interpolants[ firstInactiveIndex ] = interpolant;
  29722. lastActiveInterpolant.__cacheIndex = prevIndex;
  29723. interpolants[ prevIndex ] = lastActiveInterpolant;
  29724. }
  29725. // return an action for a clip optionally using a custom root target
  29726. // object (this method allocates a lot of dynamic memory in case a
  29727. // previously unknown clip/root combination is specified)
  29728. clipAction( clip, optionalRoot, blendMode ) {
  29729. const root = optionalRoot || this._root,
  29730. rootUuid = root.uuid;
  29731. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  29732. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  29733. const actionsForClip = this._actionsByClip[ clipUuid ];
  29734. let prototypeAction = null;
  29735. if ( blendMode === undefined ) {
  29736. if ( clipObject !== null ) {
  29737. blendMode = clipObject.blendMode;
  29738. } else {
  29739. blendMode = NormalAnimationBlendMode;
  29740. }
  29741. }
  29742. if ( actionsForClip !== undefined ) {
  29743. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  29744. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  29745. return existingAction;
  29746. }
  29747. // we know the clip, so we don't have to parse all
  29748. // the bindings again but can just copy
  29749. prototypeAction = actionsForClip.knownActions[ 0 ];
  29750. // also, take the clip from the prototype action
  29751. if ( clipObject === null )
  29752. clipObject = prototypeAction._clip;
  29753. }
  29754. // clip must be known when specified via string
  29755. if ( clipObject === null ) return null;
  29756. // allocate all resources required to run it
  29757. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  29758. this._bindAction( newAction, prototypeAction );
  29759. // and make the action known to the memory manager
  29760. this._addInactiveAction( newAction, clipUuid, rootUuid );
  29761. return newAction;
  29762. }
  29763. // get an existing action
  29764. existingAction( clip, optionalRoot ) {
  29765. const root = optionalRoot || this._root,
  29766. rootUuid = root.uuid,
  29767. clipObject = typeof clip === 'string' ?
  29768. AnimationClip.findByName( root, clip ) : clip,
  29769. clipUuid = clipObject ? clipObject.uuid : clip,
  29770. actionsForClip = this._actionsByClip[ clipUuid ];
  29771. if ( actionsForClip !== undefined ) {
  29772. return actionsForClip.actionByRoot[ rootUuid ] || null;
  29773. }
  29774. return null;
  29775. }
  29776. // deactivates all previously scheduled actions
  29777. stopAllAction() {
  29778. const actions = this._actions,
  29779. nActions = this._nActiveActions;
  29780. for ( let i = nActions - 1; i >= 0; -- i ) {
  29781. actions[ i ].stop();
  29782. }
  29783. return this;
  29784. }
  29785. // advance the time and update apply the animation
  29786. update( deltaTime ) {
  29787. deltaTime *= this.timeScale;
  29788. const actions = this._actions,
  29789. nActions = this._nActiveActions,
  29790. time = this.time += deltaTime,
  29791. timeDirection = Math.sign( deltaTime ),
  29792. accuIndex = this._accuIndex ^= 1;
  29793. // run active actions
  29794. for ( let i = 0; i !== nActions; ++ i ) {
  29795. const action = actions[ i ];
  29796. action._update( time, deltaTime, timeDirection, accuIndex );
  29797. }
  29798. // update scene graph
  29799. const bindings = this._bindings,
  29800. nBindings = this._nActiveBindings;
  29801. for ( let i = 0; i !== nBindings; ++ i ) {
  29802. bindings[ i ].apply( accuIndex );
  29803. }
  29804. return this;
  29805. }
  29806. // Allows you to seek to a specific time in an animation.
  29807. setTime( timeInSeconds ) {
  29808. this.time = 0; // Zero out time attribute for AnimationMixer object;
  29809. for ( let i = 0; i < this._actions.length; i ++ ) {
  29810. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  29811. }
  29812. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  29813. }
  29814. // return this mixer's root target object
  29815. getRoot() {
  29816. return this._root;
  29817. }
  29818. // free all resources specific to a particular clip
  29819. uncacheClip( clip ) {
  29820. const actions = this._actions,
  29821. clipUuid = clip.uuid,
  29822. actionsByClip = this._actionsByClip,
  29823. actionsForClip = actionsByClip[ clipUuid ];
  29824. if ( actionsForClip !== undefined ) {
  29825. // note: just calling _removeInactiveAction would mess up the
  29826. // iteration state and also require updating the state we can
  29827. // just throw away
  29828. const actionsToRemove = actionsForClip.knownActions;
  29829. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  29830. const action = actionsToRemove[ i ];
  29831. this._deactivateAction( action );
  29832. const cacheIndex = action._cacheIndex,
  29833. lastInactiveAction = actions[ actions.length - 1 ];
  29834. action._cacheIndex = null;
  29835. action._byClipCacheIndex = null;
  29836. lastInactiveAction._cacheIndex = cacheIndex;
  29837. actions[ cacheIndex ] = lastInactiveAction;
  29838. actions.pop();
  29839. this._removeInactiveBindingsForAction( action );
  29840. }
  29841. delete actionsByClip[ clipUuid ];
  29842. }
  29843. }
  29844. // free all resources specific to a particular root target object
  29845. uncacheRoot( root ) {
  29846. const rootUuid = root.uuid,
  29847. actionsByClip = this._actionsByClip;
  29848. for ( const clipUuid in actionsByClip ) {
  29849. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  29850. action = actionByRoot[ rootUuid ];
  29851. if ( action !== undefined ) {
  29852. this._deactivateAction( action );
  29853. this._removeInactiveAction( action );
  29854. }
  29855. }
  29856. const bindingsByRoot = this._bindingsByRootAndName,
  29857. bindingByName = bindingsByRoot[ rootUuid ];
  29858. if ( bindingByName !== undefined ) {
  29859. for ( const trackName in bindingByName ) {
  29860. const binding = bindingByName[ trackName ];
  29861. binding.restoreOriginalState();
  29862. this._removeInactiveBinding( binding );
  29863. }
  29864. }
  29865. }
  29866. // remove a targeted clip from the cache
  29867. uncacheAction( clip, optionalRoot ) {
  29868. const action = this.existingAction( clip, optionalRoot );
  29869. if ( action !== null ) {
  29870. this._deactivateAction( action );
  29871. this._removeInactiveAction( action );
  29872. }
  29873. }
  29874. }
  29875. class Uniform {
  29876. constructor( value ) {
  29877. this.value = value;
  29878. }
  29879. clone() {
  29880. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  29881. }
  29882. }
  29883. let _id = 0;
  29884. class UniformsGroup extends EventDispatcher {
  29885. constructor() {
  29886. super();
  29887. this.isUniformsGroup = true;
  29888. Object.defineProperty( this, 'id', { value: _id ++ } );
  29889. this.name = '';
  29890. this.usage = StaticDrawUsage;
  29891. this.uniforms = [];
  29892. }
  29893. add( uniform ) {
  29894. this.uniforms.push( uniform );
  29895. return this;
  29896. }
  29897. remove( uniform ) {
  29898. const index = this.uniforms.indexOf( uniform );
  29899. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  29900. return this;
  29901. }
  29902. setName( name ) {
  29903. this.name = name;
  29904. return this;
  29905. }
  29906. setUsage( value ) {
  29907. this.usage = value;
  29908. return this;
  29909. }
  29910. dispose() {
  29911. this.dispatchEvent( { type: 'dispose' } );
  29912. return this;
  29913. }
  29914. copy( source ) {
  29915. this.name = source.name;
  29916. this.usage = source.usage;
  29917. const uniformsSource = source.uniforms;
  29918. this.uniforms.length = 0;
  29919. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  29920. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  29921. for ( let j = 0; j < uniforms.length; j ++ ) {
  29922. this.uniforms.push( uniforms[ j ].clone() );
  29923. }
  29924. }
  29925. return this;
  29926. }
  29927. clone() {
  29928. return new this.constructor().copy( this );
  29929. }
  29930. }
  29931. class InstancedInterleavedBuffer extends InterleavedBuffer {
  29932. constructor( array, stride, meshPerAttribute = 1 ) {
  29933. super( array, stride );
  29934. this.isInstancedInterleavedBuffer = true;
  29935. this.meshPerAttribute = meshPerAttribute;
  29936. }
  29937. copy( source ) {
  29938. super.copy( source );
  29939. this.meshPerAttribute = source.meshPerAttribute;
  29940. return this;
  29941. }
  29942. clone( data ) {
  29943. const ib = super.clone( data );
  29944. ib.meshPerAttribute = this.meshPerAttribute;
  29945. return ib;
  29946. }
  29947. toJSON( data ) {
  29948. const json = super.toJSON( data );
  29949. json.isInstancedInterleavedBuffer = true;
  29950. json.meshPerAttribute = this.meshPerAttribute;
  29951. return json;
  29952. }
  29953. }
  29954. class GLBufferAttribute {
  29955. constructor( buffer, type, itemSize, elementSize, count ) {
  29956. this.isGLBufferAttribute = true;
  29957. this.name = '';
  29958. this.buffer = buffer;
  29959. this.type = type;
  29960. this.itemSize = itemSize;
  29961. this.elementSize = elementSize;
  29962. this.count = count;
  29963. this.version = 0;
  29964. }
  29965. set needsUpdate( value ) {
  29966. if ( value === true ) this.version ++;
  29967. }
  29968. setBuffer( buffer ) {
  29969. this.buffer = buffer;
  29970. return this;
  29971. }
  29972. setType( type, elementSize ) {
  29973. this.type = type;
  29974. this.elementSize = elementSize;
  29975. return this;
  29976. }
  29977. setItemSize( itemSize ) {
  29978. this.itemSize = itemSize;
  29979. return this;
  29980. }
  29981. setCount( count ) {
  29982. this.count = count;
  29983. return this;
  29984. }
  29985. }
  29986. const _matrix = /*@__PURE__*/ new Matrix4();
  29987. class Raycaster {
  29988. constructor( origin, direction, near = 0, far = Infinity ) {
  29989. this.ray = new Ray( origin, direction );
  29990. // direction is assumed to be normalized (for accurate distance calculations)
  29991. this.near = near;
  29992. this.far = far;
  29993. this.camera = null;
  29994. this.layers = new Layers();
  29995. this.params = {
  29996. Mesh: {},
  29997. Line: { threshold: 1 },
  29998. LOD: {},
  29999. Points: { threshold: 1 },
  30000. Sprite: {}
  30001. };
  30002. }
  30003. set( origin, direction ) {
  30004. // direction is assumed to be normalized (for accurate distance calculations)
  30005. this.ray.set( origin, direction );
  30006. }
  30007. setFromCamera( coords, camera ) {
  30008. if ( camera.isPerspectiveCamera ) {
  30009. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30010. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30011. this.camera = camera;
  30012. } else if ( camera.isOrthographicCamera ) {
  30013. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30014. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  30015. this.camera = camera;
  30016. } else {
  30017. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  30018. }
  30019. }
  30020. setFromXRController( controller ) {
  30021. _matrix.identity().extractRotation( controller.matrixWorld );
  30022. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  30023. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  30024. return this;
  30025. }
  30026. intersectObject( object, recursive = true, intersects = [] ) {
  30027. intersect( object, this, intersects, recursive );
  30028. intersects.sort( ascSort );
  30029. return intersects;
  30030. }
  30031. intersectObjects( objects, recursive = true, intersects = [] ) {
  30032. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  30033. intersect( objects[ i ], this, intersects, recursive );
  30034. }
  30035. intersects.sort( ascSort );
  30036. return intersects;
  30037. }
  30038. }
  30039. function ascSort( a, b ) {
  30040. return a.distance - b.distance;
  30041. }
  30042. function intersect( object, raycaster, intersects, recursive ) {
  30043. if ( object.layers.test( raycaster.layers ) ) {
  30044. object.raycast( raycaster, intersects );
  30045. }
  30046. if ( recursive === true ) {
  30047. const children = object.children;
  30048. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30049. intersect( children[ i ], raycaster, intersects, true );
  30050. }
  30051. }
  30052. }
  30053. /**
  30054. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  30055. *
  30056. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  30057. * theta (the azimuthal angle) is measured from the positive z-axis.
  30058. */
  30059. class Spherical {
  30060. constructor( radius = 1, phi = 0, theta = 0 ) {
  30061. this.radius = radius;
  30062. this.phi = phi; // polar angle
  30063. this.theta = theta; // azimuthal angle
  30064. return this;
  30065. }
  30066. set( radius, phi, theta ) {
  30067. this.radius = radius;
  30068. this.phi = phi;
  30069. this.theta = theta;
  30070. return this;
  30071. }
  30072. copy( other ) {
  30073. this.radius = other.radius;
  30074. this.phi = other.phi;
  30075. this.theta = other.theta;
  30076. return this;
  30077. }
  30078. // restrict phi to be between EPS and PI-EPS
  30079. makeSafe() {
  30080. const EPS = 0.000001;
  30081. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  30082. return this;
  30083. }
  30084. setFromVector3( v ) {
  30085. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30086. }
  30087. setFromCartesianCoords( x, y, z ) {
  30088. this.radius = Math.sqrt( x * x + y * y + z * z );
  30089. if ( this.radius === 0 ) {
  30090. this.theta = 0;
  30091. this.phi = 0;
  30092. } else {
  30093. this.theta = Math.atan2( x, z );
  30094. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  30095. }
  30096. return this;
  30097. }
  30098. clone() {
  30099. return new this.constructor().copy( this );
  30100. }
  30101. }
  30102. /**
  30103. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  30104. */
  30105. class Cylindrical {
  30106. constructor( radius = 1, theta = 0, y = 0 ) {
  30107. this.radius = radius; // distance from the origin to a point in the x-z plane
  30108. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  30109. this.y = y; // height above the x-z plane
  30110. return this;
  30111. }
  30112. set( radius, theta, y ) {
  30113. this.radius = radius;
  30114. this.theta = theta;
  30115. this.y = y;
  30116. return this;
  30117. }
  30118. copy( other ) {
  30119. this.radius = other.radius;
  30120. this.theta = other.theta;
  30121. this.y = other.y;
  30122. return this;
  30123. }
  30124. setFromVector3( v ) {
  30125. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30126. }
  30127. setFromCartesianCoords( x, y, z ) {
  30128. this.radius = Math.sqrt( x * x + z * z );
  30129. this.theta = Math.atan2( x, z );
  30130. this.y = y;
  30131. return this;
  30132. }
  30133. clone() {
  30134. return new this.constructor().copy( this );
  30135. }
  30136. }
  30137. const _vector$4 = /*@__PURE__*/ new Vector2();
  30138. class Box2 {
  30139. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  30140. this.isBox2 = true;
  30141. this.min = min;
  30142. this.max = max;
  30143. }
  30144. set( min, max ) {
  30145. this.min.copy( min );
  30146. this.max.copy( max );
  30147. return this;
  30148. }
  30149. setFromPoints( points ) {
  30150. this.makeEmpty();
  30151. for ( let i = 0, il = points.length; i < il; i ++ ) {
  30152. this.expandByPoint( points[ i ] );
  30153. }
  30154. return this;
  30155. }
  30156. setFromCenterAndSize( center, size ) {
  30157. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  30158. this.min.copy( center ).sub( halfSize );
  30159. this.max.copy( center ).add( halfSize );
  30160. return this;
  30161. }
  30162. clone() {
  30163. return new this.constructor().copy( this );
  30164. }
  30165. copy( box ) {
  30166. this.min.copy( box.min );
  30167. this.max.copy( box.max );
  30168. return this;
  30169. }
  30170. makeEmpty() {
  30171. this.min.x = this.min.y = + Infinity;
  30172. this.max.x = this.max.y = - Infinity;
  30173. return this;
  30174. }
  30175. isEmpty() {
  30176. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  30177. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  30178. }
  30179. getCenter( target ) {
  30180. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  30181. }
  30182. getSize( target ) {
  30183. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  30184. }
  30185. expandByPoint( point ) {
  30186. this.min.min( point );
  30187. this.max.max( point );
  30188. return this;
  30189. }
  30190. expandByVector( vector ) {
  30191. this.min.sub( vector );
  30192. this.max.add( vector );
  30193. return this;
  30194. }
  30195. expandByScalar( scalar ) {
  30196. this.min.addScalar( - scalar );
  30197. this.max.addScalar( scalar );
  30198. return this;
  30199. }
  30200. containsPoint( point ) {
  30201. return point.x < this.min.x || point.x > this.max.x ||
  30202. point.y < this.min.y || point.y > this.max.y ? false : true;
  30203. }
  30204. containsBox( box ) {
  30205. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  30206. this.min.y <= box.min.y && box.max.y <= this.max.y;
  30207. }
  30208. getParameter( point, target ) {
  30209. // This can potentially have a divide by zero if the box
  30210. // has a size dimension of 0.
  30211. return target.set(
  30212. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  30213. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  30214. );
  30215. }
  30216. intersectsBox( box ) {
  30217. // using 4 splitting planes to rule out intersections
  30218. return box.max.x < this.min.x || box.min.x > this.max.x ||
  30219. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  30220. }
  30221. clampPoint( point, target ) {
  30222. return target.copy( point ).clamp( this.min, this.max );
  30223. }
  30224. distanceToPoint( point ) {
  30225. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  30226. }
  30227. intersect( box ) {
  30228. this.min.max( box.min );
  30229. this.max.min( box.max );
  30230. if ( this.isEmpty() ) this.makeEmpty();
  30231. return this;
  30232. }
  30233. union( box ) {
  30234. this.min.min( box.min );
  30235. this.max.max( box.max );
  30236. return this;
  30237. }
  30238. translate( offset ) {
  30239. this.min.add( offset );
  30240. this.max.add( offset );
  30241. return this;
  30242. }
  30243. equals( box ) {
  30244. return box.min.equals( this.min ) && box.max.equals( this.max );
  30245. }
  30246. }
  30247. const _startP = /*@__PURE__*/ new Vector3();
  30248. const _startEnd = /*@__PURE__*/ new Vector3();
  30249. class Line3 {
  30250. constructor( start = new Vector3(), end = new Vector3() ) {
  30251. this.start = start;
  30252. this.end = end;
  30253. }
  30254. set( start, end ) {
  30255. this.start.copy( start );
  30256. this.end.copy( end );
  30257. return this;
  30258. }
  30259. copy( line ) {
  30260. this.start.copy( line.start );
  30261. this.end.copy( line.end );
  30262. return this;
  30263. }
  30264. getCenter( target ) {
  30265. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  30266. }
  30267. delta( target ) {
  30268. return target.subVectors( this.end, this.start );
  30269. }
  30270. distanceSq() {
  30271. return this.start.distanceToSquared( this.end );
  30272. }
  30273. distance() {
  30274. return this.start.distanceTo( this.end );
  30275. }
  30276. at( t, target ) {
  30277. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30278. }
  30279. closestPointToPointParameter( point, clampToLine ) {
  30280. _startP.subVectors( point, this.start );
  30281. _startEnd.subVectors( this.end, this.start );
  30282. const startEnd2 = _startEnd.dot( _startEnd );
  30283. const startEnd_startP = _startEnd.dot( _startP );
  30284. let t = startEnd_startP / startEnd2;
  30285. if ( clampToLine ) {
  30286. t = clamp( t, 0, 1 );
  30287. }
  30288. return t;
  30289. }
  30290. closestPointToPoint( point, clampToLine, target ) {
  30291. const t = this.closestPointToPointParameter( point, clampToLine );
  30292. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30293. }
  30294. applyMatrix4( matrix ) {
  30295. this.start.applyMatrix4( matrix );
  30296. this.end.applyMatrix4( matrix );
  30297. return this;
  30298. }
  30299. equals( line ) {
  30300. return line.start.equals( this.start ) && line.end.equals( this.end );
  30301. }
  30302. clone() {
  30303. return new this.constructor().copy( this );
  30304. }
  30305. }
  30306. const _vector$3 = /*@__PURE__*/ new Vector3();
  30307. class SpotLightHelper extends Object3D {
  30308. constructor( light, color ) {
  30309. super();
  30310. this.light = light;
  30311. this.matrixAutoUpdate = false;
  30312. this.color = color;
  30313. this.type = 'SpotLightHelper';
  30314. const geometry = new BufferGeometry();
  30315. const positions = [
  30316. 0, 0, 0, 0, 0, 1,
  30317. 0, 0, 0, 1, 0, 1,
  30318. 0, 0, 0, - 1, 0, 1,
  30319. 0, 0, 0, 0, 1, 1,
  30320. 0, 0, 0, 0, - 1, 1
  30321. ];
  30322. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  30323. const p1 = ( i / l ) * Math.PI * 2;
  30324. const p2 = ( j / l ) * Math.PI * 2;
  30325. positions.push(
  30326. Math.cos( p1 ), Math.sin( p1 ), 1,
  30327. Math.cos( p2 ), Math.sin( p2 ), 1
  30328. );
  30329. }
  30330. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30331. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30332. this.cone = new LineSegments( geometry, material );
  30333. this.add( this.cone );
  30334. this.update();
  30335. }
  30336. dispose() {
  30337. this.cone.geometry.dispose();
  30338. this.cone.material.dispose();
  30339. }
  30340. update() {
  30341. this.light.updateWorldMatrix( true, false );
  30342. this.light.target.updateWorldMatrix( true, false );
  30343. // update the local matrix based on the parent and light target transforms
  30344. if ( this.parent ) {
  30345. this.parent.updateWorldMatrix( true );
  30346. this.matrix
  30347. .copy( this.parent.matrixWorld )
  30348. .invert()
  30349. .multiply( this.light.matrixWorld );
  30350. } else {
  30351. this.matrix.copy( this.light.matrixWorld );
  30352. }
  30353. this.matrixWorld.copy( this.light.matrixWorld );
  30354. const coneLength = this.light.distance ? this.light.distance : 1000;
  30355. const coneWidth = coneLength * Math.tan( this.light.angle );
  30356. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  30357. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  30358. this.cone.lookAt( _vector$3 );
  30359. if ( this.color !== undefined ) {
  30360. this.cone.material.color.set( this.color );
  30361. } else {
  30362. this.cone.material.color.copy( this.light.color );
  30363. }
  30364. }
  30365. }
  30366. const _vector$2 = /*@__PURE__*/ new Vector3();
  30367. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  30368. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  30369. class SkeletonHelper extends LineSegments {
  30370. constructor( object ) {
  30371. const bones = getBoneList( object );
  30372. const geometry = new BufferGeometry();
  30373. const vertices = [];
  30374. const colors = [];
  30375. const color1 = new Color( 0, 0, 1 );
  30376. const color2 = new Color( 0, 1, 0 );
  30377. for ( let i = 0; i < bones.length; i ++ ) {
  30378. const bone = bones[ i ];
  30379. if ( bone.parent && bone.parent.isBone ) {
  30380. vertices.push( 0, 0, 0 );
  30381. vertices.push( 0, 0, 0 );
  30382. colors.push( color1.r, color1.g, color1.b );
  30383. colors.push( color2.r, color2.g, color2.b );
  30384. }
  30385. }
  30386. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30387. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30388. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  30389. super( geometry, material );
  30390. this.isSkeletonHelper = true;
  30391. this.type = 'SkeletonHelper';
  30392. this.root = object;
  30393. this.bones = bones;
  30394. this.matrix = object.matrixWorld;
  30395. this.matrixAutoUpdate = false;
  30396. }
  30397. updateMatrixWorld( force ) {
  30398. const bones = this.bones;
  30399. const geometry = this.geometry;
  30400. const position = geometry.getAttribute( 'position' );
  30401. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  30402. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  30403. const bone = bones[ i ];
  30404. if ( bone.parent && bone.parent.isBone ) {
  30405. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  30406. _vector$2.setFromMatrixPosition( _boneMatrix );
  30407. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  30408. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  30409. _vector$2.setFromMatrixPosition( _boneMatrix );
  30410. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  30411. j += 2;
  30412. }
  30413. }
  30414. geometry.getAttribute( 'position' ).needsUpdate = true;
  30415. super.updateMatrixWorld( force );
  30416. }
  30417. dispose() {
  30418. this.geometry.dispose();
  30419. this.material.dispose();
  30420. }
  30421. }
  30422. function getBoneList( object ) {
  30423. const boneList = [];
  30424. if ( object.isBone === true ) {
  30425. boneList.push( object );
  30426. }
  30427. for ( let i = 0; i < object.children.length; i ++ ) {
  30428. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  30429. }
  30430. return boneList;
  30431. }
  30432. class PointLightHelper extends Mesh {
  30433. constructor( light, sphereSize, color ) {
  30434. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  30435. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30436. super( geometry, material );
  30437. this.light = light;
  30438. this.color = color;
  30439. this.type = 'PointLightHelper';
  30440. this.matrix = this.light.matrixWorld;
  30441. this.matrixAutoUpdate = false;
  30442. this.update();
  30443. /*
  30444. // TODO: delete this comment?
  30445. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  30446. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  30447. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  30448. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  30449. const d = light.distance;
  30450. if ( d === 0.0 ) {
  30451. this.lightDistance.visible = false;
  30452. } else {
  30453. this.lightDistance.scale.set( d, d, d );
  30454. }
  30455. this.add( this.lightDistance );
  30456. */
  30457. }
  30458. dispose() {
  30459. this.geometry.dispose();
  30460. this.material.dispose();
  30461. }
  30462. update() {
  30463. this.light.updateWorldMatrix( true, false );
  30464. if ( this.color !== undefined ) {
  30465. this.material.color.set( this.color );
  30466. } else {
  30467. this.material.color.copy( this.light.color );
  30468. }
  30469. /*
  30470. const d = this.light.distance;
  30471. if ( d === 0.0 ) {
  30472. this.lightDistance.visible = false;
  30473. } else {
  30474. this.lightDistance.visible = true;
  30475. this.lightDistance.scale.set( d, d, d );
  30476. }
  30477. */
  30478. }
  30479. }
  30480. const _vector$1 = /*@__PURE__*/ new Vector3();
  30481. const _color1 = /*@__PURE__*/ new Color();
  30482. const _color2 = /*@__PURE__*/ new Color();
  30483. class HemisphereLightHelper extends Object3D {
  30484. constructor( light, size, color ) {
  30485. super();
  30486. this.light = light;
  30487. this.matrix = light.matrixWorld;
  30488. this.matrixAutoUpdate = false;
  30489. this.color = color;
  30490. this.type = 'HemisphereLightHelper';
  30491. const geometry = new OctahedronGeometry( size );
  30492. geometry.rotateY( Math.PI * 0.5 );
  30493. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30494. if ( this.color === undefined ) this.material.vertexColors = true;
  30495. const position = geometry.getAttribute( 'position' );
  30496. const colors = new Float32Array( position.count * 3 );
  30497. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  30498. this.add( new Mesh( geometry, this.material ) );
  30499. this.update();
  30500. }
  30501. dispose() {
  30502. this.children[ 0 ].geometry.dispose();
  30503. this.children[ 0 ].material.dispose();
  30504. }
  30505. update() {
  30506. const mesh = this.children[ 0 ];
  30507. if ( this.color !== undefined ) {
  30508. this.material.color.set( this.color );
  30509. } else {
  30510. const colors = mesh.geometry.getAttribute( 'color' );
  30511. _color1.copy( this.light.color );
  30512. _color2.copy( this.light.groundColor );
  30513. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  30514. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  30515. colors.setXYZ( i, color.r, color.g, color.b );
  30516. }
  30517. colors.needsUpdate = true;
  30518. }
  30519. this.light.updateWorldMatrix( true, false );
  30520. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  30521. }
  30522. }
  30523. class GridHelper extends LineSegments {
  30524. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  30525. color1 = new Color( color1 );
  30526. color2 = new Color( color2 );
  30527. const center = divisions / 2;
  30528. const step = size / divisions;
  30529. const halfSize = size / 2;
  30530. const vertices = [], colors = [];
  30531. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  30532. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  30533. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  30534. const color = i === center ? color1 : color2;
  30535. color.toArray( colors, j ); j += 3;
  30536. color.toArray( colors, j ); j += 3;
  30537. color.toArray( colors, j ); j += 3;
  30538. color.toArray( colors, j ); j += 3;
  30539. }
  30540. const geometry = new BufferGeometry();
  30541. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30542. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30543. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30544. super( geometry, material );
  30545. this.type = 'GridHelper';
  30546. }
  30547. dispose() {
  30548. this.geometry.dispose();
  30549. this.material.dispose();
  30550. }
  30551. }
  30552. class PolarGridHelper extends LineSegments {
  30553. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  30554. color1 = new Color( color1 );
  30555. color2 = new Color( color2 );
  30556. const vertices = [];
  30557. const colors = [];
  30558. // create the sectors
  30559. if ( sectors > 1 ) {
  30560. for ( let i = 0; i < sectors; i ++ ) {
  30561. const v = ( i / sectors ) * ( Math.PI * 2 );
  30562. const x = Math.sin( v ) * radius;
  30563. const z = Math.cos( v ) * radius;
  30564. vertices.push( 0, 0, 0 );
  30565. vertices.push( x, 0, z );
  30566. const color = ( i & 1 ) ? color1 : color2;
  30567. colors.push( color.r, color.g, color.b );
  30568. colors.push( color.r, color.g, color.b );
  30569. }
  30570. }
  30571. // create the rings
  30572. for ( let i = 0; i < rings; i ++ ) {
  30573. const color = ( i & 1 ) ? color1 : color2;
  30574. const r = radius - ( radius / rings * i );
  30575. for ( let j = 0; j < divisions; j ++ ) {
  30576. // first vertex
  30577. let v = ( j / divisions ) * ( Math.PI * 2 );
  30578. let x = Math.sin( v ) * r;
  30579. let z = Math.cos( v ) * r;
  30580. vertices.push( x, 0, z );
  30581. colors.push( color.r, color.g, color.b );
  30582. // second vertex
  30583. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  30584. x = Math.sin( v ) * r;
  30585. z = Math.cos( v ) * r;
  30586. vertices.push( x, 0, z );
  30587. colors.push( color.r, color.g, color.b );
  30588. }
  30589. }
  30590. const geometry = new BufferGeometry();
  30591. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30592. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30593. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30594. super( geometry, material );
  30595. this.type = 'PolarGridHelper';
  30596. }
  30597. dispose() {
  30598. this.geometry.dispose();
  30599. this.material.dispose();
  30600. }
  30601. }
  30602. const _v1 = /*@__PURE__*/ new Vector3();
  30603. const _v2 = /*@__PURE__*/ new Vector3();
  30604. const _v3 = /*@__PURE__*/ new Vector3();
  30605. class DirectionalLightHelper extends Object3D {
  30606. constructor( light, size, color ) {
  30607. super();
  30608. this.light = light;
  30609. this.matrix = light.matrixWorld;
  30610. this.matrixAutoUpdate = false;
  30611. this.color = color;
  30612. this.type = 'DirectionalLightHelper';
  30613. if ( size === undefined ) size = 1;
  30614. let geometry = new BufferGeometry();
  30615. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  30616. - size, size, 0,
  30617. size, size, 0,
  30618. size, - size, 0,
  30619. - size, - size, 0,
  30620. - size, size, 0
  30621. ], 3 ) );
  30622. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30623. this.lightPlane = new Line( geometry, material );
  30624. this.add( this.lightPlane );
  30625. geometry = new BufferGeometry();
  30626. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  30627. this.targetLine = new Line( geometry, material );
  30628. this.add( this.targetLine );
  30629. this.update();
  30630. }
  30631. dispose() {
  30632. this.lightPlane.geometry.dispose();
  30633. this.lightPlane.material.dispose();
  30634. this.targetLine.geometry.dispose();
  30635. this.targetLine.material.dispose();
  30636. }
  30637. update() {
  30638. this.light.updateWorldMatrix( true, false );
  30639. this.light.target.updateWorldMatrix( true, false );
  30640. _v1.setFromMatrixPosition( this.light.matrixWorld );
  30641. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  30642. _v3.subVectors( _v2, _v1 );
  30643. this.lightPlane.lookAt( _v2 );
  30644. if ( this.color !== undefined ) {
  30645. this.lightPlane.material.color.set( this.color );
  30646. this.targetLine.material.color.set( this.color );
  30647. } else {
  30648. this.lightPlane.material.color.copy( this.light.color );
  30649. this.targetLine.material.color.copy( this.light.color );
  30650. }
  30651. this.targetLine.lookAt( _v2 );
  30652. this.targetLine.scale.z = _v3.length();
  30653. }
  30654. }
  30655. const _vector = /*@__PURE__*/ new Vector3();
  30656. const _camera = /*@__PURE__*/ new Camera();
  30657. /**
  30658. * - shows frustum, line of sight and up of the camera
  30659. * - suitable for fast updates
  30660. * - based on frustum visualization in lightgl.js shadowmap example
  30661. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  30662. */
  30663. class CameraHelper extends LineSegments {
  30664. constructor( camera ) {
  30665. const geometry = new BufferGeometry();
  30666. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  30667. const vertices = [];
  30668. const colors = [];
  30669. const pointMap = {};
  30670. // near
  30671. addLine( 'n1', 'n2' );
  30672. addLine( 'n2', 'n4' );
  30673. addLine( 'n4', 'n3' );
  30674. addLine( 'n3', 'n1' );
  30675. // far
  30676. addLine( 'f1', 'f2' );
  30677. addLine( 'f2', 'f4' );
  30678. addLine( 'f4', 'f3' );
  30679. addLine( 'f3', 'f1' );
  30680. // sides
  30681. addLine( 'n1', 'f1' );
  30682. addLine( 'n2', 'f2' );
  30683. addLine( 'n3', 'f3' );
  30684. addLine( 'n4', 'f4' );
  30685. // cone
  30686. addLine( 'p', 'n1' );
  30687. addLine( 'p', 'n2' );
  30688. addLine( 'p', 'n3' );
  30689. addLine( 'p', 'n4' );
  30690. // up
  30691. addLine( 'u1', 'u2' );
  30692. addLine( 'u2', 'u3' );
  30693. addLine( 'u3', 'u1' );
  30694. // target
  30695. addLine( 'c', 't' );
  30696. addLine( 'p', 'c' );
  30697. // cross
  30698. addLine( 'cn1', 'cn2' );
  30699. addLine( 'cn3', 'cn4' );
  30700. addLine( 'cf1', 'cf2' );
  30701. addLine( 'cf3', 'cf4' );
  30702. function addLine( a, b ) {
  30703. addPoint( a );
  30704. addPoint( b );
  30705. }
  30706. function addPoint( id ) {
  30707. vertices.push( 0, 0, 0 );
  30708. colors.push( 0, 0, 0 );
  30709. if ( pointMap[ id ] === undefined ) {
  30710. pointMap[ id ] = [];
  30711. }
  30712. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  30713. }
  30714. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30715. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30716. super( geometry, material );
  30717. this.type = 'CameraHelper';
  30718. this.camera = camera;
  30719. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  30720. this.matrix = camera.matrixWorld;
  30721. this.matrixAutoUpdate = false;
  30722. this.pointMap = pointMap;
  30723. this.update();
  30724. // colors
  30725. const colorFrustum = new Color( 0xffaa00 );
  30726. const colorCone = new Color( 0xff0000 );
  30727. const colorUp = new Color( 0x00aaff );
  30728. const colorTarget = new Color( 0xffffff );
  30729. const colorCross = new Color( 0x333333 );
  30730. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  30731. }
  30732. setColors( frustum, cone, up, target, cross ) {
  30733. const geometry = this.geometry;
  30734. const colorAttribute = geometry.getAttribute( 'color' );
  30735. // near
  30736. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  30737. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  30738. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  30739. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  30740. // far
  30741. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  30742. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  30743. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  30744. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  30745. // sides
  30746. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  30747. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  30748. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  30749. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  30750. // cone
  30751. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  30752. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  30753. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  30754. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  30755. // up
  30756. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  30757. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  30758. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  30759. // target
  30760. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  30761. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  30762. // cross
  30763. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  30764. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  30765. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  30766. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  30767. colorAttribute.needsUpdate = true;
  30768. }
  30769. update() {
  30770. const geometry = this.geometry;
  30771. const pointMap = this.pointMap;
  30772. const w = 1, h = 1;
  30773. // we need just camera projection matrix inverse
  30774. // world matrix must be identity
  30775. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  30776. // center / target
  30777. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  30778. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  30779. // near
  30780. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  30781. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  30782. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  30783. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  30784. // far
  30785. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  30786. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  30787. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  30788. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  30789. // up
  30790. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  30791. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  30792. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  30793. // cross
  30794. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  30795. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  30796. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  30797. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  30798. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  30799. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  30800. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  30801. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  30802. geometry.getAttribute( 'position' ).needsUpdate = true;
  30803. }
  30804. dispose() {
  30805. this.geometry.dispose();
  30806. this.material.dispose();
  30807. }
  30808. }
  30809. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  30810. _vector.set( x, y, z ).unproject( camera );
  30811. const points = pointMap[ point ];
  30812. if ( points !== undefined ) {
  30813. const position = geometry.getAttribute( 'position' );
  30814. for ( let i = 0, l = points.length; i < l; i ++ ) {
  30815. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  30816. }
  30817. }
  30818. }
  30819. const _box = /*@__PURE__*/ new Box3();
  30820. class BoxHelper extends LineSegments {
  30821. constructor( object, color = 0xffff00 ) {
  30822. 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 ] );
  30823. const positions = new Float32Array( 8 * 3 );
  30824. const geometry = new BufferGeometry();
  30825. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30826. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  30827. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30828. this.object = object;
  30829. this.type = 'BoxHelper';
  30830. this.matrixAutoUpdate = false;
  30831. this.update();
  30832. }
  30833. update( object ) {
  30834. if ( object !== undefined ) {
  30835. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  30836. }
  30837. if ( this.object !== undefined ) {
  30838. _box.setFromObject( this.object );
  30839. }
  30840. if ( _box.isEmpty() ) return;
  30841. const min = _box.min;
  30842. const max = _box.max;
  30843. /*
  30844. 5____4
  30845. 1/___0/|
  30846. | 6__|_7
  30847. 2/___3/
  30848. 0: max.x, max.y, max.z
  30849. 1: min.x, max.y, max.z
  30850. 2: min.x, min.y, max.z
  30851. 3: max.x, min.y, max.z
  30852. 4: max.x, max.y, min.z
  30853. 5: min.x, max.y, min.z
  30854. 6: min.x, min.y, min.z
  30855. 7: max.x, min.y, min.z
  30856. */
  30857. const position = this.geometry.attributes.position;
  30858. const array = position.array;
  30859. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  30860. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  30861. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  30862. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  30863. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  30864. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  30865. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  30866. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  30867. position.needsUpdate = true;
  30868. this.geometry.computeBoundingSphere();
  30869. }
  30870. setFromObject( object ) {
  30871. this.object = object;
  30872. this.update();
  30873. return this;
  30874. }
  30875. copy( source, recursive ) {
  30876. super.copy( source, recursive );
  30877. this.object = source.object;
  30878. return this;
  30879. }
  30880. dispose() {
  30881. this.geometry.dispose();
  30882. this.material.dispose();
  30883. }
  30884. }
  30885. class Box3Helper extends LineSegments {
  30886. constructor( box, color = 0xffff00 ) {
  30887. 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 ] );
  30888. 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 ];
  30889. const geometry = new BufferGeometry();
  30890. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30891. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30892. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30893. this.box = box;
  30894. this.type = 'Box3Helper';
  30895. this.geometry.computeBoundingSphere();
  30896. }
  30897. updateMatrixWorld( force ) {
  30898. const box = this.box;
  30899. if ( box.isEmpty() ) return;
  30900. box.getCenter( this.position );
  30901. box.getSize( this.scale );
  30902. this.scale.multiplyScalar( 0.5 );
  30903. super.updateMatrixWorld( force );
  30904. }
  30905. dispose() {
  30906. this.geometry.dispose();
  30907. this.material.dispose();
  30908. }
  30909. }
  30910. class PlaneHelper extends Line {
  30911. constructor( plane, size = 1, hex = 0xffff00 ) {
  30912. const color = hex;
  30913. 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 ];
  30914. const geometry = new BufferGeometry();
  30915. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30916. geometry.computeBoundingSphere();
  30917. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30918. this.type = 'PlaneHelper';
  30919. this.plane = plane;
  30920. this.size = size;
  30921. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  30922. const geometry2 = new BufferGeometry();
  30923. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  30924. geometry2.computeBoundingSphere();
  30925. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  30926. }
  30927. updateMatrixWorld( force ) {
  30928. this.position.set( 0, 0, 0 );
  30929. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  30930. this.lookAt( this.plane.normal );
  30931. this.translateZ( - this.plane.constant );
  30932. super.updateMatrixWorld( force );
  30933. }
  30934. dispose() {
  30935. this.geometry.dispose();
  30936. this.material.dispose();
  30937. this.children[ 0 ].geometry.dispose();
  30938. this.children[ 0 ].material.dispose();
  30939. }
  30940. }
  30941. const _axis = /*@__PURE__*/ new Vector3();
  30942. let _lineGeometry, _coneGeometry;
  30943. class ArrowHelper extends Object3D {
  30944. // dir is assumed to be normalized
  30945. 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 ) {
  30946. super();
  30947. this.type = 'ArrowHelper';
  30948. if ( _lineGeometry === undefined ) {
  30949. _lineGeometry = new BufferGeometry();
  30950. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  30951. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  30952. _coneGeometry.translate( 0, - 0.5, 0 );
  30953. }
  30954. this.position.copy( origin );
  30955. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30956. this.line.matrixAutoUpdate = false;
  30957. this.add( this.line );
  30958. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  30959. this.cone.matrixAutoUpdate = false;
  30960. this.add( this.cone );
  30961. this.setDirection( dir );
  30962. this.setLength( length, headLength, headWidth );
  30963. }
  30964. setDirection( dir ) {
  30965. // dir is assumed to be normalized
  30966. if ( dir.y > 0.99999 ) {
  30967. this.quaternion.set( 0, 0, 0, 1 );
  30968. } else if ( dir.y < - 0.99999 ) {
  30969. this.quaternion.set( 1, 0, 0, 0 );
  30970. } else {
  30971. _axis.set( dir.z, 0, - dir.x ).normalize();
  30972. const radians = Math.acos( dir.y );
  30973. this.quaternion.setFromAxisAngle( _axis, radians );
  30974. }
  30975. }
  30976. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  30977. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  30978. this.line.updateMatrix();
  30979. this.cone.scale.set( headWidth, headLength, headWidth );
  30980. this.cone.position.y = length;
  30981. this.cone.updateMatrix();
  30982. }
  30983. setColor( color ) {
  30984. this.line.material.color.set( color );
  30985. this.cone.material.color.set( color );
  30986. }
  30987. copy( source ) {
  30988. super.copy( source, false );
  30989. this.line.copy( source.line );
  30990. this.cone.copy( source.cone );
  30991. return this;
  30992. }
  30993. dispose() {
  30994. this.line.geometry.dispose();
  30995. this.line.material.dispose();
  30996. this.cone.geometry.dispose();
  30997. this.cone.material.dispose();
  30998. }
  30999. }
  31000. class AxesHelper extends LineSegments {
  31001. constructor( size = 1 ) {
  31002. const vertices = [
  31003. 0, 0, 0, size, 0, 0,
  31004. 0, 0, 0, 0, size, 0,
  31005. 0, 0, 0, 0, 0, size
  31006. ];
  31007. const colors = [
  31008. 1, 0, 0, 1, 0.6, 0,
  31009. 0, 1, 0, 0.6, 1, 0,
  31010. 0, 0, 1, 0, 0.6, 1
  31011. ];
  31012. const geometry = new BufferGeometry();
  31013. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31014. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31015. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31016. super( geometry, material );
  31017. this.type = 'AxesHelper';
  31018. }
  31019. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  31020. const color = new Color();
  31021. const array = this.geometry.attributes.color.array;
  31022. color.set( xAxisColor );
  31023. color.toArray( array, 0 );
  31024. color.toArray( array, 3 );
  31025. color.set( yAxisColor );
  31026. color.toArray( array, 6 );
  31027. color.toArray( array, 9 );
  31028. color.set( zAxisColor );
  31029. color.toArray( array, 12 );
  31030. color.toArray( array, 15 );
  31031. this.geometry.attributes.color.needsUpdate = true;
  31032. return this;
  31033. }
  31034. dispose() {
  31035. this.geometry.dispose();
  31036. this.material.dispose();
  31037. }
  31038. }
  31039. class ShapePath {
  31040. constructor() {
  31041. this.type = 'ShapePath';
  31042. this.color = new Color();
  31043. this.subPaths = [];
  31044. this.currentPath = null;
  31045. }
  31046. moveTo( x, y ) {
  31047. this.currentPath = new Path();
  31048. this.subPaths.push( this.currentPath );
  31049. this.currentPath.moveTo( x, y );
  31050. return this;
  31051. }
  31052. lineTo( x, y ) {
  31053. this.currentPath.lineTo( x, y );
  31054. return this;
  31055. }
  31056. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  31057. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  31058. return this;
  31059. }
  31060. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  31061. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  31062. return this;
  31063. }
  31064. splineThru( pts ) {
  31065. this.currentPath.splineThru( pts );
  31066. return this;
  31067. }
  31068. toShapes( isCCW ) {
  31069. function toShapesNoHoles( inSubpaths ) {
  31070. const shapes = [];
  31071. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  31072. const tmpPath = inSubpaths[ i ];
  31073. const tmpShape = new Shape();
  31074. tmpShape.curves = tmpPath.curves;
  31075. shapes.push( tmpShape );
  31076. }
  31077. return shapes;
  31078. }
  31079. function isPointInsidePolygon( inPt, inPolygon ) {
  31080. const polyLen = inPolygon.length;
  31081. // inPt on polygon contour => immediate success or
  31082. // toggling of inside/outside at every single! intersection point of an edge
  31083. // with the horizontal line through inPt, left of inPt
  31084. // not counting lowerY endpoints of edges and whole edges on that line
  31085. let inside = false;
  31086. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  31087. let edgeLowPt = inPolygon[ p ];
  31088. let edgeHighPt = inPolygon[ q ];
  31089. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  31090. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  31091. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  31092. // not parallel
  31093. if ( edgeDy < 0 ) {
  31094. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  31095. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  31096. }
  31097. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  31098. if ( inPt.y === edgeLowPt.y ) {
  31099. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  31100. // continue; // no intersection or edgeLowPt => doesn't count !!!
  31101. } else {
  31102. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  31103. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  31104. if ( perpEdge < 0 ) continue;
  31105. inside = ! inside; // true intersection left of inPt
  31106. }
  31107. } else {
  31108. // parallel or collinear
  31109. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  31110. // edge lies on the same horizontal line as inPt
  31111. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  31112. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  31113. // continue;
  31114. }
  31115. }
  31116. return inside;
  31117. }
  31118. const isClockWise = ShapeUtils.isClockWise;
  31119. const subPaths = this.subPaths;
  31120. if ( subPaths.length === 0 ) return [];
  31121. let solid, tmpPath, tmpShape;
  31122. const shapes = [];
  31123. if ( subPaths.length === 1 ) {
  31124. tmpPath = subPaths[ 0 ];
  31125. tmpShape = new Shape();
  31126. tmpShape.curves = tmpPath.curves;
  31127. shapes.push( tmpShape );
  31128. return shapes;
  31129. }
  31130. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  31131. holesFirst = isCCW ? ! holesFirst : holesFirst;
  31132. // console.log("Holes first", holesFirst);
  31133. const betterShapeHoles = [];
  31134. const newShapes = [];
  31135. let newShapeHoles = [];
  31136. let mainIdx = 0;
  31137. let tmpPoints;
  31138. newShapes[ mainIdx ] = undefined;
  31139. newShapeHoles[ mainIdx ] = [];
  31140. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  31141. tmpPath = subPaths[ i ];
  31142. tmpPoints = tmpPath.getPoints();
  31143. solid = isClockWise( tmpPoints );
  31144. solid = isCCW ? ! solid : solid;
  31145. if ( solid ) {
  31146. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  31147. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  31148. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  31149. if ( holesFirst ) mainIdx ++;
  31150. newShapeHoles[ mainIdx ] = [];
  31151. //console.log('cw', i);
  31152. } else {
  31153. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  31154. //console.log('ccw', i);
  31155. }
  31156. }
  31157. // only Holes? -> probably all Shapes with wrong orientation
  31158. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  31159. if ( newShapes.length > 1 ) {
  31160. let ambiguous = false;
  31161. let toChange = 0;
  31162. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31163. betterShapeHoles[ sIdx ] = [];
  31164. }
  31165. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31166. const sho = newShapeHoles[ sIdx ];
  31167. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  31168. const ho = sho[ hIdx ];
  31169. let hole_unassigned = true;
  31170. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  31171. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  31172. if ( sIdx !== s2Idx ) toChange ++;
  31173. if ( hole_unassigned ) {
  31174. hole_unassigned = false;
  31175. betterShapeHoles[ s2Idx ].push( ho );
  31176. } else {
  31177. ambiguous = true;
  31178. }
  31179. }
  31180. }
  31181. if ( hole_unassigned ) {
  31182. betterShapeHoles[ sIdx ].push( ho );
  31183. }
  31184. }
  31185. }
  31186. if ( toChange > 0 && ambiguous === false ) {
  31187. newShapeHoles = betterShapeHoles;
  31188. }
  31189. }
  31190. let tmpHoles;
  31191. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  31192. tmpShape = newShapes[ i ].s;
  31193. shapes.push( tmpShape );
  31194. tmpHoles = newShapeHoles[ i ];
  31195. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  31196. tmpShape.holes.push( tmpHoles[ j ].h );
  31197. }
  31198. }
  31199. //console.log("shape", shapes);
  31200. return shapes;
  31201. }
  31202. }
  31203. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  31204. constructor( width = 1, height = 1, count = 1, options = {} ) {
  31205. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  31206. super( width, height, { ...options, count } );
  31207. this.isWebGLMultipleRenderTargets = true;
  31208. }
  31209. get texture() {
  31210. return this.textures;
  31211. }
  31212. }
  31213. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31214. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31215. revision: REVISION,
  31216. } } ) );
  31217. }
  31218. if ( typeof window !== 'undefined' ) {
  31219. if ( window.__THREE__ ) {
  31220. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  31221. } else {
  31222. window.__THREE__ = REVISION;
  31223. }
  31224. }
  31225. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  31226. exports.AddEquation = AddEquation;
  31227. exports.AddOperation = AddOperation;
  31228. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  31229. exports.AdditiveBlending = AdditiveBlending;
  31230. exports.AgXToneMapping = AgXToneMapping;
  31231. exports.AlphaFormat = AlphaFormat;
  31232. exports.AlwaysCompare = AlwaysCompare;
  31233. exports.AlwaysDepth = AlwaysDepth;
  31234. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  31235. exports.AmbientLight = AmbientLight;
  31236. exports.AnimationAction = AnimationAction;
  31237. exports.AnimationClip = AnimationClip;
  31238. exports.AnimationLoader = AnimationLoader;
  31239. exports.AnimationMixer = AnimationMixer;
  31240. exports.AnimationObjectGroup = AnimationObjectGroup;
  31241. exports.AnimationUtils = AnimationUtils;
  31242. exports.ArcCurve = ArcCurve;
  31243. exports.ArrayCamera = ArrayCamera;
  31244. exports.ArrowHelper = ArrowHelper;
  31245. exports.AttachedBindMode = AttachedBindMode;
  31246. exports.Audio = Audio;
  31247. exports.AudioAnalyser = AudioAnalyser;
  31248. exports.AudioContext = AudioContext;
  31249. exports.AudioListener = AudioListener;
  31250. exports.AudioLoader = AudioLoader;
  31251. exports.AxesHelper = AxesHelper;
  31252. exports.BackSide = BackSide;
  31253. exports.BasicDepthPacking = BasicDepthPacking;
  31254. exports.BasicShadowMap = BasicShadowMap;
  31255. exports.BatchedMesh = BatchedMesh;
  31256. exports.Bone = Bone;
  31257. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  31258. exports.Box2 = Box2;
  31259. exports.Box3 = Box3;
  31260. exports.Box3Helper = Box3Helper;
  31261. exports.BoxGeometry = BoxGeometry;
  31262. exports.BoxHelper = BoxHelper;
  31263. exports.BufferAttribute = BufferAttribute;
  31264. exports.BufferGeometry = BufferGeometry;
  31265. exports.BufferGeometryLoader = BufferGeometryLoader;
  31266. exports.ByteType = ByteType;
  31267. exports.Cache = Cache;
  31268. exports.Camera = Camera;
  31269. exports.CameraHelper = CameraHelper;
  31270. exports.CanvasTexture = CanvasTexture;
  31271. exports.CapsuleGeometry = CapsuleGeometry;
  31272. exports.CatmullRomCurve3 = CatmullRomCurve3;
  31273. exports.CineonToneMapping = CineonToneMapping;
  31274. exports.CircleGeometry = CircleGeometry;
  31275. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  31276. exports.Clock = Clock;
  31277. exports.Color = Color;
  31278. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  31279. exports.ColorManagement = ColorManagement;
  31280. exports.CompressedArrayTexture = CompressedArrayTexture;
  31281. exports.CompressedCubeTexture = CompressedCubeTexture;
  31282. exports.CompressedTexture = CompressedTexture;
  31283. exports.CompressedTextureLoader = CompressedTextureLoader;
  31284. exports.ConeGeometry = ConeGeometry;
  31285. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  31286. exports.ConstantColorFactor = ConstantColorFactor;
  31287. exports.CubeCamera = CubeCamera;
  31288. exports.CubeReflectionMapping = CubeReflectionMapping;
  31289. exports.CubeRefractionMapping = CubeRefractionMapping;
  31290. exports.CubeTexture = CubeTexture;
  31291. exports.CubeTextureLoader = CubeTextureLoader;
  31292. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  31293. exports.CubicBezierCurve = CubicBezierCurve;
  31294. exports.CubicBezierCurve3 = CubicBezierCurve3;
  31295. exports.CubicInterpolant = CubicInterpolant;
  31296. exports.CullFaceBack = CullFaceBack;
  31297. exports.CullFaceFront = CullFaceFront;
  31298. exports.CullFaceFrontBack = CullFaceFrontBack;
  31299. exports.CullFaceNone = CullFaceNone;
  31300. exports.Curve = Curve;
  31301. exports.CurvePath = CurvePath;
  31302. exports.CustomBlending = CustomBlending;
  31303. exports.CustomToneMapping = CustomToneMapping;
  31304. exports.CylinderGeometry = CylinderGeometry;
  31305. exports.Cylindrical = Cylindrical;
  31306. exports.Data3DTexture = Data3DTexture;
  31307. exports.DataArrayTexture = DataArrayTexture;
  31308. exports.DataTexture = DataTexture;
  31309. exports.DataTextureLoader = DataTextureLoader;
  31310. exports.DataUtils = DataUtils;
  31311. exports.DecrementStencilOp = DecrementStencilOp;
  31312. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  31313. exports.DefaultLoadingManager = DefaultLoadingManager;
  31314. exports.DepthFormat = DepthFormat;
  31315. exports.DepthStencilFormat = DepthStencilFormat;
  31316. exports.DepthTexture = DepthTexture;
  31317. exports.DetachedBindMode = DetachedBindMode;
  31318. exports.DirectionalLight = DirectionalLight;
  31319. exports.DirectionalLightHelper = DirectionalLightHelper;
  31320. exports.DiscreteInterpolant = DiscreteInterpolant;
  31321. exports.DisplayP3ColorSpace = DisplayP3ColorSpace;
  31322. exports.DodecahedronGeometry = DodecahedronGeometry;
  31323. exports.DoubleSide = DoubleSide;
  31324. exports.DstAlphaFactor = DstAlphaFactor;
  31325. exports.DstColorFactor = DstColorFactor;
  31326. exports.DynamicCopyUsage = DynamicCopyUsage;
  31327. exports.DynamicDrawUsage = DynamicDrawUsage;
  31328. exports.DynamicReadUsage = DynamicReadUsage;
  31329. exports.EdgesGeometry = EdgesGeometry;
  31330. exports.EllipseCurve = EllipseCurve;
  31331. exports.EqualCompare = EqualCompare;
  31332. exports.EqualDepth = EqualDepth;
  31333. exports.EqualStencilFunc = EqualStencilFunc;
  31334. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  31335. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  31336. exports.Euler = Euler;
  31337. exports.EventDispatcher = EventDispatcher;
  31338. exports.ExtrudeGeometry = ExtrudeGeometry;
  31339. exports.FileLoader = FileLoader;
  31340. exports.Float16BufferAttribute = Float16BufferAttribute;
  31341. exports.Float32BufferAttribute = Float32BufferAttribute;
  31342. exports.FloatType = FloatType;
  31343. exports.Fog = Fog;
  31344. exports.FogExp2 = FogExp2;
  31345. exports.FramebufferTexture = FramebufferTexture;
  31346. exports.FrontSide = FrontSide;
  31347. exports.Frustum = Frustum;
  31348. exports.GLBufferAttribute = GLBufferAttribute;
  31349. exports.GLSL1 = GLSL1;
  31350. exports.GLSL3 = GLSL3;
  31351. exports.GreaterCompare = GreaterCompare;
  31352. exports.GreaterDepth = GreaterDepth;
  31353. exports.GreaterEqualCompare = GreaterEqualCompare;
  31354. exports.GreaterEqualDepth = GreaterEqualDepth;
  31355. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  31356. exports.GreaterStencilFunc = GreaterStencilFunc;
  31357. exports.GridHelper = GridHelper;
  31358. exports.Group = Group;
  31359. exports.HalfFloatType = HalfFloatType;
  31360. exports.HemisphereLight = HemisphereLight;
  31361. exports.HemisphereLightHelper = HemisphereLightHelper;
  31362. exports.IcosahedronGeometry = IcosahedronGeometry;
  31363. exports.ImageBitmapLoader = ImageBitmapLoader;
  31364. exports.ImageLoader = ImageLoader;
  31365. exports.ImageUtils = ImageUtils;
  31366. exports.IncrementStencilOp = IncrementStencilOp;
  31367. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  31368. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  31369. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  31370. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  31371. exports.InstancedMesh = InstancedMesh;
  31372. exports.Int16BufferAttribute = Int16BufferAttribute;
  31373. exports.Int32BufferAttribute = Int32BufferAttribute;
  31374. exports.Int8BufferAttribute = Int8BufferAttribute;
  31375. exports.IntType = IntType;
  31376. exports.InterleavedBuffer = InterleavedBuffer;
  31377. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  31378. exports.Interpolant = Interpolant;
  31379. exports.InterpolateDiscrete = InterpolateDiscrete;
  31380. exports.InterpolateLinear = InterpolateLinear;
  31381. exports.InterpolateSmooth = InterpolateSmooth;
  31382. exports.InvertStencilOp = InvertStencilOp;
  31383. exports.KeepStencilOp = KeepStencilOp;
  31384. exports.KeyframeTrack = KeyframeTrack;
  31385. exports.LOD = LOD;
  31386. exports.LatheGeometry = LatheGeometry;
  31387. exports.Layers = Layers;
  31388. exports.LessCompare = LessCompare;
  31389. exports.LessDepth = LessDepth;
  31390. exports.LessEqualCompare = LessEqualCompare;
  31391. exports.LessEqualDepth = LessEqualDepth;
  31392. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  31393. exports.LessStencilFunc = LessStencilFunc;
  31394. exports.Light = Light;
  31395. exports.LightProbe = LightProbe;
  31396. exports.Line = Line;
  31397. exports.Line3 = Line3;
  31398. exports.LineBasicMaterial = LineBasicMaterial;
  31399. exports.LineCurve = LineCurve;
  31400. exports.LineCurve3 = LineCurve3;
  31401. exports.LineDashedMaterial = LineDashedMaterial;
  31402. exports.LineLoop = LineLoop;
  31403. exports.LineSegments = LineSegments;
  31404. exports.LinearDisplayP3ColorSpace = LinearDisplayP3ColorSpace;
  31405. exports.LinearFilter = LinearFilter;
  31406. exports.LinearInterpolant = LinearInterpolant;
  31407. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  31408. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  31409. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  31410. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  31411. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  31412. exports.LinearToneMapping = LinearToneMapping;
  31413. exports.LinearTransfer = LinearTransfer;
  31414. exports.Loader = Loader;
  31415. exports.LoaderUtils = LoaderUtils;
  31416. exports.LoadingManager = LoadingManager;
  31417. exports.LoopOnce = LoopOnce;
  31418. exports.LoopPingPong = LoopPingPong;
  31419. exports.LoopRepeat = LoopRepeat;
  31420. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  31421. exports.LuminanceFormat = LuminanceFormat;
  31422. exports.MOUSE = MOUSE;
  31423. exports.Material = Material;
  31424. exports.MaterialLoader = MaterialLoader;
  31425. exports.MathUtils = MathUtils;
  31426. exports.Matrix3 = Matrix3;
  31427. exports.Matrix4 = Matrix4;
  31428. exports.MaxEquation = MaxEquation;
  31429. exports.Mesh = Mesh;
  31430. exports.MeshBasicMaterial = MeshBasicMaterial;
  31431. exports.MeshDepthMaterial = MeshDepthMaterial;
  31432. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  31433. exports.MeshLambertMaterial = MeshLambertMaterial;
  31434. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  31435. exports.MeshNormalMaterial = MeshNormalMaterial;
  31436. exports.MeshPhongMaterial = MeshPhongMaterial;
  31437. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  31438. exports.MeshStandardMaterial = MeshStandardMaterial;
  31439. exports.MeshToonMaterial = MeshToonMaterial;
  31440. exports.MinEquation = MinEquation;
  31441. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  31442. exports.MixOperation = MixOperation;
  31443. exports.MultiplyBlending = MultiplyBlending;
  31444. exports.MultiplyOperation = MultiplyOperation;
  31445. exports.NearestFilter = NearestFilter;
  31446. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  31447. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  31448. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  31449. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  31450. exports.NeutralToneMapping = NeutralToneMapping;
  31451. exports.NeverCompare = NeverCompare;
  31452. exports.NeverDepth = NeverDepth;
  31453. exports.NeverStencilFunc = NeverStencilFunc;
  31454. exports.NoBlending = NoBlending;
  31455. exports.NoColorSpace = NoColorSpace;
  31456. exports.NoToneMapping = NoToneMapping;
  31457. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  31458. exports.NormalBlending = NormalBlending;
  31459. exports.NotEqualCompare = NotEqualCompare;
  31460. exports.NotEqualDepth = NotEqualDepth;
  31461. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  31462. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  31463. exports.Object3D = Object3D;
  31464. exports.ObjectLoader = ObjectLoader;
  31465. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  31466. exports.OctahedronGeometry = OctahedronGeometry;
  31467. exports.OneFactor = OneFactor;
  31468. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  31469. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  31470. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  31471. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  31472. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  31473. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  31474. exports.OrthographicCamera = OrthographicCamera;
  31475. exports.P3Primaries = P3Primaries;
  31476. exports.PCFShadowMap = PCFShadowMap;
  31477. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  31478. exports.PMREMGenerator = PMREMGenerator;
  31479. exports.Path = Path;
  31480. exports.PerspectiveCamera = PerspectiveCamera;
  31481. exports.Plane = Plane;
  31482. exports.PlaneGeometry = PlaneGeometry;
  31483. exports.PlaneHelper = PlaneHelper;
  31484. exports.PointLight = PointLight;
  31485. exports.PointLightHelper = PointLightHelper;
  31486. exports.Points = Points;
  31487. exports.PointsMaterial = PointsMaterial;
  31488. exports.PolarGridHelper = PolarGridHelper;
  31489. exports.PolyhedronGeometry = PolyhedronGeometry;
  31490. exports.PositionalAudio = PositionalAudio;
  31491. exports.PropertyBinding = PropertyBinding;
  31492. exports.PropertyMixer = PropertyMixer;
  31493. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  31494. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  31495. exports.Quaternion = Quaternion;
  31496. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  31497. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  31498. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  31499. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  31500. exports.REVISION = REVISION;
  31501. exports.RGBADepthPacking = RGBADepthPacking;
  31502. exports.RGBAFormat = RGBAFormat;
  31503. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  31504. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  31505. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  31506. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  31507. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  31508. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  31509. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  31510. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  31511. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  31512. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  31513. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  31514. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  31515. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  31516. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  31517. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  31518. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  31519. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  31520. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  31521. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  31522. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  31523. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  31524. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  31525. exports.RGBFormat = RGBFormat;
  31526. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  31527. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  31528. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  31529. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  31530. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  31531. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  31532. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  31533. exports.RGFormat = RGFormat;
  31534. exports.RGIntegerFormat = RGIntegerFormat;
  31535. exports.RawShaderMaterial = RawShaderMaterial;
  31536. exports.Ray = Ray;
  31537. exports.Raycaster = Raycaster;
  31538. exports.Rec709Primaries = Rec709Primaries;
  31539. exports.RectAreaLight = RectAreaLight;
  31540. exports.RedFormat = RedFormat;
  31541. exports.RedIntegerFormat = RedIntegerFormat;
  31542. exports.ReinhardToneMapping = ReinhardToneMapping;
  31543. exports.RenderTarget = RenderTarget;
  31544. exports.RepeatWrapping = RepeatWrapping;
  31545. exports.ReplaceStencilOp = ReplaceStencilOp;
  31546. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  31547. exports.RingGeometry = RingGeometry;
  31548. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  31549. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  31550. exports.SRGBColorSpace = SRGBColorSpace;
  31551. exports.SRGBTransfer = SRGBTransfer;
  31552. exports.Scene = Scene;
  31553. exports.ShaderChunk = ShaderChunk;
  31554. exports.ShaderLib = ShaderLib;
  31555. exports.ShaderMaterial = ShaderMaterial;
  31556. exports.ShadowMaterial = ShadowMaterial;
  31557. exports.Shape = Shape;
  31558. exports.ShapeGeometry = ShapeGeometry;
  31559. exports.ShapePath = ShapePath;
  31560. exports.ShapeUtils = ShapeUtils;
  31561. exports.ShortType = ShortType;
  31562. exports.Skeleton = Skeleton;
  31563. exports.SkeletonHelper = SkeletonHelper;
  31564. exports.SkinnedMesh = SkinnedMesh;
  31565. exports.Source = Source;
  31566. exports.Sphere = Sphere;
  31567. exports.SphereGeometry = SphereGeometry;
  31568. exports.Spherical = Spherical;
  31569. exports.SphericalHarmonics3 = SphericalHarmonics3;
  31570. exports.SplineCurve = SplineCurve;
  31571. exports.SpotLight = SpotLight;
  31572. exports.SpotLightHelper = SpotLightHelper;
  31573. exports.Sprite = Sprite;
  31574. exports.SpriteMaterial = SpriteMaterial;
  31575. exports.SrcAlphaFactor = SrcAlphaFactor;
  31576. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  31577. exports.SrcColorFactor = SrcColorFactor;
  31578. exports.StaticCopyUsage = StaticCopyUsage;
  31579. exports.StaticDrawUsage = StaticDrawUsage;
  31580. exports.StaticReadUsage = StaticReadUsage;
  31581. exports.StereoCamera = StereoCamera;
  31582. exports.StreamCopyUsage = StreamCopyUsage;
  31583. exports.StreamDrawUsage = StreamDrawUsage;
  31584. exports.StreamReadUsage = StreamReadUsage;
  31585. exports.StringKeyframeTrack = StringKeyframeTrack;
  31586. exports.SubtractEquation = SubtractEquation;
  31587. exports.SubtractiveBlending = SubtractiveBlending;
  31588. exports.TOUCH = TOUCH;
  31589. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  31590. exports.TetrahedronGeometry = TetrahedronGeometry;
  31591. exports.Texture = Texture;
  31592. exports.TextureLoader = TextureLoader;
  31593. exports.TorusGeometry = TorusGeometry;
  31594. exports.TorusKnotGeometry = TorusKnotGeometry;
  31595. exports.Triangle = Triangle;
  31596. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  31597. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  31598. exports.TrianglesDrawMode = TrianglesDrawMode;
  31599. exports.TubeGeometry = TubeGeometry;
  31600. exports.UVMapping = UVMapping;
  31601. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  31602. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  31603. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  31604. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  31605. exports.Uniform = Uniform;
  31606. exports.UniformsGroup = UniformsGroup;
  31607. exports.UniformsLib = UniformsLib;
  31608. exports.UniformsUtils = UniformsUtils;
  31609. exports.UnsignedByteType = UnsignedByteType;
  31610. exports.UnsignedInt248Type = UnsignedInt248Type;
  31611. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  31612. exports.UnsignedIntType = UnsignedIntType;
  31613. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  31614. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  31615. exports.UnsignedShortType = UnsignedShortType;
  31616. exports.VSMShadowMap = VSMShadowMap;
  31617. exports.Vector2 = Vector2;
  31618. exports.Vector3 = Vector3;
  31619. exports.Vector4 = Vector4;
  31620. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  31621. exports.VideoTexture = VideoTexture;
  31622. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  31623. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  31624. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  31625. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  31626. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  31627. exports.WebGLRenderTarget = WebGLRenderTarget;
  31628. exports.WebGLRenderer = WebGLRenderer;
  31629. exports.WebGLUtils = WebGLUtils;
  31630. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  31631. exports.WireframeGeometry = WireframeGeometry;
  31632. exports.WrapAroundEnding = WrapAroundEnding;
  31633. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  31634. exports.ZeroFactor = ZeroFactor;
  31635. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  31636. exports.ZeroStencilOp = ZeroStencilOp;
  31637. exports.createCanvasElement = createCanvasElement;