three.cjs 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '169dev';
  8. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  9. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  10. const CullFaceNone = 0;
  11. const CullFaceBack = 1;
  12. const CullFaceFront = 2;
  13. const CullFaceFrontBack = 3;
  14. const BasicShadowMap = 0;
  15. const PCFShadowMap = 1;
  16. const PCFSoftShadowMap = 2;
  17. const VSMShadowMap = 3;
  18. const FrontSide = 0;
  19. const BackSide = 1;
  20. const DoubleSide = 2;
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const ConstantColorFactor = 211;
  44. const OneMinusConstantColorFactor = 212;
  45. const ConstantAlphaFactor = 213;
  46. const OneMinusConstantAlphaFactor = 214;
  47. const NeverDepth = 0;
  48. const AlwaysDepth = 1;
  49. const LessDepth = 2;
  50. const LessEqualDepth = 3;
  51. const EqualDepth = 4;
  52. const GreaterEqualDepth = 5;
  53. const GreaterDepth = 6;
  54. const NotEqualDepth = 7;
  55. const MultiplyOperation = 0;
  56. const MixOperation = 1;
  57. const AddOperation = 2;
  58. const NoToneMapping = 0;
  59. const LinearToneMapping = 1;
  60. const ReinhardToneMapping = 2;
  61. const CineonToneMapping = 3;
  62. const ACESFilmicToneMapping = 4;
  63. const CustomToneMapping = 5;
  64. const AgXToneMapping = 6;
  65. const NeutralToneMapping = 7;
  66. const AttachedBindMode = 'attached';
  67. const DetachedBindMode = 'detached';
  68. const UVMapping = 300;
  69. const CubeReflectionMapping = 301;
  70. const CubeRefractionMapping = 302;
  71. const EquirectangularReflectionMapping = 303;
  72. const EquirectangularRefractionMapping = 304;
  73. const CubeUVReflectionMapping = 306;
  74. const RepeatWrapping = 1000;
  75. const ClampToEdgeWrapping = 1001;
  76. const MirroredRepeatWrapping = 1002;
  77. const NearestFilter = 1003;
  78. const NearestMipmapNearestFilter = 1004;
  79. const NearestMipMapNearestFilter = 1004;
  80. const NearestMipmapLinearFilter = 1005;
  81. const NearestMipMapLinearFilter = 1005;
  82. const LinearFilter = 1006;
  83. const LinearMipmapNearestFilter = 1007;
  84. const LinearMipMapNearestFilter = 1007;
  85. const LinearMipmapLinearFilter = 1008;
  86. const LinearMipMapLinearFilter = 1008;
  87. const UnsignedByteType = 1009;
  88. const ByteType = 1010;
  89. const ShortType = 1011;
  90. const UnsignedShortType = 1012;
  91. const IntType = 1013;
  92. const UnsignedIntType = 1014;
  93. const FloatType = 1015;
  94. const HalfFloatType = 1016;
  95. const UnsignedShort4444Type = 1017;
  96. const UnsignedShort5551Type = 1018;
  97. const UnsignedInt248Type = 1020;
  98. const UnsignedInt5999Type = 35902;
  99. const AlphaFormat = 1021;
  100. const RGBFormat = 1022;
  101. const RGBAFormat = 1023;
  102. const LuminanceFormat = 1024;
  103. const LuminanceAlphaFormat = 1025;
  104. const DepthFormat = 1026;
  105. const DepthStencilFormat = 1027;
  106. const RedFormat = 1028;
  107. const RedIntegerFormat = 1029;
  108. const RGFormat = 1030;
  109. const RGIntegerFormat = 1031;
  110. const RGBIntegerFormat = 1032;
  111. const RGBAIntegerFormat = 1033;
  112. const RGB_S3TC_DXT1_Format = 33776;
  113. const RGBA_S3TC_DXT1_Format = 33777;
  114. const RGBA_S3TC_DXT3_Format = 33778;
  115. const RGBA_S3TC_DXT5_Format = 33779;
  116. const RGB_PVRTC_4BPPV1_Format = 35840;
  117. const RGB_PVRTC_2BPPV1_Format = 35841;
  118. const RGBA_PVRTC_4BPPV1_Format = 35842;
  119. const RGBA_PVRTC_2BPPV1_Format = 35843;
  120. const RGB_ETC1_Format = 36196;
  121. const RGB_ETC2_Format = 37492;
  122. const RGBA_ETC2_EAC_Format = 37496;
  123. const RGBA_ASTC_4x4_Format = 37808;
  124. const RGBA_ASTC_5x4_Format = 37809;
  125. const RGBA_ASTC_5x5_Format = 37810;
  126. const RGBA_ASTC_6x5_Format = 37811;
  127. const RGBA_ASTC_6x6_Format = 37812;
  128. const RGBA_ASTC_8x5_Format = 37813;
  129. const RGBA_ASTC_8x6_Format = 37814;
  130. const RGBA_ASTC_8x8_Format = 37815;
  131. const RGBA_ASTC_10x5_Format = 37816;
  132. const RGBA_ASTC_10x6_Format = 37817;
  133. const RGBA_ASTC_10x8_Format = 37818;
  134. const RGBA_ASTC_10x10_Format = 37819;
  135. const RGBA_ASTC_12x10_Format = 37820;
  136. const RGBA_ASTC_12x12_Format = 37821;
  137. const RGBA_BPTC_Format = 36492;
  138. const RGB_BPTC_SIGNED_Format = 36494;
  139. const RGB_BPTC_UNSIGNED_Format = 36495;
  140. const RED_RGTC1_Format = 36283;
  141. const SIGNED_RED_RGTC1_Format = 36284;
  142. const RED_GREEN_RGTC2_Format = 36285;
  143. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  144. const LoopOnce = 2200;
  145. const LoopRepeat = 2201;
  146. const LoopPingPong = 2202;
  147. const InterpolateDiscrete = 2300;
  148. const InterpolateLinear = 2301;
  149. const InterpolateSmooth = 2302;
  150. const ZeroCurvatureEnding = 2400;
  151. const ZeroSlopeEnding = 2401;
  152. const WrapAroundEnding = 2402;
  153. const NormalAnimationBlendMode = 2500;
  154. const AdditiveAnimationBlendMode = 2501;
  155. const TrianglesDrawMode = 0;
  156. const TriangleStripDrawMode = 1;
  157. const TriangleFanDrawMode = 2;
  158. const BasicDepthPacking = 3200;
  159. const RGBADepthPacking = 3201;
  160. const RGBDepthPacking = 3202;
  161. const RGDepthPacking = 3203;
  162. const TangentSpaceNormalMap = 0;
  163. const ObjectSpaceNormalMap = 1;
  164. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  165. const NoColorSpace = '';
  166. const SRGBColorSpace = 'srgb';
  167. const LinearSRGBColorSpace = 'srgb-linear';
  168. const DisplayP3ColorSpace = 'display-p3';
  169. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  170. const LinearTransfer = 'linear';
  171. const SRGBTransfer = 'srgb';
  172. const Rec709Primaries = 'rec709';
  173. const P3Primaries = 'p3';
  174. const ZeroStencilOp = 0;
  175. const KeepStencilOp = 7680;
  176. const ReplaceStencilOp = 7681;
  177. const IncrementStencilOp = 7682;
  178. const DecrementStencilOp = 7683;
  179. const IncrementWrapStencilOp = 34055;
  180. const DecrementWrapStencilOp = 34056;
  181. const InvertStencilOp = 5386;
  182. const NeverStencilFunc = 512;
  183. const LessStencilFunc = 513;
  184. const EqualStencilFunc = 514;
  185. const LessEqualStencilFunc = 515;
  186. const GreaterStencilFunc = 516;
  187. const NotEqualStencilFunc = 517;
  188. const GreaterEqualStencilFunc = 518;
  189. const AlwaysStencilFunc = 519;
  190. const NeverCompare = 512;
  191. const LessCompare = 513;
  192. const EqualCompare = 514;
  193. const LessEqualCompare = 515;
  194. const GreaterCompare = 516;
  195. const NotEqualCompare = 517;
  196. const GreaterEqualCompare = 518;
  197. const AlwaysCompare = 519;
  198. const StaticDrawUsage = 35044;
  199. const DynamicDrawUsage = 35048;
  200. const StreamDrawUsage = 35040;
  201. const StaticReadUsage = 35045;
  202. const DynamicReadUsage = 35049;
  203. const StreamReadUsage = 35041;
  204. const StaticCopyUsage = 35046;
  205. const DynamicCopyUsage = 35050;
  206. const StreamCopyUsage = 35042;
  207. const GLSL1 = '100';
  208. const GLSL3 = '300 es';
  209. const WebGLCoordinateSystem = 2000;
  210. const WebGPUCoordinateSystem = 2001;
  211. /**
  212. * https://github.com/mrdoob/eventdispatcher.js/
  213. */
  214. class EventDispatcher {
  215. addEventListener( type, listener ) {
  216. if ( this._listeners === undefined ) this._listeners = {};
  217. const listeners = this._listeners;
  218. if ( listeners[ type ] === undefined ) {
  219. listeners[ type ] = [];
  220. }
  221. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  222. listeners[ type ].push( listener );
  223. }
  224. }
  225. hasEventListener( type, listener ) {
  226. if ( this._listeners === undefined ) return false;
  227. const listeners = this._listeners;
  228. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  229. }
  230. removeEventListener( type, listener ) {
  231. if ( this._listeners === undefined ) return;
  232. const listeners = this._listeners;
  233. const listenerArray = listeners[ type ];
  234. if ( listenerArray !== undefined ) {
  235. const index = listenerArray.indexOf( listener );
  236. if ( index !== - 1 ) {
  237. listenerArray.splice( index, 1 );
  238. }
  239. }
  240. }
  241. dispatchEvent( event ) {
  242. if ( this._listeners === undefined ) return;
  243. const listeners = this._listeners;
  244. const listenerArray = listeners[ event.type ];
  245. if ( listenerArray !== undefined ) {
  246. event.target = this;
  247. // Make a copy, in case listeners are removed while iterating.
  248. const array = listenerArray.slice( 0 );
  249. for ( let i = 0, l = array.length; i < l; i ++ ) {
  250. array[ i ].call( this, event );
  251. }
  252. event.target = null;
  253. }
  254. }
  255. }
  256. 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' ];
  257. let _seed = 1234567;
  258. const DEG2RAD = Math.PI / 180;
  259. const RAD2DEG = 180 / Math.PI;
  260. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  261. function generateUUID() {
  262. const d0 = Math.random() * 0xffffffff | 0;
  263. const d1 = Math.random() * 0xffffffff | 0;
  264. const d2 = Math.random() * 0xffffffff | 0;
  265. const d3 = Math.random() * 0xffffffff | 0;
  266. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  267. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  268. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  269. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  270. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  271. return uuid.toLowerCase();
  272. }
  273. function clamp( value, min, max ) {
  274. return Math.max( min, Math.min( max, value ) );
  275. }
  276. // compute euclidean modulo of m % n
  277. // https://en.wikipedia.org/wiki/Modulo_operation
  278. function euclideanModulo( n, m ) {
  279. return ( ( n % m ) + m ) % m;
  280. }
  281. // Linear mapping from range <a1, a2> to range <b1, b2>
  282. function mapLinear( x, a1, a2, b1, b2 ) {
  283. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  284. }
  285. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  286. function inverseLerp( x, y, value ) {
  287. if ( x !== y ) {
  288. return ( value - x ) / ( y - x );
  289. } else {
  290. return 0;
  291. }
  292. }
  293. // https://en.wikipedia.org/wiki/Linear_interpolation
  294. function lerp( x, y, t ) {
  295. return ( 1 - t ) * x + t * y;
  296. }
  297. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  298. function damp( x, y, lambda, dt ) {
  299. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  300. }
  301. // https://www.desmos.com/calculator/vcsjnyz7x4
  302. function pingpong( x, length = 1 ) {
  303. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  304. }
  305. // http://en.wikipedia.org/wiki/Smoothstep
  306. function smoothstep( x, min, max ) {
  307. if ( x <= min ) return 0;
  308. if ( x >= max ) return 1;
  309. x = ( x - min ) / ( max - min );
  310. return x * x * ( 3 - 2 * x );
  311. }
  312. function smootherstep( x, min, max ) {
  313. if ( x <= min ) return 0;
  314. if ( x >= max ) return 1;
  315. x = ( x - min ) / ( max - min );
  316. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  317. }
  318. // Random integer from <low, high> interval
  319. function randInt( low, high ) {
  320. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  321. }
  322. // Random float from <low, high> interval
  323. function randFloat( low, high ) {
  324. return low + Math.random() * ( high - low );
  325. }
  326. // Random float from <-range/2, range/2> interval
  327. function randFloatSpread( range ) {
  328. return range * ( 0.5 - Math.random() );
  329. }
  330. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  331. function seededRandom( s ) {
  332. if ( s !== undefined ) _seed = s;
  333. // Mulberry32 generator
  334. let t = _seed += 0x6D2B79F5;
  335. t = Math.imul( t ^ t >>> 15, t | 1 );
  336. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  337. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  338. }
  339. function degToRad( degrees ) {
  340. return degrees * DEG2RAD;
  341. }
  342. function radToDeg( radians ) {
  343. return radians * RAD2DEG;
  344. }
  345. function isPowerOfTwo( value ) {
  346. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  347. }
  348. function ceilPowerOfTwo( value ) {
  349. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  350. }
  351. function floorPowerOfTwo( value ) {
  352. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  353. }
  354. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  355. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  356. // rotations are applied to the axes in the order specified by 'order'
  357. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  358. // angles are in radians
  359. const cos = Math.cos;
  360. const sin = Math.sin;
  361. const c2 = cos( b / 2 );
  362. const s2 = sin( b / 2 );
  363. const c13 = cos( ( a + c ) / 2 );
  364. const s13 = sin( ( a + c ) / 2 );
  365. const c1_3 = cos( ( a - c ) / 2 );
  366. const s1_3 = sin( ( a - c ) / 2 );
  367. const c3_1 = cos( ( c - a ) / 2 );
  368. const s3_1 = sin( ( c - a ) / 2 );
  369. switch ( order ) {
  370. case 'XYX':
  371. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  372. break;
  373. case 'YZY':
  374. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  375. break;
  376. case 'ZXZ':
  377. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  378. break;
  379. case 'XZX':
  380. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  381. break;
  382. case 'YXY':
  383. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  384. break;
  385. case 'ZYZ':
  386. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  387. break;
  388. default:
  389. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  390. }
  391. }
  392. function denormalize( value, array ) {
  393. switch ( array.constructor ) {
  394. case Float32Array:
  395. return value;
  396. case Uint32Array:
  397. return value / 4294967295.0;
  398. case Uint16Array:
  399. return value / 65535.0;
  400. case Uint8Array:
  401. return value / 255.0;
  402. case Int32Array:
  403. return Math.max( value / 2147483647.0, - 1.0 );
  404. case Int16Array:
  405. return Math.max( value / 32767.0, - 1.0 );
  406. case Int8Array:
  407. return Math.max( value / 127.0, - 1.0 );
  408. default:
  409. throw new Error( 'Invalid component type.' );
  410. }
  411. }
  412. function normalize( value, array ) {
  413. switch ( array.constructor ) {
  414. case Float32Array:
  415. return value;
  416. case Uint32Array:
  417. return Math.round( value * 4294967295.0 );
  418. case Uint16Array:
  419. return Math.round( value * 65535.0 );
  420. case Uint8Array:
  421. return Math.round( value * 255.0 );
  422. case Int32Array:
  423. return Math.round( value * 2147483647.0 );
  424. case Int16Array:
  425. return Math.round( value * 32767.0 );
  426. case Int8Array:
  427. return Math.round( value * 127.0 );
  428. default:
  429. throw new Error( 'Invalid component type.' );
  430. }
  431. }
  432. const MathUtils = {
  433. DEG2RAD: DEG2RAD,
  434. RAD2DEG: RAD2DEG,
  435. generateUUID: generateUUID,
  436. clamp: clamp,
  437. euclideanModulo: euclideanModulo,
  438. mapLinear: mapLinear,
  439. inverseLerp: inverseLerp,
  440. lerp: lerp,
  441. damp: damp,
  442. pingpong: pingpong,
  443. smoothstep: smoothstep,
  444. smootherstep: smootherstep,
  445. randInt: randInt,
  446. randFloat: randFloat,
  447. randFloatSpread: randFloatSpread,
  448. seededRandom: seededRandom,
  449. degToRad: degToRad,
  450. radToDeg: radToDeg,
  451. isPowerOfTwo: isPowerOfTwo,
  452. ceilPowerOfTwo: ceilPowerOfTwo,
  453. floorPowerOfTwo: floorPowerOfTwo,
  454. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  455. normalize: normalize,
  456. denormalize: denormalize
  457. };
  458. class Vector2 {
  459. constructor( x = 0, y = 0 ) {
  460. Vector2.prototype.isVector2 = true;
  461. this.x = x;
  462. this.y = y;
  463. }
  464. get width() {
  465. return this.x;
  466. }
  467. set width( value ) {
  468. this.x = value;
  469. }
  470. get height() {
  471. return this.y;
  472. }
  473. set height( value ) {
  474. this.y = value;
  475. }
  476. set( x, y ) {
  477. this.x = x;
  478. this.y = y;
  479. return this;
  480. }
  481. setScalar( scalar ) {
  482. this.x = scalar;
  483. this.y = scalar;
  484. return this;
  485. }
  486. setX( x ) {
  487. this.x = x;
  488. return this;
  489. }
  490. setY( y ) {
  491. this.y = y;
  492. return this;
  493. }
  494. setComponent( index, value ) {
  495. switch ( index ) {
  496. case 0: this.x = value; break;
  497. case 1: this.y = value; break;
  498. default: throw new Error( 'index is out of range: ' + index );
  499. }
  500. return this;
  501. }
  502. getComponent( index ) {
  503. switch ( index ) {
  504. case 0: return this.x;
  505. case 1: return this.y;
  506. default: throw new Error( 'index is out of range: ' + index );
  507. }
  508. }
  509. clone() {
  510. return new this.constructor( this.x, this.y );
  511. }
  512. copy( v ) {
  513. this.x = v.x;
  514. this.y = v.y;
  515. return this;
  516. }
  517. add( v ) {
  518. this.x += v.x;
  519. this.y += v.y;
  520. return this;
  521. }
  522. addScalar( s ) {
  523. this.x += s;
  524. this.y += s;
  525. return this;
  526. }
  527. addVectors( a, b ) {
  528. this.x = a.x + b.x;
  529. this.y = a.y + b.y;
  530. return this;
  531. }
  532. addScaledVector( v, s ) {
  533. this.x += v.x * s;
  534. this.y += v.y * s;
  535. return this;
  536. }
  537. sub( v ) {
  538. this.x -= v.x;
  539. this.y -= v.y;
  540. return this;
  541. }
  542. subScalar( s ) {
  543. this.x -= s;
  544. this.y -= s;
  545. return this;
  546. }
  547. subVectors( a, b ) {
  548. this.x = a.x - b.x;
  549. this.y = a.y - b.y;
  550. return this;
  551. }
  552. multiply( v ) {
  553. this.x *= v.x;
  554. this.y *= v.y;
  555. return this;
  556. }
  557. multiplyScalar( scalar ) {
  558. this.x *= scalar;
  559. this.y *= scalar;
  560. return this;
  561. }
  562. divide( v ) {
  563. this.x /= v.x;
  564. this.y /= v.y;
  565. return this;
  566. }
  567. divideScalar( scalar ) {
  568. return this.multiplyScalar( 1 / scalar );
  569. }
  570. applyMatrix3( m ) {
  571. const x = this.x, y = this.y;
  572. const e = m.elements;
  573. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  574. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  575. return this;
  576. }
  577. min( v ) {
  578. this.x = Math.min( this.x, v.x );
  579. this.y = Math.min( this.y, v.y );
  580. return this;
  581. }
  582. max( v ) {
  583. this.x = Math.max( this.x, v.x );
  584. this.y = Math.max( this.y, v.y );
  585. return this;
  586. }
  587. clamp( min, max ) {
  588. // assumes min < max, componentwise
  589. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  590. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  591. return this;
  592. }
  593. clampScalar( minVal, maxVal ) {
  594. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  595. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  596. return this;
  597. }
  598. clampLength( min, max ) {
  599. const length = this.length();
  600. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  601. }
  602. floor() {
  603. this.x = Math.floor( this.x );
  604. this.y = Math.floor( this.y );
  605. return this;
  606. }
  607. ceil() {
  608. this.x = Math.ceil( this.x );
  609. this.y = Math.ceil( this.y );
  610. return this;
  611. }
  612. round() {
  613. this.x = Math.round( this.x );
  614. this.y = Math.round( this.y );
  615. return this;
  616. }
  617. roundToZero() {
  618. this.x = Math.trunc( this.x );
  619. this.y = Math.trunc( this.y );
  620. return this;
  621. }
  622. negate() {
  623. this.x = - this.x;
  624. this.y = - this.y;
  625. return this;
  626. }
  627. dot( v ) {
  628. return this.x * v.x + this.y * v.y;
  629. }
  630. cross( v ) {
  631. return this.x * v.y - this.y * v.x;
  632. }
  633. lengthSq() {
  634. return this.x * this.x + this.y * this.y;
  635. }
  636. length() {
  637. return Math.sqrt( this.x * this.x + this.y * this.y );
  638. }
  639. manhattanLength() {
  640. return Math.abs( this.x ) + Math.abs( this.y );
  641. }
  642. normalize() {
  643. return this.divideScalar( this.length() || 1 );
  644. }
  645. angle() {
  646. // computes the angle in radians with respect to the positive x-axis
  647. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  648. return angle;
  649. }
  650. angleTo( v ) {
  651. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  652. if ( denominator === 0 ) return Math.PI / 2;
  653. const theta = this.dot( v ) / denominator;
  654. // clamp, to handle numerical problems
  655. return Math.acos( clamp( theta, - 1, 1 ) );
  656. }
  657. distanceTo( v ) {
  658. return Math.sqrt( this.distanceToSquared( v ) );
  659. }
  660. distanceToSquared( v ) {
  661. const dx = this.x - v.x, dy = this.y - v.y;
  662. return dx * dx + dy * dy;
  663. }
  664. manhattanDistanceTo( v ) {
  665. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  666. }
  667. setLength( length ) {
  668. return this.normalize().multiplyScalar( length );
  669. }
  670. lerp( v, alpha ) {
  671. this.x += ( v.x - this.x ) * alpha;
  672. this.y += ( v.y - this.y ) * alpha;
  673. return this;
  674. }
  675. lerpVectors( v1, v2, alpha ) {
  676. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  677. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  678. return this;
  679. }
  680. equals( v ) {
  681. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  682. }
  683. fromArray( array, offset = 0 ) {
  684. this.x = array[ offset ];
  685. this.y = array[ offset + 1 ];
  686. return this;
  687. }
  688. toArray( array = [], offset = 0 ) {
  689. array[ offset ] = this.x;
  690. array[ offset + 1 ] = this.y;
  691. return array;
  692. }
  693. fromBufferAttribute( attribute, index ) {
  694. this.x = attribute.getX( index );
  695. this.y = attribute.getY( index );
  696. return this;
  697. }
  698. rotateAround( center, angle ) {
  699. const c = Math.cos( angle ), s = Math.sin( angle );
  700. const x = this.x - center.x;
  701. const y = this.y - center.y;
  702. this.x = x * c - y * s + center.x;
  703. this.y = x * s + y * c + center.y;
  704. return this;
  705. }
  706. random() {
  707. this.x = Math.random();
  708. this.y = Math.random();
  709. return this;
  710. }
  711. *[ Symbol.iterator ]() {
  712. yield this.x;
  713. yield this.y;
  714. }
  715. }
  716. class Matrix3 {
  717. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  718. Matrix3.prototype.isMatrix3 = true;
  719. this.elements = [
  720. 1, 0, 0,
  721. 0, 1, 0,
  722. 0, 0, 1
  723. ];
  724. if ( n11 !== undefined ) {
  725. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  726. }
  727. }
  728. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  729. const te = this.elements;
  730. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  731. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  732. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  733. return this;
  734. }
  735. identity() {
  736. this.set(
  737. 1, 0, 0,
  738. 0, 1, 0,
  739. 0, 0, 1
  740. );
  741. return this;
  742. }
  743. copy( m ) {
  744. const te = this.elements;
  745. const me = m.elements;
  746. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  747. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  748. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  749. return this;
  750. }
  751. extractBasis( xAxis, yAxis, zAxis ) {
  752. xAxis.setFromMatrix3Column( this, 0 );
  753. yAxis.setFromMatrix3Column( this, 1 );
  754. zAxis.setFromMatrix3Column( this, 2 );
  755. return this;
  756. }
  757. setFromMatrix4( m ) {
  758. const me = m.elements;
  759. this.set(
  760. me[ 0 ], me[ 4 ], me[ 8 ],
  761. me[ 1 ], me[ 5 ], me[ 9 ],
  762. me[ 2 ], me[ 6 ], me[ 10 ]
  763. );
  764. return this;
  765. }
  766. multiply( m ) {
  767. return this.multiplyMatrices( this, m );
  768. }
  769. premultiply( m ) {
  770. return this.multiplyMatrices( m, this );
  771. }
  772. multiplyMatrices( a, b ) {
  773. const ae = a.elements;
  774. const be = b.elements;
  775. const te = this.elements;
  776. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  777. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  778. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  779. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  780. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  781. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  782. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  783. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  784. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  785. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  786. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  787. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  788. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  789. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  790. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  791. return this;
  792. }
  793. multiplyScalar( s ) {
  794. const te = this.elements;
  795. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  796. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  797. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  798. return this;
  799. }
  800. determinant() {
  801. const te = this.elements;
  802. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  803. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  804. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  805. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  806. }
  807. invert() {
  808. const te = this.elements,
  809. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  810. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  811. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  812. t11 = n33 * n22 - n32 * n23,
  813. t12 = n32 * n13 - n33 * n12,
  814. t13 = n23 * n12 - n22 * n13,
  815. det = n11 * t11 + n21 * t12 + n31 * t13;
  816. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  817. const detInv = 1 / det;
  818. te[ 0 ] = t11 * detInv;
  819. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  820. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  821. te[ 3 ] = t12 * detInv;
  822. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  823. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  824. te[ 6 ] = t13 * detInv;
  825. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  826. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  827. return this;
  828. }
  829. transpose() {
  830. let tmp;
  831. const m = this.elements;
  832. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  833. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  834. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  835. return this;
  836. }
  837. getNormalMatrix( matrix4 ) {
  838. return this.setFromMatrix4( matrix4 ).invert().transpose();
  839. }
  840. transposeIntoArray( r ) {
  841. const m = this.elements;
  842. r[ 0 ] = m[ 0 ];
  843. r[ 1 ] = m[ 3 ];
  844. r[ 2 ] = m[ 6 ];
  845. r[ 3 ] = m[ 1 ];
  846. r[ 4 ] = m[ 4 ];
  847. r[ 5 ] = m[ 7 ];
  848. r[ 6 ] = m[ 2 ];
  849. r[ 7 ] = m[ 5 ];
  850. r[ 8 ] = m[ 8 ];
  851. return this;
  852. }
  853. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  854. const c = Math.cos( rotation );
  855. const s = Math.sin( rotation );
  856. this.set(
  857. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  858. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  859. 0, 0, 1
  860. );
  861. return this;
  862. }
  863. //
  864. scale( sx, sy ) {
  865. this.premultiply( _m3.makeScale( sx, sy ) );
  866. return this;
  867. }
  868. rotate( theta ) {
  869. this.premultiply( _m3.makeRotation( - theta ) );
  870. return this;
  871. }
  872. translate( tx, ty ) {
  873. this.premultiply( _m3.makeTranslation( tx, ty ) );
  874. return this;
  875. }
  876. // for 2D Transforms
  877. makeTranslation( x, y ) {
  878. if ( x.isVector2 ) {
  879. this.set(
  880. 1, 0, x.x,
  881. 0, 1, x.y,
  882. 0, 0, 1
  883. );
  884. } else {
  885. this.set(
  886. 1, 0, x,
  887. 0, 1, y,
  888. 0, 0, 1
  889. );
  890. }
  891. return this;
  892. }
  893. makeRotation( theta ) {
  894. // counterclockwise
  895. const c = Math.cos( theta );
  896. const s = Math.sin( theta );
  897. this.set(
  898. c, - s, 0,
  899. s, c, 0,
  900. 0, 0, 1
  901. );
  902. return this;
  903. }
  904. makeScale( x, y ) {
  905. this.set(
  906. x, 0, 0,
  907. 0, y, 0,
  908. 0, 0, 1
  909. );
  910. return this;
  911. }
  912. //
  913. equals( matrix ) {
  914. const te = this.elements;
  915. const me = matrix.elements;
  916. for ( let i = 0; i < 9; i ++ ) {
  917. if ( te[ i ] !== me[ i ] ) return false;
  918. }
  919. return true;
  920. }
  921. fromArray( array, offset = 0 ) {
  922. for ( let i = 0; i < 9; i ++ ) {
  923. this.elements[ i ] = array[ i + offset ];
  924. }
  925. return this;
  926. }
  927. toArray( array = [], offset = 0 ) {
  928. const te = this.elements;
  929. array[ offset ] = te[ 0 ];
  930. array[ offset + 1 ] = te[ 1 ];
  931. array[ offset + 2 ] = te[ 2 ];
  932. array[ offset + 3 ] = te[ 3 ];
  933. array[ offset + 4 ] = te[ 4 ];
  934. array[ offset + 5 ] = te[ 5 ];
  935. array[ offset + 6 ] = te[ 6 ];
  936. array[ offset + 7 ] = te[ 7 ];
  937. array[ offset + 8 ] = te[ 8 ];
  938. return array;
  939. }
  940. clone() {
  941. return new this.constructor().fromArray( this.elements );
  942. }
  943. }
  944. const _m3 = /*@__PURE__*/ new Matrix3();
  945. function arrayNeedsUint32( array ) {
  946. // assumes larger values usually on last
  947. for ( let i = array.length - 1; i >= 0; -- i ) {
  948. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  949. }
  950. return false;
  951. }
  952. const TYPED_ARRAYS = {
  953. Int8Array: Int8Array,
  954. Uint8Array: Uint8Array,
  955. Uint8ClampedArray: Uint8ClampedArray,
  956. Int16Array: Int16Array,
  957. Uint16Array: Uint16Array,
  958. Int32Array: Int32Array,
  959. Uint32Array: Uint32Array,
  960. Float32Array: Float32Array,
  961. Float64Array: Float64Array
  962. };
  963. function getTypedArray( type, buffer ) {
  964. return new TYPED_ARRAYS[ type ]( buffer );
  965. }
  966. function createElementNS( name ) {
  967. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  968. }
  969. function createCanvasElement() {
  970. const canvas = createElementNS( 'canvas' );
  971. canvas.style.display = 'block';
  972. return canvas;
  973. }
  974. const _cache = {};
  975. function warnOnce( message ) {
  976. if ( message in _cache ) return;
  977. _cache[ message ] = true;
  978. console.warn( message );
  979. }
  980. function probeAsync( gl, sync, interval ) {
  981. return new Promise( function ( resolve, reject ) {
  982. function probe() {
  983. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  984. case gl.WAIT_FAILED:
  985. reject();
  986. break;
  987. case gl.TIMEOUT_EXPIRED:
  988. setTimeout( probe, interval );
  989. break;
  990. default:
  991. resolve();
  992. }
  993. }
  994. setTimeout( probe, interval );
  995. } );
  996. }
  997. /**
  998. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  999. * or clipping. Based on W3C specifications for sRGB and Display P3,
  1000. * and ICC specifications for the D50 connection space. Values in/out
  1001. * are _linear_ sRGB and _linear_ Display P3.
  1002. *
  1003. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  1004. *
  1005. * Reference:
  1006. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  1007. */
  1008. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  1009. 0.8224621, 0.177538, 0.0,
  1010. 0.0331941, 0.9668058, 0.0,
  1011. 0.0170827, 0.0723974, 0.9105199,
  1012. );
  1013. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  1014. 1.2249401, - 0.2249404, 0.0,
  1015. - 0.0420569, 1.0420571, 0.0,
  1016. - 0.0196376, - 0.0786361, 1.0982735
  1017. );
  1018. /**
  1019. * Defines supported color spaces by transfer function and primaries,
  1020. * and provides conversions to/from the Linear-sRGB reference space.
  1021. */
  1022. const COLOR_SPACES = {
  1023. [ LinearSRGBColorSpace ]: {
  1024. transfer: LinearTransfer,
  1025. primaries: Rec709Primaries,
  1026. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1027. toReference: ( color ) => color,
  1028. fromReference: ( color ) => color,
  1029. },
  1030. [ SRGBColorSpace ]: {
  1031. transfer: SRGBTransfer,
  1032. primaries: Rec709Primaries,
  1033. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1034. toReference: ( color ) => color.convertSRGBToLinear(),
  1035. fromReference: ( color ) => color.convertLinearToSRGB(),
  1036. },
  1037. [ LinearDisplayP3ColorSpace ]: {
  1038. transfer: LinearTransfer,
  1039. primaries: P3Primaries,
  1040. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1041. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1042. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1043. },
  1044. [ DisplayP3ColorSpace ]: {
  1045. transfer: SRGBTransfer,
  1046. primaries: P3Primaries,
  1047. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1048. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1049. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1050. },
  1051. };
  1052. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1053. const ColorManagement = {
  1054. enabled: true,
  1055. _workingColorSpace: LinearSRGBColorSpace,
  1056. get workingColorSpace() {
  1057. return this._workingColorSpace;
  1058. },
  1059. set workingColorSpace( colorSpace ) {
  1060. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1061. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1062. }
  1063. this._workingColorSpace = colorSpace;
  1064. },
  1065. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1066. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1067. return color;
  1068. }
  1069. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1070. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1071. return targetFromReference( sourceToReference( color ) );
  1072. },
  1073. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1074. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1075. },
  1076. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1077. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1078. },
  1079. getPrimaries: function ( colorSpace ) {
  1080. return COLOR_SPACES[ colorSpace ].primaries;
  1081. },
  1082. getTransfer: function ( colorSpace ) {
  1083. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1084. return COLOR_SPACES[ colorSpace ].transfer;
  1085. },
  1086. getLuminanceCoefficients: function ( target, colorSpace = this._workingColorSpace ) {
  1087. return target.fromArray( COLOR_SPACES[ colorSpace ].luminanceCoefficients );
  1088. },
  1089. };
  1090. function SRGBToLinear( c ) {
  1091. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1092. }
  1093. function LinearToSRGB( c ) {
  1094. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1095. }
  1096. let _canvas;
  1097. class ImageUtils {
  1098. static getDataURL( image ) {
  1099. if ( /^data:/i.test( image.src ) ) {
  1100. return image.src;
  1101. }
  1102. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1103. return image.src;
  1104. }
  1105. let canvas;
  1106. if ( image instanceof HTMLCanvasElement ) {
  1107. canvas = image;
  1108. } else {
  1109. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1110. _canvas.width = image.width;
  1111. _canvas.height = image.height;
  1112. const context = _canvas.getContext( '2d' );
  1113. if ( image instanceof ImageData ) {
  1114. context.putImageData( image, 0, 0 );
  1115. } else {
  1116. context.drawImage( image, 0, 0, image.width, image.height );
  1117. }
  1118. canvas = _canvas;
  1119. }
  1120. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1121. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1122. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1123. } else {
  1124. return canvas.toDataURL( 'image/png' );
  1125. }
  1126. }
  1127. static sRGBToLinear( image ) {
  1128. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1129. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1130. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1131. const canvas = createElementNS( 'canvas' );
  1132. canvas.width = image.width;
  1133. canvas.height = image.height;
  1134. const context = canvas.getContext( '2d' );
  1135. context.drawImage( image, 0, 0, image.width, image.height );
  1136. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1137. const data = imageData.data;
  1138. for ( let i = 0; i < data.length; i ++ ) {
  1139. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1140. }
  1141. context.putImageData( imageData, 0, 0 );
  1142. return canvas;
  1143. } else if ( image.data ) {
  1144. const data = image.data.slice( 0 );
  1145. for ( let i = 0; i < data.length; i ++ ) {
  1146. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1147. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1148. } else {
  1149. // assuming float
  1150. data[ i ] = SRGBToLinear( data[ i ] );
  1151. }
  1152. }
  1153. return {
  1154. data: data,
  1155. width: image.width,
  1156. height: image.height
  1157. };
  1158. } else {
  1159. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1160. return image;
  1161. }
  1162. }
  1163. }
  1164. let _sourceId = 0;
  1165. class Source {
  1166. constructor( data = null ) {
  1167. this.isSource = true;
  1168. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1169. this.uuid = generateUUID();
  1170. this.data = data;
  1171. this.dataReady = true;
  1172. this.version = 0;
  1173. }
  1174. set needsUpdate( value ) {
  1175. if ( value === true ) this.version ++;
  1176. }
  1177. toJSON( meta ) {
  1178. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1179. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1180. return meta.images[ this.uuid ];
  1181. }
  1182. const output = {
  1183. uuid: this.uuid,
  1184. url: ''
  1185. };
  1186. const data = this.data;
  1187. if ( data !== null ) {
  1188. let url;
  1189. if ( Array.isArray( data ) ) {
  1190. // cube texture
  1191. url = [];
  1192. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1193. if ( data[ i ].isDataTexture ) {
  1194. url.push( serializeImage( data[ i ].image ) );
  1195. } else {
  1196. url.push( serializeImage( data[ i ] ) );
  1197. }
  1198. }
  1199. } else {
  1200. // texture
  1201. url = serializeImage( data );
  1202. }
  1203. output.url = url;
  1204. }
  1205. if ( ! isRootObject ) {
  1206. meta.images[ this.uuid ] = output;
  1207. }
  1208. return output;
  1209. }
  1210. }
  1211. function serializeImage( image ) {
  1212. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1213. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1214. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1215. // default images
  1216. return ImageUtils.getDataURL( image );
  1217. } else {
  1218. if ( image.data ) {
  1219. // images of DataTexture
  1220. return {
  1221. data: Array.from( image.data ),
  1222. width: image.width,
  1223. height: image.height,
  1224. type: image.data.constructor.name
  1225. };
  1226. } else {
  1227. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1228. return {};
  1229. }
  1230. }
  1231. }
  1232. let _textureId = 0;
  1233. class Texture extends EventDispatcher {
  1234. 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 ) {
  1235. super();
  1236. this.isTexture = true;
  1237. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1238. this.uuid = generateUUID();
  1239. this.name = '';
  1240. this.source = new Source( image );
  1241. this.mipmaps = [];
  1242. this.mapping = mapping;
  1243. this.channel = 0;
  1244. this.wrapS = wrapS;
  1245. this.wrapT = wrapT;
  1246. this.magFilter = magFilter;
  1247. this.minFilter = minFilter;
  1248. this.anisotropy = anisotropy;
  1249. this.format = format;
  1250. this.internalFormat = null;
  1251. this.type = type;
  1252. this.offset = new Vector2( 0, 0 );
  1253. this.repeat = new Vector2( 1, 1 );
  1254. this.center = new Vector2( 0, 0 );
  1255. this.rotation = 0;
  1256. this.matrixAutoUpdate = true;
  1257. this.matrix = new Matrix3();
  1258. this.generateMipmaps = true;
  1259. this.premultiplyAlpha = false;
  1260. this.flipY = true;
  1261. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1262. this.colorSpace = colorSpace;
  1263. this.userData = {};
  1264. this.version = 0;
  1265. this.onUpdate = null;
  1266. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1267. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1268. }
  1269. get image() {
  1270. return this.source.data;
  1271. }
  1272. set image( value = null ) {
  1273. this.source.data = value;
  1274. }
  1275. updateMatrix() {
  1276. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1277. }
  1278. clone() {
  1279. return new this.constructor().copy( this );
  1280. }
  1281. copy( source ) {
  1282. this.name = source.name;
  1283. this.source = source.source;
  1284. this.mipmaps = source.mipmaps.slice( 0 );
  1285. this.mapping = source.mapping;
  1286. this.channel = source.channel;
  1287. this.wrapS = source.wrapS;
  1288. this.wrapT = source.wrapT;
  1289. this.magFilter = source.magFilter;
  1290. this.minFilter = source.minFilter;
  1291. this.anisotropy = source.anisotropy;
  1292. this.format = source.format;
  1293. this.internalFormat = source.internalFormat;
  1294. this.type = source.type;
  1295. this.offset.copy( source.offset );
  1296. this.repeat.copy( source.repeat );
  1297. this.center.copy( source.center );
  1298. this.rotation = source.rotation;
  1299. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1300. this.matrix.copy( source.matrix );
  1301. this.generateMipmaps = source.generateMipmaps;
  1302. this.premultiplyAlpha = source.premultiplyAlpha;
  1303. this.flipY = source.flipY;
  1304. this.unpackAlignment = source.unpackAlignment;
  1305. this.colorSpace = source.colorSpace;
  1306. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1307. this.needsUpdate = true;
  1308. return this;
  1309. }
  1310. toJSON( meta ) {
  1311. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1312. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1313. return meta.textures[ this.uuid ];
  1314. }
  1315. const output = {
  1316. metadata: {
  1317. version: 4.6,
  1318. type: 'Texture',
  1319. generator: 'Texture.toJSON'
  1320. },
  1321. uuid: this.uuid,
  1322. name: this.name,
  1323. image: this.source.toJSON( meta ).uuid,
  1324. mapping: this.mapping,
  1325. channel: this.channel,
  1326. repeat: [ this.repeat.x, this.repeat.y ],
  1327. offset: [ this.offset.x, this.offset.y ],
  1328. center: [ this.center.x, this.center.y ],
  1329. rotation: this.rotation,
  1330. wrap: [ this.wrapS, this.wrapT ],
  1331. format: this.format,
  1332. internalFormat: this.internalFormat,
  1333. type: this.type,
  1334. colorSpace: this.colorSpace,
  1335. minFilter: this.minFilter,
  1336. magFilter: this.magFilter,
  1337. anisotropy: this.anisotropy,
  1338. flipY: this.flipY,
  1339. generateMipmaps: this.generateMipmaps,
  1340. premultiplyAlpha: this.premultiplyAlpha,
  1341. unpackAlignment: this.unpackAlignment
  1342. };
  1343. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1344. if ( ! isRootObject ) {
  1345. meta.textures[ this.uuid ] = output;
  1346. }
  1347. return output;
  1348. }
  1349. dispose() {
  1350. this.dispatchEvent( { type: 'dispose' } );
  1351. }
  1352. transformUv( uv ) {
  1353. if ( this.mapping !== UVMapping ) return uv;
  1354. uv.applyMatrix3( this.matrix );
  1355. if ( uv.x < 0 || uv.x > 1 ) {
  1356. switch ( this.wrapS ) {
  1357. case RepeatWrapping:
  1358. uv.x = uv.x - Math.floor( uv.x );
  1359. break;
  1360. case ClampToEdgeWrapping:
  1361. uv.x = uv.x < 0 ? 0 : 1;
  1362. break;
  1363. case MirroredRepeatWrapping:
  1364. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1365. uv.x = Math.ceil( uv.x ) - uv.x;
  1366. } else {
  1367. uv.x = uv.x - Math.floor( uv.x );
  1368. }
  1369. break;
  1370. }
  1371. }
  1372. if ( uv.y < 0 || uv.y > 1 ) {
  1373. switch ( this.wrapT ) {
  1374. case RepeatWrapping:
  1375. uv.y = uv.y - Math.floor( uv.y );
  1376. break;
  1377. case ClampToEdgeWrapping:
  1378. uv.y = uv.y < 0 ? 0 : 1;
  1379. break;
  1380. case MirroredRepeatWrapping:
  1381. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1382. uv.y = Math.ceil( uv.y ) - uv.y;
  1383. } else {
  1384. uv.y = uv.y - Math.floor( uv.y );
  1385. }
  1386. break;
  1387. }
  1388. }
  1389. if ( this.flipY ) {
  1390. uv.y = 1 - uv.y;
  1391. }
  1392. return uv;
  1393. }
  1394. set needsUpdate( value ) {
  1395. if ( value === true ) {
  1396. this.version ++;
  1397. this.source.needsUpdate = true;
  1398. }
  1399. }
  1400. set needsPMREMUpdate( value ) {
  1401. if ( value === true ) {
  1402. this.pmremVersion ++;
  1403. }
  1404. }
  1405. }
  1406. Texture.DEFAULT_IMAGE = null;
  1407. Texture.DEFAULT_MAPPING = UVMapping;
  1408. Texture.DEFAULT_ANISOTROPY = 1;
  1409. class Vector4 {
  1410. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1411. Vector4.prototype.isVector4 = true;
  1412. this.x = x;
  1413. this.y = y;
  1414. this.z = z;
  1415. this.w = w;
  1416. }
  1417. get width() {
  1418. return this.z;
  1419. }
  1420. set width( value ) {
  1421. this.z = value;
  1422. }
  1423. get height() {
  1424. return this.w;
  1425. }
  1426. set height( value ) {
  1427. this.w = value;
  1428. }
  1429. set( x, y, z, w ) {
  1430. this.x = x;
  1431. this.y = y;
  1432. this.z = z;
  1433. this.w = w;
  1434. return this;
  1435. }
  1436. setScalar( scalar ) {
  1437. this.x = scalar;
  1438. this.y = scalar;
  1439. this.z = scalar;
  1440. this.w = scalar;
  1441. return this;
  1442. }
  1443. setX( x ) {
  1444. this.x = x;
  1445. return this;
  1446. }
  1447. setY( y ) {
  1448. this.y = y;
  1449. return this;
  1450. }
  1451. setZ( z ) {
  1452. this.z = z;
  1453. return this;
  1454. }
  1455. setW( w ) {
  1456. this.w = w;
  1457. return this;
  1458. }
  1459. setComponent( index, value ) {
  1460. switch ( index ) {
  1461. case 0: this.x = value; break;
  1462. case 1: this.y = value; break;
  1463. case 2: this.z = value; break;
  1464. case 3: this.w = value; break;
  1465. default: throw new Error( 'index is out of range: ' + index );
  1466. }
  1467. return this;
  1468. }
  1469. getComponent( index ) {
  1470. switch ( index ) {
  1471. case 0: return this.x;
  1472. case 1: return this.y;
  1473. case 2: return this.z;
  1474. case 3: return this.w;
  1475. default: throw new Error( 'index is out of range: ' + index );
  1476. }
  1477. }
  1478. clone() {
  1479. return new this.constructor( this.x, this.y, this.z, this.w );
  1480. }
  1481. copy( v ) {
  1482. this.x = v.x;
  1483. this.y = v.y;
  1484. this.z = v.z;
  1485. this.w = ( v.w !== undefined ) ? v.w : 1;
  1486. return this;
  1487. }
  1488. add( v ) {
  1489. this.x += v.x;
  1490. this.y += v.y;
  1491. this.z += v.z;
  1492. this.w += v.w;
  1493. return this;
  1494. }
  1495. addScalar( s ) {
  1496. this.x += s;
  1497. this.y += s;
  1498. this.z += s;
  1499. this.w += s;
  1500. return this;
  1501. }
  1502. addVectors( a, b ) {
  1503. this.x = a.x + b.x;
  1504. this.y = a.y + b.y;
  1505. this.z = a.z + b.z;
  1506. this.w = a.w + b.w;
  1507. return this;
  1508. }
  1509. addScaledVector( v, s ) {
  1510. this.x += v.x * s;
  1511. this.y += v.y * s;
  1512. this.z += v.z * s;
  1513. this.w += v.w * s;
  1514. return this;
  1515. }
  1516. sub( v ) {
  1517. this.x -= v.x;
  1518. this.y -= v.y;
  1519. this.z -= v.z;
  1520. this.w -= v.w;
  1521. return this;
  1522. }
  1523. subScalar( s ) {
  1524. this.x -= s;
  1525. this.y -= s;
  1526. this.z -= s;
  1527. this.w -= s;
  1528. return this;
  1529. }
  1530. subVectors( a, b ) {
  1531. this.x = a.x - b.x;
  1532. this.y = a.y - b.y;
  1533. this.z = a.z - b.z;
  1534. this.w = a.w - b.w;
  1535. return this;
  1536. }
  1537. multiply( v ) {
  1538. this.x *= v.x;
  1539. this.y *= v.y;
  1540. this.z *= v.z;
  1541. this.w *= v.w;
  1542. return this;
  1543. }
  1544. multiplyScalar( scalar ) {
  1545. this.x *= scalar;
  1546. this.y *= scalar;
  1547. this.z *= scalar;
  1548. this.w *= scalar;
  1549. return this;
  1550. }
  1551. applyMatrix4( m ) {
  1552. const x = this.x, y = this.y, z = this.z, w = this.w;
  1553. const e = m.elements;
  1554. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1555. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1556. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1557. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1558. return this;
  1559. }
  1560. divideScalar( scalar ) {
  1561. return this.multiplyScalar( 1 / scalar );
  1562. }
  1563. setAxisAngleFromQuaternion( q ) {
  1564. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1565. // q is assumed to be normalized
  1566. this.w = 2 * Math.acos( q.w );
  1567. const s = Math.sqrt( 1 - q.w * q.w );
  1568. if ( s < 0.0001 ) {
  1569. this.x = 1;
  1570. this.y = 0;
  1571. this.z = 0;
  1572. } else {
  1573. this.x = q.x / s;
  1574. this.y = q.y / s;
  1575. this.z = q.z / s;
  1576. }
  1577. return this;
  1578. }
  1579. setAxisAngleFromRotationMatrix( m ) {
  1580. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1581. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1582. let angle, x, y, z; // variables for result
  1583. const epsilon = 0.01, // margin to allow for rounding errors
  1584. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1585. te = m.elements,
  1586. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1587. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1588. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1589. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1590. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1591. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1592. // singularity found
  1593. // first check for identity matrix which must have +1 for all terms
  1594. // in leading diagonal and zero in other terms
  1595. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1596. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1597. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1598. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1599. // this singularity is identity matrix so angle = 0
  1600. this.set( 1, 0, 0, 0 );
  1601. return this; // zero angle, arbitrary axis
  1602. }
  1603. // otherwise this singularity is angle = 180
  1604. angle = Math.PI;
  1605. const xx = ( m11 + 1 ) / 2;
  1606. const yy = ( m22 + 1 ) / 2;
  1607. const zz = ( m33 + 1 ) / 2;
  1608. const xy = ( m12 + m21 ) / 4;
  1609. const xz = ( m13 + m31 ) / 4;
  1610. const yz = ( m23 + m32 ) / 4;
  1611. if ( ( xx > yy ) && ( xx > zz ) ) {
  1612. // m11 is the largest diagonal term
  1613. if ( xx < epsilon ) {
  1614. x = 0;
  1615. y = 0.707106781;
  1616. z = 0.707106781;
  1617. } else {
  1618. x = Math.sqrt( xx );
  1619. y = xy / x;
  1620. z = xz / x;
  1621. }
  1622. } else if ( yy > zz ) {
  1623. // m22 is the largest diagonal term
  1624. if ( yy < epsilon ) {
  1625. x = 0.707106781;
  1626. y = 0;
  1627. z = 0.707106781;
  1628. } else {
  1629. y = Math.sqrt( yy );
  1630. x = xy / y;
  1631. z = yz / y;
  1632. }
  1633. } else {
  1634. // m33 is the largest diagonal term so base result on this
  1635. if ( zz < epsilon ) {
  1636. x = 0.707106781;
  1637. y = 0.707106781;
  1638. z = 0;
  1639. } else {
  1640. z = Math.sqrt( zz );
  1641. x = xz / z;
  1642. y = yz / z;
  1643. }
  1644. }
  1645. this.set( x, y, z, angle );
  1646. return this; // return 180 deg rotation
  1647. }
  1648. // as we have reached here there are no singularities so we can handle normally
  1649. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1650. ( m13 - m31 ) * ( m13 - m31 ) +
  1651. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1652. if ( Math.abs( s ) < 0.001 ) s = 1;
  1653. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1654. // caught by singularity test above, but I've left it in just in case
  1655. this.x = ( m32 - m23 ) / s;
  1656. this.y = ( m13 - m31 ) / s;
  1657. this.z = ( m21 - m12 ) / s;
  1658. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1659. return this;
  1660. }
  1661. setFromMatrixPosition( m ) {
  1662. const e = m.elements;
  1663. this.x = e[ 12 ];
  1664. this.y = e[ 13 ];
  1665. this.z = e[ 14 ];
  1666. this.w = e[ 15 ];
  1667. return this;
  1668. }
  1669. min( v ) {
  1670. this.x = Math.min( this.x, v.x );
  1671. this.y = Math.min( this.y, v.y );
  1672. this.z = Math.min( this.z, v.z );
  1673. this.w = Math.min( this.w, v.w );
  1674. return this;
  1675. }
  1676. max( v ) {
  1677. this.x = Math.max( this.x, v.x );
  1678. this.y = Math.max( this.y, v.y );
  1679. this.z = Math.max( this.z, v.z );
  1680. this.w = Math.max( this.w, v.w );
  1681. return this;
  1682. }
  1683. clamp( min, max ) {
  1684. // assumes min < max, componentwise
  1685. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1686. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1687. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1688. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1689. return this;
  1690. }
  1691. clampScalar( minVal, maxVal ) {
  1692. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1693. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1694. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1695. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1696. return this;
  1697. }
  1698. clampLength( min, max ) {
  1699. const length = this.length();
  1700. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1701. }
  1702. floor() {
  1703. this.x = Math.floor( this.x );
  1704. this.y = Math.floor( this.y );
  1705. this.z = Math.floor( this.z );
  1706. this.w = Math.floor( this.w );
  1707. return this;
  1708. }
  1709. ceil() {
  1710. this.x = Math.ceil( this.x );
  1711. this.y = Math.ceil( this.y );
  1712. this.z = Math.ceil( this.z );
  1713. this.w = Math.ceil( this.w );
  1714. return this;
  1715. }
  1716. round() {
  1717. this.x = Math.round( this.x );
  1718. this.y = Math.round( this.y );
  1719. this.z = Math.round( this.z );
  1720. this.w = Math.round( this.w );
  1721. return this;
  1722. }
  1723. roundToZero() {
  1724. this.x = Math.trunc( this.x );
  1725. this.y = Math.trunc( this.y );
  1726. this.z = Math.trunc( this.z );
  1727. this.w = Math.trunc( this.w );
  1728. return this;
  1729. }
  1730. negate() {
  1731. this.x = - this.x;
  1732. this.y = - this.y;
  1733. this.z = - this.z;
  1734. this.w = - this.w;
  1735. return this;
  1736. }
  1737. dot( v ) {
  1738. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1739. }
  1740. lengthSq() {
  1741. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1742. }
  1743. length() {
  1744. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1745. }
  1746. manhattanLength() {
  1747. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1748. }
  1749. normalize() {
  1750. return this.divideScalar( this.length() || 1 );
  1751. }
  1752. setLength( length ) {
  1753. return this.normalize().multiplyScalar( length );
  1754. }
  1755. lerp( v, alpha ) {
  1756. this.x += ( v.x - this.x ) * alpha;
  1757. this.y += ( v.y - this.y ) * alpha;
  1758. this.z += ( v.z - this.z ) * alpha;
  1759. this.w += ( v.w - this.w ) * alpha;
  1760. return this;
  1761. }
  1762. lerpVectors( v1, v2, alpha ) {
  1763. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1764. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1765. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1766. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1767. return this;
  1768. }
  1769. equals( v ) {
  1770. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1771. }
  1772. fromArray( array, offset = 0 ) {
  1773. this.x = array[ offset ];
  1774. this.y = array[ offset + 1 ];
  1775. this.z = array[ offset + 2 ];
  1776. this.w = array[ offset + 3 ];
  1777. return this;
  1778. }
  1779. toArray( array = [], offset = 0 ) {
  1780. array[ offset ] = this.x;
  1781. array[ offset + 1 ] = this.y;
  1782. array[ offset + 2 ] = this.z;
  1783. array[ offset + 3 ] = this.w;
  1784. return array;
  1785. }
  1786. fromBufferAttribute( attribute, index ) {
  1787. this.x = attribute.getX( index );
  1788. this.y = attribute.getY( index );
  1789. this.z = attribute.getZ( index );
  1790. this.w = attribute.getW( index );
  1791. return this;
  1792. }
  1793. random() {
  1794. this.x = Math.random();
  1795. this.y = Math.random();
  1796. this.z = Math.random();
  1797. this.w = Math.random();
  1798. return this;
  1799. }
  1800. *[ Symbol.iterator ]() {
  1801. yield this.x;
  1802. yield this.y;
  1803. yield this.z;
  1804. yield this.w;
  1805. }
  1806. }
  1807. /*
  1808. In options, we can specify:
  1809. * Texture parameters for an auto-generated target texture
  1810. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1811. */
  1812. class RenderTarget extends EventDispatcher {
  1813. constructor( width = 1, height = 1, options = {} ) {
  1814. super();
  1815. this.isRenderTarget = true;
  1816. this.width = width;
  1817. this.height = height;
  1818. this.depth = 1;
  1819. this.scissor = new Vector4( 0, 0, width, height );
  1820. this.scissorTest = false;
  1821. this.viewport = new Vector4( 0, 0, width, height );
  1822. const image = { width: width, height: height, depth: 1 };
  1823. options = Object.assign( {
  1824. generateMipmaps: false,
  1825. internalFormat: null,
  1826. minFilter: LinearFilter,
  1827. depthBuffer: true,
  1828. stencilBuffer: false,
  1829. resolveDepthBuffer: true,
  1830. resolveStencilBuffer: true,
  1831. depthTexture: null,
  1832. samples: 0,
  1833. count: 1
  1834. }, options );
  1835. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1836. texture.flipY = false;
  1837. texture.generateMipmaps = options.generateMipmaps;
  1838. texture.internalFormat = options.internalFormat;
  1839. this.textures = [];
  1840. const count = options.count;
  1841. for ( let i = 0; i < count; i ++ ) {
  1842. this.textures[ i ] = texture.clone();
  1843. this.textures[ i ].isRenderTargetTexture = true;
  1844. }
  1845. this.depthBuffer = options.depthBuffer;
  1846. this.stencilBuffer = options.stencilBuffer;
  1847. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1848. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1849. this.depthTexture = options.depthTexture;
  1850. this.samples = options.samples;
  1851. }
  1852. get texture() {
  1853. return this.textures[ 0 ];
  1854. }
  1855. set texture( value ) {
  1856. this.textures[ 0 ] = value;
  1857. }
  1858. setSize( width, height, depth = 1 ) {
  1859. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1860. this.width = width;
  1861. this.height = height;
  1862. this.depth = depth;
  1863. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1864. this.textures[ i ].image.width = width;
  1865. this.textures[ i ].image.height = height;
  1866. this.textures[ i ].image.depth = depth;
  1867. }
  1868. this.dispose();
  1869. }
  1870. this.viewport.set( 0, 0, width, height );
  1871. this.scissor.set( 0, 0, width, height );
  1872. }
  1873. clone() {
  1874. return new this.constructor().copy( this );
  1875. }
  1876. copy( source ) {
  1877. this.width = source.width;
  1878. this.height = source.height;
  1879. this.depth = source.depth;
  1880. this.scissor.copy( source.scissor );
  1881. this.scissorTest = source.scissorTest;
  1882. this.viewport.copy( source.viewport );
  1883. this.textures.length = 0;
  1884. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1885. this.textures[ i ] = source.textures[ i ].clone();
  1886. this.textures[ i ].isRenderTargetTexture = true;
  1887. }
  1888. // ensure image object is not shared, see #20328
  1889. const image = Object.assign( {}, source.texture.image );
  1890. this.texture.source = new Source( image );
  1891. this.depthBuffer = source.depthBuffer;
  1892. this.stencilBuffer = source.stencilBuffer;
  1893. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1894. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1895. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1896. this.samples = source.samples;
  1897. return this;
  1898. }
  1899. dispose() {
  1900. this.dispatchEvent( { type: 'dispose' } );
  1901. }
  1902. }
  1903. class WebGLRenderTarget extends RenderTarget {
  1904. constructor( width = 1, height = 1, options = {} ) {
  1905. super( width, height, options );
  1906. this.isWebGLRenderTarget = true;
  1907. }
  1908. }
  1909. class DataArrayTexture extends Texture {
  1910. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1911. super( null );
  1912. this.isDataArrayTexture = true;
  1913. this.image = { data, width, height, depth };
  1914. this.magFilter = NearestFilter;
  1915. this.minFilter = NearestFilter;
  1916. this.wrapR = ClampToEdgeWrapping;
  1917. this.generateMipmaps = false;
  1918. this.flipY = false;
  1919. this.unpackAlignment = 1;
  1920. this.layerUpdates = new Set();
  1921. }
  1922. addLayerUpdate( layerIndex ) {
  1923. this.layerUpdates.add( layerIndex );
  1924. }
  1925. clearLayerUpdates() {
  1926. this.layerUpdates.clear();
  1927. }
  1928. }
  1929. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1930. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1931. super( width, height, options );
  1932. this.isWebGLArrayRenderTarget = true;
  1933. this.depth = depth;
  1934. this.texture = new DataArrayTexture( null, width, height, depth );
  1935. this.texture.isRenderTargetTexture = true;
  1936. }
  1937. }
  1938. class Data3DTexture extends Texture {
  1939. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1940. // We're going to add .setXXX() methods for setting properties later.
  1941. // Users can still set in DataTexture3D directly.
  1942. //
  1943. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1944. // texture.anisotropy = 16;
  1945. //
  1946. // See #14839
  1947. super( null );
  1948. this.isData3DTexture = true;
  1949. this.image = { data, width, height, depth };
  1950. this.magFilter = NearestFilter;
  1951. this.minFilter = NearestFilter;
  1952. this.wrapR = ClampToEdgeWrapping;
  1953. this.generateMipmaps = false;
  1954. this.flipY = false;
  1955. this.unpackAlignment = 1;
  1956. }
  1957. }
  1958. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1959. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1960. super( width, height, options );
  1961. this.isWebGL3DRenderTarget = true;
  1962. this.depth = depth;
  1963. this.texture = new Data3DTexture( null, width, height, depth );
  1964. this.texture.isRenderTargetTexture = true;
  1965. }
  1966. }
  1967. class Quaternion {
  1968. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1969. this.isQuaternion = true;
  1970. this._x = x;
  1971. this._y = y;
  1972. this._z = z;
  1973. this._w = w;
  1974. }
  1975. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1976. // fuzz-free, array-based Quaternion SLERP operation
  1977. let x0 = src0[ srcOffset0 + 0 ],
  1978. y0 = src0[ srcOffset0 + 1 ],
  1979. z0 = src0[ srcOffset0 + 2 ],
  1980. w0 = src0[ srcOffset0 + 3 ];
  1981. const x1 = src1[ srcOffset1 + 0 ],
  1982. y1 = src1[ srcOffset1 + 1 ],
  1983. z1 = src1[ srcOffset1 + 2 ],
  1984. w1 = src1[ srcOffset1 + 3 ];
  1985. if ( t === 0 ) {
  1986. dst[ dstOffset + 0 ] = x0;
  1987. dst[ dstOffset + 1 ] = y0;
  1988. dst[ dstOffset + 2 ] = z0;
  1989. dst[ dstOffset + 3 ] = w0;
  1990. return;
  1991. }
  1992. if ( t === 1 ) {
  1993. dst[ dstOffset + 0 ] = x1;
  1994. dst[ dstOffset + 1 ] = y1;
  1995. dst[ dstOffset + 2 ] = z1;
  1996. dst[ dstOffset + 3 ] = w1;
  1997. return;
  1998. }
  1999. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2000. let s = 1 - t;
  2001. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2002. dir = ( cos >= 0 ? 1 : - 1 ),
  2003. sqrSin = 1 - cos * cos;
  2004. // Skip the Slerp for tiny steps to avoid numeric problems:
  2005. if ( sqrSin > Number.EPSILON ) {
  2006. const sin = Math.sqrt( sqrSin ),
  2007. len = Math.atan2( sin, cos * dir );
  2008. s = Math.sin( s * len ) / sin;
  2009. t = Math.sin( t * len ) / sin;
  2010. }
  2011. const tDir = t * dir;
  2012. x0 = x0 * s + x1 * tDir;
  2013. y0 = y0 * s + y1 * tDir;
  2014. z0 = z0 * s + z1 * tDir;
  2015. w0 = w0 * s + w1 * tDir;
  2016. // Normalize in case we just did a lerp:
  2017. if ( s === 1 - t ) {
  2018. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2019. x0 *= f;
  2020. y0 *= f;
  2021. z0 *= f;
  2022. w0 *= f;
  2023. }
  2024. }
  2025. dst[ dstOffset ] = x0;
  2026. dst[ dstOffset + 1 ] = y0;
  2027. dst[ dstOffset + 2 ] = z0;
  2028. dst[ dstOffset + 3 ] = w0;
  2029. }
  2030. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2031. const x0 = src0[ srcOffset0 ];
  2032. const y0 = src0[ srcOffset0 + 1 ];
  2033. const z0 = src0[ srcOffset0 + 2 ];
  2034. const w0 = src0[ srcOffset0 + 3 ];
  2035. const x1 = src1[ srcOffset1 ];
  2036. const y1 = src1[ srcOffset1 + 1 ];
  2037. const z1 = src1[ srcOffset1 + 2 ];
  2038. const w1 = src1[ srcOffset1 + 3 ];
  2039. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2040. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2041. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2042. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2043. return dst;
  2044. }
  2045. get x() {
  2046. return this._x;
  2047. }
  2048. set x( value ) {
  2049. this._x = value;
  2050. this._onChangeCallback();
  2051. }
  2052. get y() {
  2053. return this._y;
  2054. }
  2055. set y( value ) {
  2056. this._y = value;
  2057. this._onChangeCallback();
  2058. }
  2059. get z() {
  2060. return this._z;
  2061. }
  2062. set z( value ) {
  2063. this._z = value;
  2064. this._onChangeCallback();
  2065. }
  2066. get w() {
  2067. return this._w;
  2068. }
  2069. set w( value ) {
  2070. this._w = value;
  2071. this._onChangeCallback();
  2072. }
  2073. set( x, y, z, w ) {
  2074. this._x = x;
  2075. this._y = y;
  2076. this._z = z;
  2077. this._w = w;
  2078. this._onChangeCallback();
  2079. return this;
  2080. }
  2081. clone() {
  2082. return new this.constructor( this._x, this._y, this._z, this._w );
  2083. }
  2084. copy( quaternion ) {
  2085. this._x = quaternion.x;
  2086. this._y = quaternion.y;
  2087. this._z = quaternion.z;
  2088. this._w = quaternion.w;
  2089. this._onChangeCallback();
  2090. return this;
  2091. }
  2092. setFromEuler( euler, update = true ) {
  2093. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2094. // http://www.mathworks.com/matlabcentral/fileexchange/
  2095. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2096. // content/SpinCalc.m
  2097. const cos = Math.cos;
  2098. const sin = Math.sin;
  2099. const c1 = cos( x / 2 );
  2100. const c2 = cos( y / 2 );
  2101. const c3 = cos( z / 2 );
  2102. const s1 = sin( x / 2 );
  2103. const s2 = sin( y / 2 );
  2104. const s3 = sin( z / 2 );
  2105. switch ( order ) {
  2106. case 'XYZ':
  2107. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2108. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2109. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2110. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2111. break;
  2112. case 'YXZ':
  2113. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2114. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2115. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2116. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2117. break;
  2118. case 'ZXY':
  2119. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2120. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2121. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2122. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2123. break;
  2124. case 'ZYX':
  2125. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2126. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2127. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2128. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2129. break;
  2130. case 'YZX':
  2131. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2132. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2133. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2134. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2135. break;
  2136. case 'XZY':
  2137. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2138. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2139. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2140. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2141. break;
  2142. default:
  2143. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2144. }
  2145. if ( update === true ) this._onChangeCallback();
  2146. return this;
  2147. }
  2148. setFromAxisAngle( axis, angle ) {
  2149. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2150. // assumes axis is normalized
  2151. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2152. this._x = axis.x * s;
  2153. this._y = axis.y * s;
  2154. this._z = axis.z * s;
  2155. this._w = Math.cos( halfAngle );
  2156. this._onChangeCallback();
  2157. return this;
  2158. }
  2159. setFromRotationMatrix( m ) {
  2160. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2161. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2162. const te = m.elements,
  2163. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2164. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2165. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2166. trace = m11 + m22 + m33;
  2167. if ( trace > 0 ) {
  2168. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2169. this._w = 0.25 / s;
  2170. this._x = ( m32 - m23 ) * s;
  2171. this._y = ( m13 - m31 ) * s;
  2172. this._z = ( m21 - m12 ) * s;
  2173. } else if ( m11 > m22 && m11 > m33 ) {
  2174. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2175. this._w = ( m32 - m23 ) / s;
  2176. this._x = 0.25 * s;
  2177. this._y = ( m12 + m21 ) / s;
  2178. this._z = ( m13 + m31 ) / s;
  2179. } else if ( m22 > m33 ) {
  2180. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2181. this._w = ( m13 - m31 ) / s;
  2182. this._x = ( m12 + m21 ) / s;
  2183. this._y = 0.25 * s;
  2184. this._z = ( m23 + m32 ) / s;
  2185. } else {
  2186. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2187. this._w = ( m21 - m12 ) / s;
  2188. this._x = ( m13 + m31 ) / s;
  2189. this._y = ( m23 + m32 ) / s;
  2190. this._z = 0.25 * s;
  2191. }
  2192. this._onChangeCallback();
  2193. return this;
  2194. }
  2195. setFromUnitVectors( vFrom, vTo ) {
  2196. // assumes direction vectors vFrom and vTo are normalized
  2197. let r = vFrom.dot( vTo ) + 1;
  2198. if ( r < Number.EPSILON ) {
  2199. // vFrom and vTo point in opposite directions
  2200. r = 0;
  2201. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2202. this._x = - vFrom.y;
  2203. this._y = vFrom.x;
  2204. this._z = 0;
  2205. this._w = r;
  2206. } else {
  2207. this._x = 0;
  2208. this._y = - vFrom.z;
  2209. this._z = vFrom.y;
  2210. this._w = r;
  2211. }
  2212. } else {
  2213. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2214. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2215. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2216. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2217. this._w = r;
  2218. }
  2219. return this.normalize();
  2220. }
  2221. angleTo( q ) {
  2222. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2223. }
  2224. rotateTowards( q, step ) {
  2225. const angle = this.angleTo( q );
  2226. if ( angle === 0 ) return this;
  2227. const t = Math.min( 1, step / angle );
  2228. this.slerp( q, t );
  2229. return this;
  2230. }
  2231. identity() {
  2232. return this.set( 0, 0, 0, 1 );
  2233. }
  2234. invert() {
  2235. // quaternion is assumed to have unit length
  2236. return this.conjugate();
  2237. }
  2238. conjugate() {
  2239. this._x *= - 1;
  2240. this._y *= - 1;
  2241. this._z *= - 1;
  2242. this._onChangeCallback();
  2243. return this;
  2244. }
  2245. dot( v ) {
  2246. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2247. }
  2248. lengthSq() {
  2249. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2250. }
  2251. length() {
  2252. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2253. }
  2254. normalize() {
  2255. let l = this.length();
  2256. if ( l === 0 ) {
  2257. this._x = 0;
  2258. this._y = 0;
  2259. this._z = 0;
  2260. this._w = 1;
  2261. } else {
  2262. l = 1 / l;
  2263. this._x = this._x * l;
  2264. this._y = this._y * l;
  2265. this._z = this._z * l;
  2266. this._w = this._w * l;
  2267. }
  2268. this._onChangeCallback();
  2269. return this;
  2270. }
  2271. multiply( q ) {
  2272. return this.multiplyQuaternions( this, q );
  2273. }
  2274. premultiply( q ) {
  2275. return this.multiplyQuaternions( q, this );
  2276. }
  2277. multiplyQuaternions( a, b ) {
  2278. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2279. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2280. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2281. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2282. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2283. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2284. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2285. this._onChangeCallback();
  2286. return this;
  2287. }
  2288. slerp( qb, t ) {
  2289. if ( t === 0 ) return this;
  2290. if ( t === 1 ) return this.copy( qb );
  2291. const x = this._x, y = this._y, z = this._z, w = this._w;
  2292. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2293. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2294. if ( cosHalfTheta < 0 ) {
  2295. this._w = - qb._w;
  2296. this._x = - qb._x;
  2297. this._y = - qb._y;
  2298. this._z = - qb._z;
  2299. cosHalfTheta = - cosHalfTheta;
  2300. } else {
  2301. this.copy( qb );
  2302. }
  2303. if ( cosHalfTheta >= 1.0 ) {
  2304. this._w = w;
  2305. this._x = x;
  2306. this._y = y;
  2307. this._z = z;
  2308. return this;
  2309. }
  2310. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2311. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2312. const s = 1 - t;
  2313. this._w = s * w + t * this._w;
  2314. this._x = s * x + t * this._x;
  2315. this._y = s * y + t * this._y;
  2316. this._z = s * z + t * this._z;
  2317. this.normalize(); // normalize calls _onChangeCallback()
  2318. return this;
  2319. }
  2320. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2321. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2322. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2323. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2324. this._w = ( w * ratioA + this._w * ratioB );
  2325. this._x = ( x * ratioA + this._x * ratioB );
  2326. this._y = ( y * ratioA + this._y * ratioB );
  2327. this._z = ( z * ratioA + this._z * ratioB );
  2328. this._onChangeCallback();
  2329. return this;
  2330. }
  2331. slerpQuaternions( qa, qb, t ) {
  2332. return this.copy( qa ).slerp( qb, t );
  2333. }
  2334. random() {
  2335. // sets this quaternion to a uniform random unit quaternnion
  2336. // Ken Shoemake
  2337. // Uniform random rotations
  2338. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2339. const theta1 = 2 * Math.PI * Math.random();
  2340. const theta2 = 2 * Math.PI * Math.random();
  2341. const x0 = Math.random();
  2342. const r1 = Math.sqrt( 1 - x0 );
  2343. const r2 = Math.sqrt( x0 );
  2344. return this.set(
  2345. r1 * Math.sin( theta1 ),
  2346. r1 * Math.cos( theta1 ),
  2347. r2 * Math.sin( theta2 ),
  2348. r2 * Math.cos( theta2 ),
  2349. );
  2350. }
  2351. equals( quaternion ) {
  2352. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2353. }
  2354. fromArray( array, offset = 0 ) {
  2355. this._x = array[ offset ];
  2356. this._y = array[ offset + 1 ];
  2357. this._z = array[ offset + 2 ];
  2358. this._w = array[ offset + 3 ];
  2359. this._onChangeCallback();
  2360. return this;
  2361. }
  2362. toArray( array = [], offset = 0 ) {
  2363. array[ offset ] = this._x;
  2364. array[ offset + 1 ] = this._y;
  2365. array[ offset + 2 ] = this._z;
  2366. array[ offset + 3 ] = this._w;
  2367. return array;
  2368. }
  2369. fromBufferAttribute( attribute, index ) {
  2370. this._x = attribute.getX( index );
  2371. this._y = attribute.getY( index );
  2372. this._z = attribute.getZ( index );
  2373. this._w = attribute.getW( index );
  2374. this._onChangeCallback();
  2375. return this;
  2376. }
  2377. toJSON() {
  2378. return this.toArray();
  2379. }
  2380. _onChange( callback ) {
  2381. this._onChangeCallback = callback;
  2382. return this;
  2383. }
  2384. _onChangeCallback() {}
  2385. *[ Symbol.iterator ]() {
  2386. yield this._x;
  2387. yield this._y;
  2388. yield this._z;
  2389. yield this._w;
  2390. }
  2391. }
  2392. class Vector3 {
  2393. constructor( x = 0, y = 0, z = 0 ) {
  2394. Vector3.prototype.isVector3 = true;
  2395. this.x = x;
  2396. this.y = y;
  2397. this.z = z;
  2398. }
  2399. set( x, y, z ) {
  2400. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2401. this.x = x;
  2402. this.y = y;
  2403. this.z = z;
  2404. return this;
  2405. }
  2406. setScalar( scalar ) {
  2407. this.x = scalar;
  2408. this.y = scalar;
  2409. this.z = scalar;
  2410. return this;
  2411. }
  2412. setX( x ) {
  2413. this.x = x;
  2414. return this;
  2415. }
  2416. setY( y ) {
  2417. this.y = y;
  2418. return this;
  2419. }
  2420. setZ( z ) {
  2421. this.z = z;
  2422. return this;
  2423. }
  2424. setComponent( index, value ) {
  2425. switch ( index ) {
  2426. case 0: this.x = value; break;
  2427. case 1: this.y = value; break;
  2428. case 2: this.z = value; break;
  2429. default: throw new Error( 'index is out of range: ' + index );
  2430. }
  2431. return this;
  2432. }
  2433. getComponent( index ) {
  2434. switch ( index ) {
  2435. case 0: return this.x;
  2436. case 1: return this.y;
  2437. case 2: return this.z;
  2438. default: throw new Error( 'index is out of range: ' + index );
  2439. }
  2440. }
  2441. clone() {
  2442. return new this.constructor( this.x, this.y, this.z );
  2443. }
  2444. copy( v ) {
  2445. this.x = v.x;
  2446. this.y = v.y;
  2447. this.z = v.z;
  2448. return this;
  2449. }
  2450. add( v ) {
  2451. this.x += v.x;
  2452. this.y += v.y;
  2453. this.z += v.z;
  2454. return this;
  2455. }
  2456. addScalar( s ) {
  2457. this.x += s;
  2458. this.y += s;
  2459. this.z += s;
  2460. return this;
  2461. }
  2462. addVectors( a, b ) {
  2463. this.x = a.x + b.x;
  2464. this.y = a.y + b.y;
  2465. this.z = a.z + b.z;
  2466. return this;
  2467. }
  2468. addScaledVector( v, s ) {
  2469. this.x += v.x * s;
  2470. this.y += v.y * s;
  2471. this.z += v.z * s;
  2472. return this;
  2473. }
  2474. sub( v ) {
  2475. this.x -= v.x;
  2476. this.y -= v.y;
  2477. this.z -= v.z;
  2478. return this;
  2479. }
  2480. subScalar( s ) {
  2481. this.x -= s;
  2482. this.y -= s;
  2483. this.z -= s;
  2484. return this;
  2485. }
  2486. subVectors( a, b ) {
  2487. this.x = a.x - b.x;
  2488. this.y = a.y - b.y;
  2489. this.z = a.z - b.z;
  2490. return this;
  2491. }
  2492. multiply( v ) {
  2493. this.x *= v.x;
  2494. this.y *= v.y;
  2495. this.z *= v.z;
  2496. return this;
  2497. }
  2498. multiplyScalar( scalar ) {
  2499. this.x *= scalar;
  2500. this.y *= scalar;
  2501. this.z *= scalar;
  2502. return this;
  2503. }
  2504. multiplyVectors( a, b ) {
  2505. this.x = a.x * b.x;
  2506. this.y = a.y * b.y;
  2507. this.z = a.z * b.z;
  2508. return this;
  2509. }
  2510. applyEuler( euler ) {
  2511. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2512. }
  2513. applyAxisAngle( axis, angle ) {
  2514. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2515. }
  2516. applyMatrix3( m ) {
  2517. const x = this.x, y = this.y, z = this.z;
  2518. const e = m.elements;
  2519. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2520. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2521. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2522. return this;
  2523. }
  2524. applyNormalMatrix( m ) {
  2525. return this.applyMatrix3( m ).normalize();
  2526. }
  2527. applyMatrix4( m ) {
  2528. const x = this.x, y = this.y, z = this.z;
  2529. const e = m.elements;
  2530. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2531. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2532. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2533. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2534. return this;
  2535. }
  2536. applyQuaternion( q ) {
  2537. // quaternion q is assumed to have unit length
  2538. const vx = this.x, vy = this.y, vz = this.z;
  2539. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2540. // t = 2 * cross( q.xyz, v );
  2541. const tx = 2 * ( qy * vz - qz * vy );
  2542. const ty = 2 * ( qz * vx - qx * vz );
  2543. const tz = 2 * ( qx * vy - qy * vx );
  2544. // v + q.w * t + cross( q.xyz, t );
  2545. this.x = vx + qw * tx + qy * tz - qz * ty;
  2546. this.y = vy + qw * ty + qz * tx - qx * tz;
  2547. this.z = vz + qw * tz + qx * ty - qy * tx;
  2548. return this;
  2549. }
  2550. project( camera ) {
  2551. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2552. }
  2553. unproject( camera ) {
  2554. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2555. }
  2556. transformDirection( m ) {
  2557. // input: THREE.Matrix4 affine matrix
  2558. // vector interpreted as a direction
  2559. const x = this.x, y = this.y, z = this.z;
  2560. const e = m.elements;
  2561. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2562. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2563. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2564. return this.normalize();
  2565. }
  2566. divide( v ) {
  2567. this.x /= v.x;
  2568. this.y /= v.y;
  2569. this.z /= v.z;
  2570. return this;
  2571. }
  2572. divideScalar( scalar ) {
  2573. return this.multiplyScalar( 1 / scalar );
  2574. }
  2575. min( v ) {
  2576. this.x = Math.min( this.x, v.x );
  2577. this.y = Math.min( this.y, v.y );
  2578. this.z = Math.min( this.z, v.z );
  2579. return this;
  2580. }
  2581. max( v ) {
  2582. this.x = Math.max( this.x, v.x );
  2583. this.y = Math.max( this.y, v.y );
  2584. this.z = Math.max( this.z, v.z );
  2585. return this;
  2586. }
  2587. clamp( min, max ) {
  2588. // assumes min < max, componentwise
  2589. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2590. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2591. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2592. return this;
  2593. }
  2594. clampScalar( minVal, maxVal ) {
  2595. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2596. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2597. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2598. return this;
  2599. }
  2600. clampLength( min, max ) {
  2601. const length = this.length();
  2602. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2603. }
  2604. floor() {
  2605. this.x = Math.floor( this.x );
  2606. this.y = Math.floor( this.y );
  2607. this.z = Math.floor( this.z );
  2608. return this;
  2609. }
  2610. ceil() {
  2611. this.x = Math.ceil( this.x );
  2612. this.y = Math.ceil( this.y );
  2613. this.z = Math.ceil( this.z );
  2614. return this;
  2615. }
  2616. round() {
  2617. this.x = Math.round( this.x );
  2618. this.y = Math.round( this.y );
  2619. this.z = Math.round( this.z );
  2620. return this;
  2621. }
  2622. roundToZero() {
  2623. this.x = Math.trunc( this.x );
  2624. this.y = Math.trunc( this.y );
  2625. this.z = Math.trunc( this.z );
  2626. return this;
  2627. }
  2628. negate() {
  2629. this.x = - this.x;
  2630. this.y = - this.y;
  2631. this.z = - this.z;
  2632. return this;
  2633. }
  2634. dot( v ) {
  2635. return this.x * v.x + this.y * v.y + this.z * v.z;
  2636. }
  2637. // TODO lengthSquared?
  2638. lengthSq() {
  2639. return this.x * this.x + this.y * this.y + this.z * this.z;
  2640. }
  2641. length() {
  2642. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2643. }
  2644. manhattanLength() {
  2645. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2646. }
  2647. normalize() {
  2648. return this.divideScalar( this.length() || 1 );
  2649. }
  2650. setLength( length ) {
  2651. return this.normalize().multiplyScalar( length );
  2652. }
  2653. lerp( v, alpha ) {
  2654. this.x += ( v.x - this.x ) * alpha;
  2655. this.y += ( v.y - this.y ) * alpha;
  2656. this.z += ( v.z - this.z ) * alpha;
  2657. return this;
  2658. }
  2659. lerpVectors( v1, v2, alpha ) {
  2660. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2661. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2662. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2663. return this;
  2664. }
  2665. cross( v ) {
  2666. return this.crossVectors( this, v );
  2667. }
  2668. crossVectors( a, b ) {
  2669. const ax = a.x, ay = a.y, az = a.z;
  2670. const bx = b.x, by = b.y, bz = b.z;
  2671. this.x = ay * bz - az * by;
  2672. this.y = az * bx - ax * bz;
  2673. this.z = ax * by - ay * bx;
  2674. return this;
  2675. }
  2676. projectOnVector( v ) {
  2677. const denominator = v.lengthSq();
  2678. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2679. const scalar = v.dot( this ) / denominator;
  2680. return this.copy( v ).multiplyScalar( scalar );
  2681. }
  2682. projectOnPlane( planeNormal ) {
  2683. _vector$c.copy( this ).projectOnVector( planeNormal );
  2684. return this.sub( _vector$c );
  2685. }
  2686. reflect( normal ) {
  2687. // reflect incident vector off plane orthogonal to normal
  2688. // normal is assumed to have unit length
  2689. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2690. }
  2691. angleTo( v ) {
  2692. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2693. if ( denominator === 0 ) return Math.PI / 2;
  2694. const theta = this.dot( v ) / denominator;
  2695. // clamp, to handle numerical problems
  2696. return Math.acos( clamp( theta, - 1, 1 ) );
  2697. }
  2698. distanceTo( v ) {
  2699. return Math.sqrt( this.distanceToSquared( v ) );
  2700. }
  2701. distanceToSquared( v ) {
  2702. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2703. return dx * dx + dy * dy + dz * dz;
  2704. }
  2705. manhattanDistanceTo( v ) {
  2706. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2707. }
  2708. setFromSpherical( s ) {
  2709. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2710. }
  2711. setFromSphericalCoords( radius, phi, theta ) {
  2712. const sinPhiRadius = Math.sin( phi ) * radius;
  2713. this.x = sinPhiRadius * Math.sin( theta );
  2714. this.y = Math.cos( phi ) * radius;
  2715. this.z = sinPhiRadius * Math.cos( theta );
  2716. return this;
  2717. }
  2718. setFromCylindrical( c ) {
  2719. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2720. }
  2721. setFromCylindricalCoords( radius, theta, y ) {
  2722. this.x = radius * Math.sin( theta );
  2723. this.y = y;
  2724. this.z = radius * Math.cos( theta );
  2725. return this;
  2726. }
  2727. setFromMatrixPosition( m ) {
  2728. const e = m.elements;
  2729. this.x = e[ 12 ];
  2730. this.y = e[ 13 ];
  2731. this.z = e[ 14 ];
  2732. return this;
  2733. }
  2734. setFromMatrixScale( m ) {
  2735. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2736. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2737. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2738. this.x = sx;
  2739. this.y = sy;
  2740. this.z = sz;
  2741. return this;
  2742. }
  2743. setFromMatrixColumn( m, index ) {
  2744. return this.fromArray( m.elements, index * 4 );
  2745. }
  2746. setFromMatrix3Column( m, index ) {
  2747. return this.fromArray( m.elements, index * 3 );
  2748. }
  2749. setFromEuler( e ) {
  2750. this.x = e._x;
  2751. this.y = e._y;
  2752. this.z = e._z;
  2753. return this;
  2754. }
  2755. setFromColor( c ) {
  2756. this.x = c.r;
  2757. this.y = c.g;
  2758. this.z = c.b;
  2759. return this;
  2760. }
  2761. equals( v ) {
  2762. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2763. }
  2764. fromArray( array, offset = 0 ) {
  2765. this.x = array[ offset ];
  2766. this.y = array[ offset + 1 ];
  2767. this.z = array[ offset + 2 ];
  2768. return this;
  2769. }
  2770. toArray( array = [], offset = 0 ) {
  2771. array[ offset ] = this.x;
  2772. array[ offset + 1 ] = this.y;
  2773. array[ offset + 2 ] = this.z;
  2774. return array;
  2775. }
  2776. fromBufferAttribute( attribute, index ) {
  2777. this.x = attribute.getX( index );
  2778. this.y = attribute.getY( index );
  2779. this.z = attribute.getZ( index );
  2780. return this;
  2781. }
  2782. random() {
  2783. this.x = Math.random();
  2784. this.y = Math.random();
  2785. this.z = Math.random();
  2786. return this;
  2787. }
  2788. randomDirection() {
  2789. // https://mathworld.wolfram.com/SpherePointPicking.html
  2790. const theta = Math.random() * Math.PI * 2;
  2791. const u = Math.random() * 2 - 1;
  2792. const c = Math.sqrt( 1 - u * u );
  2793. this.x = c * Math.cos( theta );
  2794. this.y = u;
  2795. this.z = c * Math.sin( theta );
  2796. return this;
  2797. }
  2798. *[ Symbol.iterator ]() {
  2799. yield this.x;
  2800. yield this.y;
  2801. yield this.z;
  2802. }
  2803. }
  2804. const _vector$c = /*@__PURE__*/ new Vector3();
  2805. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2806. class Box3 {
  2807. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2808. this.isBox3 = true;
  2809. this.min = min;
  2810. this.max = max;
  2811. }
  2812. set( min, max ) {
  2813. this.min.copy( min );
  2814. this.max.copy( max );
  2815. return this;
  2816. }
  2817. setFromArray( array ) {
  2818. this.makeEmpty();
  2819. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2820. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2821. }
  2822. return this;
  2823. }
  2824. setFromBufferAttribute( attribute ) {
  2825. this.makeEmpty();
  2826. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2827. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2828. }
  2829. return this;
  2830. }
  2831. setFromPoints( points ) {
  2832. this.makeEmpty();
  2833. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2834. this.expandByPoint( points[ i ] );
  2835. }
  2836. return this;
  2837. }
  2838. setFromCenterAndSize( center, size ) {
  2839. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2840. this.min.copy( center ).sub( halfSize );
  2841. this.max.copy( center ).add( halfSize );
  2842. return this;
  2843. }
  2844. setFromObject( object, precise = false ) {
  2845. this.makeEmpty();
  2846. return this.expandByObject( object, precise );
  2847. }
  2848. clone() {
  2849. return new this.constructor().copy( this );
  2850. }
  2851. copy( box ) {
  2852. this.min.copy( box.min );
  2853. this.max.copy( box.max );
  2854. return this;
  2855. }
  2856. makeEmpty() {
  2857. this.min.x = this.min.y = this.min.z = + Infinity;
  2858. this.max.x = this.max.y = this.max.z = - Infinity;
  2859. return this;
  2860. }
  2861. isEmpty() {
  2862. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2863. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2864. }
  2865. getCenter( target ) {
  2866. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2867. }
  2868. getSize( target ) {
  2869. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2870. }
  2871. expandByPoint( point ) {
  2872. this.min.min( point );
  2873. this.max.max( point );
  2874. return this;
  2875. }
  2876. expandByVector( vector ) {
  2877. this.min.sub( vector );
  2878. this.max.add( vector );
  2879. return this;
  2880. }
  2881. expandByScalar( scalar ) {
  2882. this.min.addScalar( - scalar );
  2883. this.max.addScalar( scalar );
  2884. return this;
  2885. }
  2886. expandByObject( object, precise = false ) {
  2887. // Computes the world-axis-aligned bounding box of an object (including its children),
  2888. // accounting for both the object's, and children's, world transforms
  2889. object.updateWorldMatrix( false, false );
  2890. const geometry = object.geometry;
  2891. if ( geometry !== undefined ) {
  2892. const positionAttribute = geometry.getAttribute( 'position' );
  2893. // precise AABB computation based on vertex data requires at least a position attribute.
  2894. // instancing isn't supported so far and uses the normal (conservative) code path.
  2895. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2896. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2897. if ( object.isMesh === true ) {
  2898. object.getVertexPosition( i, _vector$b );
  2899. } else {
  2900. _vector$b.fromBufferAttribute( positionAttribute, i );
  2901. }
  2902. _vector$b.applyMatrix4( object.matrixWorld );
  2903. this.expandByPoint( _vector$b );
  2904. }
  2905. } else {
  2906. if ( object.boundingBox !== undefined ) {
  2907. // object-level bounding box
  2908. if ( object.boundingBox === null ) {
  2909. object.computeBoundingBox();
  2910. }
  2911. _box$4.copy( object.boundingBox );
  2912. } else {
  2913. // geometry-level bounding box
  2914. if ( geometry.boundingBox === null ) {
  2915. geometry.computeBoundingBox();
  2916. }
  2917. _box$4.copy( geometry.boundingBox );
  2918. }
  2919. _box$4.applyMatrix4( object.matrixWorld );
  2920. this.union( _box$4 );
  2921. }
  2922. }
  2923. const children = object.children;
  2924. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2925. this.expandByObject( children[ i ], precise );
  2926. }
  2927. return this;
  2928. }
  2929. containsPoint( point ) {
  2930. return point.x >= this.min.x && point.x <= this.max.x &&
  2931. point.y >= this.min.y && point.y <= this.max.y &&
  2932. point.z >= this.min.z && point.z <= this.max.z;
  2933. }
  2934. containsBox( box ) {
  2935. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2936. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2937. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2938. }
  2939. getParameter( point, target ) {
  2940. // This can potentially have a divide by zero if the box
  2941. // has a size dimension of 0.
  2942. return target.set(
  2943. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2944. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2945. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2946. );
  2947. }
  2948. intersectsBox( box ) {
  2949. // using 6 splitting planes to rule out intersections.
  2950. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  2951. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  2952. box.max.z >= this.min.z && box.min.z <= this.max.z;
  2953. }
  2954. intersectsSphere( sphere ) {
  2955. // Find the point on the AABB closest to the sphere center.
  2956. this.clampPoint( sphere.center, _vector$b );
  2957. // If that point is inside the sphere, the AABB and sphere intersect.
  2958. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2959. }
  2960. intersectsPlane( plane ) {
  2961. // We compute the minimum and maximum dot product values. If those values
  2962. // are on the same side (back or front) of the plane, then there is no intersection.
  2963. let min, max;
  2964. if ( plane.normal.x > 0 ) {
  2965. min = plane.normal.x * this.min.x;
  2966. max = plane.normal.x * this.max.x;
  2967. } else {
  2968. min = plane.normal.x * this.max.x;
  2969. max = plane.normal.x * this.min.x;
  2970. }
  2971. if ( plane.normal.y > 0 ) {
  2972. min += plane.normal.y * this.min.y;
  2973. max += plane.normal.y * this.max.y;
  2974. } else {
  2975. min += plane.normal.y * this.max.y;
  2976. max += plane.normal.y * this.min.y;
  2977. }
  2978. if ( plane.normal.z > 0 ) {
  2979. min += plane.normal.z * this.min.z;
  2980. max += plane.normal.z * this.max.z;
  2981. } else {
  2982. min += plane.normal.z * this.max.z;
  2983. max += plane.normal.z * this.min.z;
  2984. }
  2985. return ( min <= - plane.constant && max >= - plane.constant );
  2986. }
  2987. intersectsTriangle( triangle ) {
  2988. if ( this.isEmpty() ) {
  2989. return false;
  2990. }
  2991. // compute box center and extents
  2992. this.getCenter( _center );
  2993. _extents.subVectors( this.max, _center );
  2994. // translate triangle to aabb origin
  2995. _v0$3.subVectors( triangle.a, _center );
  2996. _v1$7.subVectors( triangle.b, _center );
  2997. _v2$4.subVectors( triangle.c, _center );
  2998. // compute edge vectors for triangle
  2999. _f0.subVectors( _v1$7, _v0$3 );
  3000. _f1.subVectors( _v2$4, _v1$7 );
  3001. _f2.subVectors( _v0$3, _v2$4 );
  3002. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3003. // 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
  3004. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3005. let axes = [
  3006. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3007. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3008. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3009. ];
  3010. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  3011. return false;
  3012. }
  3013. // test 3 face normals from the aabb
  3014. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3015. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  3016. return false;
  3017. }
  3018. // finally testing the face normal of the triangle
  3019. // use already existing triangle edge vectors here
  3020. _triangleNormal.crossVectors( _f0, _f1 );
  3021. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3022. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  3023. }
  3024. clampPoint( point, target ) {
  3025. return target.copy( point ).clamp( this.min, this.max );
  3026. }
  3027. distanceToPoint( point ) {
  3028. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3029. }
  3030. getBoundingSphere( target ) {
  3031. if ( this.isEmpty() ) {
  3032. target.makeEmpty();
  3033. } else {
  3034. this.getCenter( target.center );
  3035. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3036. }
  3037. return target;
  3038. }
  3039. intersect( box ) {
  3040. this.min.max( box.min );
  3041. this.max.min( box.max );
  3042. // 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.
  3043. if ( this.isEmpty() ) this.makeEmpty();
  3044. return this;
  3045. }
  3046. union( box ) {
  3047. this.min.min( box.min );
  3048. this.max.max( box.max );
  3049. return this;
  3050. }
  3051. applyMatrix4( matrix ) {
  3052. // transform of empty box is an empty box.
  3053. if ( this.isEmpty() ) return this;
  3054. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3055. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3056. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3057. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3058. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3059. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3060. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3061. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3062. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3063. this.setFromPoints( _points );
  3064. return this;
  3065. }
  3066. translate( offset ) {
  3067. this.min.add( offset );
  3068. this.max.add( offset );
  3069. return this;
  3070. }
  3071. equals( box ) {
  3072. return box.min.equals( this.min ) && box.max.equals( this.max );
  3073. }
  3074. }
  3075. const _points = [
  3076. /*@__PURE__*/ new Vector3(),
  3077. /*@__PURE__*/ new Vector3(),
  3078. /*@__PURE__*/ new Vector3(),
  3079. /*@__PURE__*/ new Vector3(),
  3080. /*@__PURE__*/ new Vector3(),
  3081. /*@__PURE__*/ new Vector3(),
  3082. /*@__PURE__*/ new Vector3(),
  3083. /*@__PURE__*/ new Vector3()
  3084. ];
  3085. const _vector$b = /*@__PURE__*/ new Vector3();
  3086. const _box$4 = /*@__PURE__*/ new Box3();
  3087. // triangle centered vertices
  3088. const _v0$3 = /*@__PURE__*/ new Vector3();
  3089. const _v1$7 = /*@__PURE__*/ new Vector3();
  3090. const _v2$4 = /*@__PURE__*/ new Vector3();
  3091. // triangle edge vectors
  3092. const _f0 = /*@__PURE__*/ new Vector3();
  3093. const _f1 = /*@__PURE__*/ new Vector3();
  3094. const _f2 = /*@__PURE__*/ new Vector3();
  3095. const _center = /*@__PURE__*/ new Vector3();
  3096. const _extents = /*@__PURE__*/ new Vector3();
  3097. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3098. const _testAxis = /*@__PURE__*/ new Vector3();
  3099. function satForAxes( axes, v0, v1, v2, extents ) {
  3100. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3101. _testAxis.fromArray( axes, i );
  3102. // project the aabb onto the separating axis
  3103. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3104. // project all 3 vertices of the triangle onto the separating axis
  3105. const p0 = v0.dot( _testAxis );
  3106. const p1 = v1.dot( _testAxis );
  3107. const p2 = v2.dot( _testAxis );
  3108. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3109. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3110. // points of the projected triangle are outside the projected half-length of the aabb
  3111. // the axis is separating and we can exit
  3112. return false;
  3113. }
  3114. }
  3115. return true;
  3116. }
  3117. const _box$3 = /*@__PURE__*/ new Box3();
  3118. const _v1$6 = /*@__PURE__*/ new Vector3();
  3119. const _v2$3 = /*@__PURE__*/ new Vector3();
  3120. class Sphere {
  3121. constructor( center = new Vector3(), radius = - 1 ) {
  3122. this.isSphere = true;
  3123. this.center = center;
  3124. this.radius = radius;
  3125. }
  3126. set( center, radius ) {
  3127. this.center.copy( center );
  3128. this.radius = radius;
  3129. return this;
  3130. }
  3131. setFromPoints( points, optionalCenter ) {
  3132. const center = this.center;
  3133. if ( optionalCenter !== undefined ) {
  3134. center.copy( optionalCenter );
  3135. } else {
  3136. _box$3.setFromPoints( points ).getCenter( center );
  3137. }
  3138. let maxRadiusSq = 0;
  3139. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3140. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3141. }
  3142. this.radius = Math.sqrt( maxRadiusSq );
  3143. return this;
  3144. }
  3145. copy( sphere ) {
  3146. this.center.copy( sphere.center );
  3147. this.radius = sphere.radius;
  3148. return this;
  3149. }
  3150. isEmpty() {
  3151. return ( this.radius < 0 );
  3152. }
  3153. makeEmpty() {
  3154. this.center.set( 0, 0, 0 );
  3155. this.radius = - 1;
  3156. return this;
  3157. }
  3158. containsPoint( point ) {
  3159. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3160. }
  3161. distanceToPoint( point ) {
  3162. return ( point.distanceTo( this.center ) - this.radius );
  3163. }
  3164. intersectsSphere( sphere ) {
  3165. const radiusSum = this.radius + sphere.radius;
  3166. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3167. }
  3168. intersectsBox( box ) {
  3169. return box.intersectsSphere( this );
  3170. }
  3171. intersectsPlane( plane ) {
  3172. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3173. }
  3174. clampPoint( point, target ) {
  3175. const deltaLengthSq = this.center.distanceToSquared( point );
  3176. target.copy( point );
  3177. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3178. target.sub( this.center ).normalize();
  3179. target.multiplyScalar( this.radius ).add( this.center );
  3180. }
  3181. return target;
  3182. }
  3183. getBoundingBox( target ) {
  3184. if ( this.isEmpty() ) {
  3185. // Empty sphere produces empty bounding box
  3186. target.makeEmpty();
  3187. return target;
  3188. }
  3189. target.set( this.center, this.center );
  3190. target.expandByScalar( this.radius );
  3191. return target;
  3192. }
  3193. applyMatrix4( matrix ) {
  3194. this.center.applyMatrix4( matrix );
  3195. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3196. return this;
  3197. }
  3198. translate( offset ) {
  3199. this.center.add( offset );
  3200. return this;
  3201. }
  3202. expandByPoint( point ) {
  3203. if ( this.isEmpty() ) {
  3204. this.center.copy( point );
  3205. this.radius = 0;
  3206. return this;
  3207. }
  3208. _v1$6.subVectors( point, this.center );
  3209. const lengthSq = _v1$6.lengthSq();
  3210. if ( lengthSq > ( this.radius * this.radius ) ) {
  3211. // calculate the minimal sphere
  3212. const length = Math.sqrt( lengthSq );
  3213. const delta = ( length - this.radius ) * 0.5;
  3214. this.center.addScaledVector( _v1$6, delta / length );
  3215. this.radius += delta;
  3216. }
  3217. return this;
  3218. }
  3219. union( sphere ) {
  3220. if ( sphere.isEmpty() ) {
  3221. return this;
  3222. }
  3223. if ( this.isEmpty() ) {
  3224. this.copy( sphere );
  3225. return this;
  3226. }
  3227. if ( this.center.equals( sphere.center ) === true ) {
  3228. this.radius = Math.max( this.radius, sphere.radius );
  3229. } else {
  3230. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3231. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3232. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3233. }
  3234. return this;
  3235. }
  3236. equals( sphere ) {
  3237. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3238. }
  3239. clone() {
  3240. return new this.constructor().copy( this );
  3241. }
  3242. }
  3243. const _vector$a = /*@__PURE__*/ new Vector3();
  3244. const _segCenter = /*@__PURE__*/ new Vector3();
  3245. const _segDir = /*@__PURE__*/ new Vector3();
  3246. const _diff = /*@__PURE__*/ new Vector3();
  3247. const _edge1 = /*@__PURE__*/ new Vector3();
  3248. const _edge2 = /*@__PURE__*/ new Vector3();
  3249. const _normal$1 = /*@__PURE__*/ new Vector3();
  3250. class Ray {
  3251. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3252. this.origin = origin;
  3253. this.direction = direction;
  3254. }
  3255. set( origin, direction ) {
  3256. this.origin.copy( origin );
  3257. this.direction.copy( direction );
  3258. return this;
  3259. }
  3260. copy( ray ) {
  3261. this.origin.copy( ray.origin );
  3262. this.direction.copy( ray.direction );
  3263. return this;
  3264. }
  3265. at( t, target ) {
  3266. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3267. }
  3268. lookAt( v ) {
  3269. this.direction.copy( v ).sub( this.origin ).normalize();
  3270. return this;
  3271. }
  3272. recast( t ) {
  3273. this.origin.copy( this.at( t, _vector$a ) );
  3274. return this;
  3275. }
  3276. closestPointToPoint( point, target ) {
  3277. target.subVectors( point, this.origin );
  3278. const directionDistance = target.dot( this.direction );
  3279. if ( directionDistance < 0 ) {
  3280. return target.copy( this.origin );
  3281. }
  3282. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3283. }
  3284. distanceToPoint( point ) {
  3285. return Math.sqrt( this.distanceSqToPoint( point ) );
  3286. }
  3287. distanceSqToPoint( point ) {
  3288. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3289. // point behind the ray
  3290. if ( directionDistance < 0 ) {
  3291. return this.origin.distanceToSquared( point );
  3292. }
  3293. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3294. return _vector$a.distanceToSquared( point );
  3295. }
  3296. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3297. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3298. // It returns the min distance between the ray and the segment
  3299. // defined by v0 and v1
  3300. // It can also set two optional targets :
  3301. // - The closest point on the ray
  3302. // - The closest point on the segment
  3303. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3304. _segDir.copy( v1 ).sub( v0 ).normalize();
  3305. _diff.copy( this.origin ).sub( _segCenter );
  3306. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3307. const a01 = - this.direction.dot( _segDir );
  3308. const b0 = _diff.dot( this.direction );
  3309. const b1 = - _diff.dot( _segDir );
  3310. const c = _diff.lengthSq();
  3311. const det = Math.abs( 1 - a01 * a01 );
  3312. let s0, s1, sqrDist, extDet;
  3313. if ( det > 0 ) {
  3314. // The ray and segment are not parallel.
  3315. s0 = a01 * b1 - b0;
  3316. s1 = a01 * b0 - b1;
  3317. extDet = segExtent * det;
  3318. if ( s0 >= 0 ) {
  3319. if ( s1 >= - extDet ) {
  3320. if ( s1 <= extDet ) {
  3321. // region 0
  3322. // Minimum at interior points of ray and segment.
  3323. const invDet = 1 / det;
  3324. s0 *= invDet;
  3325. s1 *= invDet;
  3326. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3327. } else {
  3328. // region 1
  3329. s1 = segExtent;
  3330. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3331. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3332. }
  3333. } else {
  3334. // region 5
  3335. s1 = - segExtent;
  3336. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3337. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3338. }
  3339. } else {
  3340. if ( s1 <= - extDet ) {
  3341. // region 4
  3342. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3343. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3344. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3345. } else if ( s1 <= extDet ) {
  3346. // region 3
  3347. s0 = 0;
  3348. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3349. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3350. } else {
  3351. // region 2
  3352. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3353. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3354. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3355. }
  3356. }
  3357. } else {
  3358. // Ray and segment are parallel.
  3359. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3360. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3361. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3362. }
  3363. if ( optionalPointOnRay ) {
  3364. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3365. }
  3366. if ( optionalPointOnSegment ) {
  3367. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3368. }
  3369. return sqrDist;
  3370. }
  3371. intersectSphere( sphere, target ) {
  3372. _vector$a.subVectors( sphere.center, this.origin );
  3373. const tca = _vector$a.dot( this.direction );
  3374. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3375. const radius2 = sphere.radius * sphere.radius;
  3376. if ( d2 > radius2 ) return null;
  3377. const thc = Math.sqrt( radius2 - d2 );
  3378. // t0 = first intersect point - entrance on front of sphere
  3379. const t0 = tca - thc;
  3380. // t1 = second intersect point - exit point on back of sphere
  3381. const t1 = tca + thc;
  3382. // test to see if t1 is behind the ray - if so, return null
  3383. if ( t1 < 0 ) return null;
  3384. // test to see if t0 is behind the ray:
  3385. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3386. // in order to always return an intersect point that is in front of the ray.
  3387. if ( t0 < 0 ) return this.at( t1, target );
  3388. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3389. return this.at( t0, target );
  3390. }
  3391. intersectsSphere( sphere ) {
  3392. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3393. }
  3394. distanceToPlane( plane ) {
  3395. const denominator = plane.normal.dot( this.direction );
  3396. if ( denominator === 0 ) {
  3397. // line is coplanar, return origin
  3398. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3399. return 0;
  3400. }
  3401. // Null is preferable to undefined since undefined means.... it is undefined
  3402. return null;
  3403. }
  3404. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3405. // Return if the ray never intersects the plane
  3406. return t >= 0 ? t : null;
  3407. }
  3408. intersectPlane( plane, target ) {
  3409. const t = this.distanceToPlane( plane );
  3410. if ( t === null ) {
  3411. return null;
  3412. }
  3413. return this.at( t, target );
  3414. }
  3415. intersectsPlane( plane ) {
  3416. // check if the ray lies on the plane first
  3417. const distToPoint = plane.distanceToPoint( this.origin );
  3418. if ( distToPoint === 0 ) {
  3419. return true;
  3420. }
  3421. const denominator = plane.normal.dot( this.direction );
  3422. if ( denominator * distToPoint < 0 ) {
  3423. return true;
  3424. }
  3425. // ray origin is behind the plane (and is pointing behind it)
  3426. return false;
  3427. }
  3428. intersectBox( box, target ) {
  3429. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3430. const invdirx = 1 / this.direction.x,
  3431. invdiry = 1 / this.direction.y,
  3432. invdirz = 1 / this.direction.z;
  3433. const origin = this.origin;
  3434. if ( invdirx >= 0 ) {
  3435. tmin = ( box.min.x - origin.x ) * invdirx;
  3436. tmax = ( box.max.x - origin.x ) * invdirx;
  3437. } else {
  3438. tmin = ( box.max.x - origin.x ) * invdirx;
  3439. tmax = ( box.min.x - origin.x ) * invdirx;
  3440. }
  3441. if ( invdiry >= 0 ) {
  3442. tymin = ( box.min.y - origin.y ) * invdiry;
  3443. tymax = ( box.max.y - origin.y ) * invdiry;
  3444. } else {
  3445. tymin = ( box.max.y - origin.y ) * invdiry;
  3446. tymax = ( box.min.y - origin.y ) * invdiry;
  3447. }
  3448. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3449. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3450. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3451. if ( invdirz >= 0 ) {
  3452. tzmin = ( box.min.z - origin.z ) * invdirz;
  3453. tzmax = ( box.max.z - origin.z ) * invdirz;
  3454. } else {
  3455. tzmin = ( box.max.z - origin.z ) * invdirz;
  3456. tzmax = ( box.min.z - origin.z ) * invdirz;
  3457. }
  3458. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3459. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3460. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3461. //return point closest to the ray (positive side)
  3462. if ( tmax < 0 ) return null;
  3463. return this.at( tmin >= 0 ? tmin : tmax, target );
  3464. }
  3465. intersectsBox( box ) {
  3466. return this.intersectBox( box, _vector$a ) !== null;
  3467. }
  3468. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3469. // Compute the offset origin, edges, and normal.
  3470. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3471. _edge1.subVectors( b, a );
  3472. _edge2.subVectors( c, a );
  3473. _normal$1.crossVectors( _edge1, _edge2 );
  3474. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3475. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3476. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3477. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3478. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3479. let DdN = this.direction.dot( _normal$1 );
  3480. let sign;
  3481. if ( DdN > 0 ) {
  3482. if ( backfaceCulling ) return null;
  3483. sign = 1;
  3484. } else if ( DdN < 0 ) {
  3485. sign = - 1;
  3486. DdN = - DdN;
  3487. } else {
  3488. return null;
  3489. }
  3490. _diff.subVectors( this.origin, a );
  3491. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3492. // b1 < 0, no intersection
  3493. if ( DdQxE2 < 0 ) {
  3494. return null;
  3495. }
  3496. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3497. // b2 < 0, no intersection
  3498. if ( DdE1xQ < 0 ) {
  3499. return null;
  3500. }
  3501. // b1+b2 > 1, no intersection
  3502. if ( DdQxE2 + DdE1xQ > DdN ) {
  3503. return null;
  3504. }
  3505. // Line intersects triangle, check if ray does.
  3506. const QdN = - sign * _diff.dot( _normal$1 );
  3507. // t < 0, no intersection
  3508. if ( QdN < 0 ) {
  3509. return null;
  3510. }
  3511. // Ray intersects triangle.
  3512. return this.at( QdN / DdN, target );
  3513. }
  3514. applyMatrix4( matrix4 ) {
  3515. this.origin.applyMatrix4( matrix4 );
  3516. this.direction.transformDirection( matrix4 );
  3517. return this;
  3518. }
  3519. equals( ray ) {
  3520. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3521. }
  3522. clone() {
  3523. return new this.constructor().copy( this );
  3524. }
  3525. }
  3526. class Matrix4 {
  3527. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3528. Matrix4.prototype.isMatrix4 = true;
  3529. this.elements = [
  3530. 1, 0, 0, 0,
  3531. 0, 1, 0, 0,
  3532. 0, 0, 1, 0,
  3533. 0, 0, 0, 1
  3534. ];
  3535. if ( n11 !== undefined ) {
  3536. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3537. }
  3538. }
  3539. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3540. const te = this.elements;
  3541. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3542. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3543. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3544. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3545. return this;
  3546. }
  3547. identity() {
  3548. this.set(
  3549. 1, 0, 0, 0,
  3550. 0, 1, 0, 0,
  3551. 0, 0, 1, 0,
  3552. 0, 0, 0, 1
  3553. );
  3554. return this;
  3555. }
  3556. clone() {
  3557. return new Matrix4().fromArray( this.elements );
  3558. }
  3559. copy( m ) {
  3560. const te = this.elements;
  3561. const me = m.elements;
  3562. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3563. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3564. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3565. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3566. return this;
  3567. }
  3568. copyPosition( m ) {
  3569. const te = this.elements, me = m.elements;
  3570. te[ 12 ] = me[ 12 ];
  3571. te[ 13 ] = me[ 13 ];
  3572. te[ 14 ] = me[ 14 ];
  3573. return this;
  3574. }
  3575. setFromMatrix3( m ) {
  3576. const me = m.elements;
  3577. this.set(
  3578. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3579. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3580. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3581. 0, 0, 0, 1
  3582. );
  3583. return this;
  3584. }
  3585. extractBasis( xAxis, yAxis, zAxis ) {
  3586. xAxis.setFromMatrixColumn( this, 0 );
  3587. yAxis.setFromMatrixColumn( this, 1 );
  3588. zAxis.setFromMatrixColumn( this, 2 );
  3589. return this;
  3590. }
  3591. makeBasis( xAxis, yAxis, zAxis ) {
  3592. this.set(
  3593. xAxis.x, yAxis.x, zAxis.x, 0,
  3594. xAxis.y, yAxis.y, zAxis.y, 0,
  3595. xAxis.z, yAxis.z, zAxis.z, 0,
  3596. 0, 0, 0, 1
  3597. );
  3598. return this;
  3599. }
  3600. extractRotation( m ) {
  3601. // this method does not support reflection matrices
  3602. const te = this.elements;
  3603. const me = m.elements;
  3604. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3605. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3606. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3607. te[ 0 ] = me[ 0 ] * scaleX;
  3608. te[ 1 ] = me[ 1 ] * scaleX;
  3609. te[ 2 ] = me[ 2 ] * scaleX;
  3610. te[ 3 ] = 0;
  3611. te[ 4 ] = me[ 4 ] * scaleY;
  3612. te[ 5 ] = me[ 5 ] * scaleY;
  3613. te[ 6 ] = me[ 6 ] * scaleY;
  3614. te[ 7 ] = 0;
  3615. te[ 8 ] = me[ 8 ] * scaleZ;
  3616. te[ 9 ] = me[ 9 ] * scaleZ;
  3617. te[ 10 ] = me[ 10 ] * scaleZ;
  3618. te[ 11 ] = 0;
  3619. te[ 12 ] = 0;
  3620. te[ 13 ] = 0;
  3621. te[ 14 ] = 0;
  3622. te[ 15 ] = 1;
  3623. return this;
  3624. }
  3625. makeRotationFromEuler( euler ) {
  3626. const te = this.elements;
  3627. const x = euler.x, y = euler.y, z = euler.z;
  3628. const a = Math.cos( x ), b = Math.sin( x );
  3629. const c = Math.cos( y ), d = Math.sin( y );
  3630. const e = Math.cos( z ), f = Math.sin( z );
  3631. if ( euler.order === 'XYZ' ) {
  3632. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3633. te[ 0 ] = c * e;
  3634. te[ 4 ] = - c * f;
  3635. te[ 8 ] = d;
  3636. te[ 1 ] = af + be * d;
  3637. te[ 5 ] = ae - bf * d;
  3638. te[ 9 ] = - b * c;
  3639. te[ 2 ] = bf - ae * d;
  3640. te[ 6 ] = be + af * d;
  3641. te[ 10 ] = a * c;
  3642. } else if ( euler.order === 'YXZ' ) {
  3643. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3644. te[ 0 ] = ce + df * b;
  3645. te[ 4 ] = de * b - cf;
  3646. te[ 8 ] = a * d;
  3647. te[ 1 ] = a * f;
  3648. te[ 5 ] = a * e;
  3649. te[ 9 ] = - b;
  3650. te[ 2 ] = cf * b - de;
  3651. te[ 6 ] = df + ce * b;
  3652. te[ 10 ] = a * c;
  3653. } else if ( euler.order === 'ZXY' ) {
  3654. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3655. te[ 0 ] = ce - df * b;
  3656. te[ 4 ] = - a * f;
  3657. te[ 8 ] = de + cf * b;
  3658. te[ 1 ] = cf + de * b;
  3659. te[ 5 ] = a * e;
  3660. te[ 9 ] = df - ce * b;
  3661. te[ 2 ] = - a * d;
  3662. te[ 6 ] = b;
  3663. te[ 10 ] = a * c;
  3664. } else if ( euler.order === 'ZYX' ) {
  3665. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3666. te[ 0 ] = c * e;
  3667. te[ 4 ] = be * d - af;
  3668. te[ 8 ] = ae * d + bf;
  3669. te[ 1 ] = c * f;
  3670. te[ 5 ] = bf * d + ae;
  3671. te[ 9 ] = af * d - be;
  3672. te[ 2 ] = - d;
  3673. te[ 6 ] = b * c;
  3674. te[ 10 ] = a * c;
  3675. } else if ( euler.order === 'YZX' ) {
  3676. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3677. te[ 0 ] = c * e;
  3678. te[ 4 ] = bd - ac * f;
  3679. te[ 8 ] = bc * f + ad;
  3680. te[ 1 ] = f;
  3681. te[ 5 ] = a * e;
  3682. te[ 9 ] = - b * e;
  3683. te[ 2 ] = - d * e;
  3684. te[ 6 ] = ad * f + bc;
  3685. te[ 10 ] = ac - bd * f;
  3686. } else if ( euler.order === 'XZY' ) {
  3687. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3688. te[ 0 ] = c * e;
  3689. te[ 4 ] = - f;
  3690. te[ 8 ] = d * e;
  3691. te[ 1 ] = ac * f + bd;
  3692. te[ 5 ] = a * e;
  3693. te[ 9 ] = ad * f - bc;
  3694. te[ 2 ] = bc * f - ad;
  3695. te[ 6 ] = b * e;
  3696. te[ 10 ] = bd * f + ac;
  3697. }
  3698. // bottom row
  3699. te[ 3 ] = 0;
  3700. te[ 7 ] = 0;
  3701. te[ 11 ] = 0;
  3702. // last column
  3703. te[ 12 ] = 0;
  3704. te[ 13 ] = 0;
  3705. te[ 14 ] = 0;
  3706. te[ 15 ] = 1;
  3707. return this;
  3708. }
  3709. makeRotationFromQuaternion( q ) {
  3710. return this.compose( _zero, q, _one );
  3711. }
  3712. lookAt( eye, target, up ) {
  3713. const te = this.elements;
  3714. _z.subVectors( eye, target );
  3715. if ( _z.lengthSq() === 0 ) {
  3716. // eye and target are in the same position
  3717. _z.z = 1;
  3718. }
  3719. _z.normalize();
  3720. _x.crossVectors( up, _z );
  3721. if ( _x.lengthSq() === 0 ) {
  3722. // up and z are parallel
  3723. if ( Math.abs( up.z ) === 1 ) {
  3724. _z.x += 0.0001;
  3725. } else {
  3726. _z.z += 0.0001;
  3727. }
  3728. _z.normalize();
  3729. _x.crossVectors( up, _z );
  3730. }
  3731. _x.normalize();
  3732. _y.crossVectors( _z, _x );
  3733. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3734. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3735. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3736. return this;
  3737. }
  3738. multiply( m ) {
  3739. return this.multiplyMatrices( this, m );
  3740. }
  3741. premultiply( m ) {
  3742. return this.multiplyMatrices( m, this );
  3743. }
  3744. multiplyMatrices( a, b ) {
  3745. const ae = a.elements;
  3746. const be = b.elements;
  3747. const te = this.elements;
  3748. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3749. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3750. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3751. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3752. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3753. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3754. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3755. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3756. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3757. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3758. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3759. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3760. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3761. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3762. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3763. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3764. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3765. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3766. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3767. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3768. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3769. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3770. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3771. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3772. return this;
  3773. }
  3774. multiplyScalar( s ) {
  3775. const te = this.elements;
  3776. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3777. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3778. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3779. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3780. return this;
  3781. }
  3782. determinant() {
  3783. const te = this.elements;
  3784. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3785. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3786. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3787. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3788. //TODO: make this more efficient
  3789. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3790. return (
  3791. n41 * (
  3792. + n14 * n23 * n32
  3793. - n13 * n24 * n32
  3794. - n14 * n22 * n33
  3795. + n12 * n24 * n33
  3796. + n13 * n22 * n34
  3797. - n12 * n23 * n34
  3798. ) +
  3799. n42 * (
  3800. + n11 * n23 * n34
  3801. - n11 * n24 * n33
  3802. + n14 * n21 * n33
  3803. - n13 * n21 * n34
  3804. + n13 * n24 * n31
  3805. - n14 * n23 * n31
  3806. ) +
  3807. n43 * (
  3808. + n11 * n24 * n32
  3809. - n11 * n22 * n34
  3810. - n14 * n21 * n32
  3811. + n12 * n21 * n34
  3812. + n14 * n22 * n31
  3813. - n12 * n24 * n31
  3814. ) +
  3815. n44 * (
  3816. - n13 * n22 * n31
  3817. - n11 * n23 * n32
  3818. + n11 * n22 * n33
  3819. + n13 * n21 * n32
  3820. - n12 * n21 * n33
  3821. + n12 * n23 * n31
  3822. )
  3823. );
  3824. }
  3825. transpose() {
  3826. const te = this.elements;
  3827. let tmp;
  3828. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3829. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3830. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3831. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3832. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3833. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3834. return this;
  3835. }
  3836. setPosition( x, y, z ) {
  3837. const te = this.elements;
  3838. if ( x.isVector3 ) {
  3839. te[ 12 ] = x.x;
  3840. te[ 13 ] = x.y;
  3841. te[ 14 ] = x.z;
  3842. } else {
  3843. te[ 12 ] = x;
  3844. te[ 13 ] = y;
  3845. te[ 14 ] = z;
  3846. }
  3847. return this;
  3848. }
  3849. invert() {
  3850. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3851. const te = this.elements,
  3852. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3853. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3854. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3855. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3856. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3857. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3858. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3859. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3860. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3861. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3862. const detInv = 1 / det;
  3863. te[ 0 ] = t11 * detInv;
  3864. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3865. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3866. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3867. te[ 4 ] = t12 * detInv;
  3868. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3869. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3870. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3871. te[ 8 ] = t13 * detInv;
  3872. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3873. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3874. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3875. te[ 12 ] = t14 * detInv;
  3876. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3877. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3878. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3879. return this;
  3880. }
  3881. scale( v ) {
  3882. const te = this.elements;
  3883. const x = v.x, y = v.y, z = v.z;
  3884. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3885. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3886. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3887. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3888. return this;
  3889. }
  3890. getMaxScaleOnAxis() {
  3891. const te = this.elements;
  3892. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3893. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3894. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3895. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3896. }
  3897. makeTranslation( x, y, z ) {
  3898. if ( x.isVector3 ) {
  3899. this.set(
  3900. 1, 0, 0, x.x,
  3901. 0, 1, 0, x.y,
  3902. 0, 0, 1, x.z,
  3903. 0, 0, 0, 1
  3904. );
  3905. } else {
  3906. this.set(
  3907. 1, 0, 0, x,
  3908. 0, 1, 0, y,
  3909. 0, 0, 1, z,
  3910. 0, 0, 0, 1
  3911. );
  3912. }
  3913. return this;
  3914. }
  3915. makeRotationX( theta ) {
  3916. const c = Math.cos( theta ), s = Math.sin( theta );
  3917. this.set(
  3918. 1, 0, 0, 0,
  3919. 0, c, - s, 0,
  3920. 0, s, c, 0,
  3921. 0, 0, 0, 1
  3922. );
  3923. return this;
  3924. }
  3925. makeRotationY( theta ) {
  3926. const c = Math.cos( theta ), s = Math.sin( theta );
  3927. this.set(
  3928. c, 0, s, 0,
  3929. 0, 1, 0, 0,
  3930. - s, 0, c, 0,
  3931. 0, 0, 0, 1
  3932. );
  3933. return this;
  3934. }
  3935. makeRotationZ( theta ) {
  3936. const c = Math.cos( theta ), s = Math.sin( theta );
  3937. this.set(
  3938. c, - s, 0, 0,
  3939. s, c, 0, 0,
  3940. 0, 0, 1, 0,
  3941. 0, 0, 0, 1
  3942. );
  3943. return this;
  3944. }
  3945. makeRotationAxis( axis, angle ) {
  3946. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3947. const c = Math.cos( angle );
  3948. const s = Math.sin( angle );
  3949. const t = 1 - c;
  3950. const x = axis.x, y = axis.y, z = axis.z;
  3951. const tx = t * x, ty = t * y;
  3952. this.set(
  3953. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3954. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3955. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3956. 0, 0, 0, 1
  3957. );
  3958. return this;
  3959. }
  3960. makeScale( x, y, z ) {
  3961. this.set(
  3962. x, 0, 0, 0,
  3963. 0, y, 0, 0,
  3964. 0, 0, z, 0,
  3965. 0, 0, 0, 1
  3966. );
  3967. return this;
  3968. }
  3969. makeShear( xy, xz, yx, yz, zx, zy ) {
  3970. this.set(
  3971. 1, yx, zx, 0,
  3972. xy, 1, zy, 0,
  3973. xz, yz, 1, 0,
  3974. 0, 0, 0, 1
  3975. );
  3976. return this;
  3977. }
  3978. compose( position, quaternion, scale ) {
  3979. const te = this.elements;
  3980. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3981. const x2 = x + x, y2 = y + y, z2 = z + z;
  3982. const xx = x * x2, xy = x * y2, xz = x * z2;
  3983. const yy = y * y2, yz = y * z2, zz = z * z2;
  3984. const wx = w * x2, wy = w * y2, wz = w * z2;
  3985. const sx = scale.x, sy = scale.y, sz = scale.z;
  3986. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3987. te[ 1 ] = ( xy + wz ) * sx;
  3988. te[ 2 ] = ( xz - wy ) * sx;
  3989. te[ 3 ] = 0;
  3990. te[ 4 ] = ( xy - wz ) * sy;
  3991. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3992. te[ 6 ] = ( yz + wx ) * sy;
  3993. te[ 7 ] = 0;
  3994. te[ 8 ] = ( xz + wy ) * sz;
  3995. te[ 9 ] = ( yz - wx ) * sz;
  3996. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3997. te[ 11 ] = 0;
  3998. te[ 12 ] = position.x;
  3999. te[ 13 ] = position.y;
  4000. te[ 14 ] = position.z;
  4001. te[ 15 ] = 1;
  4002. return this;
  4003. }
  4004. decompose( position, quaternion, scale ) {
  4005. const te = this.elements;
  4006. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4007. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4008. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4009. // if determine is negative, we need to invert one scale
  4010. const det = this.determinant();
  4011. if ( det < 0 ) sx = - sx;
  4012. position.x = te[ 12 ];
  4013. position.y = te[ 13 ];
  4014. position.z = te[ 14 ];
  4015. // scale the rotation part
  4016. _m1$4.copy( this );
  4017. const invSX = 1 / sx;
  4018. const invSY = 1 / sy;
  4019. const invSZ = 1 / sz;
  4020. _m1$4.elements[ 0 ] *= invSX;
  4021. _m1$4.elements[ 1 ] *= invSX;
  4022. _m1$4.elements[ 2 ] *= invSX;
  4023. _m1$4.elements[ 4 ] *= invSY;
  4024. _m1$4.elements[ 5 ] *= invSY;
  4025. _m1$4.elements[ 6 ] *= invSY;
  4026. _m1$4.elements[ 8 ] *= invSZ;
  4027. _m1$4.elements[ 9 ] *= invSZ;
  4028. _m1$4.elements[ 10 ] *= invSZ;
  4029. quaternion.setFromRotationMatrix( _m1$4 );
  4030. scale.x = sx;
  4031. scale.y = sy;
  4032. scale.z = sz;
  4033. return this;
  4034. }
  4035. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4036. const te = this.elements;
  4037. const x = 2 * near / ( right - left );
  4038. const y = 2 * near / ( top - bottom );
  4039. const a = ( right + left ) / ( right - left );
  4040. const b = ( top + bottom ) / ( top - bottom );
  4041. let c, d;
  4042. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4043. c = - ( far + near ) / ( far - near );
  4044. d = ( - 2 * far * near ) / ( far - near );
  4045. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4046. c = - far / ( far - near );
  4047. d = ( - far * near ) / ( far - near );
  4048. } else {
  4049. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4050. }
  4051. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4052. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4053. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4054. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4055. return this;
  4056. }
  4057. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4058. const te = this.elements;
  4059. const w = 1.0 / ( right - left );
  4060. const h = 1.0 / ( top - bottom );
  4061. const p = 1.0 / ( far - near );
  4062. const x = ( right + left ) * w;
  4063. const y = ( top + bottom ) * h;
  4064. let z, zInv;
  4065. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4066. z = ( far + near ) * p;
  4067. zInv = - 2 * p;
  4068. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4069. z = near * p;
  4070. zInv = - 1 * p;
  4071. } else {
  4072. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4073. }
  4074. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4075. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4076. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4077. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4078. return this;
  4079. }
  4080. equals( matrix ) {
  4081. const te = this.elements;
  4082. const me = matrix.elements;
  4083. for ( let i = 0; i < 16; i ++ ) {
  4084. if ( te[ i ] !== me[ i ] ) return false;
  4085. }
  4086. return true;
  4087. }
  4088. fromArray( array, offset = 0 ) {
  4089. for ( let i = 0; i < 16; i ++ ) {
  4090. this.elements[ i ] = array[ i + offset ];
  4091. }
  4092. return this;
  4093. }
  4094. toArray( array = [], offset = 0 ) {
  4095. const te = this.elements;
  4096. array[ offset ] = te[ 0 ];
  4097. array[ offset + 1 ] = te[ 1 ];
  4098. array[ offset + 2 ] = te[ 2 ];
  4099. array[ offset + 3 ] = te[ 3 ];
  4100. array[ offset + 4 ] = te[ 4 ];
  4101. array[ offset + 5 ] = te[ 5 ];
  4102. array[ offset + 6 ] = te[ 6 ];
  4103. array[ offset + 7 ] = te[ 7 ];
  4104. array[ offset + 8 ] = te[ 8 ];
  4105. array[ offset + 9 ] = te[ 9 ];
  4106. array[ offset + 10 ] = te[ 10 ];
  4107. array[ offset + 11 ] = te[ 11 ];
  4108. array[ offset + 12 ] = te[ 12 ];
  4109. array[ offset + 13 ] = te[ 13 ];
  4110. array[ offset + 14 ] = te[ 14 ];
  4111. array[ offset + 15 ] = te[ 15 ];
  4112. return array;
  4113. }
  4114. }
  4115. const _v1$5 = /*@__PURE__*/ new Vector3();
  4116. const _m1$4 = /*@__PURE__*/ new Matrix4();
  4117. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4118. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4119. const _x = /*@__PURE__*/ new Vector3();
  4120. const _y = /*@__PURE__*/ new Vector3();
  4121. const _z = /*@__PURE__*/ new Vector3();
  4122. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4123. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4124. class Euler {
  4125. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4126. this.isEuler = true;
  4127. this._x = x;
  4128. this._y = y;
  4129. this._z = z;
  4130. this._order = order;
  4131. }
  4132. get x() {
  4133. return this._x;
  4134. }
  4135. set x( value ) {
  4136. this._x = value;
  4137. this._onChangeCallback();
  4138. }
  4139. get y() {
  4140. return this._y;
  4141. }
  4142. set y( value ) {
  4143. this._y = value;
  4144. this._onChangeCallback();
  4145. }
  4146. get z() {
  4147. return this._z;
  4148. }
  4149. set z( value ) {
  4150. this._z = value;
  4151. this._onChangeCallback();
  4152. }
  4153. get order() {
  4154. return this._order;
  4155. }
  4156. set order( value ) {
  4157. this._order = value;
  4158. this._onChangeCallback();
  4159. }
  4160. set( x, y, z, order = this._order ) {
  4161. this._x = x;
  4162. this._y = y;
  4163. this._z = z;
  4164. this._order = order;
  4165. this._onChangeCallback();
  4166. return this;
  4167. }
  4168. clone() {
  4169. return new this.constructor( this._x, this._y, this._z, this._order );
  4170. }
  4171. copy( euler ) {
  4172. this._x = euler._x;
  4173. this._y = euler._y;
  4174. this._z = euler._z;
  4175. this._order = euler._order;
  4176. this._onChangeCallback();
  4177. return this;
  4178. }
  4179. setFromRotationMatrix( m, order = this._order, update = true ) {
  4180. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4181. const te = m.elements;
  4182. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4183. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4184. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4185. switch ( order ) {
  4186. case 'XYZ':
  4187. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4188. if ( Math.abs( m13 ) < 0.9999999 ) {
  4189. this._x = Math.atan2( - m23, m33 );
  4190. this._z = Math.atan2( - m12, m11 );
  4191. } else {
  4192. this._x = Math.atan2( m32, m22 );
  4193. this._z = 0;
  4194. }
  4195. break;
  4196. case 'YXZ':
  4197. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4198. if ( Math.abs( m23 ) < 0.9999999 ) {
  4199. this._y = Math.atan2( m13, m33 );
  4200. this._z = Math.atan2( m21, m22 );
  4201. } else {
  4202. this._y = Math.atan2( - m31, m11 );
  4203. this._z = 0;
  4204. }
  4205. break;
  4206. case 'ZXY':
  4207. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4208. if ( Math.abs( m32 ) < 0.9999999 ) {
  4209. this._y = Math.atan2( - m31, m33 );
  4210. this._z = Math.atan2( - m12, m22 );
  4211. } else {
  4212. this._y = 0;
  4213. this._z = Math.atan2( m21, m11 );
  4214. }
  4215. break;
  4216. case 'ZYX':
  4217. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4218. if ( Math.abs( m31 ) < 0.9999999 ) {
  4219. this._x = Math.atan2( m32, m33 );
  4220. this._z = Math.atan2( m21, m11 );
  4221. } else {
  4222. this._x = 0;
  4223. this._z = Math.atan2( - m12, m22 );
  4224. }
  4225. break;
  4226. case 'YZX':
  4227. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4228. if ( Math.abs( m21 ) < 0.9999999 ) {
  4229. this._x = Math.atan2( - m23, m22 );
  4230. this._y = Math.atan2( - m31, m11 );
  4231. } else {
  4232. this._x = 0;
  4233. this._y = Math.atan2( m13, m33 );
  4234. }
  4235. break;
  4236. case 'XZY':
  4237. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4238. if ( Math.abs( m12 ) < 0.9999999 ) {
  4239. this._x = Math.atan2( m32, m22 );
  4240. this._y = Math.atan2( m13, m11 );
  4241. } else {
  4242. this._x = Math.atan2( - m23, m33 );
  4243. this._y = 0;
  4244. }
  4245. break;
  4246. default:
  4247. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4248. }
  4249. this._order = order;
  4250. if ( update === true ) this._onChangeCallback();
  4251. return this;
  4252. }
  4253. setFromQuaternion( q, order, update ) {
  4254. _matrix$2.makeRotationFromQuaternion( q );
  4255. return this.setFromRotationMatrix( _matrix$2, order, update );
  4256. }
  4257. setFromVector3( v, order = this._order ) {
  4258. return this.set( v.x, v.y, v.z, order );
  4259. }
  4260. reorder( newOrder ) {
  4261. // WARNING: this discards revolution information -bhouston
  4262. _quaternion$3.setFromEuler( this );
  4263. return this.setFromQuaternion( _quaternion$3, newOrder );
  4264. }
  4265. equals( euler ) {
  4266. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4267. }
  4268. fromArray( array ) {
  4269. this._x = array[ 0 ];
  4270. this._y = array[ 1 ];
  4271. this._z = array[ 2 ];
  4272. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4273. this._onChangeCallback();
  4274. return this;
  4275. }
  4276. toArray( array = [], offset = 0 ) {
  4277. array[ offset ] = this._x;
  4278. array[ offset + 1 ] = this._y;
  4279. array[ offset + 2 ] = this._z;
  4280. array[ offset + 3 ] = this._order;
  4281. return array;
  4282. }
  4283. _onChange( callback ) {
  4284. this._onChangeCallback = callback;
  4285. return this;
  4286. }
  4287. _onChangeCallback() {}
  4288. *[ Symbol.iterator ]() {
  4289. yield this._x;
  4290. yield this._y;
  4291. yield this._z;
  4292. yield this._order;
  4293. }
  4294. }
  4295. Euler.DEFAULT_ORDER = 'XYZ';
  4296. class Layers {
  4297. constructor() {
  4298. this.mask = 1 | 0;
  4299. }
  4300. set( channel ) {
  4301. this.mask = ( 1 << channel | 0 ) >>> 0;
  4302. }
  4303. enable( channel ) {
  4304. this.mask |= 1 << channel | 0;
  4305. }
  4306. enableAll() {
  4307. this.mask = 0xffffffff | 0;
  4308. }
  4309. toggle( channel ) {
  4310. this.mask ^= 1 << channel | 0;
  4311. }
  4312. disable( channel ) {
  4313. this.mask &= ~ ( 1 << channel | 0 );
  4314. }
  4315. disableAll() {
  4316. this.mask = 0;
  4317. }
  4318. test( layers ) {
  4319. return ( this.mask & layers.mask ) !== 0;
  4320. }
  4321. isEnabled( channel ) {
  4322. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4323. }
  4324. }
  4325. let _object3DId = 0;
  4326. const _v1$4 = /*@__PURE__*/ new Vector3();
  4327. const _q1 = /*@__PURE__*/ new Quaternion();
  4328. const _m1$3 = /*@__PURE__*/ new Matrix4();
  4329. const _target = /*@__PURE__*/ new Vector3();
  4330. const _position$3 = /*@__PURE__*/ new Vector3();
  4331. const _scale$2 = /*@__PURE__*/ new Vector3();
  4332. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4333. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4334. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4335. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4336. const _addedEvent = { type: 'added' };
  4337. const _removedEvent = { type: 'removed' };
  4338. const _childaddedEvent = { type: 'childadded', child: null };
  4339. const _childremovedEvent = { type: 'childremoved', child: null };
  4340. class Object3D extends EventDispatcher {
  4341. constructor() {
  4342. super();
  4343. this.isObject3D = true;
  4344. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4345. this.uuid = generateUUID();
  4346. this.name = '';
  4347. this.type = 'Object3D';
  4348. this.parent = null;
  4349. this.children = [];
  4350. this.up = Object3D.DEFAULT_UP.clone();
  4351. const position = new Vector3();
  4352. const rotation = new Euler();
  4353. const quaternion = new Quaternion();
  4354. const scale = new Vector3( 1, 1, 1 );
  4355. function onRotationChange() {
  4356. quaternion.setFromEuler( rotation, false );
  4357. }
  4358. function onQuaternionChange() {
  4359. rotation.setFromQuaternion( quaternion, undefined, false );
  4360. }
  4361. rotation._onChange( onRotationChange );
  4362. quaternion._onChange( onQuaternionChange );
  4363. Object.defineProperties( this, {
  4364. position: {
  4365. configurable: true,
  4366. enumerable: true,
  4367. value: position
  4368. },
  4369. rotation: {
  4370. configurable: true,
  4371. enumerable: true,
  4372. value: rotation
  4373. },
  4374. quaternion: {
  4375. configurable: true,
  4376. enumerable: true,
  4377. value: quaternion
  4378. },
  4379. scale: {
  4380. configurable: true,
  4381. enumerable: true,
  4382. value: scale
  4383. },
  4384. modelViewMatrix: {
  4385. value: new Matrix4()
  4386. },
  4387. normalMatrix: {
  4388. value: new Matrix3()
  4389. }
  4390. } );
  4391. this.matrix = new Matrix4();
  4392. this.matrixWorld = new Matrix4();
  4393. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4394. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4395. this.matrixWorldNeedsUpdate = false;
  4396. this.layers = new Layers();
  4397. this.visible = true;
  4398. this.castShadow = false;
  4399. this.receiveShadow = false;
  4400. this.frustumCulled = true;
  4401. this.renderOrder = 0;
  4402. this.animations = [];
  4403. this.userData = {};
  4404. }
  4405. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4406. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4407. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4408. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4409. applyMatrix4( matrix ) {
  4410. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4411. this.matrix.premultiply( matrix );
  4412. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4413. }
  4414. applyQuaternion( q ) {
  4415. this.quaternion.premultiply( q );
  4416. return this;
  4417. }
  4418. setRotationFromAxisAngle( axis, angle ) {
  4419. // assumes axis is normalized
  4420. this.quaternion.setFromAxisAngle( axis, angle );
  4421. }
  4422. setRotationFromEuler( euler ) {
  4423. this.quaternion.setFromEuler( euler, true );
  4424. }
  4425. setRotationFromMatrix( m ) {
  4426. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4427. this.quaternion.setFromRotationMatrix( m );
  4428. }
  4429. setRotationFromQuaternion( q ) {
  4430. // assumes q is normalized
  4431. this.quaternion.copy( q );
  4432. }
  4433. rotateOnAxis( axis, angle ) {
  4434. // rotate object on axis in object space
  4435. // axis is assumed to be normalized
  4436. _q1.setFromAxisAngle( axis, angle );
  4437. this.quaternion.multiply( _q1 );
  4438. return this;
  4439. }
  4440. rotateOnWorldAxis( axis, angle ) {
  4441. // rotate object on axis in world space
  4442. // axis is assumed to be normalized
  4443. // method assumes no rotated parent
  4444. _q1.setFromAxisAngle( axis, angle );
  4445. this.quaternion.premultiply( _q1 );
  4446. return this;
  4447. }
  4448. rotateX( angle ) {
  4449. return this.rotateOnAxis( _xAxis, angle );
  4450. }
  4451. rotateY( angle ) {
  4452. return this.rotateOnAxis( _yAxis, angle );
  4453. }
  4454. rotateZ( angle ) {
  4455. return this.rotateOnAxis( _zAxis, angle );
  4456. }
  4457. translateOnAxis( axis, distance ) {
  4458. // translate object by distance along axis in object space
  4459. // axis is assumed to be normalized
  4460. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4461. this.position.add( _v1$4.multiplyScalar( distance ) );
  4462. return this;
  4463. }
  4464. translateX( distance ) {
  4465. return this.translateOnAxis( _xAxis, distance );
  4466. }
  4467. translateY( distance ) {
  4468. return this.translateOnAxis( _yAxis, distance );
  4469. }
  4470. translateZ( distance ) {
  4471. return this.translateOnAxis( _zAxis, distance );
  4472. }
  4473. localToWorld( vector ) {
  4474. this.updateWorldMatrix( true, false );
  4475. return vector.applyMatrix4( this.matrixWorld );
  4476. }
  4477. worldToLocal( vector ) {
  4478. this.updateWorldMatrix( true, false );
  4479. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  4480. }
  4481. lookAt( x, y, z ) {
  4482. // This method does not support objects having non-uniformly-scaled parent(s)
  4483. if ( x.isVector3 ) {
  4484. _target.copy( x );
  4485. } else {
  4486. _target.set( x, y, z );
  4487. }
  4488. const parent = this.parent;
  4489. this.updateWorldMatrix( true, false );
  4490. _position$3.setFromMatrixPosition( this.matrixWorld );
  4491. if ( this.isCamera || this.isLight ) {
  4492. _m1$3.lookAt( _position$3, _target, this.up );
  4493. } else {
  4494. _m1$3.lookAt( _target, _position$3, this.up );
  4495. }
  4496. this.quaternion.setFromRotationMatrix( _m1$3 );
  4497. if ( parent ) {
  4498. _m1$3.extractRotation( parent.matrixWorld );
  4499. _q1.setFromRotationMatrix( _m1$3 );
  4500. this.quaternion.premultiply( _q1.invert() );
  4501. }
  4502. }
  4503. add( object ) {
  4504. if ( arguments.length > 1 ) {
  4505. for ( let i = 0; i < arguments.length; i ++ ) {
  4506. this.add( arguments[ i ] );
  4507. }
  4508. return this;
  4509. }
  4510. if ( object === this ) {
  4511. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4512. return this;
  4513. }
  4514. if ( object && object.isObject3D ) {
  4515. object.removeFromParent();
  4516. object.parent = this;
  4517. this.children.push( object );
  4518. object.dispatchEvent( _addedEvent );
  4519. _childaddedEvent.child = object;
  4520. this.dispatchEvent( _childaddedEvent );
  4521. _childaddedEvent.child = null;
  4522. } else {
  4523. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4524. }
  4525. return this;
  4526. }
  4527. remove( object ) {
  4528. if ( arguments.length > 1 ) {
  4529. for ( let i = 0; i < arguments.length; i ++ ) {
  4530. this.remove( arguments[ i ] );
  4531. }
  4532. return this;
  4533. }
  4534. const index = this.children.indexOf( object );
  4535. if ( index !== - 1 ) {
  4536. object.parent = null;
  4537. this.children.splice( index, 1 );
  4538. object.dispatchEvent( _removedEvent );
  4539. _childremovedEvent.child = object;
  4540. this.dispatchEvent( _childremovedEvent );
  4541. _childremovedEvent.child = null;
  4542. }
  4543. return this;
  4544. }
  4545. removeFromParent() {
  4546. const parent = this.parent;
  4547. if ( parent !== null ) {
  4548. parent.remove( this );
  4549. }
  4550. return this;
  4551. }
  4552. clear() {
  4553. return this.remove( ... this.children );
  4554. }
  4555. attach( object ) {
  4556. // adds object as a child of this, while maintaining the object's world transform
  4557. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4558. this.updateWorldMatrix( true, false );
  4559. _m1$3.copy( this.matrixWorld ).invert();
  4560. if ( object.parent !== null ) {
  4561. object.parent.updateWorldMatrix( true, false );
  4562. _m1$3.multiply( object.parent.matrixWorld );
  4563. }
  4564. object.applyMatrix4( _m1$3 );
  4565. object.removeFromParent();
  4566. object.parent = this;
  4567. this.children.push( object );
  4568. object.updateWorldMatrix( false, true );
  4569. object.dispatchEvent( _addedEvent );
  4570. _childaddedEvent.child = object;
  4571. this.dispatchEvent( _childaddedEvent );
  4572. _childaddedEvent.child = null;
  4573. return this;
  4574. }
  4575. getObjectById( id ) {
  4576. return this.getObjectByProperty( 'id', id );
  4577. }
  4578. getObjectByName( name ) {
  4579. return this.getObjectByProperty( 'name', name );
  4580. }
  4581. getObjectByProperty( name, value ) {
  4582. if ( this[ name ] === value ) return this;
  4583. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4584. const child = this.children[ i ];
  4585. const object = child.getObjectByProperty( name, value );
  4586. if ( object !== undefined ) {
  4587. return object;
  4588. }
  4589. }
  4590. return undefined;
  4591. }
  4592. getObjectsByProperty( name, value, result = [] ) {
  4593. if ( this[ name ] === value ) result.push( this );
  4594. const children = this.children;
  4595. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4596. children[ i ].getObjectsByProperty( name, value, result );
  4597. }
  4598. return result;
  4599. }
  4600. getWorldPosition( target ) {
  4601. this.updateWorldMatrix( true, false );
  4602. return target.setFromMatrixPosition( this.matrixWorld );
  4603. }
  4604. getWorldQuaternion( target ) {
  4605. this.updateWorldMatrix( true, false );
  4606. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4607. return target;
  4608. }
  4609. getWorldScale( target ) {
  4610. this.updateWorldMatrix( true, false );
  4611. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4612. return target;
  4613. }
  4614. getWorldDirection( target ) {
  4615. this.updateWorldMatrix( true, false );
  4616. const e = this.matrixWorld.elements;
  4617. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4618. }
  4619. raycast( /* raycaster, intersects */ ) {}
  4620. traverse( callback ) {
  4621. callback( this );
  4622. const children = this.children;
  4623. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4624. children[ i ].traverse( callback );
  4625. }
  4626. }
  4627. traverseVisible( callback ) {
  4628. if ( this.visible === false ) return;
  4629. callback( this );
  4630. const children = this.children;
  4631. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4632. children[ i ].traverseVisible( callback );
  4633. }
  4634. }
  4635. traverseAncestors( callback ) {
  4636. const parent = this.parent;
  4637. if ( parent !== null ) {
  4638. callback( parent );
  4639. parent.traverseAncestors( callback );
  4640. }
  4641. }
  4642. updateMatrix() {
  4643. this.matrix.compose( this.position, this.quaternion, this.scale );
  4644. this.matrixWorldNeedsUpdate = true;
  4645. }
  4646. updateMatrixWorld( force ) {
  4647. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4648. if ( this.matrixWorldNeedsUpdate || force ) {
  4649. if ( this.matrixWorldAutoUpdate === true ) {
  4650. if ( this.parent === null ) {
  4651. this.matrixWorld.copy( this.matrix );
  4652. } else {
  4653. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4654. }
  4655. }
  4656. this.matrixWorldNeedsUpdate = false;
  4657. force = true;
  4658. }
  4659. // make sure descendants are updated if required
  4660. const children = this.children;
  4661. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4662. const child = children[ i ];
  4663. child.updateMatrixWorld( force );
  4664. }
  4665. }
  4666. updateWorldMatrix( updateParents, updateChildren ) {
  4667. const parent = this.parent;
  4668. if ( updateParents === true && parent !== null ) {
  4669. parent.updateWorldMatrix( true, false );
  4670. }
  4671. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4672. if ( this.matrixWorldAutoUpdate === true ) {
  4673. if ( this.parent === null ) {
  4674. this.matrixWorld.copy( this.matrix );
  4675. } else {
  4676. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4677. }
  4678. }
  4679. // make sure descendants are updated
  4680. if ( updateChildren === true ) {
  4681. const children = this.children;
  4682. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4683. const child = children[ i ];
  4684. child.updateWorldMatrix( false, true );
  4685. }
  4686. }
  4687. }
  4688. toJSON( meta ) {
  4689. // meta is a string when called from JSON.stringify
  4690. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4691. const output = {};
  4692. // meta is a hash used to collect geometries, materials.
  4693. // not providing it implies that this is the root object
  4694. // being serialized.
  4695. if ( isRootObject ) {
  4696. // initialize meta obj
  4697. meta = {
  4698. geometries: {},
  4699. materials: {},
  4700. textures: {},
  4701. images: {},
  4702. shapes: {},
  4703. skeletons: {},
  4704. animations: {},
  4705. nodes: {}
  4706. };
  4707. output.metadata = {
  4708. version: 4.6,
  4709. type: 'Object',
  4710. generator: 'Object3D.toJSON'
  4711. };
  4712. }
  4713. // standard Object3D serialization
  4714. const object = {};
  4715. object.uuid = this.uuid;
  4716. object.type = this.type;
  4717. if ( this.name !== '' ) object.name = this.name;
  4718. if ( this.castShadow === true ) object.castShadow = true;
  4719. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4720. if ( this.visible === false ) object.visible = false;
  4721. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4722. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4723. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4724. object.layers = this.layers.mask;
  4725. object.matrix = this.matrix.toArray();
  4726. object.up = this.up.toArray();
  4727. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4728. // object specific properties
  4729. if ( this.isInstancedMesh ) {
  4730. object.type = 'InstancedMesh';
  4731. object.count = this.count;
  4732. object.instanceMatrix = this.instanceMatrix.toJSON();
  4733. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4734. }
  4735. if ( this.isBatchedMesh ) {
  4736. object.type = 'BatchedMesh';
  4737. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4738. object.sortObjects = this.sortObjects;
  4739. object.drawRanges = this._drawRanges;
  4740. object.reservedRanges = this._reservedRanges;
  4741. object.visibility = this._visibility;
  4742. object.active = this._active;
  4743. object.bounds = this._bounds.map( bound => ( {
  4744. boxInitialized: bound.boxInitialized,
  4745. boxMin: bound.box.min.toArray(),
  4746. boxMax: bound.box.max.toArray(),
  4747. sphereInitialized: bound.sphereInitialized,
  4748. sphereRadius: bound.sphere.radius,
  4749. sphereCenter: bound.sphere.center.toArray()
  4750. } ) );
  4751. object.maxInstanceCount = this._maxInstanceCount;
  4752. object.maxVertexCount = this._maxVertexCount;
  4753. object.maxIndexCount = this._maxIndexCount;
  4754. object.geometryInitialized = this._geometryInitialized;
  4755. object.geometryCount = this._geometryCount;
  4756. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4757. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4758. if ( this.boundingSphere !== null ) {
  4759. object.boundingSphere = {
  4760. center: object.boundingSphere.center.toArray(),
  4761. radius: object.boundingSphere.radius
  4762. };
  4763. }
  4764. if ( this.boundingBox !== null ) {
  4765. object.boundingBox = {
  4766. min: object.boundingBox.min.toArray(),
  4767. max: object.boundingBox.max.toArray()
  4768. };
  4769. }
  4770. }
  4771. //
  4772. function serialize( library, element ) {
  4773. if ( library[ element.uuid ] === undefined ) {
  4774. library[ element.uuid ] = element.toJSON( meta );
  4775. }
  4776. return element.uuid;
  4777. }
  4778. if ( this.isScene ) {
  4779. if ( this.background ) {
  4780. if ( this.background.isColor ) {
  4781. object.background = this.background.toJSON();
  4782. } else if ( this.background.isTexture ) {
  4783. object.background = this.background.toJSON( meta ).uuid;
  4784. }
  4785. }
  4786. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4787. object.environment = this.environment.toJSON( meta ).uuid;
  4788. }
  4789. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4790. object.geometry = serialize( meta.geometries, this.geometry );
  4791. const parameters = this.geometry.parameters;
  4792. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4793. const shapes = parameters.shapes;
  4794. if ( Array.isArray( shapes ) ) {
  4795. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4796. const shape = shapes[ i ];
  4797. serialize( meta.shapes, shape );
  4798. }
  4799. } else {
  4800. serialize( meta.shapes, shapes );
  4801. }
  4802. }
  4803. }
  4804. if ( this.isSkinnedMesh ) {
  4805. object.bindMode = this.bindMode;
  4806. object.bindMatrix = this.bindMatrix.toArray();
  4807. if ( this.skeleton !== undefined ) {
  4808. serialize( meta.skeletons, this.skeleton );
  4809. object.skeleton = this.skeleton.uuid;
  4810. }
  4811. }
  4812. if ( this.material !== undefined ) {
  4813. if ( Array.isArray( this.material ) ) {
  4814. const uuids = [];
  4815. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4816. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4817. }
  4818. object.material = uuids;
  4819. } else {
  4820. object.material = serialize( meta.materials, this.material );
  4821. }
  4822. }
  4823. //
  4824. if ( this.children.length > 0 ) {
  4825. object.children = [];
  4826. for ( let i = 0; i < this.children.length; i ++ ) {
  4827. object.children.push( this.children[ i ].toJSON( meta ).object );
  4828. }
  4829. }
  4830. //
  4831. if ( this.animations.length > 0 ) {
  4832. object.animations = [];
  4833. for ( let i = 0; i < this.animations.length; i ++ ) {
  4834. const animation = this.animations[ i ];
  4835. object.animations.push( serialize( meta.animations, animation ) );
  4836. }
  4837. }
  4838. if ( isRootObject ) {
  4839. const geometries = extractFromCache( meta.geometries );
  4840. const materials = extractFromCache( meta.materials );
  4841. const textures = extractFromCache( meta.textures );
  4842. const images = extractFromCache( meta.images );
  4843. const shapes = extractFromCache( meta.shapes );
  4844. const skeletons = extractFromCache( meta.skeletons );
  4845. const animations = extractFromCache( meta.animations );
  4846. const nodes = extractFromCache( meta.nodes );
  4847. if ( geometries.length > 0 ) output.geometries = geometries;
  4848. if ( materials.length > 0 ) output.materials = materials;
  4849. if ( textures.length > 0 ) output.textures = textures;
  4850. if ( images.length > 0 ) output.images = images;
  4851. if ( shapes.length > 0 ) output.shapes = shapes;
  4852. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4853. if ( animations.length > 0 ) output.animations = animations;
  4854. if ( nodes.length > 0 ) output.nodes = nodes;
  4855. }
  4856. output.object = object;
  4857. return output;
  4858. // extract data from the cache hash
  4859. // remove metadata on each item
  4860. // and return as array
  4861. function extractFromCache( cache ) {
  4862. const values = [];
  4863. for ( const key in cache ) {
  4864. const data = cache[ key ];
  4865. delete data.metadata;
  4866. values.push( data );
  4867. }
  4868. return values;
  4869. }
  4870. }
  4871. clone( recursive ) {
  4872. return new this.constructor().copy( this, recursive );
  4873. }
  4874. copy( source, recursive = true ) {
  4875. this.name = source.name;
  4876. this.up.copy( source.up );
  4877. this.position.copy( source.position );
  4878. this.rotation.order = source.rotation.order;
  4879. this.quaternion.copy( source.quaternion );
  4880. this.scale.copy( source.scale );
  4881. this.matrix.copy( source.matrix );
  4882. this.matrixWorld.copy( source.matrixWorld );
  4883. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4884. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4885. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4886. this.layers.mask = source.layers.mask;
  4887. this.visible = source.visible;
  4888. this.castShadow = source.castShadow;
  4889. this.receiveShadow = source.receiveShadow;
  4890. this.frustumCulled = source.frustumCulled;
  4891. this.renderOrder = source.renderOrder;
  4892. this.animations = source.animations.slice();
  4893. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4894. if ( recursive === true ) {
  4895. for ( let i = 0; i < source.children.length; i ++ ) {
  4896. const child = source.children[ i ];
  4897. this.add( child.clone() );
  4898. }
  4899. }
  4900. return this;
  4901. }
  4902. }
  4903. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4904. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4905. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4906. const _v0$2 = /*@__PURE__*/ new Vector3();
  4907. const _v1$3 = /*@__PURE__*/ new Vector3();
  4908. const _v2$2 = /*@__PURE__*/ new Vector3();
  4909. const _v3$2 = /*@__PURE__*/ new Vector3();
  4910. const _vab = /*@__PURE__*/ new Vector3();
  4911. const _vac = /*@__PURE__*/ new Vector3();
  4912. const _vbc = /*@__PURE__*/ new Vector3();
  4913. const _vap = /*@__PURE__*/ new Vector3();
  4914. const _vbp = /*@__PURE__*/ new Vector3();
  4915. const _vcp = /*@__PURE__*/ new Vector3();
  4916. class Triangle {
  4917. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4918. this.a = a;
  4919. this.b = b;
  4920. this.c = c;
  4921. }
  4922. static getNormal( a, b, c, target ) {
  4923. target.subVectors( c, b );
  4924. _v0$2.subVectors( a, b );
  4925. target.cross( _v0$2 );
  4926. const targetLengthSq = target.lengthSq();
  4927. if ( targetLengthSq > 0 ) {
  4928. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4929. }
  4930. return target.set( 0, 0, 0 );
  4931. }
  4932. // static/instance method to calculate barycentric coordinates
  4933. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4934. static getBarycoord( point, a, b, c, target ) {
  4935. _v0$2.subVectors( c, a );
  4936. _v1$3.subVectors( b, a );
  4937. _v2$2.subVectors( point, a );
  4938. const dot00 = _v0$2.dot( _v0$2 );
  4939. const dot01 = _v0$2.dot( _v1$3 );
  4940. const dot02 = _v0$2.dot( _v2$2 );
  4941. const dot11 = _v1$3.dot( _v1$3 );
  4942. const dot12 = _v1$3.dot( _v2$2 );
  4943. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4944. // collinear or singular triangle
  4945. if ( denom === 0 ) {
  4946. target.set( 0, 0, 0 );
  4947. return null;
  4948. }
  4949. const invDenom = 1 / denom;
  4950. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4951. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4952. // barycentric coordinates must always sum to 1
  4953. return target.set( 1 - u - v, v, u );
  4954. }
  4955. static containsPoint( point, a, b, c ) {
  4956. // if the triangle is degenerate then we can't contain a point
  4957. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4958. return false;
  4959. }
  4960. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4961. }
  4962. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4963. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4964. target.x = 0;
  4965. target.y = 0;
  4966. if ( 'z' in target ) target.z = 0;
  4967. if ( 'w' in target ) target.w = 0;
  4968. return null;
  4969. }
  4970. target.setScalar( 0 );
  4971. target.addScaledVector( v1, _v3$2.x );
  4972. target.addScaledVector( v2, _v3$2.y );
  4973. target.addScaledVector( v3, _v3$2.z );
  4974. return target;
  4975. }
  4976. static isFrontFacing( a, b, c, direction ) {
  4977. _v0$2.subVectors( c, b );
  4978. _v1$3.subVectors( a, b );
  4979. // strictly front facing
  4980. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4981. }
  4982. set( a, b, c ) {
  4983. this.a.copy( a );
  4984. this.b.copy( b );
  4985. this.c.copy( c );
  4986. return this;
  4987. }
  4988. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4989. this.a.copy( points[ i0 ] );
  4990. this.b.copy( points[ i1 ] );
  4991. this.c.copy( points[ i2 ] );
  4992. return this;
  4993. }
  4994. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4995. this.a.fromBufferAttribute( attribute, i0 );
  4996. this.b.fromBufferAttribute( attribute, i1 );
  4997. this.c.fromBufferAttribute( attribute, i2 );
  4998. return this;
  4999. }
  5000. clone() {
  5001. return new this.constructor().copy( this );
  5002. }
  5003. copy( triangle ) {
  5004. this.a.copy( triangle.a );
  5005. this.b.copy( triangle.b );
  5006. this.c.copy( triangle.c );
  5007. return this;
  5008. }
  5009. getArea() {
  5010. _v0$2.subVectors( this.c, this.b );
  5011. _v1$3.subVectors( this.a, this.b );
  5012. return _v0$2.cross( _v1$3 ).length() * 0.5;
  5013. }
  5014. getMidpoint( target ) {
  5015. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5016. }
  5017. getNormal( target ) {
  5018. return Triangle.getNormal( this.a, this.b, this.c, target );
  5019. }
  5020. getPlane( target ) {
  5021. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5022. }
  5023. getBarycoord( point, target ) {
  5024. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5025. }
  5026. getInterpolation( point, v1, v2, v3, target ) {
  5027. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5028. }
  5029. containsPoint( point ) {
  5030. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5031. }
  5032. isFrontFacing( direction ) {
  5033. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5034. }
  5035. intersectsBox( box ) {
  5036. return box.intersectsTriangle( this );
  5037. }
  5038. closestPointToPoint( p, target ) {
  5039. const a = this.a, b = this.b, c = this.c;
  5040. let v, w;
  5041. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5042. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5043. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5044. // basically, we're distinguishing which of the voronoi regions of the triangle
  5045. // the point lies in with the minimum amount of redundant computation.
  5046. _vab.subVectors( b, a );
  5047. _vac.subVectors( c, a );
  5048. _vap.subVectors( p, a );
  5049. const d1 = _vab.dot( _vap );
  5050. const d2 = _vac.dot( _vap );
  5051. if ( d1 <= 0 && d2 <= 0 ) {
  5052. // vertex region of A; barycentric coords (1, 0, 0)
  5053. return target.copy( a );
  5054. }
  5055. _vbp.subVectors( p, b );
  5056. const d3 = _vab.dot( _vbp );
  5057. const d4 = _vac.dot( _vbp );
  5058. if ( d3 >= 0 && d4 <= d3 ) {
  5059. // vertex region of B; barycentric coords (0, 1, 0)
  5060. return target.copy( b );
  5061. }
  5062. const vc = d1 * d4 - d3 * d2;
  5063. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5064. v = d1 / ( d1 - d3 );
  5065. // edge region of AB; barycentric coords (1-v, v, 0)
  5066. return target.copy( a ).addScaledVector( _vab, v );
  5067. }
  5068. _vcp.subVectors( p, c );
  5069. const d5 = _vab.dot( _vcp );
  5070. const d6 = _vac.dot( _vcp );
  5071. if ( d6 >= 0 && d5 <= d6 ) {
  5072. // vertex region of C; barycentric coords (0, 0, 1)
  5073. return target.copy( c );
  5074. }
  5075. const vb = d5 * d2 - d1 * d6;
  5076. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5077. w = d2 / ( d2 - d6 );
  5078. // edge region of AC; barycentric coords (1-w, 0, w)
  5079. return target.copy( a ).addScaledVector( _vac, w );
  5080. }
  5081. const va = d3 * d6 - d5 * d4;
  5082. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5083. _vbc.subVectors( c, b );
  5084. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5085. // edge region of BC; barycentric coords (0, 1-w, w)
  5086. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5087. }
  5088. // face region
  5089. const denom = 1 / ( va + vb + vc );
  5090. // u = va * denom
  5091. v = vb * denom;
  5092. w = vc * denom;
  5093. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5094. }
  5095. equals( triangle ) {
  5096. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5097. }
  5098. }
  5099. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5100. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5101. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5102. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5103. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5104. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5105. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5106. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5107. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5108. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5109. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5110. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5111. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5112. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5113. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5114. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5115. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5116. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5117. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5118. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5119. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5120. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5121. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5122. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5123. const _hslA = { h: 0, s: 0, l: 0 };
  5124. const _hslB = { h: 0, s: 0, l: 0 };
  5125. function hue2rgb( p, q, t ) {
  5126. if ( t < 0 ) t += 1;
  5127. if ( t > 1 ) t -= 1;
  5128. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5129. if ( t < 1 / 2 ) return q;
  5130. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5131. return p;
  5132. }
  5133. class Color {
  5134. constructor( r, g, b ) {
  5135. this.isColor = true;
  5136. this.r = 1;
  5137. this.g = 1;
  5138. this.b = 1;
  5139. return this.set( r, g, b );
  5140. }
  5141. set( r, g, b ) {
  5142. if ( g === undefined && b === undefined ) {
  5143. // r is THREE.Color, hex or string
  5144. const value = r;
  5145. if ( value && value.isColor ) {
  5146. this.copy( value );
  5147. } else if ( typeof value === 'number' ) {
  5148. this.setHex( value );
  5149. } else if ( typeof value === 'string' ) {
  5150. this.setStyle( value );
  5151. }
  5152. } else {
  5153. this.setRGB( r, g, b );
  5154. }
  5155. return this;
  5156. }
  5157. setScalar( scalar ) {
  5158. this.r = scalar;
  5159. this.g = scalar;
  5160. this.b = scalar;
  5161. return this;
  5162. }
  5163. setHex( hex, colorSpace = SRGBColorSpace ) {
  5164. hex = Math.floor( hex );
  5165. this.r = ( hex >> 16 & 255 ) / 255;
  5166. this.g = ( hex >> 8 & 255 ) / 255;
  5167. this.b = ( hex & 255 ) / 255;
  5168. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5169. return this;
  5170. }
  5171. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5172. this.r = r;
  5173. this.g = g;
  5174. this.b = b;
  5175. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5176. return this;
  5177. }
  5178. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5179. // h,s,l ranges are in 0.0 - 1.0
  5180. h = euclideanModulo( h, 1 );
  5181. s = clamp( s, 0, 1 );
  5182. l = clamp( l, 0, 1 );
  5183. if ( s === 0 ) {
  5184. this.r = this.g = this.b = l;
  5185. } else {
  5186. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5187. const q = ( 2 * l ) - p;
  5188. this.r = hue2rgb( q, p, h + 1 / 3 );
  5189. this.g = hue2rgb( q, p, h );
  5190. this.b = hue2rgb( q, p, h - 1 / 3 );
  5191. }
  5192. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5193. return this;
  5194. }
  5195. setStyle( style, colorSpace = SRGBColorSpace ) {
  5196. function handleAlpha( string ) {
  5197. if ( string === undefined ) return;
  5198. if ( parseFloat( string ) < 1 ) {
  5199. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5200. }
  5201. }
  5202. let m;
  5203. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5204. // rgb / hsl
  5205. let color;
  5206. const name = m[ 1 ];
  5207. const components = m[ 2 ];
  5208. switch ( name ) {
  5209. case 'rgb':
  5210. case 'rgba':
  5211. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5212. // rgb(255,0,0) rgba(255,0,0,0.5)
  5213. handleAlpha( color[ 4 ] );
  5214. return this.setRGB(
  5215. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5216. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5217. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5218. colorSpace
  5219. );
  5220. }
  5221. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5222. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5223. handleAlpha( color[ 4 ] );
  5224. return this.setRGB(
  5225. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5226. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5227. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5228. colorSpace
  5229. );
  5230. }
  5231. break;
  5232. case 'hsl':
  5233. case 'hsla':
  5234. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5235. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5236. handleAlpha( color[ 4 ] );
  5237. return this.setHSL(
  5238. parseFloat( color[ 1 ] ) / 360,
  5239. parseFloat( color[ 2 ] ) / 100,
  5240. parseFloat( color[ 3 ] ) / 100,
  5241. colorSpace
  5242. );
  5243. }
  5244. break;
  5245. default:
  5246. console.warn( 'THREE.Color: Unknown color model ' + style );
  5247. }
  5248. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5249. // hex color
  5250. const hex = m[ 1 ];
  5251. const size = hex.length;
  5252. if ( size === 3 ) {
  5253. // #ff0
  5254. return this.setRGB(
  5255. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5256. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5257. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5258. colorSpace
  5259. );
  5260. } else if ( size === 6 ) {
  5261. // #ff0000
  5262. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5263. } else {
  5264. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5265. }
  5266. } else if ( style && style.length > 0 ) {
  5267. return this.setColorName( style, colorSpace );
  5268. }
  5269. return this;
  5270. }
  5271. setColorName( style, colorSpace = SRGBColorSpace ) {
  5272. // color keywords
  5273. const hex = _colorKeywords[ style.toLowerCase() ];
  5274. if ( hex !== undefined ) {
  5275. // red
  5276. this.setHex( hex, colorSpace );
  5277. } else {
  5278. // unknown color
  5279. console.warn( 'THREE.Color: Unknown color ' + style );
  5280. }
  5281. return this;
  5282. }
  5283. clone() {
  5284. return new this.constructor( this.r, this.g, this.b );
  5285. }
  5286. copy( color ) {
  5287. this.r = color.r;
  5288. this.g = color.g;
  5289. this.b = color.b;
  5290. return this;
  5291. }
  5292. copySRGBToLinear( color ) {
  5293. this.r = SRGBToLinear( color.r );
  5294. this.g = SRGBToLinear( color.g );
  5295. this.b = SRGBToLinear( color.b );
  5296. return this;
  5297. }
  5298. copyLinearToSRGB( color ) {
  5299. this.r = LinearToSRGB( color.r );
  5300. this.g = LinearToSRGB( color.g );
  5301. this.b = LinearToSRGB( color.b );
  5302. return this;
  5303. }
  5304. convertSRGBToLinear() {
  5305. this.copySRGBToLinear( this );
  5306. return this;
  5307. }
  5308. convertLinearToSRGB() {
  5309. this.copyLinearToSRGB( this );
  5310. return this;
  5311. }
  5312. getHex( colorSpace = SRGBColorSpace ) {
  5313. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5314. 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 ) );
  5315. }
  5316. getHexString( colorSpace = SRGBColorSpace ) {
  5317. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5318. }
  5319. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5320. // h,s,l ranges are in 0.0 - 1.0
  5321. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5322. const r = _color.r, g = _color.g, b = _color.b;
  5323. const max = Math.max( r, g, b );
  5324. const min = Math.min( r, g, b );
  5325. let hue, saturation;
  5326. const lightness = ( min + max ) / 2.0;
  5327. if ( min === max ) {
  5328. hue = 0;
  5329. saturation = 0;
  5330. } else {
  5331. const delta = max - min;
  5332. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5333. switch ( max ) {
  5334. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5335. case g: hue = ( b - r ) / delta + 2; break;
  5336. case b: hue = ( r - g ) / delta + 4; break;
  5337. }
  5338. hue /= 6;
  5339. }
  5340. target.h = hue;
  5341. target.s = saturation;
  5342. target.l = lightness;
  5343. return target;
  5344. }
  5345. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5346. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5347. target.r = _color.r;
  5348. target.g = _color.g;
  5349. target.b = _color.b;
  5350. return target;
  5351. }
  5352. getStyle( colorSpace = SRGBColorSpace ) {
  5353. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5354. const r = _color.r, g = _color.g, b = _color.b;
  5355. if ( colorSpace !== SRGBColorSpace ) {
  5356. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5357. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5358. }
  5359. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5360. }
  5361. offsetHSL( h, s, l ) {
  5362. this.getHSL( _hslA );
  5363. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5364. }
  5365. add( color ) {
  5366. this.r += color.r;
  5367. this.g += color.g;
  5368. this.b += color.b;
  5369. return this;
  5370. }
  5371. addColors( color1, color2 ) {
  5372. this.r = color1.r + color2.r;
  5373. this.g = color1.g + color2.g;
  5374. this.b = color1.b + color2.b;
  5375. return this;
  5376. }
  5377. addScalar( s ) {
  5378. this.r += s;
  5379. this.g += s;
  5380. this.b += s;
  5381. return this;
  5382. }
  5383. sub( color ) {
  5384. this.r = Math.max( 0, this.r - color.r );
  5385. this.g = Math.max( 0, this.g - color.g );
  5386. this.b = Math.max( 0, this.b - color.b );
  5387. return this;
  5388. }
  5389. multiply( color ) {
  5390. this.r *= color.r;
  5391. this.g *= color.g;
  5392. this.b *= color.b;
  5393. return this;
  5394. }
  5395. multiplyScalar( s ) {
  5396. this.r *= s;
  5397. this.g *= s;
  5398. this.b *= s;
  5399. return this;
  5400. }
  5401. lerp( color, alpha ) {
  5402. this.r += ( color.r - this.r ) * alpha;
  5403. this.g += ( color.g - this.g ) * alpha;
  5404. this.b += ( color.b - this.b ) * alpha;
  5405. return this;
  5406. }
  5407. lerpColors( color1, color2, alpha ) {
  5408. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5409. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5410. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5411. return this;
  5412. }
  5413. lerpHSL( color, alpha ) {
  5414. this.getHSL( _hslA );
  5415. color.getHSL( _hslB );
  5416. const h = lerp( _hslA.h, _hslB.h, alpha );
  5417. const s = lerp( _hslA.s, _hslB.s, alpha );
  5418. const l = lerp( _hslA.l, _hslB.l, alpha );
  5419. this.setHSL( h, s, l );
  5420. return this;
  5421. }
  5422. setFromVector3( v ) {
  5423. this.r = v.x;
  5424. this.g = v.y;
  5425. this.b = v.z;
  5426. return this;
  5427. }
  5428. applyMatrix3( m ) {
  5429. const r = this.r, g = this.g, b = this.b;
  5430. const e = m.elements;
  5431. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5432. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5433. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5434. return this;
  5435. }
  5436. equals( c ) {
  5437. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5438. }
  5439. fromArray( array, offset = 0 ) {
  5440. this.r = array[ offset ];
  5441. this.g = array[ offset + 1 ];
  5442. this.b = array[ offset + 2 ];
  5443. return this;
  5444. }
  5445. toArray( array = [], offset = 0 ) {
  5446. array[ offset ] = this.r;
  5447. array[ offset + 1 ] = this.g;
  5448. array[ offset + 2 ] = this.b;
  5449. return array;
  5450. }
  5451. fromBufferAttribute( attribute, index ) {
  5452. this.r = attribute.getX( index );
  5453. this.g = attribute.getY( index );
  5454. this.b = attribute.getZ( index );
  5455. return this;
  5456. }
  5457. toJSON() {
  5458. return this.getHex();
  5459. }
  5460. *[ Symbol.iterator ]() {
  5461. yield this.r;
  5462. yield this.g;
  5463. yield this.b;
  5464. }
  5465. }
  5466. const _color = /*@__PURE__*/ new Color();
  5467. Color.NAMES = _colorKeywords;
  5468. let _materialId = 0;
  5469. class Material extends EventDispatcher {
  5470. constructor() {
  5471. super();
  5472. this.isMaterial = true;
  5473. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5474. this.uuid = generateUUID();
  5475. this.name = '';
  5476. this.type = 'Material';
  5477. this.blending = NormalBlending;
  5478. this.side = FrontSide;
  5479. this.vertexColors = false;
  5480. this.opacity = 1;
  5481. this.transparent = false;
  5482. this.alphaHash = false;
  5483. this.blendSrc = SrcAlphaFactor;
  5484. this.blendDst = OneMinusSrcAlphaFactor;
  5485. this.blendEquation = AddEquation;
  5486. this.blendSrcAlpha = null;
  5487. this.blendDstAlpha = null;
  5488. this.blendEquationAlpha = null;
  5489. this.blendColor = new Color( 0, 0, 0 );
  5490. this.blendAlpha = 0;
  5491. this.depthFunc = LessEqualDepth;
  5492. this.depthTest = true;
  5493. this.depthWrite = true;
  5494. this.stencilWriteMask = 0xff;
  5495. this.stencilFunc = AlwaysStencilFunc;
  5496. this.stencilRef = 0;
  5497. this.stencilFuncMask = 0xff;
  5498. this.stencilFail = KeepStencilOp;
  5499. this.stencilZFail = KeepStencilOp;
  5500. this.stencilZPass = KeepStencilOp;
  5501. this.stencilWrite = false;
  5502. this.clippingPlanes = null;
  5503. this.clipIntersection = false;
  5504. this.clipShadows = false;
  5505. this.shadowSide = null;
  5506. this.colorWrite = true;
  5507. this.precision = null; // override the renderer's default precision for this material
  5508. this.polygonOffset = false;
  5509. this.polygonOffsetFactor = 0;
  5510. this.polygonOffsetUnits = 0;
  5511. this.dithering = false;
  5512. this.alphaToCoverage = false;
  5513. this.premultipliedAlpha = false;
  5514. this.forceSinglePass = false;
  5515. this.visible = true;
  5516. this.toneMapped = true;
  5517. this.userData = {};
  5518. this.version = 0;
  5519. this._alphaTest = 0;
  5520. }
  5521. get alphaTest() {
  5522. return this._alphaTest;
  5523. }
  5524. set alphaTest( value ) {
  5525. if ( this._alphaTest > 0 !== value > 0 ) {
  5526. this.version ++;
  5527. }
  5528. this._alphaTest = value;
  5529. }
  5530. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5531. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5532. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5533. customProgramCacheKey() {
  5534. return this.onBeforeCompile.toString();
  5535. }
  5536. setValues( values ) {
  5537. if ( values === undefined ) return;
  5538. for ( const key in values ) {
  5539. const newValue = values[ key ];
  5540. if ( newValue === undefined ) {
  5541. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5542. continue;
  5543. }
  5544. const currentValue = this[ key ];
  5545. if ( currentValue === undefined ) {
  5546. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5547. continue;
  5548. }
  5549. if ( currentValue && currentValue.isColor ) {
  5550. currentValue.set( newValue );
  5551. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5552. currentValue.copy( newValue );
  5553. } else {
  5554. this[ key ] = newValue;
  5555. }
  5556. }
  5557. }
  5558. toJSON( meta ) {
  5559. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5560. if ( isRootObject ) {
  5561. meta = {
  5562. textures: {},
  5563. images: {}
  5564. };
  5565. }
  5566. const data = {
  5567. metadata: {
  5568. version: 4.6,
  5569. type: 'Material',
  5570. generator: 'Material.toJSON'
  5571. }
  5572. };
  5573. // standard Material serialization
  5574. data.uuid = this.uuid;
  5575. data.type = this.type;
  5576. if ( this.name !== '' ) data.name = this.name;
  5577. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5578. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5579. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5580. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5581. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5582. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5583. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5584. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5585. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5586. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5587. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5588. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5589. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5590. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5591. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5592. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5593. }
  5594. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5595. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5596. }
  5597. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5598. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5599. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5600. }
  5601. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5602. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5603. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5604. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5605. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5606. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5607. }
  5608. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5609. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5610. }
  5611. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5612. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5613. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5614. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5615. }
  5616. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5617. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5618. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5619. if ( this.lightMap && this.lightMap.isTexture ) {
  5620. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5621. data.lightMapIntensity = this.lightMapIntensity;
  5622. }
  5623. if ( this.aoMap && this.aoMap.isTexture ) {
  5624. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5625. data.aoMapIntensity = this.aoMapIntensity;
  5626. }
  5627. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5628. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5629. data.bumpScale = this.bumpScale;
  5630. }
  5631. if ( this.normalMap && this.normalMap.isTexture ) {
  5632. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5633. data.normalMapType = this.normalMapType;
  5634. data.normalScale = this.normalScale.toArray();
  5635. }
  5636. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5637. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5638. data.displacementScale = this.displacementScale;
  5639. data.displacementBias = this.displacementBias;
  5640. }
  5641. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5642. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5643. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5644. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5645. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5646. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5647. if ( this.envMap && this.envMap.isTexture ) {
  5648. data.envMap = this.envMap.toJSON( meta ).uuid;
  5649. if ( this.combine !== undefined ) data.combine = this.combine;
  5650. }
  5651. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5652. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5653. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5654. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5655. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5656. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5657. }
  5658. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5659. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5660. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5661. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5662. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5663. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5664. if ( this.size !== undefined ) data.size = this.size;
  5665. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5666. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5667. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5668. if ( this.side !== FrontSide ) data.side = this.side;
  5669. if ( this.vertexColors === true ) data.vertexColors = true;
  5670. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5671. if ( this.transparent === true ) data.transparent = true;
  5672. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5673. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5674. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5675. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5676. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5677. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5678. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5679. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5680. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5681. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5682. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5683. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5684. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5685. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5686. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5687. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5688. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5689. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5690. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5691. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5692. // rotation (SpriteMaterial)
  5693. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5694. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5695. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5696. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5697. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5698. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5699. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5700. if ( this.scale !== undefined ) data.scale = this.scale;
  5701. if ( this.dithering === true ) data.dithering = true;
  5702. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5703. if ( this.alphaHash === true ) data.alphaHash = true;
  5704. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5705. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5706. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5707. if ( this.wireframe === true ) data.wireframe = true;
  5708. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5709. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5710. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5711. if ( this.flatShading === true ) data.flatShading = true;
  5712. if ( this.visible === false ) data.visible = false;
  5713. if ( this.toneMapped === false ) data.toneMapped = false;
  5714. if ( this.fog === false ) data.fog = false;
  5715. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5716. // TODO: Copied from Object3D.toJSON
  5717. function extractFromCache( cache ) {
  5718. const values = [];
  5719. for ( const key in cache ) {
  5720. const data = cache[ key ];
  5721. delete data.metadata;
  5722. values.push( data );
  5723. }
  5724. return values;
  5725. }
  5726. if ( isRootObject ) {
  5727. const textures = extractFromCache( meta.textures );
  5728. const images = extractFromCache( meta.images );
  5729. if ( textures.length > 0 ) data.textures = textures;
  5730. if ( images.length > 0 ) data.images = images;
  5731. }
  5732. return data;
  5733. }
  5734. clone() {
  5735. return new this.constructor().copy( this );
  5736. }
  5737. copy( source ) {
  5738. this.name = source.name;
  5739. this.blending = source.blending;
  5740. this.side = source.side;
  5741. this.vertexColors = source.vertexColors;
  5742. this.opacity = source.opacity;
  5743. this.transparent = source.transparent;
  5744. this.blendSrc = source.blendSrc;
  5745. this.blendDst = source.blendDst;
  5746. this.blendEquation = source.blendEquation;
  5747. this.blendSrcAlpha = source.blendSrcAlpha;
  5748. this.blendDstAlpha = source.blendDstAlpha;
  5749. this.blendEquationAlpha = source.blendEquationAlpha;
  5750. this.blendColor.copy( source.blendColor );
  5751. this.blendAlpha = source.blendAlpha;
  5752. this.depthFunc = source.depthFunc;
  5753. this.depthTest = source.depthTest;
  5754. this.depthWrite = source.depthWrite;
  5755. this.stencilWriteMask = source.stencilWriteMask;
  5756. this.stencilFunc = source.stencilFunc;
  5757. this.stencilRef = source.stencilRef;
  5758. this.stencilFuncMask = source.stencilFuncMask;
  5759. this.stencilFail = source.stencilFail;
  5760. this.stencilZFail = source.stencilZFail;
  5761. this.stencilZPass = source.stencilZPass;
  5762. this.stencilWrite = source.stencilWrite;
  5763. const srcPlanes = source.clippingPlanes;
  5764. let dstPlanes = null;
  5765. if ( srcPlanes !== null ) {
  5766. const n = srcPlanes.length;
  5767. dstPlanes = new Array( n );
  5768. for ( let i = 0; i !== n; ++ i ) {
  5769. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5770. }
  5771. }
  5772. this.clippingPlanes = dstPlanes;
  5773. this.clipIntersection = source.clipIntersection;
  5774. this.clipShadows = source.clipShadows;
  5775. this.shadowSide = source.shadowSide;
  5776. this.colorWrite = source.colorWrite;
  5777. this.precision = source.precision;
  5778. this.polygonOffset = source.polygonOffset;
  5779. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5780. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5781. this.dithering = source.dithering;
  5782. this.alphaTest = source.alphaTest;
  5783. this.alphaHash = source.alphaHash;
  5784. this.alphaToCoverage = source.alphaToCoverage;
  5785. this.premultipliedAlpha = source.premultipliedAlpha;
  5786. this.forceSinglePass = source.forceSinglePass;
  5787. this.visible = source.visible;
  5788. this.toneMapped = source.toneMapped;
  5789. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5790. return this;
  5791. }
  5792. dispose() {
  5793. this.dispatchEvent( { type: 'dispose' } );
  5794. }
  5795. set needsUpdate( value ) {
  5796. if ( value === true ) this.version ++;
  5797. }
  5798. onBuild( /* shaderobject, renderer */ ) {
  5799. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5800. }
  5801. }
  5802. class MeshBasicMaterial extends Material {
  5803. constructor( parameters ) {
  5804. super();
  5805. this.isMeshBasicMaterial = true;
  5806. this.type = 'MeshBasicMaterial';
  5807. this.color = new Color( 0xffffff ); // emissive
  5808. this.map = null;
  5809. this.lightMap = null;
  5810. this.lightMapIntensity = 1.0;
  5811. this.aoMap = null;
  5812. this.aoMapIntensity = 1.0;
  5813. this.specularMap = null;
  5814. this.alphaMap = null;
  5815. this.envMap = null;
  5816. this.envMapRotation = new Euler();
  5817. this.combine = MultiplyOperation;
  5818. this.reflectivity = 1;
  5819. this.refractionRatio = 0.98;
  5820. this.wireframe = false;
  5821. this.wireframeLinewidth = 1;
  5822. this.wireframeLinecap = 'round';
  5823. this.wireframeLinejoin = 'round';
  5824. this.fog = true;
  5825. this.setValues( parameters );
  5826. }
  5827. copy( source ) {
  5828. super.copy( source );
  5829. this.color.copy( source.color );
  5830. this.map = source.map;
  5831. this.lightMap = source.lightMap;
  5832. this.lightMapIntensity = source.lightMapIntensity;
  5833. this.aoMap = source.aoMap;
  5834. this.aoMapIntensity = source.aoMapIntensity;
  5835. this.specularMap = source.specularMap;
  5836. this.alphaMap = source.alphaMap;
  5837. this.envMap = source.envMap;
  5838. this.envMapRotation.copy( source.envMapRotation );
  5839. this.combine = source.combine;
  5840. this.reflectivity = source.reflectivity;
  5841. this.refractionRatio = source.refractionRatio;
  5842. this.wireframe = source.wireframe;
  5843. this.wireframeLinewidth = source.wireframeLinewidth;
  5844. this.wireframeLinecap = source.wireframeLinecap;
  5845. this.wireframeLinejoin = source.wireframeLinejoin;
  5846. this.fog = source.fog;
  5847. return this;
  5848. }
  5849. }
  5850. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5851. const _tables = /*@__PURE__*/ _generateTables();
  5852. function _generateTables() {
  5853. // float32 to float16 helpers
  5854. const buffer = new ArrayBuffer( 4 );
  5855. const floatView = new Float32Array( buffer );
  5856. const uint32View = new Uint32Array( buffer );
  5857. const baseTable = new Uint32Array( 512 );
  5858. const shiftTable = new Uint32Array( 512 );
  5859. for ( let i = 0; i < 256; ++ i ) {
  5860. const e = i - 127;
  5861. // very small number (0, -0)
  5862. if ( e < - 27 ) {
  5863. baseTable[ i ] = 0x0000;
  5864. baseTable[ i | 0x100 ] = 0x8000;
  5865. shiftTable[ i ] = 24;
  5866. shiftTable[ i | 0x100 ] = 24;
  5867. // small number (denorm)
  5868. } else if ( e < - 14 ) {
  5869. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5870. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5871. shiftTable[ i ] = - e - 1;
  5872. shiftTable[ i | 0x100 ] = - e - 1;
  5873. // normal number
  5874. } else if ( e <= 15 ) {
  5875. baseTable[ i ] = ( e + 15 ) << 10;
  5876. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5877. shiftTable[ i ] = 13;
  5878. shiftTable[ i | 0x100 ] = 13;
  5879. // large number (Infinity, -Infinity)
  5880. } else if ( e < 128 ) {
  5881. baseTable[ i ] = 0x7c00;
  5882. baseTable[ i | 0x100 ] = 0xfc00;
  5883. shiftTable[ i ] = 24;
  5884. shiftTable[ i | 0x100 ] = 24;
  5885. // stay (NaN, Infinity, -Infinity)
  5886. } else {
  5887. baseTable[ i ] = 0x7c00;
  5888. baseTable[ i | 0x100 ] = 0xfc00;
  5889. shiftTable[ i ] = 13;
  5890. shiftTable[ i | 0x100 ] = 13;
  5891. }
  5892. }
  5893. // float16 to float32 helpers
  5894. const mantissaTable = new Uint32Array( 2048 );
  5895. const exponentTable = new Uint32Array( 64 );
  5896. const offsetTable = new Uint32Array( 64 );
  5897. for ( let i = 1; i < 1024; ++ i ) {
  5898. let m = i << 13; // zero pad mantissa bits
  5899. let e = 0; // zero exponent
  5900. // normalized
  5901. while ( ( m & 0x00800000 ) === 0 ) {
  5902. m <<= 1;
  5903. e -= 0x00800000; // decrement exponent
  5904. }
  5905. m &= ~ 0x00800000; // clear leading 1 bit
  5906. e += 0x38800000; // adjust bias
  5907. mantissaTable[ i ] = m | e;
  5908. }
  5909. for ( let i = 1024; i < 2048; ++ i ) {
  5910. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5911. }
  5912. for ( let i = 1; i < 31; ++ i ) {
  5913. exponentTable[ i ] = i << 23;
  5914. }
  5915. exponentTable[ 31 ] = 0x47800000;
  5916. exponentTable[ 32 ] = 0x80000000;
  5917. for ( let i = 33; i < 63; ++ i ) {
  5918. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5919. }
  5920. exponentTable[ 63 ] = 0xc7800000;
  5921. for ( let i = 1; i < 64; ++ i ) {
  5922. if ( i !== 32 ) {
  5923. offsetTable[ i ] = 1024;
  5924. }
  5925. }
  5926. return {
  5927. floatView: floatView,
  5928. uint32View: uint32View,
  5929. baseTable: baseTable,
  5930. shiftTable: shiftTable,
  5931. mantissaTable: mantissaTable,
  5932. exponentTable: exponentTable,
  5933. offsetTable: offsetTable
  5934. };
  5935. }
  5936. // float32 to float16
  5937. function toHalfFloat( val ) {
  5938. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5939. val = clamp( val, - 65504, 65504 );
  5940. _tables.floatView[ 0 ] = val;
  5941. const f = _tables.uint32View[ 0 ];
  5942. const e = ( f >> 23 ) & 0x1ff;
  5943. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5944. }
  5945. // float16 to float32
  5946. function fromHalfFloat( val ) {
  5947. const m = val >> 10;
  5948. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5949. return _tables.floatView[ 0 ];
  5950. }
  5951. const DataUtils = {
  5952. toHalfFloat: toHalfFloat,
  5953. fromHalfFloat: fromHalfFloat,
  5954. };
  5955. const _vector$9 = /*@__PURE__*/ new Vector3();
  5956. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5957. class BufferAttribute {
  5958. constructor( array, itemSize, normalized = false ) {
  5959. if ( Array.isArray( array ) ) {
  5960. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5961. }
  5962. this.isBufferAttribute = true;
  5963. this.name = '';
  5964. this.array = array;
  5965. this.itemSize = itemSize;
  5966. this.count = array !== undefined ? array.length / itemSize : 0;
  5967. this.normalized = normalized;
  5968. this.usage = StaticDrawUsage;
  5969. this.updateRanges = [];
  5970. this.gpuType = FloatType;
  5971. this.version = 0;
  5972. }
  5973. onUploadCallback() {}
  5974. set needsUpdate( value ) {
  5975. if ( value === true ) this.version ++;
  5976. }
  5977. setUsage( value ) {
  5978. this.usage = value;
  5979. return this;
  5980. }
  5981. addUpdateRange( start, count ) {
  5982. this.updateRanges.push( { start, count } );
  5983. }
  5984. clearUpdateRanges() {
  5985. this.updateRanges.length = 0;
  5986. }
  5987. copy( source ) {
  5988. this.name = source.name;
  5989. this.array = new source.array.constructor( source.array );
  5990. this.itemSize = source.itemSize;
  5991. this.count = source.count;
  5992. this.normalized = source.normalized;
  5993. this.usage = source.usage;
  5994. this.gpuType = source.gpuType;
  5995. return this;
  5996. }
  5997. copyAt( index1, attribute, index2 ) {
  5998. index1 *= this.itemSize;
  5999. index2 *= attribute.itemSize;
  6000. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6001. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6002. }
  6003. return this;
  6004. }
  6005. copyArray( array ) {
  6006. this.array.set( array );
  6007. return this;
  6008. }
  6009. applyMatrix3( m ) {
  6010. if ( this.itemSize === 2 ) {
  6011. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6012. _vector2$1.fromBufferAttribute( this, i );
  6013. _vector2$1.applyMatrix3( m );
  6014. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6015. }
  6016. } else if ( this.itemSize === 3 ) {
  6017. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6018. _vector$9.fromBufferAttribute( this, i );
  6019. _vector$9.applyMatrix3( m );
  6020. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6021. }
  6022. }
  6023. return this;
  6024. }
  6025. applyMatrix4( m ) {
  6026. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6027. _vector$9.fromBufferAttribute( this, i );
  6028. _vector$9.applyMatrix4( m );
  6029. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6030. }
  6031. return this;
  6032. }
  6033. applyNormalMatrix( m ) {
  6034. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6035. _vector$9.fromBufferAttribute( this, i );
  6036. _vector$9.applyNormalMatrix( m );
  6037. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6038. }
  6039. return this;
  6040. }
  6041. transformDirection( m ) {
  6042. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6043. _vector$9.fromBufferAttribute( this, i );
  6044. _vector$9.transformDirection( m );
  6045. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6046. }
  6047. return this;
  6048. }
  6049. set( value, offset = 0 ) {
  6050. // Matching BufferAttribute constructor, do not normalize the array.
  6051. this.array.set( value, offset );
  6052. return this;
  6053. }
  6054. getComponent( index, component ) {
  6055. let value = this.array[ index * this.itemSize + component ];
  6056. if ( this.normalized ) value = denormalize( value, this.array );
  6057. return value;
  6058. }
  6059. setComponent( index, component, value ) {
  6060. if ( this.normalized ) value = normalize( value, this.array );
  6061. this.array[ index * this.itemSize + component ] = value;
  6062. return this;
  6063. }
  6064. getX( index ) {
  6065. let x = this.array[ index * this.itemSize ];
  6066. if ( this.normalized ) x = denormalize( x, this.array );
  6067. return x;
  6068. }
  6069. setX( index, x ) {
  6070. if ( this.normalized ) x = normalize( x, this.array );
  6071. this.array[ index * this.itemSize ] = x;
  6072. return this;
  6073. }
  6074. getY( index ) {
  6075. let y = this.array[ index * this.itemSize + 1 ];
  6076. if ( this.normalized ) y = denormalize( y, this.array );
  6077. return y;
  6078. }
  6079. setY( index, y ) {
  6080. if ( this.normalized ) y = normalize( y, this.array );
  6081. this.array[ index * this.itemSize + 1 ] = y;
  6082. return this;
  6083. }
  6084. getZ( index ) {
  6085. let z = this.array[ index * this.itemSize + 2 ];
  6086. if ( this.normalized ) z = denormalize( z, this.array );
  6087. return z;
  6088. }
  6089. setZ( index, z ) {
  6090. if ( this.normalized ) z = normalize( z, this.array );
  6091. this.array[ index * this.itemSize + 2 ] = z;
  6092. return this;
  6093. }
  6094. getW( index ) {
  6095. let w = this.array[ index * this.itemSize + 3 ];
  6096. if ( this.normalized ) w = denormalize( w, this.array );
  6097. return w;
  6098. }
  6099. setW( index, w ) {
  6100. if ( this.normalized ) w = normalize( w, this.array );
  6101. this.array[ index * this.itemSize + 3 ] = w;
  6102. return this;
  6103. }
  6104. setXY( index, x, y ) {
  6105. index *= this.itemSize;
  6106. if ( this.normalized ) {
  6107. x = normalize( x, this.array );
  6108. y = normalize( y, this.array );
  6109. }
  6110. this.array[ index + 0 ] = x;
  6111. this.array[ index + 1 ] = y;
  6112. return this;
  6113. }
  6114. setXYZ( index, x, y, z ) {
  6115. index *= this.itemSize;
  6116. if ( this.normalized ) {
  6117. x = normalize( x, this.array );
  6118. y = normalize( y, this.array );
  6119. z = normalize( z, this.array );
  6120. }
  6121. this.array[ index + 0 ] = x;
  6122. this.array[ index + 1 ] = y;
  6123. this.array[ index + 2 ] = z;
  6124. return this;
  6125. }
  6126. setXYZW( index, x, y, z, w ) {
  6127. index *= this.itemSize;
  6128. if ( this.normalized ) {
  6129. x = normalize( x, this.array );
  6130. y = normalize( y, this.array );
  6131. z = normalize( z, this.array );
  6132. w = normalize( w, this.array );
  6133. }
  6134. this.array[ index + 0 ] = x;
  6135. this.array[ index + 1 ] = y;
  6136. this.array[ index + 2 ] = z;
  6137. this.array[ index + 3 ] = w;
  6138. return this;
  6139. }
  6140. onUpload( callback ) {
  6141. this.onUploadCallback = callback;
  6142. return this;
  6143. }
  6144. clone() {
  6145. return new this.constructor( this.array, this.itemSize ).copy( this );
  6146. }
  6147. toJSON() {
  6148. const data = {
  6149. itemSize: this.itemSize,
  6150. type: this.array.constructor.name,
  6151. array: Array.from( this.array ),
  6152. normalized: this.normalized
  6153. };
  6154. if ( this.name !== '' ) data.name = this.name;
  6155. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6156. return data;
  6157. }
  6158. }
  6159. //
  6160. class Int8BufferAttribute extends BufferAttribute {
  6161. constructor( array, itemSize, normalized ) {
  6162. super( new Int8Array( array ), itemSize, normalized );
  6163. }
  6164. }
  6165. class Uint8BufferAttribute extends BufferAttribute {
  6166. constructor( array, itemSize, normalized ) {
  6167. super( new Uint8Array( array ), itemSize, normalized );
  6168. }
  6169. }
  6170. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6171. constructor( array, itemSize, normalized ) {
  6172. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6173. }
  6174. }
  6175. class Int16BufferAttribute extends BufferAttribute {
  6176. constructor( array, itemSize, normalized ) {
  6177. super( new Int16Array( array ), itemSize, normalized );
  6178. }
  6179. }
  6180. class Uint16BufferAttribute extends BufferAttribute {
  6181. constructor( array, itemSize, normalized ) {
  6182. super( new Uint16Array( array ), itemSize, normalized );
  6183. }
  6184. }
  6185. class Int32BufferAttribute extends BufferAttribute {
  6186. constructor( array, itemSize, normalized ) {
  6187. super( new Int32Array( array ), itemSize, normalized );
  6188. }
  6189. }
  6190. class Uint32BufferAttribute extends BufferAttribute {
  6191. constructor( array, itemSize, normalized ) {
  6192. super( new Uint32Array( array ), itemSize, normalized );
  6193. }
  6194. }
  6195. class Float16BufferAttribute extends BufferAttribute {
  6196. constructor( array, itemSize, normalized ) {
  6197. super( new Uint16Array( array ), itemSize, normalized );
  6198. this.isFloat16BufferAttribute = true;
  6199. }
  6200. getX( index ) {
  6201. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6202. if ( this.normalized ) x = denormalize( x, this.array );
  6203. return x;
  6204. }
  6205. setX( index, x ) {
  6206. if ( this.normalized ) x = normalize( x, this.array );
  6207. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6208. return this;
  6209. }
  6210. getY( index ) {
  6211. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6212. if ( this.normalized ) y = denormalize( y, this.array );
  6213. return y;
  6214. }
  6215. setY( index, y ) {
  6216. if ( this.normalized ) y = normalize( y, this.array );
  6217. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6218. return this;
  6219. }
  6220. getZ( index ) {
  6221. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6222. if ( this.normalized ) z = denormalize( z, this.array );
  6223. return z;
  6224. }
  6225. setZ( index, z ) {
  6226. if ( this.normalized ) z = normalize( z, this.array );
  6227. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6228. return this;
  6229. }
  6230. getW( index ) {
  6231. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6232. if ( this.normalized ) w = denormalize( w, this.array );
  6233. return w;
  6234. }
  6235. setW( index, w ) {
  6236. if ( this.normalized ) w = normalize( w, this.array );
  6237. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6238. return this;
  6239. }
  6240. setXY( index, x, y ) {
  6241. index *= this.itemSize;
  6242. if ( this.normalized ) {
  6243. x = normalize( x, this.array );
  6244. y = normalize( y, this.array );
  6245. }
  6246. this.array[ index + 0 ] = toHalfFloat( x );
  6247. this.array[ index + 1 ] = toHalfFloat( y );
  6248. return this;
  6249. }
  6250. setXYZ( index, x, y, z ) {
  6251. index *= this.itemSize;
  6252. if ( this.normalized ) {
  6253. x = normalize( x, this.array );
  6254. y = normalize( y, this.array );
  6255. z = normalize( z, this.array );
  6256. }
  6257. this.array[ index + 0 ] = toHalfFloat( x );
  6258. this.array[ index + 1 ] = toHalfFloat( y );
  6259. this.array[ index + 2 ] = toHalfFloat( z );
  6260. return this;
  6261. }
  6262. setXYZW( index, x, y, z, w ) {
  6263. index *= this.itemSize;
  6264. if ( this.normalized ) {
  6265. x = normalize( x, this.array );
  6266. y = normalize( y, this.array );
  6267. z = normalize( z, this.array );
  6268. w = normalize( w, this.array );
  6269. }
  6270. this.array[ index + 0 ] = toHalfFloat( x );
  6271. this.array[ index + 1 ] = toHalfFloat( y );
  6272. this.array[ index + 2 ] = toHalfFloat( z );
  6273. this.array[ index + 3 ] = toHalfFloat( w );
  6274. return this;
  6275. }
  6276. }
  6277. class Float32BufferAttribute extends BufferAttribute {
  6278. constructor( array, itemSize, normalized ) {
  6279. super( new Float32Array( array ), itemSize, normalized );
  6280. }
  6281. }
  6282. let _id$2 = 0;
  6283. const _m1$2 = /*@__PURE__*/ new Matrix4();
  6284. const _obj = /*@__PURE__*/ new Object3D();
  6285. const _offset = /*@__PURE__*/ new Vector3();
  6286. const _box$2 = /*@__PURE__*/ new Box3();
  6287. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6288. const _vector$8 = /*@__PURE__*/ new Vector3();
  6289. class BufferGeometry extends EventDispatcher {
  6290. constructor() {
  6291. super();
  6292. this.isBufferGeometry = true;
  6293. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  6294. this.uuid = generateUUID();
  6295. this.name = '';
  6296. this.type = 'BufferGeometry';
  6297. this.index = null;
  6298. this.attributes = {};
  6299. this.morphAttributes = {};
  6300. this.morphTargetsRelative = false;
  6301. this.groups = [];
  6302. this.boundingBox = null;
  6303. this.boundingSphere = null;
  6304. this.drawRange = { start: 0, count: Infinity };
  6305. this.userData = {};
  6306. }
  6307. getIndex() {
  6308. return this.index;
  6309. }
  6310. setIndex( index ) {
  6311. if ( Array.isArray( index ) ) {
  6312. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6313. } else {
  6314. this.index = index;
  6315. }
  6316. return this;
  6317. }
  6318. getAttribute( name ) {
  6319. return this.attributes[ name ];
  6320. }
  6321. setAttribute( name, attribute ) {
  6322. this.attributes[ name ] = attribute;
  6323. return this;
  6324. }
  6325. deleteAttribute( name ) {
  6326. delete this.attributes[ name ];
  6327. return this;
  6328. }
  6329. hasAttribute( name ) {
  6330. return this.attributes[ name ] !== undefined;
  6331. }
  6332. addGroup( start, count, materialIndex = 0 ) {
  6333. this.groups.push( {
  6334. start: start,
  6335. count: count,
  6336. materialIndex: materialIndex
  6337. } );
  6338. }
  6339. clearGroups() {
  6340. this.groups = [];
  6341. }
  6342. setDrawRange( start, count ) {
  6343. this.drawRange.start = start;
  6344. this.drawRange.count = count;
  6345. }
  6346. applyMatrix4( matrix ) {
  6347. const position = this.attributes.position;
  6348. if ( position !== undefined ) {
  6349. position.applyMatrix4( matrix );
  6350. position.needsUpdate = true;
  6351. }
  6352. const normal = this.attributes.normal;
  6353. if ( normal !== undefined ) {
  6354. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6355. normal.applyNormalMatrix( normalMatrix );
  6356. normal.needsUpdate = true;
  6357. }
  6358. const tangent = this.attributes.tangent;
  6359. if ( tangent !== undefined ) {
  6360. tangent.transformDirection( matrix );
  6361. tangent.needsUpdate = true;
  6362. }
  6363. if ( this.boundingBox !== null ) {
  6364. this.computeBoundingBox();
  6365. }
  6366. if ( this.boundingSphere !== null ) {
  6367. this.computeBoundingSphere();
  6368. }
  6369. return this;
  6370. }
  6371. applyQuaternion( q ) {
  6372. _m1$2.makeRotationFromQuaternion( q );
  6373. this.applyMatrix4( _m1$2 );
  6374. return this;
  6375. }
  6376. rotateX( angle ) {
  6377. // rotate geometry around world x-axis
  6378. _m1$2.makeRotationX( angle );
  6379. this.applyMatrix4( _m1$2 );
  6380. return this;
  6381. }
  6382. rotateY( angle ) {
  6383. // rotate geometry around world y-axis
  6384. _m1$2.makeRotationY( angle );
  6385. this.applyMatrix4( _m1$2 );
  6386. return this;
  6387. }
  6388. rotateZ( angle ) {
  6389. // rotate geometry around world z-axis
  6390. _m1$2.makeRotationZ( angle );
  6391. this.applyMatrix4( _m1$2 );
  6392. return this;
  6393. }
  6394. translate( x, y, z ) {
  6395. // translate geometry
  6396. _m1$2.makeTranslation( x, y, z );
  6397. this.applyMatrix4( _m1$2 );
  6398. return this;
  6399. }
  6400. scale( x, y, z ) {
  6401. // scale geometry
  6402. _m1$2.makeScale( x, y, z );
  6403. this.applyMatrix4( _m1$2 );
  6404. return this;
  6405. }
  6406. lookAt( vector ) {
  6407. _obj.lookAt( vector );
  6408. _obj.updateMatrix();
  6409. this.applyMatrix4( _obj.matrix );
  6410. return this;
  6411. }
  6412. center() {
  6413. this.computeBoundingBox();
  6414. this.boundingBox.getCenter( _offset ).negate();
  6415. this.translate( _offset.x, _offset.y, _offset.z );
  6416. return this;
  6417. }
  6418. setFromPoints( points ) {
  6419. const position = [];
  6420. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6421. const point = points[ i ];
  6422. position.push( point.x, point.y, point.z || 0 );
  6423. }
  6424. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6425. return this;
  6426. }
  6427. computeBoundingBox() {
  6428. if ( this.boundingBox === null ) {
  6429. this.boundingBox = new Box3();
  6430. }
  6431. const position = this.attributes.position;
  6432. const morphAttributesPosition = this.morphAttributes.position;
  6433. if ( position && position.isGLBufferAttribute ) {
  6434. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6435. this.boundingBox.set(
  6436. new Vector3( - Infinity, - Infinity, - Infinity ),
  6437. new Vector3( + Infinity, + Infinity, + Infinity )
  6438. );
  6439. return;
  6440. }
  6441. if ( position !== undefined ) {
  6442. this.boundingBox.setFromBufferAttribute( position );
  6443. // process morph attributes if present
  6444. if ( morphAttributesPosition ) {
  6445. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6446. const morphAttribute = morphAttributesPosition[ i ];
  6447. _box$2.setFromBufferAttribute( morphAttribute );
  6448. if ( this.morphTargetsRelative ) {
  6449. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6450. this.boundingBox.expandByPoint( _vector$8 );
  6451. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6452. this.boundingBox.expandByPoint( _vector$8 );
  6453. } else {
  6454. this.boundingBox.expandByPoint( _box$2.min );
  6455. this.boundingBox.expandByPoint( _box$2.max );
  6456. }
  6457. }
  6458. }
  6459. } else {
  6460. this.boundingBox.makeEmpty();
  6461. }
  6462. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6463. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6464. }
  6465. }
  6466. computeBoundingSphere() {
  6467. if ( this.boundingSphere === null ) {
  6468. this.boundingSphere = new Sphere();
  6469. }
  6470. const position = this.attributes.position;
  6471. const morphAttributesPosition = this.morphAttributes.position;
  6472. if ( position && position.isGLBufferAttribute ) {
  6473. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6474. this.boundingSphere.set( new Vector3(), Infinity );
  6475. return;
  6476. }
  6477. if ( position ) {
  6478. // first, find the center of the bounding sphere
  6479. const center = this.boundingSphere.center;
  6480. _box$2.setFromBufferAttribute( position );
  6481. // process morph attributes if present
  6482. if ( morphAttributesPosition ) {
  6483. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6484. const morphAttribute = morphAttributesPosition[ i ];
  6485. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6486. if ( this.morphTargetsRelative ) {
  6487. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6488. _box$2.expandByPoint( _vector$8 );
  6489. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6490. _box$2.expandByPoint( _vector$8 );
  6491. } else {
  6492. _box$2.expandByPoint( _boxMorphTargets.min );
  6493. _box$2.expandByPoint( _boxMorphTargets.max );
  6494. }
  6495. }
  6496. }
  6497. _box$2.getCenter( center );
  6498. // second, try to find a boundingSphere with a radius smaller than the
  6499. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6500. let maxRadiusSq = 0;
  6501. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6502. _vector$8.fromBufferAttribute( position, i );
  6503. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6504. }
  6505. // process morph attributes if present
  6506. if ( morphAttributesPosition ) {
  6507. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6508. const morphAttribute = morphAttributesPosition[ i ];
  6509. const morphTargetsRelative = this.morphTargetsRelative;
  6510. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6511. _vector$8.fromBufferAttribute( morphAttribute, j );
  6512. if ( morphTargetsRelative ) {
  6513. _offset.fromBufferAttribute( position, j );
  6514. _vector$8.add( _offset );
  6515. }
  6516. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6517. }
  6518. }
  6519. }
  6520. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6521. if ( isNaN( this.boundingSphere.radius ) ) {
  6522. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6523. }
  6524. }
  6525. }
  6526. computeTangents() {
  6527. const index = this.index;
  6528. const attributes = this.attributes;
  6529. // based on http://www.terathon.com/code/tangent.html
  6530. // (per vertex tangents)
  6531. if ( index === null ||
  6532. attributes.position === undefined ||
  6533. attributes.normal === undefined ||
  6534. attributes.uv === undefined ) {
  6535. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6536. return;
  6537. }
  6538. const positionAttribute = attributes.position;
  6539. const normalAttribute = attributes.normal;
  6540. const uvAttribute = attributes.uv;
  6541. if ( this.hasAttribute( 'tangent' ) === false ) {
  6542. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6543. }
  6544. const tangentAttribute = this.getAttribute( 'tangent' );
  6545. const tan1 = [], tan2 = [];
  6546. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6547. tan1[ i ] = new Vector3();
  6548. tan2[ i ] = new Vector3();
  6549. }
  6550. const vA = new Vector3(),
  6551. vB = new Vector3(),
  6552. vC = new Vector3(),
  6553. uvA = new Vector2(),
  6554. uvB = new Vector2(),
  6555. uvC = new Vector2(),
  6556. sdir = new Vector3(),
  6557. tdir = new Vector3();
  6558. function handleTriangle( a, b, c ) {
  6559. vA.fromBufferAttribute( positionAttribute, a );
  6560. vB.fromBufferAttribute( positionAttribute, b );
  6561. vC.fromBufferAttribute( positionAttribute, c );
  6562. uvA.fromBufferAttribute( uvAttribute, a );
  6563. uvB.fromBufferAttribute( uvAttribute, b );
  6564. uvC.fromBufferAttribute( uvAttribute, c );
  6565. vB.sub( vA );
  6566. vC.sub( vA );
  6567. uvB.sub( uvA );
  6568. uvC.sub( uvA );
  6569. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6570. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6571. if ( ! isFinite( r ) ) return;
  6572. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6573. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6574. tan1[ a ].add( sdir );
  6575. tan1[ b ].add( sdir );
  6576. tan1[ c ].add( sdir );
  6577. tan2[ a ].add( tdir );
  6578. tan2[ b ].add( tdir );
  6579. tan2[ c ].add( tdir );
  6580. }
  6581. let groups = this.groups;
  6582. if ( groups.length === 0 ) {
  6583. groups = [ {
  6584. start: 0,
  6585. count: index.count
  6586. } ];
  6587. }
  6588. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6589. const group = groups[ i ];
  6590. const start = group.start;
  6591. const count = group.count;
  6592. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6593. handleTriangle(
  6594. index.getX( j + 0 ),
  6595. index.getX( j + 1 ),
  6596. index.getX( j + 2 )
  6597. );
  6598. }
  6599. }
  6600. const tmp = new Vector3(), tmp2 = new Vector3();
  6601. const n = new Vector3(), n2 = new Vector3();
  6602. function handleVertex( v ) {
  6603. n.fromBufferAttribute( normalAttribute, v );
  6604. n2.copy( n );
  6605. const t = tan1[ v ];
  6606. // Gram-Schmidt orthogonalize
  6607. tmp.copy( t );
  6608. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6609. // Calculate handedness
  6610. tmp2.crossVectors( n2, t );
  6611. const test = tmp2.dot( tan2[ v ] );
  6612. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6613. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6614. }
  6615. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6616. const group = groups[ i ];
  6617. const start = group.start;
  6618. const count = group.count;
  6619. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6620. handleVertex( index.getX( j + 0 ) );
  6621. handleVertex( index.getX( j + 1 ) );
  6622. handleVertex( index.getX( j + 2 ) );
  6623. }
  6624. }
  6625. }
  6626. computeVertexNormals() {
  6627. const index = this.index;
  6628. const positionAttribute = this.getAttribute( 'position' );
  6629. if ( positionAttribute !== undefined ) {
  6630. let normalAttribute = this.getAttribute( 'normal' );
  6631. if ( normalAttribute === undefined ) {
  6632. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6633. this.setAttribute( 'normal', normalAttribute );
  6634. } else {
  6635. // reset existing normals to zero
  6636. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6637. normalAttribute.setXYZ( i, 0, 0, 0 );
  6638. }
  6639. }
  6640. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6641. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6642. const cb = new Vector3(), ab = new Vector3();
  6643. // indexed elements
  6644. if ( index ) {
  6645. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6646. const vA = index.getX( i + 0 );
  6647. const vB = index.getX( i + 1 );
  6648. const vC = index.getX( i + 2 );
  6649. pA.fromBufferAttribute( positionAttribute, vA );
  6650. pB.fromBufferAttribute( positionAttribute, vB );
  6651. pC.fromBufferAttribute( positionAttribute, vC );
  6652. cb.subVectors( pC, pB );
  6653. ab.subVectors( pA, pB );
  6654. cb.cross( ab );
  6655. nA.fromBufferAttribute( normalAttribute, vA );
  6656. nB.fromBufferAttribute( normalAttribute, vB );
  6657. nC.fromBufferAttribute( normalAttribute, vC );
  6658. nA.add( cb );
  6659. nB.add( cb );
  6660. nC.add( cb );
  6661. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6662. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6663. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6664. }
  6665. } else {
  6666. // non-indexed elements (unconnected triangle soup)
  6667. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6668. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6669. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6670. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6671. cb.subVectors( pC, pB );
  6672. ab.subVectors( pA, pB );
  6673. cb.cross( ab );
  6674. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6675. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6676. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6677. }
  6678. }
  6679. this.normalizeNormals();
  6680. normalAttribute.needsUpdate = true;
  6681. }
  6682. }
  6683. normalizeNormals() {
  6684. const normals = this.attributes.normal;
  6685. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6686. _vector$8.fromBufferAttribute( normals, i );
  6687. _vector$8.normalize();
  6688. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6689. }
  6690. }
  6691. toNonIndexed() {
  6692. function convertBufferAttribute( attribute, indices ) {
  6693. const array = attribute.array;
  6694. const itemSize = attribute.itemSize;
  6695. const normalized = attribute.normalized;
  6696. const array2 = new array.constructor( indices.length * itemSize );
  6697. let index = 0, index2 = 0;
  6698. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6699. if ( attribute.isInterleavedBufferAttribute ) {
  6700. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6701. } else {
  6702. index = indices[ i ] * itemSize;
  6703. }
  6704. for ( let j = 0; j < itemSize; j ++ ) {
  6705. array2[ index2 ++ ] = array[ index ++ ];
  6706. }
  6707. }
  6708. return new BufferAttribute( array2, itemSize, normalized );
  6709. }
  6710. //
  6711. if ( this.index === null ) {
  6712. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6713. return this;
  6714. }
  6715. const geometry2 = new BufferGeometry();
  6716. const indices = this.index.array;
  6717. const attributes = this.attributes;
  6718. // attributes
  6719. for ( const name in attributes ) {
  6720. const attribute = attributes[ name ];
  6721. const newAttribute = convertBufferAttribute( attribute, indices );
  6722. geometry2.setAttribute( name, newAttribute );
  6723. }
  6724. // morph attributes
  6725. const morphAttributes = this.morphAttributes;
  6726. for ( const name in morphAttributes ) {
  6727. const morphArray = [];
  6728. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6729. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6730. const attribute = morphAttribute[ i ];
  6731. const newAttribute = convertBufferAttribute( attribute, indices );
  6732. morphArray.push( newAttribute );
  6733. }
  6734. geometry2.morphAttributes[ name ] = morphArray;
  6735. }
  6736. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6737. // groups
  6738. const groups = this.groups;
  6739. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6740. const group = groups[ i ];
  6741. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6742. }
  6743. return geometry2;
  6744. }
  6745. toJSON() {
  6746. const data = {
  6747. metadata: {
  6748. version: 4.6,
  6749. type: 'BufferGeometry',
  6750. generator: 'BufferGeometry.toJSON'
  6751. }
  6752. };
  6753. // standard BufferGeometry serialization
  6754. data.uuid = this.uuid;
  6755. data.type = this.type;
  6756. if ( this.name !== '' ) data.name = this.name;
  6757. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6758. if ( this.parameters !== undefined ) {
  6759. const parameters = this.parameters;
  6760. for ( const key in parameters ) {
  6761. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6762. }
  6763. return data;
  6764. }
  6765. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6766. data.data = { attributes: {} };
  6767. const index = this.index;
  6768. if ( index !== null ) {
  6769. data.data.index = {
  6770. type: index.array.constructor.name,
  6771. array: Array.prototype.slice.call( index.array )
  6772. };
  6773. }
  6774. const attributes = this.attributes;
  6775. for ( const key in attributes ) {
  6776. const attribute = attributes[ key ];
  6777. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6778. }
  6779. const morphAttributes = {};
  6780. let hasMorphAttributes = false;
  6781. for ( const key in this.morphAttributes ) {
  6782. const attributeArray = this.morphAttributes[ key ];
  6783. const array = [];
  6784. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6785. const attribute = attributeArray[ i ];
  6786. array.push( attribute.toJSON( data.data ) );
  6787. }
  6788. if ( array.length > 0 ) {
  6789. morphAttributes[ key ] = array;
  6790. hasMorphAttributes = true;
  6791. }
  6792. }
  6793. if ( hasMorphAttributes ) {
  6794. data.data.morphAttributes = morphAttributes;
  6795. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6796. }
  6797. const groups = this.groups;
  6798. if ( groups.length > 0 ) {
  6799. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6800. }
  6801. const boundingSphere = this.boundingSphere;
  6802. if ( boundingSphere !== null ) {
  6803. data.data.boundingSphere = {
  6804. center: boundingSphere.center.toArray(),
  6805. radius: boundingSphere.radius
  6806. };
  6807. }
  6808. return data;
  6809. }
  6810. clone() {
  6811. return new this.constructor().copy( this );
  6812. }
  6813. copy( source ) {
  6814. // reset
  6815. this.index = null;
  6816. this.attributes = {};
  6817. this.morphAttributes = {};
  6818. this.groups = [];
  6819. this.boundingBox = null;
  6820. this.boundingSphere = null;
  6821. // used for storing cloned, shared data
  6822. const data = {};
  6823. // name
  6824. this.name = source.name;
  6825. // index
  6826. const index = source.index;
  6827. if ( index !== null ) {
  6828. this.setIndex( index.clone( data ) );
  6829. }
  6830. // attributes
  6831. const attributes = source.attributes;
  6832. for ( const name in attributes ) {
  6833. const attribute = attributes[ name ];
  6834. this.setAttribute( name, attribute.clone( data ) );
  6835. }
  6836. // morph attributes
  6837. const morphAttributes = source.morphAttributes;
  6838. for ( const name in morphAttributes ) {
  6839. const array = [];
  6840. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6841. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6842. array.push( morphAttribute[ i ].clone( data ) );
  6843. }
  6844. this.morphAttributes[ name ] = array;
  6845. }
  6846. this.morphTargetsRelative = source.morphTargetsRelative;
  6847. // groups
  6848. const groups = source.groups;
  6849. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6850. const group = groups[ i ];
  6851. this.addGroup( group.start, group.count, group.materialIndex );
  6852. }
  6853. // bounding box
  6854. const boundingBox = source.boundingBox;
  6855. if ( boundingBox !== null ) {
  6856. this.boundingBox = boundingBox.clone();
  6857. }
  6858. // bounding sphere
  6859. const boundingSphere = source.boundingSphere;
  6860. if ( boundingSphere !== null ) {
  6861. this.boundingSphere = boundingSphere.clone();
  6862. }
  6863. // draw range
  6864. this.drawRange.start = source.drawRange.start;
  6865. this.drawRange.count = source.drawRange.count;
  6866. // user data
  6867. this.userData = source.userData;
  6868. return this;
  6869. }
  6870. dispose() {
  6871. this.dispatchEvent( { type: 'dispose' } );
  6872. }
  6873. }
  6874. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6875. const _ray$3 = /*@__PURE__*/ new Ray();
  6876. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6877. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6878. const _vA$1 = /*@__PURE__*/ new Vector3();
  6879. const _vB$1 = /*@__PURE__*/ new Vector3();
  6880. const _vC$1 = /*@__PURE__*/ new Vector3();
  6881. const _tempA = /*@__PURE__*/ new Vector3();
  6882. const _morphA = /*@__PURE__*/ new Vector3();
  6883. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6884. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6885. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6886. const _normalA = /*@__PURE__*/ new Vector3();
  6887. const _normalB = /*@__PURE__*/ new Vector3();
  6888. const _normalC = /*@__PURE__*/ new Vector3();
  6889. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6890. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6891. class Mesh extends Object3D {
  6892. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6893. super();
  6894. this.isMesh = true;
  6895. this.type = 'Mesh';
  6896. this.geometry = geometry;
  6897. this.material = material;
  6898. this.updateMorphTargets();
  6899. }
  6900. copy( source, recursive ) {
  6901. super.copy( source, recursive );
  6902. if ( source.morphTargetInfluences !== undefined ) {
  6903. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6904. }
  6905. if ( source.morphTargetDictionary !== undefined ) {
  6906. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6907. }
  6908. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6909. this.geometry = source.geometry;
  6910. return this;
  6911. }
  6912. updateMorphTargets() {
  6913. const geometry = this.geometry;
  6914. const morphAttributes = geometry.morphAttributes;
  6915. const keys = Object.keys( morphAttributes );
  6916. if ( keys.length > 0 ) {
  6917. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6918. if ( morphAttribute !== undefined ) {
  6919. this.morphTargetInfluences = [];
  6920. this.morphTargetDictionary = {};
  6921. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6922. const name = morphAttribute[ m ].name || String( m );
  6923. this.morphTargetInfluences.push( 0 );
  6924. this.morphTargetDictionary[ name ] = m;
  6925. }
  6926. }
  6927. }
  6928. }
  6929. getVertexPosition( index, target ) {
  6930. const geometry = this.geometry;
  6931. const position = geometry.attributes.position;
  6932. const morphPosition = geometry.morphAttributes.position;
  6933. const morphTargetsRelative = geometry.morphTargetsRelative;
  6934. target.fromBufferAttribute( position, index );
  6935. const morphInfluences = this.morphTargetInfluences;
  6936. if ( morphPosition && morphInfluences ) {
  6937. _morphA.set( 0, 0, 0 );
  6938. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6939. const influence = morphInfluences[ i ];
  6940. const morphAttribute = morphPosition[ i ];
  6941. if ( influence === 0 ) continue;
  6942. _tempA.fromBufferAttribute( morphAttribute, index );
  6943. if ( morphTargetsRelative ) {
  6944. _morphA.addScaledVector( _tempA, influence );
  6945. } else {
  6946. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6947. }
  6948. }
  6949. target.add( _morphA );
  6950. }
  6951. return target;
  6952. }
  6953. raycast( raycaster, intersects ) {
  6954. const geometry = this.geometry;
  6955. const material = this.material;
  6956. const matrixWorld = this.matrixWorld;
  6957. if ( material === undefined ) return;
  6958. // test with bounding sphere in world space
  6959. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6960. _sphere$6.copy( geometry.boundingSphere );
  6961. _sphere$6.applyMatrix4( matrixWorld );
  6962. // check distance from ray origin to bounding sphere
  6963. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6964. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6965. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6966. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6967. }
  6968. // convert ray to local space of mesh
  6969. _inverseMatrix$3.copy( matrixWorld ).invert();
  6970. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6971. // test with bounding box in local space
  6972. if ( geometry.boundingBox !== null ) {
  6973. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6974. }
  6975. // test for intersections with geometry
  6976. this._computeIntersections( raycaster, intersects, _ray$3 );
  6977. }
  6978. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6979. let intersection;
  6980. const geometry = this.geometry;
  6981. const material = this.material;
  6982. const index = geometry.index;
  6983. const position = geometry.attributes.position;
  6984. const uv = geometry.attributes.uv;
  6985. const uv1 = geometry.attributes.uv1;
  6986. const normal = geometry.attributes.normal;
  6987. const groups = geometry.groups;
  6988. const drawRange = geometry.drawRange;
  6989. if ( index !== null ) {
  6990. // indexed buffer geometry
  6991. if ( Array.isArray( material ) ) {
  6992. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6993. const group = groups[ i ];
  6994. const groupMaterial = material[ group.materialIndex ];
  6995. const start = Math.max( group.start, drawRange.start );
  6996. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6997. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6998. const a = index.getX( j );
  6999. const b = index.getX( j + 1 );
  7000. const c = index.getX( j + 2 );
  7001. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7002. if ( intersection ) {
  7003. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7004. intersection.face.materialIndex = group.materialIndex;
  7005. intersects.push( intersection );
  7006. }
  7007. }
  7008. }
  7009. } else {
  7010. const start = Math.max( 0, drawRange.start );
  7011. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7012. for ( let i = start, il = end; i < il; i += 3 ) {
  7013. const a = index.getX( i );
  7014. const b = index.getX( i + 1 );
  7015. const c = index.getX( i + 2 );
  7016. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7017. if ( intersection ) {
  7018. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7019. intersects.push( intersection );
  7020. }
  7021. }
  7022. }
  7023. } else if ( position !== undefined ) {
  7024. // non-indexed buffer geometry
  7025. if ( Array.isArray( material ) ) {
  7026. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7027. const group = groups[ i ];
  7028. const groupMaterial = material[ group.materialIndex ];
  7029. const start = Math.max( group.start, drawRange.start );
  7030. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7031. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7032. const a = j;
  7033. const b = j + 1;
  7034. const c = j + 2;
  7035. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7036. if ( intersection ) {
  7037. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7038. intersection.face.materialIndex = group.materialIndex;
  7039. intersects.push( intersection );
  7040. }
  7041. }
  7042. }
  7043. } else {
  7044. const start = Math.max( 0, drawRange.start );
  7045. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7046. for ( let i = start, il = end; i < il; i += 3 ) {
  7047. const a = i;
  7048. const b = i + 1;
  7049. const c = i + 2;
  7050. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7051. if ( intersection ) {
  7052. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7053. intersects.push( intersection );
  7054. }
  7055. }
  7056. }
  7057. }
  7058. }
  7059. }
  7060. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7061. let intersect;
  7062. if ( material.side === BackSide ) {
  7063. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7064. } else {
  7065. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7066. }
  7067. if ( intersect === null ) return null;
  7068. _intersectionPointWorld.copy( point );
  7069. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7070. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7071. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7072. return {
  7073. distance: distance,
  7074. point: _intersectionPointWorld.clone(),
  7075. object: object
  7076. };
  7077. }
  7078. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7079. object.getVertexPosition( a, _vA$1 );
  7080. object.getVertexPosition( b, _vB$1 );
  7081. object.getVertexPosition( c, _vC$1 );
  7082. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7083. if ( intersection ) {
  7084. if ( uv ) {
  7085. _uvA$1.fromBufferAttribute( uv, a );
  7086. _uvB$1.fromBufferAttribute( uv, b );
  7087. _uvC$1.fromBufferAttribute( uv, c );
  7088. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7089. }
  7090. if ( uv1 ) {
  7091. _uvA$1.fromBufferAttribute( uv1, a );
  7092. _uvB$1.fromBufferAttribute( uv1, b );
  7093. _uvC$1.fromBufferAttribute( uv1, c );
  7094. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7095. }
  7096. if ( normal ) {
  7097. _normalA.fromBufferAttribute( normal, a );
  7098. _normalB.fromBufferAttribute( normal, b );
  7099. _normalC.fromBufferAttribute( normal, c );
  7100. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7101. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7102. intersection.normal.multiplyScalar( - 1 );
  7103. }
  7104. }
  7105. const face = {
  7106. a: a,
  7107. b: b,
  7108. c: c,
  7109. normal: new Vector3(),
  7110. materialIndex: 0
  7111. };
  7112. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7113. intersection.face = face;
  7114. }
  7115. return intersection;
  7116. }
  7117. class BoxGeometry extends BufferGeometry {
  7118. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7119. super();
  7120. this.type = 'BoxGeometry';
  7121. this.parameters = {
  7122. width: width,
  7123. height: height,
  7124. depth: depth,
  7125. widthSegments: widthSegments,
  7126. heightSegments: heightSegments,
  7127. depthSegments: depthSegments
  7128. };
  7129. const scope = this;
  7130. // segments
  7131. widthSegments = Math.floor( widthSegments );
  7132. heightSegments = Math.floor( heightSegments );
  7133. depthSegments = Math.floor( depthSegments );
  7134. // buffers
  7135. const indices = [];
  7136. const vertices = [];
  7137. const normals = [];
  7138. const uvs = [];
  7139. // helper variables
  7140. let numberOfVertices = 0;
  7141. let groupStart = 0;
  7142. // build each side of the box geometry
  7143. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7144. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7145. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7146. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7147. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7148. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7149. // build geometry
  7150. this.setIndex( indices );
  7151. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7152. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7153. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7154. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7155. const segmentWidth = width / gridX;
  7156. const segmentHeight = height / gridY;
  7157. const widthHalf = width / 2;
  7158. const heightHalf = height / 2;
  7159. const depthHalf = depth / 2;
  7160. const gridX1 = gridX + 1;
  7161. const gridY1 = gridY + 1;
  7162. let vertexCounter = 0;
  7163. let groupCount = 0;
  7164. const vector = new Vector3();
  7165. // generate vertices, normals and uvs
  7166. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7167. const y = iy * segmentHeight - heightHalf;
  7168. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7169. const x = ix * segmentWidth - widthHalf;
  7170. // set values to correct vector component
  7171. vector[ u ] = x * udir;
  7172. vector[ v ] = y * vdir;
  7173. vector[ w ] = depthHalf;
  7174. // now apply vector to vertex buffer
  7175. vertices.push( vector.x, vector.y, vector.z );
  7176. // set values to correct vector component
  7177. vector[ u ] = 0;
  7178. vector[ v ] = 0;
  7179. vector[ w ] = depth > 0 ? 1 : - 1;
  7180. // now apply vector to normal buffer
  7181. normals.push( vector.x, vector.y, vector.z );
  7182. // uvs
  7183. uvs.push( ix / gridX );
  7184. uvs.push( 1 - ( iy / gridY ) );
  7185. // counters
  7186. vertexCounter += 1;
  7187. }
  7188. }
  7189. // indices
  7190. // 1. you need three indices to draw a single face
  7191. // 2. a single segment consists of two faces
  7192. // 3. so we need to generate six (2*3) indices per segment
  7193. for ( let iy = 0; iy < gridY; iy ++ ) {
  7194. for ( let ix = 0; ix < gridX; ix ++ ) {
  7195. const a = numberOfVertices + ix + gridX1 * iy;
  7196. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7197. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7198. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7199. // faces
  7200. indices.push( a, b, d );
  7201. indices.push( b, c, d );
  7202. // increase counter
  7203. groupCount += 6;
  7204. }
  7205. }
  7206. // add a group to the geometry. this will ensure multi material support
  7207. scope.addGroup( groupStart, groupCount, materialIndex );
  7208. // calculate new start value for groups
  7209. groupStart += groupCount;
  7210. // update total number of vertices
  7211. numberOfVertices += vertexCounter;
  7212. }
  7213. }
  7214. copy( source ) {
  7215. super.copy( source );
  7216. this.parameters = Object.assign( {}, source.parameters );
  7217. return this;
  7218. }
  7219. static fromJSON( data ) {
  7220. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7221. }
  7222. }
  7223. /**
  7224. * Uniform Utilities
  7225. */
  7226. function cloneUniforms( src ) {
  7227. const dst = {};
  7228. for ( const u in src ) {
  7229. dst[ u ] = {};
  7230. for ( const p in src[ u ] ) {
  7231. const property = src[ u ][ p ];
  7232. if ( property && ( property.isColor ||
  7233. property.isMatrix3 || property.isMatrix4 ||
  7234. property.isVector2 || property.isVector3 || property.isVector4 ||
  7235. property.isTexture || property.isQuaternion ) ) {
  7236. if ( property.isRenderTargetTexture ) {
  7237. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7238. dst[ u ][ p ] = null;
  7239. } else {
  7240. dst[ u ][ p ] = property.clone();
  7241. }
  7242. } else if ( Array.isArray( property ) ) {
  7243. dst[ u ][ p ] = property.slice();
  7244. } else {
  7245. dst[ u ][ p ] = property;
  7246. }
  7247. }
  7248. }
  7249. return dst;
  7250. }
  7251. function mergeUniforms( uniforms ) {
  7252. const merged = {};
  7253. for ( let u = 0; u < uniforms.length; u ++ ) {
  7254. const tmp = cloneUniforms( uniforms[ u ] );
  7255. for ( const p in tmp ) {
  7256. merged[ p ] = tmp[ p ];
  7257. }
  7258. }
  7259. return merged;
  7260. }
  7261. function cloneUniformsGroups( src ) {
  7262. const dst = [];
  7263. for ( let u = 0; u < src.length; u ++ ) {
  7264. dst.push( src[ u ].clone() );
  7265. }
  7266. return dst;
  7267. }
  7268. function getUnlitUniformColorSpace( renderer ) {
  7269. const currentRenderTarget = renderer.getRenderTarget();
  7270. if ( currentRenderTarget === null ) {
  7271. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7272. return renderer.outputColorSpace;
  7273. }
  7274. // https://github.com/mrdoob/three.js/issues/27868
  7275. if ( currentRenderTarget.isXRRenderTarget === true ) {
  7276. return currentRenderTarget.texture.colorSpace;
  7277. }
  7278. return ColorManagement.workingColorSpace;
  7279. }
  7280. // Legacy
  7281. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7282. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7283. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7284. class ShaderMaterial extends Material {
  7285. constructor( parameters ) {
  7286. super();
  7287. this.isShaderMaterial = true;
  7288. this.type = 'ShaderMaterial';
  7289. this.defines = {};
  7290. this.uniforms = {};
  7291. this.uniformsGroups = [];
  7292. this.vertexShader = default_vertex;
  7293. this.fragmentShader = default_fragment;
  7294. this.linewidth = 1;
  7295. this.wireframe = false;
  7296. this.wireframeLinewidth = 1;
  7297. this.fog = false; // set to use scene fog
  7298. this.lights = false; // set to use scene lights
  7299. this.clipping = false; // set to use user-defined clipping planes
  7300. this.forceSinglePass = true;
  7301. this.extensions = {
  7302. clipCullDistance: false, // set to use vertex shader clipping
  7303. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7304. };
  7305. // When rendered geometry doesn't include these attributes but the material does,
  7306. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7307. this.defaultAttributeValues = {
  7308. 'color': [ 1, 1, 1 ],
  7309. 'uv': [ 0, 0 ],
  7310. 'uv1': [ 0, 0 ]
  7311. };
  7312. this.index0AttributeName = undefined;
  7313. this.uniformsNeedUpdate = false;
  7314. this.glslVersion = null;
  7315. if ( parameters !== undefined ) {
  7316. this.setValues( parameters );
  7317. }
  7318. }
  7319. copy( source ) {
  7320. super.copy( source );
  7321. this.fragmentShader = source.fragmentShader;
  7322. this.vertexShader = source.vertexShader;
  7323. this.uniforms = cloneUniforms( source.uniforms );
  7324. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7325. this.defines = Object.assign( {}, source.defines );
  7326. this.wireframe = source.wireframe;
  7327. this.wireframeLinewidth = source.wireframeLinewidth;
  7328. this.fog = source.fog;
  7329. this.lights = source.lights;
  7330. this.clipping = source.clipping;
  7331. this.extensions = Object.assign( {}, source.extensions );
  7332. this.glslVersion = source.glslVersion;
  7333. return this;
  7334. }
  7335. toJSON( meta ) {
  7336. const data = super.toJSON( meta );
  7337. data.glslVersion = this.glslVersion;
  7338. data.uniforms = {};
  7339. for ( const name in this.uniforms ) {
  7340. const uniform = this.uniforms[ name ];
  7341. const value = uniform.value;
  7342. if ( value && value.isTexture ) {
  7343. data.uniforms[ name ] = {
  7344. type: 't',
  7345. value: value.toJSON( meta ).uuid
  7346. };
  7347. } else if ( value && value.isColor ) {
  7348. data.uniforms[ name ] = {
  7349. type: 'c',
  7350. value: value.getHex()
  7351. };
  7352. } else if ( value && value.isVector2 ) {
  7353. data.uniforms[ name ] = {
  7354. type: 'v2',
  7355. value: value.toArray()
  7356. };
  7357. } else if ( value && value.isVector3 ) {
  7358. data.uniforms[ name ] = {
  7359. type: 'v3',
  7360. value: value.toArray()
  7361. };
  7362. } else if ( value && value.isVector4 ) {
  7363. data.uniforms[ name ] = {
  7364. type: 'v4',
  7365. value: value.toArray()
  7366. };
  7367. } else if ( value && value.isMatrix3 ) {
  7368. data.uniforms[ name ] = {
  7369. type: 'm3',
  7370. value: value.toArray()
  7371. };
  7372. } else if ( value && value.isMatrix4 ) {
  7373. data.uniforms[ name ] = {
  7374. type: 'm4',
  7375. value: value.toArray()
  7376. };
  7377. } else {
  7378. data.uniforms[ name ] = {
  7379. value: value
  7380. };
  7381. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7382. }
  7383. }
  7384. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7385. data.vertexShader = this.vertexShader;
  7386. data.fragmentShader = this.fragmentShader;
  7387. data.lights = this.lights;
  7388. data.clipping = this.clipping;
  7389. const extensions = {};
  7390. for ( const key in this.extensions ) {
  7391. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7392. }
  7393. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7394. return data;
  7395. }
  7396. }
  7397. class Camera extends Object3D {
  7398. constructor() {
  7399. super();
  7400. this.isCamera = true;
  7401. this.type = 'Camera';
  7402. this.matrixWorldInverse = new Matrix4();
  7403. this.projectionMatrix = new Matrix4();
  7404. this.projectionMatrixInverse = new Matrix4();
  7405. this.coordinateSystem = WebGLCoordinateSystem;
  7406. }
  7407. copy( source, recursive ) {
  7408. super.copy( source, recursive );
  7409. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7410. this.projectionMatrix.copy( source.projectionMatrix );
  7411. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7412. this.coordinateSystem = source.coordinateSystem;
  7413. return this;
  7414. }
  7415. getWorldDirection( target ) {
  7416. return super.getWorldDirection( target ).negate();
  7417. }
  7418. updateMatrixWorld( force ) {
  7419. super.updateMatrixWorld( force );
  7420. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7421. }
  7422. updateWorldMatrix( updateParents, updateChildren ) {
  7423. super.updateWorldMatrix( updateParents, updateChildren );
  7424. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7425. }
  7426. clone() {
  7427. return new this.constructor().copy( this );
  7428. }
  7429. }
  7430. const _v3$1 = /*@__PURE__*/ new Vector3();
  7431. const _minTarget = /*@__PURE__*/ new Vector2();
  7432. const _maxTarget = /*@__PURE__*/ new Vector2();
  7433. class PerspectiveCamera extends Camera {
  7434. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7435. super();
  7436. this.isPerspectiveCamera = true;
  7437. this.type = 'PerspectiveCamera';
  7438. this.fov = fov;
  7439. this.zoom = 1;
  7440. this.near = near;
  7441. this.far = far;
  7442. this.focus = 10;
  7443. this.aspect = aspect;
  7444. this.view = null;
  7445. this.filmGauge = 35; // width of the film (default in millimeters)
  7446. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7447. this.updateProjectionMatrix();
  7448. }
  7449. copy( source, recursive ) {
  7450. super.copy( source, recursive );
  7451. this.fov = source.fov;
  7452. this.zoom = source.zoom;
  7453. this.near = source.near;
  7454. this.far = source.far;
  7455. this.focus = source.focus;
  7456. this.aspect = source.aspect;
  7457. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7458. this.filmGauge = source.filmGauge;
  7459. this.filmOffset = source.filmOffset;
  7460. return this;
  7461. }
  7462. /**
  7463. * Sets the FOV by focal length in respect to the current .filmGauge.
  7464. *
  7465. * The default film gauge is 35, so that the focal length can be specified for
  7466. * a 35mm (full frame) camera.
  7467. *
  7468. * Values for focal length and film gauge must have the same unit.
  7469. */
  7470. setFocalLength( focalLength ) {
  7471. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7472. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7473. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7474. this.updateProjectionMatrix();
  7475. }
  7476. /**
  7477. * Calculates the focal length from the current .fov and .filmGauge.
  7478. */
  7479. getFocalLength() {
  7480. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7481. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7482. }
  7483. getEffectiveFOV() {
  7484. return RAD2DEG * 2 * Math.atan(
  7485. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7486. }
  7487. getFilmWidth() {
  7488. // film not completely covered in portrait format (aspect < 1)
  7489. return this.filmGauge * Math.min( this.aspect, 1 );
  7490. }
  7491. getFilmHeight() {
  7492. // film not completely covered in landscape format (aspect > 1)
  7493. return this.filmGauge / Math.max( this.aspect, 1 );
  7494. }
  7495. /**
  7496. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7497. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7498. */
  7499. getViewBounds( distance, minTarget, maxTarget ) {
  7500. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7501. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7502. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7503. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7504. }
  7505. /**
  7506. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7507. * Copies the result into the target Vector2, where x is width and y is height.
  7508. */
  7509. getViewSize( distance, target ) {
  7510. this.getViewBounds( distance, _minTarget, _maxTarget );
  7511. return target.subVectors( _maxTarget, _minTarget );
  7512. }
  7513. /**
  7514. * Sets an offset in a larger frustum. This is useful for multi-window or
  7515. * multi-monitor/multi-machine setups.
  7516. *
  7517. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7518. * the monitors are in grid like this
  7519. *
  7520. * +---+---+---+
  7521. * | A | B | C |
  7522. * +---+---+---+
  7523. * | D | E | F |
  7524. * +---+---+---+
  7525. *
  7526. * then for each monitor you would call it like this
  7527. *
  7528. * const w = 1920;
  7529. * const h = 1080;
  7530. * const fullWidth = w * 3;
  7531. * const fullHeight = h * 2;
  7532. *
  7533. * --A--
  7534. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7535. * --B--
  7536. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7537. * --C--
  7538. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7539. * --D--
  7540. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7541. * --E--
  7542. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7543. * --F--
  7544. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7545. *
  7546. * Note there is no reason monitors have to be the same size or in a grid.
  7547. */
  7548. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7549. this.aspect = fullWidth / fullHeight;
  7550. if ( this.view === null ) {
  7551. this.view = {
  7552. enabled: true,
  7553. fullWidth: 1,
  7554. fullHeight: 1,
  7555. offsetX: 0,
  7556. offsetY: 0,
  7557. width: 1,
  7558. height: 1
  7559. };
  7560. }
  7561. this.view.enabled = true;
  7562. this.view.fullWidth = fullWidth;
  7563. this.view.fullHeight = fullHeight;
  7564. this.view.offsetX = x;
  7565. this.view.offsetY = y;
  7566. this.view.width = width;
  7567. this.view.height = height;
  7568. this.updateProjectionMatrix();
  7569. }
  7570. clearViewOffset() {
  7571. if ( this.view !== null ) {
  7572. this.view.enabled = false;
  7573. }
  7574. this.updateProjectionMatrix();
  7575. }
  7576. updateProjectionMatrix() {
  7577. const near = this.near;
  7578. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7579. let height = 2 * top;
  7580. let width = this.aspect * height;
  7581. let left = - 0.5 * width;
  7582. const view = this.view;
  7583. if ( this.view !== null && this.view.enabled ) {
  7584. const fullWidth = view.fullWidth,
  7585. fullHeight = view.fullHeight;
  7586. left += view.offsetX * width / fullWidth;
  7587. top -= view.offsetY * height / fullHeight;
  7588. width *= view.width / fullWidth;
  7589. height *= view.height / fullHeight;
  7590. }
  7591. const skew = this.filmOffset;
  7592. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7593. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7594. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7595. }
  7596. toJSON( meta ) {
  7597. const data = super.toJSON( meta );
  7598. data.object.fov = this.fov;
  7599. data.object.zoom = this.zoom;
  7600. data.object.near = this.near;
  7601. data.object.far = this.far;
  7602. data.object.focus = this.focus;
  7603. data.object.aspect = this.aspect;
  7604. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7605. data.object.filmGauge = this.filmGauge;
  7606. data.object.filmOffset = this.filmOffset;
  7607. return data;
  7608. }
  7609. }
  7610. const fov = - 90; // negative fov is not an error
  7611. const aspect = 1;
  7612. class CubeCamera extends Object3D {
  7613. constructor( near, far, renderTarget ) {
  7614. super();
  7615. this.type = 'CubeCamera';
  7616. this.renderTarget = renderTarget;
  7617. this.coordinateSystem = null;
  7618. this.activeMipmapLevel = 0;
  7619. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7620. cameraPX.layers = this.layers;
  7621. this.add( cameraPX );
  7622. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7623. cameraNX.layers = this.layers;
  7624. this.add( cameraNX );
  7625. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7626. cameraPY.layers = this.layers;
  7627. this.add( cameraPY );
  7628. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7629. cameraNY.layers = this.layers;
  7630. this.add( cameraNY );
  7631. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7632. cameraPZ.layers = this.layers;
  7633. this.add( cameraPZ );
  7634. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7635. cameraNZ.layers = this.layers;
  7636. this.add( cameraNZ );
  7637. }
  7638. updateCoordinateSystem() {
  7639. const coordinateSystem = this.coordinateSystem;
  7640. const cameras = this.children.concat();
  7641. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7642. for ( const camera of cameras ) this.remove( camera );
  7643. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7644. cameraPX.up.set( 0, 1, 0 );
  7645. cameraPX.lookAt( 1, 0, 0 );
  7646. cameraNX.up.set( 0, 1, 0 );
  7647. cameraNX.lookAt( - 1, 0, 0 );
  7648. cameraPY.up.set( 0, 0, - 1 );
  7649. cameraPY.lookAt( 0, 1, 0 );
  7650. cameraNY.up.set( 0, 0, 1 );
  7651. cameraNY.lookAt( 0, - 1, 0 );
  7652. cameraPZ.up.set( 0, 1, 0 );
  7653. cameraPZ.lookAt( 0, 0, 1 );
  7654. cameraNZ.up.set( 0, 1, 0 );
  7655. cameraNZ.lookAt( 0, 0, - 1 );
  7656. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7657. cameraPX.up.set( 0, - 1, 0 );
  7658. cameraPX.lookAt( - 1, 0, 0 );
  7659. cameraNX.up.set( 0, - 1, 0 );
  7660. cameraNX.lookAt( 1, 0, 0 );
  7661. cameraPY.up.set( 0, 0, 1 );
  7662. cameraPY.lookAt( 0, 1, 0 );
  7663. cameraNY.up.set( 0, 0, - 1 );
  7664. cameraNY.lookAt( 0, - 1, 0 );
  7665. cameraPZ.up.set( 0, - 1, 0 );
  7666. cameraPZ.lookAt( 0, 0, 1 );
  7667. cameraNZ.up.set( 0, - 1, 0 );
  7668. cameraNZ.lookAt( 0, 0, - 1 );
  7669. } else {
  7670. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7671. }
  7672. for ( const camera of cameras ) {
  7673. this.add( camera );
  7674. camera.updateMatrixWorld();
  7675. }
  7676. }
  7677. update( renderer, scene ) {
  7678. if ( this.parent === null ) this.updateMatrixWorld();
  7679. const { renderTarget, activeMipmapLevel } = this;
  7680. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7681. this.coordinateSystem = renderer.coordinateSystem;
  7682. this.updateCoordinateSystem();
  7683. }
  7684. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7685. const currentRenderTarget = renderer.getRenderTarget();
  7686. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7687. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7688. const currentXrEnabled = renderer.xr.enabled;
  7689. renderer.xr.enabled = false;
  7690. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7691. renderTarget.texture.generateMipmaps = false;
  7692. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7693. renderer.render( scene, cameraPX );
  7694. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7695. renderer.render( scene, cameraNX );
  7696. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7697. renderer.render( scene, cameraPY );
  7698. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7699. renderer.render( scene, cameraNY );
  7700. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7701. renderer.render( scene, cameraPZ );
  7702. // mipmaps are generated during the last call of render()
  7703. // at this point, all sides of the cube render target are defined
  7704. renderTarget.texture.generateMipmaps = generateMipmaps;
  7705. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7706. renderer.render( scene, cameraNZ );
  7707. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7708. renderer.xr.enabled = currentXrEnabled;
  7709. renderTarget.texture.needsPMREMUpdate = true;
  7710. }
  7711. }
  7712. class CubeTexture extends Texture {
  7713. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7714. images = images !== undefined ? images : [];
  7715. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7716. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7717. this.isCubeTexture = true;
  7718. this.flipY = false;
  7719. }
  7720. get images() {
  7721. return this.image;
  7722. }
  7723. set images( value ) {
  7724. this.image = value;
  7725. }
  7726. }
  7727. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7728. constructor( size = 1, options = {} ) {
  7729. super( size, size, options );
  7730. this.isWebGLCubeRenderTarget = true;
  7731. const image = { width: size, height: size, depth: 1 };
  7732. const images = [ image, image, image, image, image, image ];
  7733. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7734. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7735. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7736. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7737. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7738. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7739. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7740. this.texture.isRenderTargetTexture = true;
  7741. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7742. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7743. }
  7744. fromEquirectangularTexture( renderer, texture ) {
  7745. this.texture.type = texture.type;
  7746. this.texture.colorSpace = texture.colorSpace;
  7747. this.texture.generateMipmaps = texture.generateMipmaps;
  7748. this.texture.minFilter = texture.minFilter;
  7749. this.texture.magFilter = texture.magFilter;
  7750. const shader = {
  7751. uniforms: {
  7752. tEquirect: { value: null },
  7753. },
  7754. vertexShader: /* glsl */`
  7755. varying vec3 vWorldDirection;
  7756. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7757. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7758. }
  7759. void main() {
  7760. vWorldDirection = transformDirection( position, modelMatrix );
  7761. #include <begin_vertex>
  7762. #include <project_vertex>
  7763. }
  7764. `,
  7765. fragmentShader: /* glsl */`
  7766. uniform sampler2D tEquirect;
  7767. varying vec3 vWorldDirection;
  7768. #include <common>
  7769. void main() {
  7770. vec3 direction = normalize( vWorldDirection );
  7771. vec2 sampleUV = equirectUv( direction );
  7772. gl_FragColor = texture2D( tEquirect, sampleUV );
  7773. }
  7774. `
  7775. };
  7776. const geometry = new BoxGeometry( 5, 5, 5 );
  7777. const material = new ShaderMaterial( {
  7778. name: 'CubemapFromEquirect',
  7779. uniforms: cloneUniforms( shader.uniforms ),
  7780. vertexShader: shader.vertexShader,
  7781. fragmentShader: shader.fragmentShader,
  7782. side: BackSide,
  7783. blending: NoBlending
  7784. } );
  7785. material.uniforms.tEquirect.value = texture;
  7786. const mesh = new Mesh( geometry, material );
  7787. const currentMinFilter = texture.minFilter;
  7788. // Avoid blurred poles
  7789. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7790. const camera = new CubeCamera( 1, 10, this );
  7791. camera.update( renderer, mesh );
  7792. texture.minFilter = currentMinFilter;
  7793. mesh.geometry.dispose();
  7794. mesh.material.dispose();
  7795. return this;
  7796. }
  7797. clear( renderer, color, depth, stencil ) {
  7798. const currentRenderTarget = renderer.getRenderTarget();
  7799. for ( let i = 0; i < 6; i ++ ) {
  7800. renderer.setRenderTarget( this, i );
  7801. renderer.clear( color, depth, stencil );
  7802. }
  7803. renderer.setRenderTarget( currentRenderTarget );
  7804. }
  7805. }
  7806. const _vector1 = /*@__PURE__*/ new Vector3();
  7807. const _vector2 = /*@__PURE__*/ new Vector3();
  7808. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7809. class Plane {
  7810. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7811. this.isPlane = true;
  7812. // normal is assumed to be normalized
  7813. this.normal = normal;
  7814. this.constant = constant;
  7815. }
  7816. set( normal, constant ) {
  7817. this.normal.copy( normal );
  7818. this.constant = constant;
  7819. return this;
  7820. }
  7821. setComponents( x, y, z, w ) {
  7822. this.normal.set( x, y, z );
  7823. this.constant = w;
  7824. return this;
  7825. }
  7826. setFromNormalAndCoplanarPoint( normal, point ) {
  7827. this.normal.copy( normal );
  7828. this.constant = - point.dot( this.normal );
  7829. return this;
  7830. }
  7831. setFromCoplanarPoints( a, b, c ) {
  7832. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7833. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7834. this.setFromNormalAndCoplanarPoint( normal, a );
  7835. return this;
  7836. }
  7837. copy( plane ) {
  7838. this.normal.copy( plane.normal );
  7839. this.constant = plane.constant;
  7840. return this;
  7841. }
  7842. normalize() {
  7843. // Note: will lead to a divide by zero if the plane is invalid.
  7844. const inverseNormalLength = 1.0 / this.normal.length();
  7845. this.normal.multiplyScalar( inverseNormalLength );
  7846. this.constant *= inverseNormalLength;
  7847. return this;
  7848. }
  7849. negate() {
  7850. this.constant *= - 1;
  7851. this.normal.negate();
  7852. return this;
  7853. }
  7854. distanceToPoint( point ) {
  7855. return this.normal.dot( point ) + this.constant;
  7856. }
  7857. distanceToSphere( sphere ) {
  7858. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7859. }
  7860. projectPoint( point, target ) {
  7861. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7862. }
  7863. intersectLine( line, target ) {
  7864. const direction = line.delta( _vector1 );
  7865. const denominator = this.normal.dot( direction );
  7866. if ( denominator === 0 ) {
  7867. // line is coplanar, return origin
  7868. if ( this.distanceToPoint( line.start ) === 0 ) {
  7869. return target.copy( line.start );
  7870. }
  7871. // Unsure if this is the correct method to handle this case.
  7872. return null;
  7873. }
  7874. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7875. if ( t < 0 || t > 1 ) {
  7876. return null;
  7877. }
  7878. return target.copy( line.start ).addScaledVector( direction, t );
  7879. }
  7880. intersectsLine( line ) {
  7881. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7882. const startSign = this.distanceToPoint( line.start );
  7883. const endSign = this.distanceToPoint( line.end );
  7884. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7885. }
  7886. intersectsBox( box ) {
  7887. return box.intersectsPlane( this );
  7888. }
  7889. intersectsSphere( sphere ) {
  7890. return sphere.intersectsPlane( this );
  7891. }
  7892. coplanarPoint( target ) {
  7893. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7894. }
  7895. applyMatrix4( matrix, optionalNormalMatrix ) {
  7896. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7897. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7898. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7899. this.constant = - referencePoint.dot( normal );
  7900. return this;
  7901. }
  7902. translate( offset ) {
  7903. this.constant -= offset.dot( this.normal );
  7904. return this;
  7905. }
  7906. equals( plane ) {
  7907. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7908. }
  7909. clone() {
  7910. return new this.constructor().copy( this );
  7911. }
  7912. }
  7913. const _sphere$5 = /*@__PURE__*/ new Sphere();
  7914. const _vector$7 = /*@__PURE__*/ new Vector3();
  7915. class Frustum {
  7916. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7917. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7918. }
  7919. set( p0, p1, p2, p3, p4, p5 ) {
  7920. const planes = this.planes;
  7921. planes[ 0 ].copy( p0 );
  7922. planes[ 1 ].copy( p1 );
  7923. planes[ 2 ].copy( p2 );
  7924. planes[ 3 ].copy( p3 );
  7925. planes[ 4 ].copy( p4 );
  7926. planes[ 5 ].copy( p5 );
  7927. return this;
  7928. }
  7929. copy( frustum ) {
  7930. const planes = this.planes;
  7931. for ( let i = 0; i < 6; i ++ ) {
  7932. planes[ i ].copy( frustum.planes[ i ] );
  7933. }
  7934. return this;
  7935. }
  7936. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7937. const planes = this.planes;
  7938. const me = m.elements;
  7939. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7940. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7941. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7942. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7943. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7944. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7945. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7946. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7947. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7948. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7949. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7950. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7951. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7952. } else {
  7953. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7954. }
  7955. return this;
  7956. }
  7957. intersectsObject( object ) {
  7958. if ( object.boundingSphere !== undefined ) {
  7959. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7960. _sphere$5.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7961. } else {
  7962. const geometry = object.geometry;
  7963. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7964. _sphere$5.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7965. }
  7966. return this.intersectsSphere( _sphere$5 );
  7967. }
  7968. intersectsSprite( sprite ) {
  7969. _sphere$5.center.set( 0, 0, 0 );
  7970. _sphere$5.radius = 0.7071067811865476;
  7971. _sphere$5.applyMatrix4( sprite.matrixWorld );
  7972. return this.intersectsSphere( _sphere$5 );
  7973. }
  7974. intersectsSphere( sphere ) {
  7975. const planes = this.planes;
  7976. const center = sphere.center;
  7977. const negRadius = - sphere.radius;
  7978. for ( let i = 0; i < 6; i ++ ) {
  7979. const distance = planes[ i ].distanceToPoint( center );
  7980. if ( distance < negRadius ) {
  7981. return false;
  7982. }
  7983. }
  7984. return true;
  7985. }
  7986. intersectsBox( box ) {
  7987. const planes = this.planes;
  7988. for ( let i = 0; i < 6; i ++ ) {
  7989. const plane = planes[ i ];
  7990. // corner at max distance
  7991. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7992. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7993. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7994. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7995. return false;
  7996. }
  7997. }
  7998. return true;
  7999. }
  8000. containsPoint( point ) {
  8001. const planes = this.planes;
  8002. for ( let i = 0; i < 6; i ++ ) {
  8003. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8004. return false;
  8005. }
  8006. }
  8007. return true;
  8008. }
  8009. clone() {
  8010. return new this.constructor().copy( this );
  8011. }
  8012. }
  8013. function WebGLAnimation() {
  8014. let context = null;
  8015. let isAnimating = false;
  8016. let animationLoop = null;
  8017. let requestId = null;
  8018. function onAnimationFrame( time, frame ) {
  8019. animationLoop( time, frame );
  8020. requestId = context.requestAnimationFrame( onAnimationFrame );
  8021. }
  8022. return {
  8023. start: function () {
  8024. if ( isAnimating === true ) return;
  8025. if ( animationLoop === null ) return;
  8026. requestId = context.requestAnimationFrame( onAnimationFrame );
  8027. isAnimating = true;
  8028. },
  8029. stop: function () {
  8030. context.cancelAnimationFrame( requestId );
  8031. isAnimating = false;
  8032. },
  8033. setAnimationLoop: function ( callback ) {
  8034. animationLoop = callback;
  8035. },
  8036. setContext: function ( value ) {
  8037. context = value;
  8038. }
  8039. };
  8040. }
  8041. function WebGLAttributes( gl ) {
  8042. const buffers = new WeakMap();
  8043. function createBuffer( attribute, bufferType ) {
  8044. const array = attribute.array;
  8045. const usage = attribute.usage;
  8046. const size = array.byteLength;
  8047. const buffer = gl.createBuffer();
  8048. gl.bindBuffer( bufferType, buffer );
  8049. gl.bufferData( bufferType, array, usage );
  8050. attribute.onUploadCallback();
  8051. let type;
  8052. if ( array instanceof Float32Array ) {
  8053. type = gl.FLOAT;
  8054. } else if ( array instanceof Uint16Array ) {
  8055. if ( attribute.isFloat16BufferAttribute ) {
  8056. type = gl.HALF_FLOAT;
  8057. } else {
  8058. type = gl.UNSIGNED_SHORT;
  8059. }
  8060. } else if ( array instanceof Int16Array ) {
  8061. type = gl.SHORT;
  8062. } else if ( array instanceof Uint32Array ) {
  8063. type = gl.UNSIGNED_INT;
  8064. } else if ( array instanceof Int32Array ) {
  8065. type = gl.INT;
  8066. } else if ( array instanceof Int8Array ) {
  8067. type = gl.BYTE;
  8068. } else if ( array instanceof Uint8Array ) {
  8069. type = gl.UNSIGNED_BYTE;
  8070. } else if ( array instanceof Uint8ClampedArray ) {
  8071. type = gl.UNSIGNED_BYTE;
  8072. } else {
  8073. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  8074. }
  8075. return {
  8076. buffer: buffer,
  8077. type: type,
  8078. bytesPerElement: array.BYTES_PER_ELEMENT,
  8079. version: attribute.version,
  8080. size: size
  8081. };
  8082. }
  8083. function updateBuffer( buffer, attribute, bufferType ) {
  8084. const array = attribute.array;
  8085. const updateRanges = attribute.updateRanges;
  8086. gl.bindBuffer( bufferType, buffer );
  8087. if ( updateRanges.length === 0 ) {
  8088. // Not using update ranges
  8089. gl.bufferSubData( bufferType, 0, array );
  8090. } else {
  8091. // Before applying update ranges, we merge any adjacent / overlapping
  8092. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  8093. // to performance improvements for applications which make heavy use of
  8094. // update ranges. Likely due to GPU command overhead.
  8095. //
  8096. // Note that to reduce garbage collection between frames, we merge the
  8097. // update ranges in-place. This is safe because this method will clear the
  8098. // update ranges once updated.
  8099. updateRanges.sort( ( a, b ) => a.start - b.start );
  8100. // To merge the update ranges in-place, we work from left to right in the
  8101. // existing updateRanges array, merging ranges. This may result in a final
  8102. // array which is smaller than the original. This index tracks the last
  8103. // index representing a merged range, any data after this index can be
  8104. // trimmed once the merge algorithm is completed.
  8105. let mergeIndex = 0;
  8106. for ( let i = 1; i < updateRanges.length; i ++ ) {
  8107. const previousRange = updateRanges[ mergeIndex ];
  8108. const range = updateRanges[ i ];
  8109. // We add one here to merge adjacent ranges. This is safe because ranges
  8110. // operate over positive integers.
  8111. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  8112. previousRange.count = Math.max(
  8113. previousRange.count,
  8114. range.start + range.count - previousRange.start
  8115. );
  8116. } else {
  8117. ++ mergeIndex;
  8118. updateRanges[ mergeIndex ] = range;
  8119. }
  8120. }
  8121. // Trim the array to only contain the merged ranges.
  8122. updateRanges.length = mergeIndex + 1;
  8123. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  8124. const range = updateRanges[ i ];
  8125. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  8126. array, range.start, range.count );
  8127. }
  8128. attribute.clearUpdateRanges();
  8129. }
  8130. attribute.onUploadCallback();
  8131. }
  8132. //
  8133. function get( attribute ) {
  8134. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8135. return buffers.get( attribute );
  8136. }
  8137. function remove( attribute ) {
  8138. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8139. const data = buffers.get( attribute );
  8140. if ( data ) {
  8141. gl.deleteBuffer( data.buffer );
  8142. buffers.delete( attribute );
  8143. }
  8144. }
  8145. function update( attribute, bufferType ) {
  8146. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8147. if ( attribute.isGLBufferAttribute ) {
  8148. const cached = buffers.get( attribute );
  8149. if ( ! cached || cached.version < attribute.version ) {
  8150. buffers.set( attribute, {
  8151. buffer: attribute.buffer,
  8152. type: attribute.type,
  8153. bytesPerElement: attribute.elementSize,
  8154. version: attribute.version
  8155. } );
  8156. }
  8157. return;
  8158. }
  8159. const data = buffers.get( attribute );
  8160. if ( data === undefined ) {
  8161. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8162. } else if ( data.version < attribute.version ) {
  8163. if ( data.size !== attribute.array.byteLength ) {
  8164. 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.' );
  8165. }
  8166. updateBuffer( data.buffer, attribute, bufferType );
  8167. data.version = attribute.version;
  8168. }
  8169. }
  8170. return {
  8171. get: get,
  8172. remove: remove,
  8173. update: update
  8174. };
  8175. }
  8176. class PlaneGeometry extends BufferGeometry {
  8177. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8178. super();
  8179. this.type = 'PlaneGeometry';
  8180. this.parameters = {
  8181. width: width,
  8182. height: height,
  8183. widthSegments: widthSegments,
  8184. heightSegments: heightSegments
  8185. };
  8186. const width_half = width / 2;
  8187. const height_half = height / 2;
  8188. const gridX = Math.floor( widthSegments );
  8189. const gridY = Math.floor( heightSegments );
  8190. const gridX1 = gridX + 1;
  8191. const gridY1 = gridY + 1;
  8192. const segment_width = width / gridX;
  8193. const segment_height = height / gridY;
  8194. //
  8195. const indices = [];
  8196. const vertices = [];
  8197. const normals = [];
  8198. const uvs = [];
  8199. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8200. const y = iy * segment_height - height_half;
  8201. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8202. const x = ix * segment_width - width_half;
  8203. vertices.push( x, - y, 0 );
  8204. normals.push( 0, 0, 1 );
  8205. uvs.push( ix / gridX );
  8206. uvs.push( 1 - ( iy / gridY ) );
  8207. }
  8208. }
  8209. for ( let iy = 0; iy < gridY; iy ++ ) {
  8210. for ( let ix = 0; ix < gridX; ix ++ ) {
  8211. const a = ix + gridX1 * iy;
  8212. const b = ix + gridX1 * ( iy + 1 );
  8213. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8214. const d = ( ix + 1 ) + gridX1 * iy;
  8215. indices.push( a, b, d );
  8216. indices.push( b, c, d );
  8217. }
  8218. }
  8219. this.setIndex( indices );
  8220. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8221. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8222. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8223. }
  8224. copy( source ) {
  8225. super.copy( source );
  8226. this.parameters = Object.assign( {}, source.parameters );
  8227. return this;
  8228. }
  8229. static fromJSON( data ) {
  8230. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8231. }
  8232. }
  8233. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  8234. 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";
  8235. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8236. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8237. 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";
  8238. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8239. 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";
  8240. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8241. var batching_pars_vertex = "#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec3 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n\t}\n#endif";
  8242. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  8243. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  8244. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8245. 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";
  8246. 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";
  8247. 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";
  8248. 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";
  8249. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8250. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8251. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8252. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8253. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8254. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8255. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif";
  8256. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated";
  8257. 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";
  8258. 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";
  8259. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8260. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8261. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8262. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8263. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8264. 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}";
  8265. 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";
  8266. 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";
  8267. 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";
  8268. 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";
  8269. 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";
  8270. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8271. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8272. 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";
  8273. 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";
  8274. 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}";
  8275. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8276. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8277. 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";
  8278. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  8279. 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";
  8280. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8281. 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";
  8282. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8283. 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";
  8284. 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";
  8285. 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}";
  8286. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  8287. 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";
  8288. 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";
  8289. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8290. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8291. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8292. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  8293. 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";
  8294. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8295. 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";
  8296. 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";
  8297. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8298. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8299. 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";
  8300. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  8301. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  8302. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif";
  8303. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  8304. 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;";
  8305. 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";
  8306. 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";
  8307. 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";
  8308. 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";
  8309. 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";
  8310. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  8311. 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";
  8312. 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";
  8313. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8314. 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 );";
  8315. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  8316. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8317. 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;";
  8318. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8319. 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";
  8320. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8321. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8322. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif";
  8323. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8324. 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";
  8325. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8326. 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";
  8327. 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";
  8328. 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";
  8329. 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";
  8330. 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";
  8331. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8332. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8333. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8334. 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";
  8335. 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";
  8336. 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";
  8337. 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";
  8338. 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";
  8339. 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";
  8340. 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}";
  8341. 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}";
  8342. 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}";
  8343. 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}";
  8344. 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}";
  8345. 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}";
  8346. 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}";
  8347. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}";
  8348. 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}";
  8349. 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}";
  8350. 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}";
  8351. 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}";
  8352. 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}";
  8353. 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}";
  8354. 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}";
  8355. 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}";
  8356. 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}";
  8357. 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}";
  8358. 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}";
  8359. 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}";
  8360. 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}";
  8361. 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}";
  8362. 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}";
  8363. 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}";
  8364. 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}";
  8365. 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}";
  8366. 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}";
  8367. 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}";
  8368. 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}";
  8369. 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}";
  8370. 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}";
  8371. 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}";
  8372. 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}";
  8373. 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}";
  8374. const ShaderChunk = {
  8375. alphahash_fragment: alphahash_fragment,
  8376. alphahash_pars_fragment: alphahash_pars_fragment,
  8377. alphamap_fragment: alphamap_fragment,
  8378. alphamap_pars_fragment: alphamap_pars_fragment,
  8379. alphatest_fragment: alphatest_fragment,
  8380. alphatest_pars_fragment: alphatest_pars_fragment,
  8381. aomap_fragment: aomap_fragment,
  8382. aomap_pars_fragment: aomap_pars_fragment,
  8383. batching_pars_vertex: batching_pars_vertex,
  8384. batching_vertex: batching_vertex,
  8385. begin_vertex: begin_vertex,
  8386. beginnormal_vertex: beginnormal_vertex,
  8387. bsdfs: bsdfs,
  8388. iridescence_fragment: iridescence_fragment,
  8389. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8390. clipping_planes_fragment: clipping_planes_fragment,
  8391. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8392. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8393. clipping_planes_vertex: clipping_planes_vertex,
  8394. color_fragment: color_fragment,
  8395. color_pars_fragment: color_pars_fragment,
  8396. color_pars_vertex: color_pars_vertex,
  8397. color_vertex: color_vertex,
  8398. common: common,
  8399. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8400. defaultnormal_vertex: defaultnormal_vertex,
  8401. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8402. displacementmap_vertex: displacementmap_vertex,
  8403. emissivemap_fragment: emissivemap_fragment,
  8404. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8405. colorspace_fragment: colorspace_fragment,
  8406. colorspace_pars_fragment: colorspace_pars_fragment,
  8407. envmap_fragment: envmap_fragment,
  8408. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8409. envmap_pars_fragment: envmap_pars_fragment,
  8410. envmap_pars_vertex: envmap_pars_vertex,
  8411. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8412. envmap_vertex: envmap_vertex,
  8413. fog_vertex: fog_vertex,
  8414. fog_pars_vertex: fog_pars_vertex,
  8415. fog_fragment: fog_fragment,
  8416. fog_pars_fragment: fog_pars_fragment,
  8417. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8418. lightmap_pars_fragment: lightmap_pars_fragment,
  8419. lights_lambert_fragment: lights_lambert_fragment,
  8420. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8421. lights_pars_begin: lights_pars_begin,
  8422. lights_toon_fragment: lights_toon_fragment,
  8423. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8424. lights_phong_fragment: lights_phong_fragment,
  8425. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8426. lights_physical_fragment: lights_physical_fragment,
  8427. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8428. lights_fragment_begin: lights_fragment_begin,
  8429. lights_fragment_maps: lights_fragment_maps,
  8430. lights_fragment_end: lights_fragment_end,
  8431. logdepthbuf_fragment: logdepthbuf_fragment,
  8432. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8433. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8434. logdepthbuf_vertex: logdepthbuf_vertex,
  8435. map_fragment: map_fragment,
  8436. map_pars_fragment: map_pars_fragment,
  8437. map_particle_fragment: map_particle_fragment,
  8438. map_particle_pars_fragment: map_particle_pars_fragment,
  8439. metalnessmap_fragment: metalnessmap_fragment,
  8440. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8441. morphinstance_vertex: morphinstance_vertex,
  8442. morphcolor_vertex: morphcolor_vertex,
  8443. morphnormal_vertex: morphnormal_vertex,
  8444. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8445. morphtarget_vertex: morphtarget_vertex,
  8446. normal_fragment_begin: normal_fragment_begin,
  8447. normal_fragment_maps: normal_fragment_maps,
  8448. normal_pars_fragment: normal_pars_fragment,
  8449. normal_pars_vertex: normal_pars_vertex,
  8450. normal_vertex: normal_vertex,
  8451. normalmap_pars_fragment: normalmap_pars_fragment,
  8452. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8453. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8454. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8455. iridescence_pars_fragment: iridescence_pars_fragment,
  8456. opaque_fragment: opaque_fragment,
  8457. packing: packing,
  8458. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8459. project_vertex: project_vertex,
  8460. dithering_fragment: dithering_fragment,
  8461. dithering_pars_fragment: dithering_pars_fragment,
  8462. roughnessmap_fragment: roughnessmap_fragment,
  8463. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8464. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8465. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8466. shadowmap_vertex: shadowmap_vertex,
  8467. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8468. skinbase_vertex: skinbase_vertex,
  8469. skinning_pars_vertex: skinning_pars_vertex,
  8470. skinning_vertex: skinning_vertex,
  8471. skinnormal_vertex: skinnormal_vertex,
  8472. specularmap_fragment: specularmap_fragment,
  8473. specularmap_pars_fragment: specularmap_pars_fragment,
  8474. tonemapping_fragment: tonemapping_fragment,
  8475. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8476. transmission_fragment: transmission_fragment,
  8477. transmission_pars_fragment: transmission_pars_fragment,
  8478. uv_pars_fragment: uv_pars_fragment,
  8479. uv_pars_vertex: uv_pars_vertex,
  8480. uv_vertex: uv_vertex,
  8481. worldpos_vertex: worldpos_vertex,
  8482. background_vert: vertex$h,
  8483. background_frag: fragment$h,
  8484. backgroundCube_vert: vertex$g,
  8485. backgroundCube_frag: fragment$g,
  8486. cube_vert: vertex$f,
  8487. cube_frag: fragment$f,
  8488. depth_vert: vertex$e,
  8489. depth_frag: fragment$e,
  8490. distanceRGBA_vert: vertex$d,
  8491. distanceRGBA_frag: fragment$d,
  8492. equirect_vert: vertex$c,
  8493. equirect_frag: fragment$c,
  8494. linedashed_vert: vertex$b,
  8495. linedashed_frag: fragment$b,
  8496. meshbasic_vert: vertex$a,
  8497. meshbasic_frag: fragment$a,
  8498. meshlambert_vert: vertex$9,
  8499. meshlambert_frag: fragment$9,
  8500. meshmatcap_vert: vertex$8,
  8501. meshmatcap_frag: fragment$8,
  8502. meshnormal_vert: vertex$7,
  8503. meshnormal_frag: fragment$7,
  8504. meshphong_vert: vertex$6,
  8505. meshphong_frag: fragment$6,
  8506. meshphysical_vert: vertex$5,
  8507. meshphysical_frag: fragment$5,
  8508. meshtoon_vert: vertex$4,
  8509. meshtoon_frag: fragment$4,
  8510. points_vert: vertex$3,
  8511. points_frag: fragment$3,
  8512. shadow_vert: vertex$2,
  8513. shadow_frag: fragment$2,
  8514. sprite_vert: vertex$1,
  8515. sprite_frag: fragment$1
  8516. };
  8517. /**
  8518. * Uniforms library for shared webgl shaders
  8519. */
  8520. const UniformsLib = {
  8521. common: {
  8522. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8523. opacity: { value: 1.0 },
  8524. map: { value: null },
  8525. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8526. alphaMap: { value: null },
  8527. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8528. alphaTest: { value: 0 }
  8529. },
  8530. specularmap: {
  8531. specularMap: { value: null },
  8532. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8533. },
  8534. envmap: {
  8535. envMap: { value: null },
  8536. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  8537. flipEnvMap: { value: - 1 },
  8538. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8539. ior: { value: 1.5 }, // physical
  8540. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8541. },
  8542. aomap: {
  8543. aoMap: { value: null },
  8544. aoMapIntensity: { value: 1 },
  8545. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8546. },
  8547. lightmap: {
  8548. lightMap: { value: null },
  8549. lightMapIntensity: { value: 1 },
  8550. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8551. },
  8552. bumpmap: {
  8553. bumpMap: { value: null },
  8554. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8555. bumpScale: { value: 1 }
  8556. },
  8557. normalmap: {
  8558. normalMap: { value: null },
  8559. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8560. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8561. },
  8562. displacementmap: {
  8563. displacementMap: { value: null },
  8564. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8565. displacementScale: { value: 1 },
  8566. displacementBias: { value: 0 }
  8567. },
  8568. emissivemap: {
  8569. emissiveMap: { value: null },
  8570. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8571. },
  8572. metalnessmap: {
  8573. metalnessMap: { value: null },
  8574. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8575. },
  8576. roughnessmap: {
  8577. roughnessMap: { value: null },
  8578. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8579. },
  8580. gradientmap: {
  8581. gradientMap: { value: null }
  8582. },
  8583. fog: {
  8584. fogDensity: { value: 0.00025 },
  8585. fogNear: { value: 1 },
  8586. fogFar: { value: 2000 },
  8587. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8588. },
  8589. lights: {
  8590. ambientLightColor: { value: [] },
  8591. lightProbe: { value: [] },
  8592. directionalLights: { value: [], properties: {
  8593. direction: {},
  8594. color: {}
  8595. } },
  8596. directionalLightShadows: { value: [], properties: {
  8597. shadowIntensity: 1,
  8598. shadowBias: {},
  8599. shadowNormalBias: {},
  8600. shadowRadius: {},
  8601. shadowMapSize: {}
  8602. } },
  8603. directionalShadowMap: { value: [] },
  8604. directionalShadowMatrix: { value: [] },
  8605. spotLights: { value: [], properties: {
  8606. color: {},
  8607. position: {},
  8608. direction: {},
  8609. distance: {},
  8610. coneCos: {},
  8611. penumbraCos: {},
  8612. decay: {}
  8613. } },
  8614. spotLightShadows: { value: [], properties: {
  8615. shadowIntensity: 1,
  8616. shadowBias: {},
  8617. shadowNormalBias: {},
  8618. shadowRadius: {},
  8619. shadowMapSize: {}
  8620. } },
  8621. spotLightMap: { value: [] },
  8622. spotShadowMap: { value: [] },
  8623. spotLightMatrix: { value: [] },
  8624. pointLights: { value: [], properties: {
  8625. color: {},
  8626. position: {},
  8627. decay: {},
  8628. distance: {}
  8629. } },
  8630. pointLightShadows: { value: [], properties: {
  8631. shadowIntensity: 1,
  8632. shadowBias: {},
  8633. shadowNormalBias: {},
  8634. shadowRadius: {},
  8635. shadowMapSize: {},
  8636. shadowCameraNear: {},
  8637. shadowCameraFar: {}
  8638. } },
  8639. pointShadowMap: { value: [] },
  8640. pointShadowMatrix: { value: [] },
  8641. hemisphereLights: { value: [], properties: {
  8642. direction: {},
  8643. skyColor: {},
  8644. groundColor: {}
  8645. } },
  8646. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8647. rectAreaLights: { value: [], properties: {
  8648. color: {},
  8649. position: {},
  8650. width: {},
  8651. height: {}
  8652. } },
  8653. ltc_1: { value: null },
  8654. ltc_2: { value: null }
  8655. },
  8656. points: {
  8657. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8658. opacity: { value: 1.0 },
  8659. size: { value: 1.0 },
  8660. scale: { value: 1.0 },
  8661. map: { value: null },
  8662. alphaMap: { value: null },
  8663. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8664. alphaTest: { value: 0 },
  8665. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8666. },
  8667. sprite: {
  8668. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8669. opacity: { value: 1.0 },
  8670. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8671. rotation: { value: 0.0 },
  8672. map: { value: null },
  8673. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8674. alphaMap: { value: null },
  8675. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8676. alphaTest: { value: 0 }
  8677. }
  8678. };
  8679. const ShaderLib = {
  8680. basic: {
  8681. uniforms: /*@__PURE__*/ mergeUniforms( [
  8682. UniformsLib.common,
  8683. UniformsLib.specularmap,
  8684. UniformsLib.envmap,
  8685. UniformsLib.aomap,
  8686. UniformsLib.lightmap,
  8687. UniformsLib.fog
  8688. ] ),
  8689. vertexShader: ShaderChunk.meshbasic_vert,
  8690. fragmentShader: ShaderChunk.meshbasic_frag
  8691. },
  8692. lambert: {
  8693. uniforms: /*@__PURE__*/ mergeUniforms( [
  8694. UniformsLib.common,
  8695. UniformsLib.specularmap,
  8696. UniformsLib.envmap,
  8697. UniformsLib.aomap,
  8698. UniformsLib.lightmap,
  8699. UniformsLib.emissivemap,
  8700. UniformsLib.bumpmap,
  8701. UniformsLib.normalmap,
  8702. UniformsLib.displacementmap,
  8703. UniformsLib.fog,
  8704. UniformsLib.lights,
  8705. {
  8706. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8707. }
  8708. ] ),
  8709. vertexShader: ShaderChunk.meshlambert_vert,
  8710. fragmentShader: ShaderChunk.meshlambert_frag
  8711. },
  8712. phong: {
  8713. uniforms: /*@__PURE__*/ mergeUniforms( [
  8714. UniformsLib.common,
  8715. UniformsLib.specularmap,
  8716. UniformsLib.envmap,
  8717. UniformsLib.aomap,
  8718. UniformsLib.lightmap,
  8719. UniformsLib.emissivemap,
  8720. UniformsLib.bumpmap,
  8721. UniformsLib.normalmap,
  8722. UniformsLib.displacementmap,
  8723. UniformsLib.fog,
  8724. UniformsLib.lights,
  8725. {
  8726. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8727. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8728. shininess: { value: 30 }
  8729. }
  8730. ] ),
  8731. vertexShader: ShaderChunk.meshphong_vert,
  8732. fragmentShader: ShaderChunk.meshphong_frag
  8733. },
  8734. standard: {
  8735. uniforms: /*@__PURE__*/ mergeUniforms( [
  8736. UniformsLib.common,
  8737. UniformsLib.envmap,
  8738. UniformsLib.aomap,
  8739. UniformsLib.lightmap,
  8740. UniformsLib.emissivemap,
  8741. UniformsLib.bumpmap,
  8742. UniformsLib.normalmap,
  8743. UniformsLib.displacementmap,
  8744. UniformsLib.roughnessmap,
  8745. UniformsLib.metalnessmap,
  8746. UniformsLib.fog,
  8747. UniformsLib.lights,
  8748. {
  8749. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8750. roughness: { value: 1.0 },
  8751. metalness: { value: 0.0 },
  8752. envMapIntensity: { value: 1 }
  8753. }
  8754. ] ),
  8755. vertexShader: ShaderChunk.meshphysical_vert,
  8756. fragmentShader: ShaderChunk.meshphysical_frag
  8757. },
  8758. toon: {
  8759. uniforms: /*@__PURE__*/ mergeUniforms( [
  8760. UniformsLib.common,
  8761. UniformsLib.aomap,
  8762. UniformsLib.lightmap,
  8763. UniformsLib.emissivemap,
  8764. UniformsLib.bumpmap,
  8765. UniformsLib.normalmap,
  8766. UniformsLib.displacementmap,
  8767. UniformsLib.gradientmap,
  8768. UniformsLib.fog,
  8769. UniformsLib.lights,
  8770. {
  8771. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8772. }
  8773. ] ),
  8774. vertexShader: ShaderChunk.meshtoon_vert,
  8775. fragmentShader: ShaderChunk.meshtoon_frag
  8776. },
  8777. matcap: {
  8778. uniforms: /*@__PURE__*/ mergeUniforms( [
  8779. UniformsLib.common,
  8780. UniformsLib.bumpmap,
  8781. UniformsLib.normalmap,
  8782. UniformsLib.displacementmap,
  8783. UniformsLib.fog,
  8784. {
  8785. matcap: { value: null }
  8786. }
  8787. ] ),
  8788. vertexShader: ShaderChunk.meshmatcap_vert,
  8789. fragmentShader: ShaderChunk.meshmatcap_frag
  8790. },
  8791. points: {
  8792. uniforms: /*@__PURE__*/ mergeUniforms( [
  8793. UniformsLib.points,
  8794. UniformsLib.fog
  8795. ] ),
  8796. vertexShader: ShaderChunk.points_vert,
  8797. fragmentShader: ShaderChunk.points_frag
  8798. },
  8799. dashed: {
  8800. uniforms: /*@__PURE__*/ mergeUniforms( [
  8801. UniformsLib.common,
  8802. UniformsLib.fog,
  8803. {
  8804. scale: { value: 1 },
  8805. dashSize: { value: 1 },
  8806. totalSize: { value: 2 }
  8807. }
  8808. ] ),
  8809. vertexShader: ShaderChunk.linedashed_vert,
  8810. fragmentShader: ShaderChunk.linedashed_frag
  8811. },
  8812. depth: {
  8813. uniforms: /*@__PURE__*/ mergeUniforms( [
  8814. UniformsLib.common,
  8815. UniformsLib.displacementmap
  8816. ] ),
  8817. vertexShader: ShaderChunk.depth_vert,
  8818. fragmentShader: ShaderChunk.depth_frag
  8819. },
  8820. normal: {
  8821. uniforms: /*@__PURE__*/ mergeUniforms( [
  8822. UniformsLib.common,
  8823. UniformsLib.bumpmap,
  8824. UniformsLib.normalmap,
  8825. UniformsLib.displacementmap,
  8826. {
  8827. opacity: { value: 1.0 }
  8828. }
  8829. ] ),
  8830. vertexShader: ShaderChunk.meshnormal_vert,
  8831. fragmentShader: ShaderChunk.meshnormal_frag
  8832. },
  8833. sprite: {
  8834. uniforms: /*@__PURE__*/ mergeUniforms( [
  8835. UniformsLib.sprite,
  8836. UniformsLib.fog
  8837. ] ),
  8838. vertexShader: ShaderChunk.sprite_vert,
  8839. fragmentShader: ShaderChunk.sprite_frag
  8840. },
  8841. background: {
  8842. uniforms: {
  8843. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8844. t2D: { value: null },
  8845. backgroundIntensity: { value: 1 }
  8846. },
  8847. vertexShader: ShaderChunk.background_vert,
  8848. fragmentShader: ShaderChunk.background_frag
  8849. },
  8850. backgroundCube: {
  8851. uniforms: {
  8852. envMap: { value: null },
  8853. flipEnvMap: { value: - 1 },
  8854. backgroundBlurriness: { value: 0 },
  8855. backgroundIntensity: { value: 1 },
  8856. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  8857. },
  8858. vertexShader: ShaderChunk.backgroundCube_vert,
  8859. fragmentShader: ShaderChunk.backgroundCube_frag
  8860. },
  8861. cube: {
  8862. uniforms: {
  8863. tCube: { value: null },
  8864. tFlip: { value: - 1 },
  8865. opacity: { value: 1.0 }
  8866. },
  8867. vertexShader: ShaderChunk.cube_vert,
  8868. fragmentShader: ShaderChunk.cube_frag
  8869. },
  8870. equirect: {
  8871. uniforms: {
  8872. tEquirect: { value: null },
  8873. },
  8874. vertexShader: ShaderChunk.equirect_vert,
  8875. fragmentShader: ShaderChunk.equirect_frag
  8876. },
  8877. distanceRGBA: {
  8878. uniforms: /*@__PURE__*/ mergeUniforms( [
  8879. UniformsLib.common,
  8880. UniformsLib.displacementmap,
  8881. {
  8882. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8883. nearDistance: { value: 1 },
  8884. farDistance: { value: 1000 }
  8885. }
  8886. ] ),
  8887. vertexShader: ShaderChunk.distanceRGBA_vert,
  8888. fragmentShader: ShaderChunk.distanceRGBA_frag
  8889. },
  8890. shadow: {
  8891. uniforms: /*@__PURE__*/ mergeUniforms( [
  8892. UniformsLib.lights,
  8893. UniformsLib.fog,
  8894. {
  8895. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8896. opacity: { value: 1.0 }
  8897. },
  8898. ] ),
  8899. vertexShader: ShaderChunk.shadow_vert,
  8900. fragmentShader: ShaderChunk.shadow_frag
  8901. }
  8902. };
  8903. ShaderLib.physical = {
  8904. uniforms: /*@__PURE__*/ mergeUniforms( [
  8905. ShaderLib.standard.uniforms,
  8906. {
  8907. clearcoat: { value: 0 },
  8908. clearcoatMap: { value: null },
  8909. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8910. clearcoatNormalMap: { value: null },
  8911. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8912. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8913. clearcoatRoughness: { value: 0 },
  8914. clearcoatRoughnessMap: { value: null },
  8915. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8916. dispersion: { value: 0 },
  8917. iridescence: { value: 0 },
  8918. iridescenceMap: { value: null },
  8919. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8920. iridescenceIOR: { value: 1.3 },
  8921. iridescenceThicknessMinimum: { value: 100 },
  8922. iridescenceThicknessMaximum: { value: 400 },
  8923. iridescenceThicknessMap: { value: null },
  8924. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8925. sheen: { value: 0 },
  8926. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8927. sheenColorMap: { value: null },
  8928. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8929. sheenRoughness: { value: 1 },
  8930. sheenRoughnessMap: { value: null },
  8931. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8932. transmission: { value: 0 },
  8933. transmissionMap: { value: null },
  8934. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8935. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8936. transmissionSamplerMap: { value: null },
  8937. thickness: { value: 0 },
  8938. thicknessMap: { value: null },
  8939. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8940. attenuationDistance: { value: 0 },
  8941. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8942. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8943. specularColorMap: { value: null },
  8944. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8945. specularIntensity: { value: 1 },
  8946. specularIntensityMap: { value: null },
  8947. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8948. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8949. anisotropyMap: { value: null },
  8950. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8951. }
  8952. ] ),
  8953. vertexShader: ShaderChunk.meshphysical_vert,
  8954. fragmentShader: ShaderChunk.meshphysical_frag
  8955. };
  8956. const _rgb = { r: 0, b: 0, g: 0 };
  8957. const _e1$1 = /*@__PURE__*/ new Euler();
  8958. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8959. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8960. const clearColor = new Color( 0x000000 );
  8961. let clearAlpha = alpha === true ? 0 : 1;
  8962. let planeMesh;
  8963. let boxMesh;
  8964. let currentBackground = null;
  8965. let currentBackgroundVersion = 0;
  8966. let currentTonemapping = null;
  8967. function getBackground( scene ) {
  8968. let background = scene.isScene === true ? scene.background : null;
  8969. if ( background && background.isTexture ) {
  8970. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8971. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8972. }
  8973. return background;
  8974. }
  8975. function render( scene ) {
  8976. let forceClear = false;
  8977. const background = getBackground( scene );
  8978. if ( background === null ) {
  8979. setClear( clearColor, clearAlpha );
  8980. } else if ( background && background.isColor ) {
  8981. setClear( background, 1 );
  8982. forceClear = true;
  8983. }
  8984. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  8985. if ( environmentBlendMode === 'additive' ) {
  8986. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8987. } else if ( environmentBlendMode === 'alpha-blend' ) {
  8988. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8989. }
  8990. if ( renderer.autoClear || forceClear ) {
  8991. // buffers might not be writable which is required to ensure a correct clear
  8992. state.buffers.depth.setTest( true );
  8993. state.buffers.depth.setMask( true );
  8994. state.buffers.color.setMask( true );
  8995. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8996. }
  8997. }
  8998. function addToRenderList( renderList, scene ) {
  8999. const background = getBackground( scene );
  9000. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  9001. if ( boxMesh === undefined ) {
  9002. boxMesh = new Mesh(
  9003. new BoxGeometry( 1, 1, 1 ),
  9004. new ShaderMaterial( {
  9005. name: 'BackgroundCubeMaterial',
  9006. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  9007. vertexShader: ShaderLib.backgroundCube.vertexShader,
  9008. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  9009. side: BackSide,
  9010. depthTest: false,
  9011. depthWrite: false,
  9012. fog: false
  9013. } )
  9014. );
  9015. boxMesh.geometry.deleteAttribute( 'normal' );
  9016. boxMesh.geometry.deleteAttribute( 'uv' );
  9017. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  9018. this.matrixWorld.copyPosition( camera.matrixWorld );
  9019. };
  9020. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  9021. Object.defineProperty( boxMesh.material, 'envMap', {
  9022. get: function () {
  9023. return this.uniforms.envMap.value;
  9024. }
  9025. } );
  9026. objects.update( boxMesh );
  9027. }
  9028. _e1$1.copy( scene.backgroundRotation );
  9029. // accommodate left-handed frame
  9030. _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1;
  9031. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  9032. // environment maps which are not cube render targets or PMREMs follow a different convention
  9033. _e1$1.y *= - 1;
  9034. _e1$1.z *= - 1;
  9035. }
  9036. boxMesh.material.uniforms.envMap.value = background;
  9037. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  9038. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  9039. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  9040. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  9041. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  9042. if ( currentBackground !== background ||
  9043. currentBackgroundVersion !== background.version ||
  9044. currentTonemapping !== renderer.toneMapping ) {
  9045. boxMesh.material.needsUpdate = true;
  9046. currentBackground = background;
  9047. currentBackgroundVersion = background.version;
  9048. currentTonemapping = renderer.toneMapping;
  9049. }
  9050. boxMesh.layers.enableAll();
  9051. // push to the pre-sorted opaque render list
  9052. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9053. } else if ( background && background.isTexture ) {
  9054. if ( planeMesh === undefined ) {
  9055. planeMesh = new Mesh(
  9056. new PlaneGeometry( 2, 2 ),
  9057. new ShaderMaterial( {
  9058. name: 'BackgroundMaterial',
  9059. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9060. vertexShader: ShaderLib.background.vertexShader,
  9061. fragmentShader: ShaderLib.background.fragmentShader,
  9062. side: FrontSide,
  9063. depthTest: false,
  9064. depthWrite: false,
  9065. fog: false
  9066. } )
  9067. );
  9068. planeMesh.geometry.deleteAttribute( 'normal' );
  9069. // add "map" material property so the renderer can evaluate it like for built-in materials
  9070. Object.defineProperty( planeMesh.material, 'map', {
  9071. get: function () {
  9072. return this.uniforms.t2D.value;
  9073. }
  9074. } );
  9075. objects.update( planeMesh );
  9076. }
  9077. planeMesh.material.uniforms.t2D.value = background;
  9078. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  9079. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  9080. if ( background.matrixAutoUpdate === true ) {
  9081. background.updateMatrix();
  9082. }
  9083. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9084. if ( currentBackground !== background ||
  9085. currentBackgroundVersion !== background.version ||
  9086. currentTonemapping !== renderer.toneMapping ) {
  9087. planeMesh.material.needsUpdate = true;
  9088. currentBackground = background;
  9089. currentBackgroundVersion = background.version;
  9090. currentTonemapping = renderer.toneMapping;
  9091. }
  9092. planeMesh.layers.enableAll();
  9093. // push to the pre-sorted opaque render list
  9094. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9095. }
  9096. }
  9097. function setClear( color, alpha ) {
  9098. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  9099. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  9100. }
  9101. return {
  9102. getClearColor: function () {
  9103. return clearColor;
  9104. },
  9105. setClearColor: function ( color, alpha = 1 ) {
  9106. clearColor.set( color );
  9107. clearAlpha = alpha;
  9108. setClear( clearColor, clearAlpha );
  9109. },
  9110. getClearAlpha: function () {
  9111. return clearAlpha;
  9112. },
  9113. setClearAlpha: function ( alpha ) {
  9114. clearAlpha = alpha;
  9115. setClear( clearColor, clearAlpha );
  9116. },
  9117. render: render,
  9118. addToRenderList: addToRenderList
  9119. };
  9120. }
  9121. function WebGLBindingStates( gl, attributes ) {
  9122. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9123. const bindingStates = {};
  9124. const defaultState = createBindingState( null );
  9125. let currentState = defaultState;
  9126. let forceUpdate = false;
  9127. function setup( object, material, program, geometry, index ) {
  9128. let updateBuffers = false;
  9129. const state = getBindingState( geometry, program, material );
  9130. if ( currentState !== state ) {
  9131. currentState = state;
  9132. bindVertexArrayObject( currentState.object );
  9133. }
  9134. updateBuffers = needsUpdate( object, geometry, program, index );
  9135. if ( updateBuffers ) saveCache( object, geometry, program, index );
  9136. if ( index !== null ) {
  9137. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9138. }
  9139. if ( updateBuffers || forceUpdate ) {
  9140. forceUpdate = false;
  9141. setupVertexAttributes( object, material, program, geometry );
  9142. if ( index !== null ) {
  9143. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  9144. }
  9145. }
  9146. }
  9147. function createVertexArrayObject() {
  9148. return gl.createVertexArray();
  9149. }
  9150. function bindVertexArrayObject( vao ) {
  9151. return gl.bindVertexArray( vao );
  9152. }
  9153. function deleteVertexArrayObject( vao ) {
  9154. return gl.deleteVertexArray( vao );
  9155. }
  9156. function getBindingState( geometry, program, material ) {
  9157. const wireframe = ( material.wireframe === true );
  9158. let programMap = bindingStates[ geometry.id ];
  9159. if ( programMap === undefined ) {
  9160. programMap = {};
  9161. bindingStates[ geometry.id ] = programMap;
  9162. }
  9163. let stateMap = programMap[ program.id ];
  9164. if ( stateMap === undefined ) {
  9165. stateMap = {};
  9166. programMap[ program.id ] = stateMap;
  9167. }
  9168. let state = stateMap[ wireframe ];
  9169. if ( state === undefined ) {
  9170. state = createBindingState( createVertexArrayObject() );
  9171. stateMap[ wireframe ] = state;
  9172. }
  9173. return state;
  9174. }
  9175. function createBindingState( vao ) {
  9176. const newAttributes = [];
  9177. const enabledAttributes = [];
  9178. const attributeDivisors = [];
  9179. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9180. newAttributes[ i ] = 0;
  9181. enabledAttributes[ i ] = 0;
  9182. attributeDivisors[ i ] = 0;
  9183. }
  9184. return {
  9185. // for backward compatibility on non-VAO support browser
  9186. geometry: null,
  9187. program: null,
  9188. wireframe: false,
  9189. newAttributes: newAttributes,
  9190. enabledAttributes: enabledAttributes,
  9191. attributeDivisors: attributeDivisors,
  9192. object: vao,
  9193. attributes: {},
  9194. index: null
  9195. };
  9196. }
  9197. function needsUpdate( object, geometry, program, index ) {
  9198. const cachedAttributes = currentState.attributes;
  9199. const geometryAttributes = geometry.attributes;
  9200. let attributesNum = 0;
  9201. const programAttributes = program.getAttributes();
  9202. for ( const name in programAttributes ) {
  9203. const programAttribute = programAttributes[ name ];
  9204. if ( programAttribute.location >= 0 ) {
  9205. const cachedAttribute = cachedAttributes[ name ];
  9206. let geometryAttribute = geometryAttributes[ name ];
  9207. if ( geometryAttribute === undefined ) {
  9208. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9209. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9210. }
  9211. if ( cachedAttribute === undefined ) return true;
  9212. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9213. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9214. attributesNum ++;
  9215. }
  9216. }
  9217. if ( currentState.attributesNum !== attributesNum ) return true;
  9218. if ( currentState.index !== index ) return true;
  9219. return false;
  9220. }
  9221. function saveCache( object, geometry, program, index ) {
  9222. const cache = {};
  9223. const attributes = geometry.attributes;
  9224. let attributesNum = 0;
  9225. const programAttributes = program.getAttributes();
  9226. for ( const name in programAttributes ) {
  9227. const programAttribute = programAttributes[ name ];
  9228. if ( programAttribute.location >= 0 ) {
  9229. let attribute = attributes[ name ];
  9230. if ( attribute === undefined ) {
  9231. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9232. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9233. }
  9234. const data = {};
  9235. data.attribute = attribute;
  9236. if ( attribute && attribute.data ) {
  9237. data.data = attribute.data;
  9238. }
  9239. cache[ name ] = data;
  9240. attributesNum ++;
  9241. }
  9242. }
  9243. currentState.attributes = cache;
  9244. currentState.attributesNum = attributesNum;
  9245. currentState.index = index;
  9246. }
  9247. function initAttributes() {
  9248. const newAttributes = currentState.newAttributes;
  9249. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9250. newAttributes[ i ] = 0;
  9251. }
  9252. }
  9253. function enableAttribute( attribute ) {
  9254. enableAttributeAndDivisor( attribute, 0 );
  9255. }
  9256. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9257. const newAttributes = currentState.newAttributes;
  9258. const enabledAttributes = currentState.enabledAttributes;
  9259. const attributeDivisors = currentState.attributeDivisors;
  9260. newAttributes[ attribute ] = 1;
  9261. if ( enabledAttributes[ attribute ] === 0 ) {
  9262. gl.enableVertexAttribArray( attribute );
  9263. enabledAttributes[ attribute ] = 1;
  9264. }
  9265. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9266. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  9267. attributeDivisors[ attribute ] = meshPerAttribute;
  9268. }
  9269. }
  9270. function disableUnusedAttributes() {
  9271. const newAttributes = currentState.newAttributes;
  9272. const enabledAttributes = currentState.enabledAttributes;
  9273. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9274. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9275. gl.disableVertexAttribArray( i );
  9276. enabledAttributes[ i ] = 0;
  9277. }
  9278. }
  9279. }
  9280. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9281. if ( integer === true ) {
  9282. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9283. } else {
  9284. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9285. }
  9286. }
  9287. function setupVertexAttributes( object, material, program, geometry ) {
  9288. initAttributes();
  9289. const geometryAttributes = geometry.attributes;
  9290. const programAttributes = program.getAttributes();
  9291. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9292. for ( const name in programAttributes ) {
  9293. const programAttribute = programAttributes[ name ];
  9294. if ( programAttribute.location >= 0 ) {
  9295. let geometryAttribute = geometryAttributes[ name ];
  9296. if ( geometryAttribute === undefined ) {
  9297. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9298. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9299. }
  9300. if ( geometryAttribute !== undefined ) {
  9301. const normalized = geometryAttribute.normalized;
  9302. const size = geometryAttribute.itemSize;
  9303. const attribute = attributes.get( geometryAttribute );
  9304. // TODO Attribute may not be available on context restore
  9305. if ( attribute === undefined ) continue;
  9306. const buffer = attribute.buffer;
  9307. const type = attribute.type;
  9308. const bytesPerElement = attribute.bytesPerElement;
  9309. // check for integer attributes
  9310. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  9311. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9312. const data = geometryAttribute.data;
  9313. const stride = data.stride;
  9314. const offset = geometryAttribute.offset;
  9315. if ( data.isInstancedInterleavedBuffer ) {
  9316. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9317. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9318. }
  9319. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9320. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9321. }
  9322. } else {
  9323. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9324. enableAttribute( programAttribute.location + i );
  9325. }
  9326. }
  9327. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9328. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9329. vertexAttribPointer(
  9330. programAttribute.location + i,
  9331. size / programAttribute.locationSize,
  9332. type,
  9333. normalized,
  9334. stride * bytesPerElement,
  9335. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9336. integer
  9337. );
  9338. }
  9339. } else {
  9340. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9341. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9342. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9343. }
  9344. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9345. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9346. }
  9347. } else {
  9348. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9349. enableAttribute( programAttribute.location + i );
  9350. }
  9351. }
  9352. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9353. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9354. vertexAttribPointer(
  9355. programAttribute.location + i,
  9356. size / programAttribute.locationSize,
  9357. type,
  9358. normalized,
  9359. size * bytesPerElement,
  9360. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9361. integer
  9362. );
  9363. }
  9364. }
  9365. } else if ( materialDefaultAttributeValues !== undefined ) {
  9366. const value = materialDefaultAttributeValues[ name ];
  9367. if ( value !== undefined ) {
  9368. switch ( value.length ) {
  9369. case 2:
  9370. gl.vertexAttrib2fv( programAttribute.location, value );
  9371. break;
  9372. case 3:
  9373. gl.vertexAttrib3fv( programAttribute.location, value );
  9374. break;
  9375. case 4:
  9376. gl.vertexAttrib4fv( programAttribute.location, value );
  9377. break;
  9378. default:
  9379. gl.vertexAttrib1fv( programAttribute.location, value );
  9380. }
  9381. }
  9382. }
  9383. }
  9384. }
  9385. disableUnusedAttributes();
  9386. }
  9387. function dispose() {
  9388. reset();
  9389. for ( const geometryId in bindingStates ) {
  9390. const programMap = bindingStates[ geometryId ];
  9391. for ( const programId in programMap ) {
  9392. const stateMap = programMap[ programId ];
  9393. for ( const wireframe in stateMap ) {
  9394. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9395. delete stateMap[ wireframe ];
  9396. }
  9397. delete programMap[ programId ];
  9398. }
  9399. delete bindingStates[ geometryId ];
  9400. }
  9401. }
  9402. function releaseStatesOfGeometry( geometry ) {
  9403. if ( bindingStates[ geometry.id ] === undefined ) return;
  9404. const programMap = bindingStates[ geometry.id ];
  9405. for ( const programId in programMap ) {
  9406. const stateMap = programMap[ programId ];
  9407. for ( const wireframe in stateMap ) {
  9408. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9409. delete stateMap[ wireframe ];
  9410. }
  9411. delete programMap[ programId ];
  9412. }
  9413. delete bindingStates[ geometry.id ];
  9414. }
  9415. function releaseStatesOfProgram( program ) {
  9416. for ( const geometryId in bindingStates ) {
  9417. const programMap = bindingStates[ geometryId ];
  9418. if ( programMap[ program.id ] === undefined ) continue;
  9419. const stateMap = programMap[ program.id ];
  9420. for ( const wireframe in stateMap ) {
  9421. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9422. delete stateMap[ wireframe ];
  9423. }
  9424. delete programMap[ program.id ];
  9425. }
  9426. }
  9427. function reset() {
  9428. resetDefaultState();
  9429. forceUpdate = true;
  9430. if ( currentState === defaultState ) return;
  9431. currentState = defaultState;
  9432. bindVertexArrayObject( currentState.object );
  9433. }
  9434. // for backward-compatibility
  9435. function resetDefaultState() {
  9436. defaultState.geometry = null;
  9437. defaultState.program = null;
  9438. defaultState.wireframe = false;
  9439. }
  9440. return {
  9441. setup: setup,
  9442. reset: reset,
  9443. resetDefaultState: resetDefaultState,
  9444. dispose: dispose,
  9445. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9446. releaseStatesOfProgram: releaseStatesOfProgram,
  9447. initAttributes: initAttributes,
  9448. enableAttribute: enableAttribute,
  9449. disableUnusedAttributes: disableUnusedAttributes
  9450. };
  9451. }
  9452. function WebGLBufferRenderer( gl, extensions, info ) {
  9453. let mode;
  9454. function setMode( value ) {
  9455. mode = value;
  9456. }
  9457. function render( start, count ) {
  9458. gl.drawArrays( mode, start, count );
  9459. info.update( count, mode, 1 );
  9460. }
  9461. function renderInstances( start, count, primcount ) {
  9462. if ( primcount === 0 ) return;
  9463. gl.drawArraysInstanced( mode, start, count, primcount );
  9464. info.update( count, mode, primcount );
  9465. }
  9466. function renderMultiDraw( starts, counts, drawCount ) {
  9467. if ( drawCount === 0 ) return;
  9468. const extension = extensions.get( 'WEBGL_multi_draw' );
  9469. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  9470. let elementCount = 0;
  9471. for ( let i = 0; i < drawCount; i ++ ) {
  9472. elementCount += counts[ i ];
  9473. }
  9474. info.update( elementCount, mode, 1 );
  9475. }
  9476. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  9477. if ( drawCount === 0 ) return;
  9478. const extension = extensions.get( 'WEBGL_multi_draw' );
  9479. if ( extension === null ) {
  9480. for ( let i = 0; i < starts.length; i ++ ) {
  9481. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  9482. }
  9483. } else {
  9484. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  9485. let elementCount = 0;
  9486. for ( let i = 0; i < drawCount; i ++ ) {
  9487. elementCount += counts[ i ];
  9488. }
  9489. for ( let i = 0; i < primcount.length; i ++ ) {
  9490. info.update( elementCount, mode, primcount[ i ] );
  9491. }
  9492. }
  9493. }
  9494. //
  9495. this.setMode = setMode;
  9496. this.render = render;
  9497. this.renderInstances = renderInstances;
  9498. this.renderMultiDraw = renderMultiDraw;
  9499. this.renderMultiDrawInstances = renderMultiDrawInstances;
  9500. }
  9501. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  9502. let maxAnisotropy;
  9503. function getMaxAnisotropy() {
  9504. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9505. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9506. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9507. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9508. } else {
  9509. maxAnisotropy = 0;
  9510. }
  9511. return maxAnisotropy;
  9512. }
  9513. function textureFormatReadable( textureFormat ) {
  9514. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  9515. return false;
  9516. }
  9517. return true;
  9518. }
  9519. function textureTypeReadable( textureType ) {
  9520. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  9521. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  9522. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  9523. return false;
  9524. }
  9525. return true;
  9526. }
  9527. function getMaxPrecision( precision ) {
  9528. if ( precision === 'highp' ) {
  9529. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9530. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9531. return 'highp';
  9532. }
  9533. precision = 'mediump';
  9534. }
  9535. if ( precision === 'mediump' ) {
  9536. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9537. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9538. return 'mediump';
  9539. }
  9540. }
  9541. return 'lowp';
  9542. }
  9543. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9544. const maxPrecision = getMaxPrecision( precision );
  9545. if ( maxPrecision !== precision ) {
  9546. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9547. precision = maxPrecision;
  9548. }
  9549. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9550. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9551. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9552. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9553. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9554. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9555. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9556. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9557. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9558. const vertexTextures = maxVertexTextures > 0;
  9559. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  9560. return {
  9561. isWebGL2: true, // keeping this for backwards compatibility
  9562. getMaxAnisotropy: getMaxAnisotropy,
  9563. getMaxPrecision: getMaxPrecision,
  9564. textureFormatReadable: textureFormatReadable,
  9565. textureTypeReadable: textureTypeReadable,
  9566. precision: precision,
  9567. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9568. maxTextures: maxTextures,
  9569. maxVertexTextures: maxVertexTextures,
  9570. maxTextureSize: maxTextureSize,
  9571. maxCubemapSize: maxCubemapSize,
  9572. maxAttributes: maxAttributes,
  9573. maxVertexUniforms: maxVertexUniforms,
  9574. maxVaryings: maxVaryings,
  9575. maxFragmentUniforms: maxFragmentUniforms,
  9576. vertexTextures: vertexTextures,
  9577. maxSamples: maxSamples
  9578. };
  9579. }
  9580. function WebGLClipping( properties ) {
  9581. const scope = this;
  9582. let globalState = null,
  9583. numGlobalPlanes = 0,
  9584. localClippingEnabled = false,
  9585. renderingShadows = false;
  9586. const plane = new Plane(),
  9587. viewNormalMatrix = new Matrix3(),
  9588. uniform = { value: null, needsUpdate: false };
  9589. this.uniform = uniform;
  9590. this.numPlanes = 0;
  9591. this.numIntersection = 0;
  9592. this.init = function ( planes, enableLocalClipping ) {
  9593. const enabled =
  9594. planes.length !== 0 ||
  9595. enableLocalClipping ||
  9596. // enable state of previous frame - the clipping code has to
  9597. // run another frame in order to reset the state:
  9598. numGlobalPlanes !== 0 ||
  9599. localClippingEnabled;
  9600. localClippingEnabled = enableLocalClipping;
  9601. numGlobalPlanes = planes.length;
  9602. return enabled;
  9603. };
  9604. this.beginShadows = function () {
  9605. renderingShadows = true;
  9606. projectPlanes( null );
  9607. };
  9608. this.endShadows = function () {
  9609. renderingShadows = false;
  9610. };
  9611. this.setGlobalState = function ( planes, camera ) {
  9612. globalState = projectPlanes( planes, camera, 0 );
  9613. };
  9614. this.setState = function ( material, camera, useCache ) {
  9615. const planes = material.clippingPlanes,
  9616. clipIntersection = material.clipIntersection,
  9617. clipShadows = material.clipShadows;
  9618. const materialProperties = properties.get( material );
  9619. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9620. // there's no local clipping
  9621. if ( renderingShadows ) {
  9622. // there's no global clipping
  9623. projectPlanes( null );
  9624. } else {
  9625. resetGlobalState();
  9626. }
  9627. } else {
  9628. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9629. lGlobal = nGlobal * 4;
  9630. let dstArray = materialProperties.clippingState || null;
  9631. uniform.value = dstArray; // ensure unique state
  9632. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9633. for ( let i = 0; i !== lGlobal; ++ i ) {
  9634. dstArray[ i ] = globalState[ i ];
  9635. }
  9636. materialProperties.clippingState = dstArray;
  9637. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9638. this.numPlanes += nGlobal;
  9639. }
  9640. };
  9641. function resetGlobalState() {
  9642. if ( uniform.value !== globalState ) {
  9643. uniform.value = globalState;
  9644. uniform.needsUpdate = numGlobalPlanes > 0;
  9645. }
  9646. scope.numPlanes = numGlobalPlanes;
  9647. scope.numIntersection = 0;
  9648. }
  9649. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9650. const nPlanes = planes !== null ? planes.length : 0;
  9651. let dstArray = null;
  9652. if ( nPlanes !== 0 ) {
  9653. dstArray = uniform.value;
  9654. if ( skipTransform !== true || dstArray === null ) {
  9655. const flatSize = dstOffset + nPlanes * 4,
  9656. viewMatrix = camera.matrixWorldInverse;
  9657. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9658. if ( dstArray === null || dstArray.length < flatSize ) {
  9659. dstArray = new Float32Array( flatSize );
  9660. }
  9661. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9662. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9663. plane.normal.toArray( dstArray, i4 );
  9664. dstArray[ i4 + 3 ] = plane.constant;
  9665. }
  9666. }
  9667. uniform.value = dstArray;
  9668. uniform.needsUpdate = true;
  9669. }
  9670. scope.numPlanes = nPlanes;
  9671. scope.numIntersection = 0;
  9672. return dstArray;
  9673. }
  9674. }
  9675. function WebGLCubeMaps( renderer ) {
  9676. let cubemaps = new WeakMap();
  9677. function mapTextureMapping( texture, mapping ) {
  9678. if ( mapping === EquirectangularReflectionMapping ) {
  9679. texture.mapping = CubeReflectionMapping;
  9680. } else if ( mapping === EquirectangularRefractionMapping ) {
  9681. texture.mapping = CubeRefractionMapping;
  9682. }
  9683. return texture;
  9684. }
  9685. function get( texture ) {
  9686. if ( texture && texture.isTexture ) {
  9687. const mapping = texture.mapping;
  9688. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9689. if ( cubemaps.has( texture ) ) {
  9690. const cubemap = cubemaps.get( texture ).texture;
  9691. return mapTextureMapping( cubemap, texture.mapping );
  9692. } else {
  9693. const image = texture.image;
  9694. if ( image && image.height > 0 ) {
  9695. const renderTarget = new WebGLCubeRenderTarget( image.height );
  9696. renderTarget.fromEquirectangularTexture( renderer, texture );
  9697. cubemaps.set( texture, renderTarget );
  9698. texture.addEventListener( 'dispose', onTextureDispose );
  9699. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9700. } else {
  9701. // image not yet ready. try the conversion next frame
  9702. return null;
  9703. }
  9704. }
  9705. }
  9706. }
  9707. return texture;
  9708. }
  9709. function onTextureDispose( event ) {
  9710. const texture = event.target;
  9711. texture.removeEventListener( 'dispose', onTextureDispose );
  9712. const cubemap = cubemaps.get( texture );
  9713. if ( cubemap !== undefined ) {
  9714. cubemaps.delete( texture );
  9715. cubemap.dispose();
  9716. }
  9717. }
  9718. function dispose() {
  9719. cubemaps = new WeakMap();
  9720. }
  9721. return {
  9722. get: get,
  9723. dispose: dispose
  9724. };
  9725. }
  9726. class OrthographicCamera extends Camera {
  9727. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9728. super();
  9729. this.isOrthographicCamera = true;
  9730. this.type = 'OrthographicCamera';
  9731. this.zoom = 1;
  9732. this.view = null;
  9733. this.left = left;
  9734. this.right = right;
  9735. this.top = top;
  9736. this.bottom = bottom;
  9737. this.near = near;
  9738. this.far = far;
  9739. this.updateProjectionMatrix();
  9740. }
  9741. copy( source, recursive ) {
  9742. super.copy( source, recursive );
  9743. this.left = source.left;
  9744. this.right = source.right;
  9745. this.top = source.top;
  9746. this.bottom = source.bottom;
  9747. this.near = source.near;
  9748. this.far = source.far;
  9749. this.zoom = source.zoom;
  9750. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9751. return this;
  9752. }
  9753. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9754. if ( this.view === null ) {
  9755. this.view = {
  9756. enabled: true,
  9757. fullWidth: 1,
  9758. fullHeight: 1,
  9759. offsetX: 0,
  9760. offsetY: 0,
  9761. width: 1,
  9762. height: 1
  9763. };
  9764. }
  9765. this.view.enabled = true;
  9766. this.view.fullWidth = fullWidth;
  9767. this.view.fullHeight = fullHeight;
  9768. this.view.offsetX = x;
  9769. this.view.offsetY = y;
  9770. this.view.width = width;
  9771. this.view.height = height;
  9772. this.updateProjectionMatrix();
  9773. }
  9774. clearViewOffset() {
  9775. if ( this.view !== null ) {
  9776. this.view.enabled = false;
  9777. }
  9778. this.updateProjectionMatrix();
  9779. }
  9780. updateProjectionMatrix() {
  9781. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9782. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9783. const cx = ( this.right + this.left ) / 2;
  9784. const cy = ( this.top + this.bottom ) / 2;
  9785. let left = cx - dx;
  9786. let right = cx + dx;
  9787. let top = cy + dy;
  9788. let bottom = cy - dy;
  9789. if ( this.view !== null && this.view.enabled ) {
  9790. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9791. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9792. left += scaleW * this.view.offsetX;
  9793. right = left + scaleW * this.view.width;
  9794. top -= scaleH * this.view.offsetY;
  9795. bottom = top - scaleH * this.view.height;
  9796. }
  9797. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9798. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9799. }
  9800. toJSON( meta ) {
  9801. const data = super.toJSON( meta );
  9802. data.object.zoom = this.zoom;
  9803. data.object.left = this.left;
  9804. data.object.right = this.right;
  9805. data.object.top = this.top;
  9806. data.object.bottom = this.bottom;
  9807. data.object.near = this.near;
  9808. data.object.far = this.far;
  9809. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9810. return data;
  9811. }
  9812. }
  9813. const LOD_MIN = 4;
  9814. // The standard deviations (radians) associated with the extra mips. These are
  9815. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9816. // geometric shadowing function. These sigma values squared must match the
  9817. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9818. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9819. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9820. // samples and exit early, but not recompile the shader.
  9821. const MAX_SAMPLES = 20;
  9822. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9823. const _clearColor = /*@__PURE__*/ new Color();
  9824. let _oldTarget = null;
  9825. let _oldActiveCubeFace = 0;
  9826. let _oldActiveMipmapLevel = 0;
  9827. let _oldXrEnabled = false;
  9828. // Golden Ratio
  9829. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9830. const INV_PHI = 1 / PHI;
  9831. // Vertices of a dodecahedron (except the opposites, which represent the
  9832. // same axis), used as axis directions evenly spread on a sphere.
  9833. const _axisDirections = [
  9834. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  9835. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9836. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9837. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9838. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9839. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9840. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9841. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9842. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9843. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  9844. /**
  9845. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9846. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9847. * blur to be quickly accessed based on material roughness. It is packed into a
  9848. * special CubeUV format that allows us to perform custom interpolation so that
  9849. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9850. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9851. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9852. * higher roughness levels. In this way we maintain resolution to smoothly
  9853. * interpolate diffuse lighting while limiting sampling computation.
  9854. *
  9855. * Paper: Fast, Accurate Image-Based Lighting
  9856. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9857. */
  9858. class PMREMGenerator {
  9859. constructor( renderer ) {
  9860. this._renderer = renderer;
  9861. this._pingPongRenderTarget = null;
  9862. this._lodMax = 0;
  9863. this._cubeSize = 0;
  9864. this._lodPlanes = [];
  9865. this._sizeLods = [];
  9866. this._sigmas = [];
  9867. this._blurMaterial = null;
  9868. this._cubemapMaterial = null;
  9869. this._equirectMaterial = null;
  9870. this._compileMaterial( this._blurMaterial );
  9871. }
  9872. /**
  9873. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9874. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9875. * in radians to be applied to the scene before PMREM generation. Optional near
  9876. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9877. * is placed at the origin).
  9878. */
  9879. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9880. _oldTarget = this._renderer.getRenderTarget();
  9881. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9882. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9883. _oldXrEnabled = this._renderer.xr.enabled;
  9884. this._renderer.xr.enabled = false;
  9885. this._setSize( 256 );
  9886. const cubeUVRenderTarget = this._allocateTargets();
  9887. cubeUVRenderTarget.depthBuffer = true;
  9888. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9889. if ( sigma > 0 ) {
  9890. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9891. }
  9892. this._applyPMREM( cubeUVRenderTarget );
  9893. this._cleanup( cubeUVRenderTarget );
  9894. return cubeUVRenderTarget;
  9895. }
  9896. /**
  9897. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9898. * or HDR. The ideal input image size is 1k (1024 x 512),
  9899. * as this matches best with the 256 x 256 cubemap output.
  9900. * The smallest supported equirectangular image size is 64 x 32.
  9901. */
  9902. fromEquirectangular( equirectangular, renderTarget = null ) {
  9903. return this._fromTexture( equirectangular, renderTarget );
  9904. }
  9905. /**
  9906. * Generates a PMREM from an cubemap texture, which can be either LDR
  9907. * or HDR. The ideal input cube size is 256 x 256,
  9908. * as this matches best with the 256 x 256 cubemap output.
  9909. * The smallest supported cube size is 16 x 16.
  9910. */
  9911. fromCubemap( cubemap, renderTarget = null ) {
  9912. return this._fromTexture( cubemap, renderTarget );
  9913. }
  9914. /**
  9915. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9916. * your texture's network fetch for increased concurrency.
  9917. */
  9918. compileCubemapShader() {
  9919. if ( this._cubemapMaterial === null ) {
  9920. this._cubemapMaterial = _getCubemapMaterial();
  9921. this._compileMaterial( this._cubemapMaterial );
  9922. }
  9923. }
  9924. /**
  9925. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9926. * your texture's network fetch for increased concurrency.
  9927. */
  9928. compileEquirectangularShader() {
  9929. if ( this._equirectMaterial === null ) {
  9930. this._equirectMaterial = _getEquirectMaterial();
  9931. this._compileMaterial( this._equirectMaterial );
  9932. }
  9933. }
  9934. /**
  9935. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9936. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9937. * one of them will cause any others to also become unusable.
  9938. */
  9939. dispose() {
  9940. this._dispose();
  9941. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9942. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9943. }
  9944. // private interface
  9945. _setSize( cubeSize ) {
  9946. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9947. this._cubeSize = Math.pow( 2, this._lodMax );
  9948. }
  9949. _dispose() {
  9950. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9951. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9952. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9953. this._lodPlanes[ i ].dispose();
  9954. }
  9955. }
  9956. _cleanup( outputTarget ) {
  9957. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  9958. this._renderer.xr.enabled = _oldXrEnabled;
  9959. outputTarget.scissorTest = false;
  9960. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9961. }
  9962. _fromTexture( texture, renderTarget ) {
  9963. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9964. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9965. } else { // Equirectangular
  9966. this._setSize( texture.image.width / 4 );
  9967. }
  9968. _oldTarget = this._renderer.getRenderTarget();
  9969. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9970. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9971. _oldXrEnabled = this._renderer.xr.enabled;
  9972. this._renderer.xr.enabled = false;
  9973. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9974. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9975. this._applyPMREM( cubeUVRenderTarget );
  9976. this._cleanup( cubeUVRenderTarget );
  9977. return cubeUVRenderTarget;
  9978. }
  9979. _allocateTargets() {
  9980. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9981. const height = 4 * this._cubeSize;
  9982. const params = {
  9983. magFilter: LinearFilter,
  9984. minFilter: LinearFilter,
  9985. generateMipmaps: false,
  9986. type: HalfFloatType,
  9987. format: RGBAFormat,
  9988. colorSpace: LinearSRGBColorSpace,
  9989. depthBuffer: false
  9990. };
  9991. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9992. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9993. if ( this._pingPongRenderTarget !== null ) {
  9994. this._dispose();
  9995. }
  9996. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9997. const { _lodMax } = this;
  9998. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9999. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  10000. }
  10001. return cubeUVRenderTarget;
  10002. }
  10003. _compileMaterial( material ) {
  10004. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  10005. this._renderer.compile( tmpMesh, _flatCamera );
  10006. }
  10007. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  10008. const fov = 90;
  10009. const aspect = 1;
  10010. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  10011. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  10012. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  10013. const renderer = this._renderer;
  10014. const originalAutoClear = renderer.autoClear;
  10015. const toneMapping = renderer.toneMapping;
  10016. renderer.getClearColor( _clearColor );
  10017. renderer.toneMapping = NoToneMapping;
  10018. renderer.autoClear = false;
  10019. const backgroundMaterial = new MeshBasicMaterial( {
  10020. name: 'PMREM.Background',
  10021. side: BackSide,
  10022. depthWrite: false,
  10023. depthTest: false,
  10024. } );
  10025. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  10026. let useSolidColor = false;
  10027. const background = scene.background;
  10028. if ( background ) {
  10029. if ( background.isColor ) {
  10030. backgroundMaterial.color.copy( background );
  10031. scene.background = null;
  10032. useSolidColor = true;
  10033. }
  10034. } else {
  10035. backgroundMaterial.color.copy( _clearColor );
  10036. useSolidColor = true;
  10037. }
  10038. for ( let i = 0; i < 6; i ++ ) {
  10039. const col = i % 3;
  10040. if ( col === 0 ) {
  10041. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10042. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  10043. } else if ( col === 1 ) {
  10044. cubeCamera.up.set( 0, 0, upSign[ i ] );
  10045. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  10046. } else {
  10047. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10048. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  10049. }
  10050. const size = this._cubeSize;
  10051. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  10052. renderer.setRenderTarget( cubeUVRenderTarget );
  10053. if ( useSolidColor ) {
  10054. renderer.render( backgroundBox, cubeCamera );
  10055. }
  10056. renderer.render( scene, cubeCamera );
  10057. }
  10058. backgroundBox.geometry.dispose();
  10059. backgroundBox.material.dispose();
  10060. renderer.toneMapping = toneMapping;
  10061. renderer.autoClear = originalAutoClear;
  10062. scene.background = background;
  10063. }
  10064. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  10065. const renderer = this._renderer;
  10066. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  10067. if ( isCubeTexture ) {
  10068. if ( this._cubemapMaterial === null ) {
  10069. this._cubemapMaterial = _getCubemapMaterial();
  10070. }
  10071. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  10072. } else {
  10073. if ( this._equirectMaterial === null ) {
  10074. this._equirectMaterial = _getEquirectMaterial();
  10075. }
  10076. }
  10077. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  10078. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  10079. const uniforms = material.uniforms;
  10080. uniforms[ 'envMap' ].value = texture;
  10081. const size = this._cubeSize;
  10082. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  10083. renderer.setRenderTarget( cubeUVRenderTarget );
  10084. renderer.render( mesh, _flatCamera );
  10085. }
  10086. _applyPMREM( cubeUVRenderTarget ) {
  10087. const renderer = this._renderer;
  10088. const autoClear = renderer.autoClear;
  10089. renderer.autoClear = false;
  10090. const n = this._lodPlanes.length;
  10091. for ( let i = 1; i < n; i ++ ) {
  10092. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  10093. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  10094. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  10095. }
  10096. renderer.autoClear = autoClear;
  10097. }
  10098. /**
  10099. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  10100. * vertically and horizontally, but this breaks down on a cube. Here we apply
  10101. * the blur latitudinally (around the poles), and then longitudinally (towards
  10102. * the poles) to approximate the orthogonally-separable blur. It is least
  10103. * accurate at the poles, but still does a decent job.
  10104. */
  10105. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  10106. const pingPongRenderTarget = this._pingPongRenderTarget;
  10107. this._halfBlur(
  10108. cubeUVRenderTarget,
  10109. pingPongRenderTarget,
  10110. lodIn,
  10111. lodOut,
  10112. sigma,
  10113. 'latitudinal',
  10114. poleAxis );
  10115. this._halfBlur(
  10116. pingPongRenderTarget,
  10117. cubeUVRenderTarget,
  10118. lodOut,
  10119. lodOut,
  10120. sigma,
  10121. 'longitudinal',
  10122. poleAxis );
  10123. }
  10124. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  10125. const renderer = this._renderer;
  10126. const blurMaterial = this._blurMaterial;
  10127. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  10128. console.error(
  10129. 'blur direction must be either latitudinal or longitudinal!' );
  10130. }
  10131. // Number of standard deviations at which to cut off the discrete approximation.
  10132. const STANDARD_DEVIATIONS = 3;
  10133. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  10134. const blurUniforms = blurMaterial.uniforms;
  10135. const pixels = this._sizeLods[ lodIn ] - 1;
  10136. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  10137. const sigmaPixels = sigmaRadians / radiansPerPixel;
  10138. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  10139. if ( samples > MAX_SAMPLES ) {
  10140. console.warn( `sigmaRadians, ${
  10141. sigmaRadians}, is too large and will clip, as it requested ${
  10142. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  10143. }
  10144. const weights = [];
  10145. let sum = 0;
  10146. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  10147. const x = i / sigmaPixels;
  10148. const weight = Math.exp( - x * x / 2 );
  10149. weights.push( weight );
  10150. if ( i === 0 ) {
  10151. sum += weight;
  10152. } else if ( i < samples ) {
  10153. sum += 2 * weight;
  10154. }
  10155. }
  10156. for ( let i = 0; i < weights.length; i ++ ) {
  10157. weights[ i ] = weights[ i ] / sum;
  10158. }
  10159. blurUniforms[ 'envMap' ].value = targetIn.texture;
  10160. blurUniforms[ 'samples' ].value = samples;
  10161. blurUniforms[ 'weights' ].value = weights;
  10162. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  10163. if ( poleAxis ) {
  10164. blurUniforms[ 'poleAxis' ].value = poleAxis;
  10165. }
  10166. const { _lodMax } = this;
  10167. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  10168. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  10169. const outputSize = this._sizeLods[ lodOut ];
  10170. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  10171. const y = 4 * ( this._cubeSize - outputSize );
  10172. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10173. renderer.setRenderTarget( targetOut );
  10174. renderer.render( blurMesh, _flatCamera );
  10175. }
  10176. }
  10177. function _createPlanes( lodMax ) {
  10178. const lodPlanes = [];
  10179. const sizeLods = [];
  10180. const sigmas = [];
  10181. let lod = lodMax;
  10182. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10183. for ( let i = 0; i < totalLods; i ++ ) {
  10184. const sizeLod = Math.pow( 2, lod );
  10185. sizeLods.push( sizeLod );
  10186. let sigma = 1.0 / sizeLod;
  10187. if ( i > lodMax - LOD_MIN ) {
  10188. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  10189. } else if ( i === 0 ) {
  10190. sigma = 0;
  10191. }
  10192. sigmas.push( sigma );
  10193. const texelSize = 1.0 / ( sizeLod - 2 );
  10194. const min = - texelSize;
  10195. const max = 1 + texelSize;
  10196. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10197. const cubeFaces = 6;
  10198. const vertices = 6;
  10199. const positionSize = 3;
  10200. const uvSize = 2;
  10201. const faceIndexSize = 1;
  10202. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10203. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10204. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10205. for ( let face = 0; face < cubeFaces; face ++ ) {
  10206. const x = ( face % 3 ) * 2 / 3 - 1;
  10207. const y = face > 2 ? 0 : - 1;
  10208. const coordinates = [
  10209. x, y, 0,
  10210. x + 2 / 3, y, 0,
  10211. x + 2 / 3, y + 1, 0,
  10212. x, y, 0,
  10213. x + 2 / 3, y + 1, 0,
  10214. x, y + 1, 0
  10215. ];
  10216. position.set( coordinates, positionSize * vertices * face );
  10217. uv.set( uv1, uvSize * vertices * face );
  10218. const fill = [ face, face, face, face, face, face ];
  10219. faceIndex.set( fill, faceIndexSize * vertices * face );
  10220. }
  10221. const planes = new BufferGeometry();
  10222. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10223. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10224. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10225. lodPlanes.push( planes );
  10226. if ( lod > LOD_MIN ) {
  10227. lod --;
  10228. }
  10229. }
  10230. return { lodPlanes, sizeLods, sigmas };
  10231. }
  10232. function _createRenderTarget( width, height, params ) {
  10233. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10234. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10235. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10236. cubeUVRenderTarget.scissorTest = true;
  10237. return cubeUVRenderTarget;
  10238. }
  10239. function _setViewport( target, x, y, width, height ) {
  10240. target.viewport.set( x, y, width, height );
  10241. target.scissor.set( x, y, width, height );
  10242. }
  10243. function _getBlurShader( lodMax, width, height ) {
  10244. const weights = new Float32Array( MAX_SAMPLES );
  10245. const poleAxis = new Vector3( 0, 1, 0 );
  10246. const shaderMaterial = new ShaderMaterial( {
  10247. name: 'SphericalGaussianBlur',
  10248. defines: {
  10249. 'n': MAX_SAMPLES,
  10250. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10251. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10252. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10253. },
  10254. uniforms: {
  10255. 'envMap': { value: null },
  10256. 'samples': { value: 1 },
  10257. 'weights': { value: weights },
  10258. 'latitudinal': { value: false },
  10259. 'dTheta': { value: 0 },
  10260. 'mipInt': { value: 0 },
  10261. 'poleAxis': { value: poleAxis }
  10262. },
  10263. vertexShader: _getCommonVertexShader(),
  10264. fragmentShader: /* glsl */`
  10265. precision mediump float;
  10266. precision mediump int;
  10267. varying vec3 vOutputDirection;
  10268. uniform sampler2D envMap;
  10269. uniform int samples;
  10270. uniform float weights[ n ];
  10271. uniform bool latitudinal;
  10272. uniform float dTheta;
  10273. uniform float mipInt;
  10274. uniform vec3 poleAxis;
  10275. #define ENVMAP_TYPE_CUBE_UV
  10276. #include <cube_uv_reflection_fragment>
  10277. vec3 getSample( float theta, vec3 axis ) {
  10278. float cosTheta = cos( theta );
  10279. // Rodrigues' axis-angle rotation
  10280. vec3 sampleDirection = vOutputDirection * cosTheta
  10281. + cross( axis, vOutputDirection ) * sin( theta )
  10282. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10283. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10284. }
  10285. void main() {
  10286. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10287. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10288. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10289. }
  10290. axis = normalize( axis );
  10291. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10292. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10293. for ( int i = 1; i < n; i++ ) {
  10294. if ( i >= samples ) {
  10295. break;
  10296. }
  10297. float theta = dTheta * float( i );
  10298. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10299. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10300. }
  10301. }
  10302. `,
  10303. blending: NoBlending,
  10304. depthTest: false,
  10305. depthWrite: false
  10306. } );
  10307. return shaderMaterial;
  10308. }
  10309. function _getEquirectMaterial() {
  10310. return new ShaderMaterial( {
  10311. name: 'EquirectangularToCubeUV',
  10312. uniforms: {
  10313. 'envMap': { value: null }
  10314. },
  10315. vertexShader: _getCommonVertexShader(),
  10316. fragmentShader: /* glsl */`
  10317. precision mediump float;
  10318. precision mediump int;
  10319. varying vec3 vOutputDirection;
  10320. uniform sampler2D envMap;
  10321. #include <common>
  10322. void main() {
  10323. vec3 outputDirection = normalize( vOutputDirection );
  10324. vec2 uv = equirectUv( outputDirection );
  10325. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10326. }
  10327. `,
  10328. blending: NoBlending,
  10329. depthTest: false,
  10330. depthWrite: false
  10331. } );
  10332. }
  10333. function _getCubemapMaterial() {
  10334. return new ShaderMaterial( {
  10335. name: 'CubemapToCubeUV',
  10336. uniforms: {
  10337. 'envMap': { value: null },
  10338. 'flipEnvMap': { value: - 1 }
  10339. },
  10340. vertexShader: _getCommonVertexShader(),
  10341. fragmentShader: /* glsl */`
  10342. precision mediump float;
  10343. precision mediump int;
  10344. uniform float flipEnvMap;
  10345. varying vec3 vOutputDirection;
  10346. uniform samplerCube envMap;
  10347. void main() {
  10348. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10349. }
  10350. `,
  10351. blending: NoBlending,
  10352. depthTest: false,
  10353. depthWrite: false
  10354. } );
  10355. }
  10356. function _getCommonVertexShader() {
  10357. return /* glsl */`
  10358. precision mediump float;
  10359. precision mediump int;
  10360. attribute float faceIndex;
  10361. varying vec3 vOutputDirection;
  10362. // RH coordinate system; PMREM face-indexing convention
  10363. vec3 getDirection( vec2 uv, float face ) {
  10364. uv = 2.0 * uv - 1.0;
  10365. vec3 direction = vec3( uv, 1.0 );
  10366. if ( face == 0.0 ) {
  10367. direction = direction.zyx; // ( 1, v, u ) pos x
  10368. } else if ( face == 1.0 ) {
  10369. direction = direction.xzy;
  10370. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10371. } else if ( face == 2.0 ) {
  10372. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10373. } else if ( face == 3.0 ) {
  10374. direction = direction.zyx;
  10375. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10376. } else if ( face == 4.0 ) {
  10377. direction = direction.xzy;
  10378. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10379. } else if ( face == 5.0 ) {
  10380. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10381. }
  10382. return direction;
  10383. }
  10384. void main() {
  10385. vOutputDirection = getDirection( uv, faceIndex );
  10386. gl_Position = vec4( position, 1.0 );
  10387. }
  10388. `;
  10389. }
  10390. function WebGLCubeUVMaps( renderer ) {
  10391. let cubeUVmaps = new WeakMap();
  10392. let pmremGenerator = null;
  10393. function get( texture ) {
  10394. if ( texture && texture.isTexture ) {
  10395. const mapping = texture.mapping;
  10396. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10397. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10398. // equirect/cube map to cubeUV conversion
  10399. if ( isEquirectMap || isCubeMap ) {
  10400. let renderTarget = cubeUVmaps.get( texture );
  10401. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  10402. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  10403. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10404. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10405. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10406. cubeUVmaps.set( texture, renderTarget );
  10407. return renderTarget.texture;
  10408. } else {
  10409. if ( renderTarget !== undefined ) {
  10410. return renderTarget.texture;
  10411. } else {
  10412. const image = texture.image;
  10413. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10414. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10415. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10416. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10417. cubeUVmaps.set( texture, renderTarget );
  10418. texture.addEventListener( 'dispose', onTextureDispose );
  10419. return renderTarget.texture;
  10420. } else {
  10421. // image not yet ready. try the conversion next frame
  10422. return null;
  10423. }
  10424. }
  10425. }
  10426. }
  10427. }
  10428. return texture;
  10429. }
  10430. function isCubeTextureComplete( image ) {
  10431. let count = 0;
  10432. const length = 6;
  10433. for ( let i = 0; i < length; i ++ ) {
  10434. if ( image[ i ] !== undefined ) count ++;
  10435. }
  10436. return count === length;
  10437. }
  10438. function onTextureDispose( event ) {
  10439. const texture = event.target;
  10440. texture.removeEventListener( 'dispose', onTextureDispose );
  10441. const cubemapUV = cubeUVmaps.get( texture );
  10442. if ( cubemapUV !== undefined ) {
  10443. cubeUVmaps.delete( texture );
  10444. cubemapUV.dispose();
  10445. }
  10446. }
  10447. function dispose() {
  10448. cubeUVmaps = new WeakMap();
  10449. if ( pmremGenerator !== null ) {
  10450. pmremGenerator.dispose();
  10451. pmremGenerator = null;
  10452. }
  10453. }
  10454. return {
  10455. get: get,
  10456. dispose: dispose
  10457. };
  10458. }
  10459. function WebGLExtensions( gl ) {
  10460. const extensions = {};
  10461. function getExtension( name ) {
  10462. if ( extensions[ name ] !== undefined ) {
  10463. return extensions[ name ];
  10464. }
  10465. let extension;
  10466. switch ( name ) {
  10467. case 'WEBGL_depth_texture':
  10468. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10469. break;
  10470. case 'EXT_texture_filter_anisotropic':
  10471. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10472. break;
  10473. case 'WEBGL_compressed_texture_s3tc':
  10474. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10475. break;
  10476. case 'WEBGL_compressed_texture_pvrtc':
  10477. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10478. break;
  10479. default:
  10480. extension = gl.getExtension( name );
  10481. }
  10482. extensions[ name ] = extension;
  10483. return extension;
  10484. }
  10485. return {
  10486. has: function ( name ) {
  10487. return getExtension( name ) !== null;
  10488. },
  10489. init: function () {
  10490. getExtension( 'EXT_color_buffer_float' );
  10491. getExtension( 'WEBGL_clip_cull_distance' );
  10492. getExtension( 'OES_texture_float_linear' );
  10493. getExtension( 'EXT_color_buffer_half_float' );
  10494. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10495. getExtension( 'WEBGL_render_shared_exponent' );
  10496. },
  10497. get: function ( name ) {
  10498. const extension = getExtension( name );
  10499. if ( extension === null ) {
  10500. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10501. }
  10502. return extension;
  10503. }
  10504. };
  10505. }
  10506. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10507. const geometries = {};
  10508. const wireframeAttributes = new WeakMap();
  10509. function onGeometryDispose( event ) {
  10510. const geometry = event.target;
  10511. if ( geometry.index !== null ) {
  10512. attributes.remove( geometry.index );
  10513. }
  10514. for ( const name in geometry.attributes ) {
  10515. attributes.remove( geometry.attributes[ name ] );
  10516. }
  10517. for ( const name in geometry.morphAttributes ) {
  10518. const array = geometry.morphAttributes[ name ];
  10519. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10520. attributes.remove( array[ i ] );
  10521. }
  10522. }
  10523. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10524. delete geometries[ geometry.id ];
  10525. const attribute = wireframeAttributes.get( geometry );
  10526. if ( attribute ) {
  10527. attributes.remove( attribute );
  10528. wireframeAttributes.delete( geometry );
  10529. }
  10530. bindingStates.releaseStatesOfGeometry( geometry );
  10531. if ( geometry.isInstancedBufferGeometry === true ) {
  10532. delete geometry._maxInstanceCount;
  10533. }
  10534. //
  10535. info.memory.geometries --;
  10536. }
  10537. function get( object, geometry ) {
  10538. if ( geometries[ geometry.id ] === true ) return geometry;
  10539. geometry.addEventListener( 'dispose', onGeometryDispose );
  10540. geometries[ geometry.id ] = true;
  10541. info.memory.geometries ++;
  10542. return geometry;
  10543. }
  10544. function update( geometry ) {
  10545. const geometryAttributes = geometry.attributes;
  10546. // Updating index buffer in VAO now. See WebGLBindingStates.
  10547. for ( const name in geometryAttributes ) {
  10548. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10549. }
  10550. // morph targets
  10551. const morphAttributes = geometry.morphAttributes;
  10552. for ( const name in morphAttributes ) {
  10553. const array = morphAttributes[ name ];
  10554. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10555. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10556. }
  10557. }
  10558. }
  10559. function updateWireframeAttribute( geometry ) {
  10560. const indices = [];
  10561. const geometryIndex = geometry.index;
  10562. const geometryPosition = geometry.attributes.position;
  10563. let version = 0;
  10564. if ( geometryIndex !== null ) {
  10565. const array = geometryIndex.array;
  10566. version = geometryIndex.version;
  10567. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10568. const a = array[ i + 0 ];
  10569. const b = array[ i + 1 ];
  10570. const c = array[ i + 2 ];
  10571. indices.push( a, b, b, c, c, a );
  10572. }
  10573. } else if ( geometryPosition !== undefined ) {
  10574. const array = geometryPosition.array;
  10575. version = geometryPosition.version;
  10576. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10577. const a = i + 0;
  10578. const b = i + 1;
  10579. const c = i + 2;
  10580. indices.push( a, b, b, c, c, a );
  10581. }
  10582. } else {
  10583. return;
  10584. }
  10585. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10586. attribute.version = version;
  10587. // Updating index buffer in VAO now. See WebGLBindingStates
  10588. //
  10589. const previousAttribute = wireframeAttributes.get( geometry );
  10590. if ( previousAttribute ) attributes.remove( previousAttribute );
  10591. //
  10592. wireframeAttributes.set( geometry, attribute );
  10593. }
  10594. function getWireframeAttribute( geometry ) {
  10595. const currentAttribute = wireframeAttributes.get( geometry );
  10596. if ( currentAttribute ) {
  10597. const geometryIndex = geometry.index;
  10598. if ( geometryIndex !== null ) {
  10599. // if the attribute is obsolete, create a new one
  10600. if ( currentAttribute.version < geometryIndex.version ) {
  10601. updateWireframeAttribute( geometry );
  10602. }
  10603. }
  10604. } else {
  10605. updateWireframeAttribute( geometry );
  10606. }
  10607. return wireframeAttributes.get( geometry );
  10608. }
  10609. return {
  10610. get: get,
  10611. update: update,
  10612. getWireframeAttribute: getWireframeAttribute
  10613. };
  10614. }
  10615. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  10616. let mode;
  10617. function setMode( value ) {
  10618. mode = value;
  10619. }
  10620. let type, bytesPerElement;
  10621. function setIndex( value ) {
  10622. type = value.type;
  10623. bytesPerElement = value.bytesPerElement;
  10624. }
  10625. function render( start, count ) {
  10626. gl.drawElements( mode, count, type, start * bytesPerElement );
  10627. info.update( count, mode, 1 );
  10628. }
  10629. function renderInstances( start, count, primcount ) {
  10630. if ( primcount === 0 ) return;
  10631. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  10632. info.update( count, mode, primcount );
  10633. }
  10634. function renderMultiDraw( starts, counts, drawCount ) {
  10635. if ( drawCount === 0 ) return;
  10636. const extension = extensions.get( 'WEBGL_multi_draw' );
  10637. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  10638. let elementCount = 0;
  10639. for ( let i = 0; i < drawCount; i ++ ) {
  10640. elementCount += counts[ i ];
  10641. }
  10642. info.update( elementCount, mode, 1 );
  10643. }
  10644. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  10645. if ( drawCount === 0 ) return;
  10646. const extension = extensions.get( 'WEBGL_multi_draw' );
  10647. if ( extension === null ) {
  10648. for ( let i = 0; i < starts.length; i ++ ) {
  10649. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  10650. }
  10651. } else {
  10652. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  10653. let elementCount = 0;
  10654. for ( let i = 0; i < drawCount; i ++ ) {
  10655. elementCount += counts[ i ];
  10656. }
  10657. for ( let i = 0; i < primcount.length; i ++ ) {
  10658. info.update( elementCount, mode, primcount[ i ] );
  10659. }
  10660. }
  10661. }
  10662. //
  10663. this.setMode = setMode;
  10664. this.setIndex = setIndex;
  10665. this.render = render;
  10666. this.renderInstances = renderInstances;
  10667. this.renderMultiDraw = renderMultiDraw;
  10668. this.renderMultiDrawInstances = renderMultiDrawInstances;
  10669. }
  10670. function WebGLInfo( gl ) {
  10671. const memory = {
  10672. geometries: 0,
  10673. textures: 0
  10674. };
  10675. const render = {
  10676. frame: 0,
  10677. calls: 0,
  10678. triangles: 0,
  10679. points: 0,
  10680. lines: 0
  10681. };
  10682. function update( count, mode, instanceCount ) {
  10683. render.calls ++;
  10684. switch ( mode ) {
  10685. case gl.TRIANGLES:
  10686. render.triangles += instanceCount * ( count / 3 );
  10687. break;
  10688. case gl.LINES:
  10689. render.lines += instanceCount * ( count / 2 );
  10690. break;
  10691. case gl.LINE_STRIP:
  10692. render.lines += instanceCount * ( count - 1 );
  10693. break;
  10694. case gl.LINE_LOOP:
  10695. render.lines += instanceCount * count;
  10696. break;
  10697. case gl.POINTS:
  10698. render.points += instanceCount * count;
  10699. break;
  10700. default:
  10701. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10702. break;
  10703. }
  10704. }
  10705. function reset() {
  10706. render.calls = 0;
  10707. render.triangles = 0;
  10708. render.points = 0;
  10709. render.lines = 0;
  10710. }
  10711. return {
  10712. memory: memory,
  10713. render: render,
  10714. programs: null,
  10715. autoReset: true,
  10716. reset: reset,
  10717. update: update
  10718. };
  10719. }
  10720. function WebGLMorphtargets( gl, capabilities, textures ) {
  10721. const morphTextures = new WeakMap();
  10722. const morph = new Vector4();
  10723. function update( object, geometry, program ) {
  10724. const objectInfluences = object.morphTargetInfluences;
  10725. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  10726. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10727. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10728. let entry = morphTextures.get( geometry );
  10729. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10730. if ( entry !== undefined ) entry.texture.dispose();
  10731. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10732. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10733. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10734. const morphTargets = geometry.morphAttributes.position || [];
  10735. const morphNormals = geometry.morphAttributes.normal || [];
  10736. const morphColors = geometry.morphAttributes.color || [];
  10737. let vertexDataCount = 0;
  10738. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10739. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10740. if ( hasMorphColors === true ) vertexDataCount = 3;
  10741. let width = geometry.attributes.position.count * vertexDataCount;
  10742. let height = 1;
  10743. if ( width > capabilities.maxTextureSize ) {
  10744. height = Math.ceil( width / capabilities.maxTextureSize );
  10745. width = capabilities.maxTextureSize;
  10746. }
  10747. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10748. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10749. texture.type = FloatType;
  10750. texture.needsUpdate = true;
  10751. // fill buffer
  10752. const vertexDataStride = vertexDataCount * 4;
  10753. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10754. const morphTarget = morphTargets[ i ];
  10755. const morphNormal = morphNormals[ i ];
  10756. const morphColor = morphColors[ i ];
  10757. const offset = width * height * 4 * i;
  10758. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10759. const stride = j * vertexDataStride;
  10760. if ( hasMorphPosition === true ) {
  10761. morph.fromBufferAttribute( morphTarget, j );
  10762. buffer[ offset + stride + 0 ] = morph.x;
  10763. buffer[ offset + stride + 1 ] = morph.y;
  10764. buffer[ offset + stride + 2 ] = morph.z;
  10765. buffer[ offset + stride + 3 ] = 0;
  10766. }
  10767. if ( hasMorphNormals === true ) {
  10768. morph.fromBufferAttribute( morphNormal, j );
  10769. buffer[ offset + stride + 4 ] = morph.x;
  10770. buffer[ offset + stride + 5 ] = morph.y;
  10771. buffer[ offset + stride + 6 ] = morph.z;
  10772. buffer[ offset + stride + 7 ] = 0;
  10773. }
  10774. if ( hasMorphColors === true ) {
  10775. morph.fromBufferAttribute( morphColor, j );
  10776. buffer[ offset + stride + 8 ] = morph.x;
  10777. buffer[ offset + stride + 9 ] = morph.y;
  10778. buffer[ offset + stride + 10 ] = morph.z;
  10779. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10780. }
  10781. }
  10782. }
  10783. entry = {
  10784. count: morphTargetsCount,
  10785. texture: texture,
  10786. size: new Vector2( width, height )
  10787. };
  10788. morphTextures.set( geometry, entry );
  10789. function disposeTexture() {
  10790. texture.dispose();
  10791. morphTextures.delete( geometry );
  10792. geometry.removeEventListener( 'dispose', disposeTexture );
  10793. }
  10794. geometry.addEventListener( 'dispose', disposeTexture );
  10795. }
  10796. //
  10797. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  10798. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  10799. } else {
  10800. let morphInfluencesSum = 0;
  10801. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10802. morphInfluencesSum += objectInfluences[ i ];
  10803. }
  10804. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10805. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10806. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10807. }
  10808. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10809. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10810. }
  10811. return {
  10812. update: update
  10813. };
  10814. }
  10815. function WebGLObjects( gl, geometries, attributes, info ) {
  10816. let updateMap = new WeakMap();
  10817. function update( object ) {
  10818. const frame = info.render.frame;
  10819. const geometry = object.geometry;
  10820. const buffergeometry = geometries.get( object, geometry );
  10821. // Update once per frame
  10822. if ( updateMap.get( buffergeometry ) !== frame ) {
  10823. geometries.update( buffergeometry );
  10824. updateMap.set( buffergeometry, frame );
  10825. }
  10826. if ( object.isInstancedMesh ) {
  10827. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10828. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10829. }
  10830. if ( updateMap.get( object ) !== frame ) {
  10831. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10832. if ( object.instanceColor !== null ) {
  10833. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10834. }
  10835. updateMap.set( object, frame );
  10836. }
  10837. }
  10838. if ( object.isSkinnedMesh ) {
  10839. const skeleton = object.skeleton;
  10840. if ( updateMap.get( skeleton ) !== frame ) {
  10841. skeleton.update();
  10842. updateMap.set( skeleton, frame );
  10843. }
  10844. }
  10845. return buffergeometry;
  10846. }
  10847. function dispose() {
  10848. updateMap = new WeakMap();
  10849. }
  10850. function onInstancedMeshDispose( event ) {
  10851. const instancedMesh = event.target;
  10852. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10853. attributes.remove( instancedMesh.instanceMatrix );
  10854. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10855. }
  10856. return {
  10857. update: update,
  10858. dispose: dispose
  10859. };
  10860. }
  10861. class DepthTexture extends Texture {
  10862. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10863. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10864. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10865. }
  10866. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10867. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10868. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10869. this.isDepthTexture = true;
  10870. this.image = { width: width, height: height };
  10871. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10872. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10873. this.flipY = false;
  10874. this.generateMipmaps = false;
  10875. this.compareFunction = null;
  10876. }
  10877. copy( source ) {
  10878. super.copy( source );
  10879. this.compareFunction = source.compareFunction;
  10880. return this;
  10881. }
  10882. toJSON( meta ) {
  10883. const data = super.toJSON( meta );
  10884. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10885. return data;
  10886. }
  10887. }
  10888. /**
  10889. * Uniforms of a program.
  10890. * Those form a tree structure with a special top-level container for the root,
  10891. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10892. *
  10893. *
  10894. * Properties of inner nodes including the top-level container:
  10895. *
  10896. * .seq - array of nested uniforms
  10897. * .map - nested uniforms by name
  10898. *
  10899. *
  10900. * Methods of all nodes except the top-level container:
  10901. *
  10902. * .setValue( gl, value, [textures] )
  10903. *
  10904. * uploads a uniform value(s)
  10905. * the 'textures' parameter is needed for sampler uniforms
  10906. *
  10907. *
  10908. * Static methods of the top-level container (textures factorizations):
  10909. *
  10910. * .upload( gl, seq, values, textures )
  10911. *
  10912. * sets uniforms in 'seq' to 'values[id].value'
  10913. *
  10914. * .seqWithValue( seq, values ) : filteredSeq
  10915. *
  10916. * filters 'seq' entries with corresponding entry in values
  10917. *
  10918. *
  10919. * Methods of the top-level container (textures factorizations):
  10920. *
  10921. * .setValue( gl, name, value, textures )
  10922. *
  10923. * sets uniform with name 'name' to 'value'
  10924. *
  10925. * .setOptional( gl, obj, prop )
  10926. *
  10927. * like .set for an optional property of the object
  10928. *
  10929. */
  10930. const emptyTexture = /*@__PURE__*/ new Texture();
  10931. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  10932. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10933. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10934. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10935. // --- Utilities ---
  10936. // Array Caches (provide typed arrays for temporary by size)
  10937. const arrayCacheF32 = [];
  10938. const arrayCacheI32 = [];
  10939. // Float32Array caches used for uploading Matrix uniforms
  10940. const mat4array = new Float32Array( 16 );
  10941. const mat3array = new Float32Array( 9 );
  10942. const mat2array = new Float32Array( 4 );
  10943. // Flattening for arrays of vectors and matrices
  10944. function flatten( array, nBlocks, blockSize ) {
  10945. const firstElem = array[ 0 ];
  10946. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10947. // unoptimized: ! isNaN( firstElem )
  10948. // see http://jacksondunstan.com/articles/983
  10949. const n = nBlocks * blockSize;
  10950. let r = arrayCacheF32[ n ];
  10951. if ( r === undefined ) {
  10952. r = new Float32Array( n );
  10953. arrayCacheF32[ n ] = r;
  10954. }
  10955. if ( nBlocks !== 0 ) {
  10956. firstElem.toArray( r, 0 );
  10957. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10958. offset += blockSize;
  10959. array[ i ].toArray( r, offset );
  10960. }
  10961. }
  10962. return r;
  10963. }
  10964. function arraysEqual( a, b ) {
  10965. if ( a.length !== b.length ) return false;
  10966. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10967. if ( a[ i ] !== b[ i ] ) return false;
  10968. }
  10969. return true;
  10970. }
  10971. function copyArray( a, b ) {
  10972. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10973. a[ i ] = b[ i ];
  10974. }
  10975. }
  10976. // Texture unit allocation
  10977. function allocTexUnits( textures, n ) {
  10978. let r = arrayCacheI32[ n ];
  10979. if ( r === undefined ) {
  10980. r = new Int32Array( n );
  10981. arrayCacheI32[ n ] = r;
  10982. }
  10983. for ( let i = 0; i !== n; ++ i ) {
  10984. r[ i ] = textures.allocateTextureUnit();
  10985. }
  10986. return r;
  10987. }
  10988. // --- Setters ---
  10989. // Note: Defining these methods externally, because they come in a bunch
  10990. // and this way their names minify.
  10991. // Single scalar
  10992. function setValueV1f( gl, v ) {
  10993. const cache = this.cache;
  10994. if ( cache[ 0 ] === v ) return;
  10995. gl.uniform1f( this.addr, v );
  10996. cache[ 0 ] = v;
  10997. }
  10998. // Single float vector (from flat array or THREE.VectorN)
  10999. function setValueV2f( gl, v ) {
  11000. const cache = this.cache;
  11001. if ( v.x !== undefined ) {
  11002. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11003. gl.uniform2f( this.addr, v.x, v.y );
  11004. cache[ 0 ] = v.x;
  11005. cache[ 1 ] = v.y;
  11006. }
  11007. } else {
  11008. if ( arraysEqual( cache, v ) ) return;
  11009. gl.uniform2fv( this.addr, v );
  11010. copyArray( cache, v );
  11011. }
  11012. }
  11013. function setValueV3f( gl, v ) {
  11014. const cache = this.cache;
  11015. if ( v.x !== undefined ) {
  11016. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11017. gl.uniform3f( this.addr, v.x, v.y, v.z );
  11018. cache[ 0 ] = v.x;
  11019. cache[ 1 ] = v.y;
  11020. cache[ 2 ] = v.z;
  11021. }
  11022. } else if ( v.r !== undefined ) {
  11023. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  11024. gl.uniform3f( this.addr, v.r, v.g, v.b );
  11025. cache[ 0 ] = v.r;
  11026. cache[ 1 ] = v.g;
  11027. cache[ 2 ] = v.b;
  11028. }
  11029. } else {
  11030. if ( arraysEqual( cache, v ) ) return;
  11031. gl.uniform3fv( this.addr, v );
  11032. copyArray( cache, v );
  11033. }
  11034. }
  11035. function setValueV4f( gl, v ) {
  11036. const cache = this.cache;
  11037. if ( v.x !== undefined ) {
  11038. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11039. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  11040. cache[ 0 ] = v.x;
  11041. cache[ 1 ] = v.y;
  11042. cache[ 2 ] = v.z;
  11043. cache[ 3 ] = v.w;
  11044. }
  11045. } else {
  11046. if ( arraysEqual( cache, v ) ) return;
  11047. gl.uniform4fv( this.addr, v );
  11048. copyArray( cache, v );
  11049. }
  11050. }
  11051. // Single matrix (from flat array or THREE.MatrixN)
  11052. function setValueM2( gl, v ) {
  11053. const cache = this.cache;
  11054. const elements = v.elements;
  11055. if ( elements === undefined ) {
  11056. if ( arraysEqual( cache, v ) ) return;
  11057. gl.uniformMatrix2fv( this.addr, false, v );
  11058. copyArray( cache, v );
  11059. } else {
  11060. if ( arraysEqual( cache, elements ) ) return;
  11061. mat2array.set( elements );
  11062. gl.uniformMatrix2fv( this.addr, false, mat2array );
  11063. copyArray( cache, elements );
  11064. }
  11065. }
  11066. function setValueM3( gl, v ) {
  11067. const cache = this.cache;
  11068. const elements = v.elements;
  11069. if ( elements === undefined ) {
  11070. if ( arraysEqual( cache, v ) ) return;
  11071. gl.uniformMatrix3fv( this.addr, false, v );
  11072. copyArray( cache, v );
  11073. } else {
  11074. if ( arraysEqual( cache, elements ) ) return;
  11075. mat3array.set( elements );
  11076. gl.uniformMatrix3fv( this.addr, false, mat3array );
  11077. copyArray( cache, elements );
  11078. }
  11079. }
  11080. function setValueM4( gl, v ) {
  11081. const cache = this.cache;
  11082. const elements = v.elements;
  11083. if ( elements === undefined ) {
  11084. if ( arraysEqual( cache, v ) ) return;
  11085. gl.uniformMatrix4fv( this.addr, false, v );
  11086. copyArray( cache, v );
  11087. } else {
  11088. if ( arraysEqual( cache, elements ) ) return;
  11089. mat4array.set( elements );
  11090. gl.uniformMatrix4fv( this.addr, false, mat4array );
  11091. copyArray( cache, elements );
  11092. }
  11093. }
  11094. // Single integer / boolean
  11095. function setValueV1i( gl, v ) {
  11096. const cache = this.cache;
  11097. if ( cache[ 0 ] === v ) return;
  11098. gl.uniform1i( this.addr, v );
  11099. cache[ 0 ] = v;
  11100. }
  11101. // Single integer / boolean vector (from flat array or THREE.VectorN)
  11102. function setValueV2i( gl, v ) {
  11103. const cache = this.cache;
  11104. if ( v.x !== undefined ) {
  11105. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11106. gl.uniform2i( this.addr, v.x, v.y );
  11107. cache[ 0 ] = v.x;
  11108. cache[ 1 ] = v.y;
  11109. }
  11110. } else {
  11111. if ( arraysEqual( cache, v ) ) return;
  11112. gl.uniform2iv( this.addr, v );
  11113. copyArray( cache, v );
  11114. }
  11115. }
  11116. function setValueV3i( gl, v ) {
  11117. const cache = this.cache;
  11118. if ( v.x !== undefined ) {
  11119. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11120. gl.uniform3i( this.addr, v.x, v.y, v.z );
  11121. cache[ 0 ] = v.x;
  11122. cache[ 1 ] = v.y;
  11123. cache[ 2 ] = v.z;
  11124. }
  11125. } else {
  11126. if ( arraysEqual( cache, v ) ) return;
  11127. gl.uniform3iv( this.addr, v );
  11128. copyArray( cache, v );
  11129. }
  11130. }
  11131. function setValueV4i( gl, v ) {
  11132. const cache = this.cache;
  11133. if ( v.x !== undefined ) {
  11134. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11135. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  11136. cache[ 0 ] = v.x;
  11137. cache[ 1 ] = v.y;
  11138. cache[ 2 ] = v.z;
  11139. cache[ 3 ] = v.w;
  11140. }
  11141. } else {
  11142. if ( arraysEqual( cache, v ) ) return;
  11143. gl.uniform4iv( this.addr, v );
  11144. copyArray( cache, v );
  11145. }
  11146. }
  11147. // Single unsigned integer
  11148. function setValueV1ui( gl, v ) {
  11149. const cache = this.cache;
  11150. if ( cache[ 0 ] === v ) return;
  11151. gl.uniform1ui( this.addr, v );
  11152. cache[ 0 ] = v;
  11153. }
  11154. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11155. function setValueV2ui( gl, v ) {
  11156. const cache = this.cache;
  11157. if ( v.x !== undefined ) {
  11158. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11159. gl.uniform2ui( this.addr, v.x, v.y );
  11160. cache[ 0 ] = v.x;
  11161. cache[ 1 ] = v.y;
  11162. }
  11163. } else {
  11164. if ( arraysEqual( cache, v ) ) return;
  11165. gl.uniform2uiv( this.addr, v );
  11166. copyArray( cache, v );
  11167. }
  11168. }
  11169. function setValueV3ui( gl, v ) {
  11170. const cache = this.cache;
  11171. if ( v.x !== undefined ) {
  11172. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11173. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11174. cache[ 0 ] = v.x;
  11175. cache[ 1 ] = v.y;
  11176. cache[ 2 ] = v.z;
  11177. }
  11178. } else {
  11179. if ( arraysEqual( cache, v ) ) return;
  11180. gl.uniform3uiv( this.addr, v );
  11181. copyArray( cache, v );
  11182. }
  11183. }
  11184. function setValueV4ui( gl, v ) {
  11185. const cache = this.cache;
  11186. if ( v.x !== undefined ) {
  11187. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11188. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11189. cache[ 0 ] = v.x;
  11190. cache[ 1 ] = v.y;
  11191. cache[ 2 ] = v.z;
  11192. cache[ 3 ] = v.w;
  11193. }
  11194. } else {
  11195. if ( arraysEqual( cache, v ) ) return;
  11196. gl.uniform4uiv( this.addr, v );
  11197. copyArray( cache, v );
  11198. }
  11199. }
  11200. // Single texture (2D / Cube)
  11201. function setValueT1( gl, v, textures ) {
  11202. const cache = this.cache;
  11203. const unit = textures.allocateTextureUnit();
  11204. if ( cache[ 0 ] !== unit ) {
  11205. gl.uniform1i( this.addr, unit );
  11206. cache[ 0 ] = unit;
  11207. }
  11208. let emptyTexture2D;
  11209. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  11210. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  11211. emptyTexture2D = emptyShadowTexture;
  11212. } else {
  11213. emptyTexture2D = emptyTexture;
  11214. }
  11215. textures.setTexture2D( v || emptyTexture2D, unit );
  11216. }
  11217. function setValueT3D1( gl, v, textures ) {
  11218. const cache = this.cache;
  11219. const unit = textures.allocateTextureUnit();
  11220. if ( cache[ 0 ] !== unit ) {
  11221. gl.uniform1i( this.addr, unit );
  11222. cache[ 0 ] = unit;
  11223. }
  11224. textures.setTexture3D( v || empty3dTexture, unit );
  11225. }
  11226. function setValueT6( gl, v, textures ) {
  11227. const cache = this.cache;
  11228. const unit = textures.allocateTextureUnit();
  11229. if ( cache[ 0 ] !== unit ) {
  11230. gl.uniform1i( this.addr, unit );
  11231. cache[ 0 ] = unit;
  11232. }
  11233. textures.setTextureCube( v || emptyCubeTexture, unit );
  11234. }
  11235. function setValueT2DArray1( gl, v, textures ) {
  11236. const cache = this.cache;
  11237. const unit = textures.allocateTextureUnit();
  11238. if ( cache[ 0 ] !== unit ) {
  11239. gl.uniform1i( this.addr, unit );
  11240. cache[ 0 ] = unit;
  11241. }
  11242. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11243. }
  11244. // Helper to pick the right setter for the singular case
  11245. function getSingularSetter( type ) {
  11246. switch ( type ) {
  11247. case 0x1406: return setValueV1f; // FLOAT
  11248. case 0x8b50: return setValueV2f; // _VEC2
  11249. case 0x8b51: return setValueV3f; // _VEC3
  11250. case 0x8b52: return setValueV4f; // _VEC4
  11251. case 0x8b5a: return setValueM2; // _MAT2
  11252. case 0x8b5b: return setValueM3; // _MAT3
  11253. case 0x8b5c: return setValueM4; // _MAT4
  11254. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11255. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11256. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11257. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11258. case 0x1405: return setValueV1ui; // UINT
  11259. case 0x8dc6: return setValueV2ui; // _VEC2
  11260. case 0x8dc7: return setValueV3ui; // _VEC3
  11261. case 0x8dc8: return setValueV4ui; // _VEC4
  11262. case 0x8b5e: // SAMPLER_2D
  11263. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11264. case 0x8dca: // INT_SAMPLER_2D
  11265. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11266. case 0x8b62: // SAMPLER_2D_SHADOW
  11267. return setValueT1;
  11268. case 0x8b5f: // SAMPLER_3D
  11269. case 0x8dcb: // INT_SAMPLER_3D
  11270. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11271. return setValueT3D1;
  11272. case 0x8b60: // SAMPLER_CUBE
  11273. case 0x8dcc: // INT_SAMPLER_CUBE
  11274. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11275. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11276. return setValueT6;
  11277. case 0x8dc1: // SAMPLER_2D_ARRAY
  11278. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11279. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11280. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11281. return setValueT2DArray1;
  11282. }
  11283. }
  11284. // Array of scalars
  11285. function setValueV1fArray( gl, v ) {
  11286. gl.uniform1fv( this.addr, v );
  11287. }
  11288. // Array of vectors (from flat array or array of THREE.VectorN)
  11289. function setValueV2fArray( gl, v ) {
  11290. const data = flatten( v, this.size, 2 );
  11291. gl.uniform2fv( this.addr, data );
  11292. }
  11293. function setValueV3fArray( gl, v ) {
  11294. const data = flatten( v, this.size, 3 );
  11295. gl.uniform3fv( this.addr, data );
  11296. }
  11297. function setValueV4fArray( gl, v ) {
  11298. const data = flatten( v, this.size, 4 );
  11299. gl.uniform4fv( this.addr, data );
  11300. }
  11301. // Array of matrices (from flat array or array of THREE.MatrixN)
  11302. function setValueM2Array( gl, v ) {
  11303. const data = flatten( v, this.size, 4 );
  11304. gl.uniformMatrix2fv( this.addr, false, data );
  11305. }
  11306. function setValueM3Array( gl, v ) {
  11307. const data = flatten( v, this.size, 9 );
  11308. gl.uniformMatrix3fv( this.addr, false, data );
  11309. }
  11310. function setValueM4Array( gl, v ) {
  11311. const data = flatten( v, this.size, 16 );
  11312. gl.uniformMatrix4fv( this.addr, false, data );
  11313. }
  11314. // Array of integer / boolean
  11315. function setValueV1iArray( gl, v ) {
  11316. gl.uniform1iv( this.addr, v );
  11317. }
  11318. // Array of integer / boolean vectors (from flat array)
  11319. function setValueV2iArray( gl, v ) {
  11320. gl.uniform2iv( this.addr, v );
  11321. }
  11322. function setValueV3iArray( gl, v ) {
  11323. gl.uniform3iv( this.addr, v );
  11324. }
  11325. function setValueV4iArray( gl, v ) {
  11326. gl.uniform4iv( this.addr, v );
  11327. }
  11328. // Array of unsigned integer
  11329. function setValueV1uiArray( gl, v ) {
  11330. gl.uniform1uiv( this.addr, v );
  11331. }
  11332. // Array of unsigned integer vectors (from flat array)
  11333. function setValueV2uiArray( gl, v ) {
  11334. gl.uniform2uiv( this.addr, v );
  11335. }
  11336. function setValueV3uiArray( gl, v ) {
  11337. gl.uniform3uiv( this.addr, v );
  11338. }
  11339. function setValueV4uiArray( gl, v ) {
  11340. gl.uniform4uiv( this.addr, v );
  11341. }
  11342. // Array of textures (2D / 3D / Cube / 2DArray)
  11343. function setValueT1Array( gl, v, textures ) {
  11344. const cache = this.cache;
  11345. const n = v.length;
  11346. const units = allocTexUnits( textures, n );
  11347. if ( ! arraysEqual( cache, units ) ) {
  11348. gl.uniform1iv( this.addr, units );
  11349. copyArray( cache, units );
  11350. }
  11351. for ( let i = 0; i !== n; ++ i ) {
  11352. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11353. }
  11354. }
  11355. function setValueT3DArray( gl, v, textures ) {
  11356. const cache = this.cache;
  11357. const n = v.length;
  11358. const units = allocTexUnits( textures, n );
  11359. if ( ! arraysEqual( cache, units ) ) {
  11360. gl.uniform1iv( this.addr, units );
  11361. copyArray( cache, units );
  11362. }
  11363. for ( let i = 0; i !== n; ++ i ) {
  11364. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11365. }
  11366. }
  11367. function setValueT6Array( gl, v, textures ) {
  11368. const cache = this.cache;
  11369. const n = v.length;
  11370. const units = allocTexUnits( textures, n );
  11371. if ( ! arraysEqual( cache, units ) ) {
  11372. gl.uniform1iv( this.addr, units );
  11373. copyArray( cache, units );
  11374. }
  11375. for ( let i = 0; i !== n; ++ i ) {
  11376. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11377. }
  11378. }
  11379. function setValueT2DArrayArray( gl, v, textures ) {
  11380. const cache = this.cache;
  11381. const n = v.length;
  11382. const units = allocTexUnits( textures, n );
  11383. if ( ! arraysEqual( cache, units ) ) {
  11384. gl.uniform1iv( this.addr, units );
  11385. copyArray( cache, units );
  11386. }
  11387. for ( let i = 0; i !== n; ++ i ) {
  11388. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11389. }
  11390. }
  11391. // Helper to pick the right setter for a pure (bottom-level) array
  11392. function getPureArraySetter( type ) {
  11393. switch ( type ) {
  11394. case 0x1406: return setValueV1fArray; // FLOAT
  11395. case 0x8b50: return setValueV2fArray; // _VEC2
  11396. case 0x8b51: return setValueV3fArray; // _VEC3
  11397. case 0x8b52: return setValueV4fArray; // _VEC4
  11398. case 0x8b5a: return setValueM2Array; // _MAT2
  11399. case 0x8b5b: return setValueM3Array; // _MAT3
  11400. case 0x8b5c: return setValueM4Array; // _MAT4
  11401. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11402. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11403. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11404. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11405. case 0x1405: return setValueV1uiArray; // UINT
  11406. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11407. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11408. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11409. case 0x8b5e: // SAMPLER_2D
  11410. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11411. case 0x8dca: // INT_SAMPLER_2D
  11412. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11413. case 0x8b62: // SAMPLER_2D_SHADOW
  11414. return setValueT1Array;
  11415. case 0x8b5f: // SAMPLER_3D
  11416. case 0x8dcb: // INT_SAMPLER_3D
  11417. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11418. return setValueT3DArray;
  11419. case 0x8b60: // SAMPLER_CUBE
  11420. case 0x8dcc: // INT_SAMPLER_CUBE
  11421. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11422. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11423. return setValueT6Array;
  11424. case 0x8dc1: // SAMPLER_2D_ARRAY
  11425. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11426. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11427. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11428. return setValueT2DArrayArray;
  11429. }
  11430. }
  11431. // --- Uniform Classes ---
  11432. class SingleUniform {
  11433. constructor( id, activeInfo, addr ) {
  11434. this.id = id;
  11435. this.addr = addr;
  11436. this.cache = [];
  11437. this.type = activeInfo.type;
  11438. this.setValue = getSingularSetter( activeInfo.type );
  11439. // this.path = activeInfo.name; // DEBUG
  11440. }
  11441. }
  11442. class PureArrayUniform {
  11443. constructor( id, activeInfo, addr ) {
  11444. this.id = id;
  11445. this.addr = addr;
  11446. this.cache = [];
  11447. this.type = activeInfo.type;
  11448. this.size = activeInfo.size;
  11449. this.setValue = getPureArraySetter( activeInfo.type );
  11450. // this.path = activeInfo.name; // DEBUG
  11451. }
  11452. }
  11453. class StructuredUniform {
  11454. constructor( id ) {
  11455. this.id = id;
  11456. this.seq = [];
  11457. this.map = {};
  11458. }
  11459. setValue( gl, value, textures ) {
  11460. const seq = this.seq;
  11461. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11462. const u = seq[ i ];
  11463. u.setValue( gl, value[ u.id ], textures );
  11464. }
  11465. }
  11466. }
  11467. // --- Top-level ---
  11468. // Parser - builds up the property tree from the path strings
  11469. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11470. // extracts
  11471. // - the identifier (member name or array index)
  11472. // - followed by an optional right bracket (found when array index)
  11473. // - followed by an optional left bracket or dot (type of subscript)
  11474. //
  11475. // Note: These portions can be read in a non-overlapping fashion and
  11476. // allow straightforward parsing of the hierarchy that WebGL encodes
  11477. // in the uniform names.
  11478. function addUniform( container, uniformObject ) {
  11479. container.seq.push( uniformObject );
  11480. container.map[ uniformObject.id ] = uniformObject;
  11481. }
  11482. function parseUniform( activeInfo, addr, container ) {
  11483. const path = activeInfo.name,
  11484. pathLength = path.length;
  11485. // reset RegExp object, because of the early exit of a previous run
  11486. RePathPart.lastIndex = 0;
  11487. while ( true ) {
  11488. const match = RePathPart.exec( path ),
  11489. matchEnd = RePathPart.lastIndex;
  11490. let id = match[ 1 ];
  11491. const idIsIndex = match[ 2 ] === ']',
  11492. subscript = match[ 3 ];
  11493. if ( idIsIndex ) id = id | 0; // convert to integer
  11494. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11495. // bare name or "pure" bottom-level array "[0]" suffix
  11496. addUniform( container, subscript === undefined ?
  11497. new SingleUniform( id, activeInfo, addr ) :
  11498. new PureArrayUniform( id, activeInfo, addr ) );
  11499. break;
  11500. } else {
  11501. // step into inner node / create it in case it doesn't exist
  11502. const map = container.map;
  11503. let next = map[ id ];
  11504. if ( next === undefined ) {
  11505. next = new StructuredUniform( id );
  11506. addUniform( container, next );
  11507. }
  11508. container = next;
  11509. }
  11510. }
  11511. }
  11512. // Root Container
  11513. class WebGLUniforms {
  11514. constructor( gl, program ) {
  11515. this.seq = [];
  11516. this.map = {};
  11517. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11518. for ( let i = 0; i < n; ++ i ) {
  11519. const info = gl.getActiveUniform( program, i ),
  11520. addr = gl.getUniformLocation( program, info.name );
  11521. parseUniform( info, addr, this );
  11522. }
  11523. }
  11524. setValue( gl, name, value, textures ) {
  11525. const u = this.map[ name ];
  11526. if ( u !== undefined ) u.setValue( gl, value, textures );
  11527. }
  11528. setOptional( gl, object, name ) {
  11529. const v = object[ name ];
  11530. if ( v !== undefined ) this.setValue( gl, name, v );
  11531. }
  11532. static upload( gl, seq, values, textures ) {
  11533. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11534. const u = seq[ i ],
  11535. v = values[ u.id ];
  11536. if ( v.needsUpdate !== false ) {
  11537. // note: always updating when .needsUpdate is undefined
  11538. u.setValue( gl, v.value, textures );
  11539. }
  11540. }
  11541. }
  11542. static seqWithValue( seq, values ) {
  11543. const r = [];
  11544. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11545. const u = seq[ i ];
  11546. if ( u.id in values ) r.push( u );
  11547. }
  11548. return r;
  11549. }
  11550. }
  11551. function WebGLShader( gl, type, string ) {
  11552. const shader = gl.createShader( type );
  11553. gl.shaderSource( shader, string );
  11554. gl.compileShader( shader );
  11555. return shader;
  11556. }
  11557. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  11558. const COMPLETION_STATUS_KHR = 0x91B1;
  11559. let programIdCount = 0;
  11560. function handleSource( string, errorLine ) {
  11561. const lines = string.split( '\n' );
  11562. const lines2 = [];
  11563. const from = Math.max( errorLine - 6, 0 );
  11564. const to = Math.min( errorLine + 6, lines.length );
  11565. for ( let i = from; i < to; i ++ ) {
  11566. const line = i + 1;
  11567. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11568. }
  11569. return lines2.join( '\n' );
  11570. }
  11571. function getEncodingComponents( colorSpace ) {
  11572. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  11573. const encodingPrimaries = ColorManagement.getPrimaries( colorSpace );
  11574. let gamutMapping;
  11575. if ( workingPrimaries === encodingPrimaries ) {
  11576. gamutMapping = '';
  11577. } else if ( workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries ) {
  11578. gamutMapping = 'LinearDisplayP3ToLinearSRGB';
  11579. } else if ( workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries ) {
  11580. gamutMapping = 'LinearSRGBToLinearDisplayP3';
  11581. }
  11582. switch ( colorSpace ) {
  11583. case LinearSRGBColorSpace:
  11584. case LinearDisplayP3ColorSpace:
  11585. return [ gamutMapping, 'LinearTransferOETF' ];
  11586. case SRGBColorSpace:
  11587. case DisplayP3ColorSpace:
  11588. return [ gamutMapping, 'sRGBTransferOETF' ];
  11589. default:
  11590. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11591. return [ gamutMapping, 'LinearTransferOETF' ];
  11592. }
  11593. }
  11594. function getShaderErrors( gl, shader, type ) {
  11595. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11596. const errors = gl.getShaderInfoLog( shader ).trim();
  11597. if ( status && errors === '' ) return '';
  11598. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11599. if ( errorMatches ) {
  11600. // --enable-privileged-webgl-extension
  11601. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11602. const errorLine = parseInt( errorMatches[ 1 ] );
  11603. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11604. } else {
  11605. return errors;
  11606. }
  11607. }
  11608. function getTexelEncodingFunction( functionName, colorSpace ) {
  11609. const components = getEncodingComponents( colorSpace );
  11610. return `vec4 ${functionName}( vec4 value ) { return ${components[ 0 ]}( ${components[ 1 ]}( value ) ); }`;
  11611. }
  11612. function getToneMappingFunction( functionName, toneMapping ) {
  11613. let toneMappingName;
  11614. switch ( toneMapping ) {
  11615. case LinearToneMapping:
  11616. toneMappingName = 'Linear';
  11617. break;
  11618. case ReinhardToneMapping:
  11619. toneMappingName = 'Reinhard';
  11620. break;
  11621. case CineonToneMapping:
  11622. toneMappingName = 'Cineon';
  11623. break;
  11624. case ACESFilmicToneMapping:
  11625. toneMappingName = 'ACESFilmic';
  11626. break;
  11627. case AgXToneMapping:
  11628. toneMappingName = 'AgX';
  11629. break;
  11630. case NeutralToneMapping:
  11631. toneMappingName = 'Neutral';
  11632. break;
  11633. case CustomToneMapping:
  11634. toneMappingName = 'Custom';
  11635. break;
  11636. default:
  11637. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11638. toneMappingName = 'Linear';
  11639. }
  11640. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11641. }
  11642. const _v0$1 = /*@__PURE__*/ new Vector3();
  11643. function getLuminanceFunction() {
  11644. ColorManagement.getLuminanceCoefficients( _v0$1 );
  11645. const r = _v0$1.x.toFixed( 4 );
  11646. const g = _v0$1.y.toFixed( 4 );
  11647. const b = _v0$1.z.toFixed( 4 );
  11648. return [
  11649. 'float luminance( const in vec3 rgb ) {',
  11650. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  11651. ' return dot( weights, rgb );',
  11652. '}'
  11653. ].join( '\n' );
  11654. }
  11655. function generateVertexExtensions( parameters ) {
  11656. const chunks = [
  11657. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  11658. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  11659. ];
  11660. return chunks.filter( filterEmptyLine ).join( '\n' );
  11661. }
  11662. function generateDefines( defines ) {
  11663. const chunks = [];
  11664. for ( const name in defines ) {
  11665. const value = defines[ name ];
  11666. if ( value === false ) continue;
  11667. chunks.push( '#define ' + name + ' ' + value );
  11668. }
  11669. return chunks.join( '\n' );
  11670. }
  11671. function fetchAttributeLocations( gl, program ) {
  11672. const attributes = {};
  11673. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11674. for ( let i = 0; i < n; i ++ ) {
  11675. const info = gl.getActiveAttrib( program, i );
  11676. const name = info.name;
  11677. let locationSize = 1;
  11678. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11679. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11680. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11681. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11682. attributes[ name ] = {
  11683. type: info.type,
  11684. location: gl.getAttribLocation( program, name ),
  11685. locationSize: locationSize
  11686. };
  11687. }
  11688. return attributes;
  11689. }
  11690. function filterEmptyLine( string ) {
  11691. return string !== '';
  11692. }
  11693. function replaceLightNums( string, parameters ) {
  11694. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11695. return string
  11696. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11697. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11698. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11699. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11700. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11701. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11702. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11703. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11704. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11705. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11706. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11707. }
  11708. function replaceClippingPlaneNums( string, parameters ) {
  11709. return string
  11710. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11711. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11712. }
  11713. // Resolve Includes
  11714. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11715. function resolveIncludes( string ) {
  11716. return string.replace( includePattern, includeReplacer );
  11717. }
  11718. const shaderChunkMap = new Map();
  11719. function includeReplacer( match, include ) {
  11720. let string = ShaderChunk[ include ];
  11721. if ( string === undefined ) {
  11722. const newInclude = shaderChunkMap.get( include );
  11723. if ( newInclude !== undefined ) {
  11724. string = ShaderChunk[ newInclude ];
  11725. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  11726. } else {
  11727. throw new Error( 'Can not resolve #include <' + include + '>' );
  11728. }
  11729. }
  11730. return resolveIncludes( string );
  11731. }
  11732. // Unroll Loops
  11733. 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;
  11734. function unrollLoops( string ) {
  11735. return string.replace( unrollLoopPattern, loopReplacer );
  11736. }
  11737. function loopReplacer( match, start, end, snippet ) {
  11738. let string = '';
  11739. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11740. string += snippet
  11741. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11742. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11743. }
  11744. return string;
  11745. }
  11746. //
  11747. function generatePrecision( parameters ) {
  11748. let precisionstring = `precision ${parameters.precision} float;
  11749. precision ${parameters.precision} int;
  11750. precision ${parameters.precision} sampler2D;
  11751. precision ${parameters.precision} samplerCube;
  11752. precision ${parameters.precision} sampler3D;
  11753. precision ${parameters.precision} sampler2DArray;
  11754. precision ${parameters.precision} sampler2DShadow;
  11755. precision ${parameters.precision} samplerCubeShadow;
  11756. precision ${parameters.precision} sampler2DArrayShadow;
  11757. precision ${parameters.precision} isampler2D;
  11758. precision ${parameters.precision} isampler3D;
  11759. precision ${parameters.precision} isamplerCube;
  11760. precision ${parameters.precision} isampler2DArray;
  11761. precision ${parameters.precision} usampler2D;
  11762. precision ${parameters.precision} usampler3D;
  11763. precision ${parameters.precision} usamplerCube;
  11764. precision ${parameters.precision} usampler2DArray;
  11765. `;
  11766. if ( parameters.precision === 'highp' ) {
  11767. precisionstring += '\n#define HIGH_PRECISION';
  11768. } else if ( parameters.precision === 'mediump' ) {
  11769. precisionstring += '\n#define MEDIUM_PRECISION';
  11770. } else if ( parameters.precision === 'lowp' ) {
  11771. precisionstring += '\n#define LOW_PRECISION';
  11772. }
  11773. return precisionstring;
  11774. }
  11775. function generateShadowMapTypeDefine( parameters ) {
  11776. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11777. if ( parameters.shadowMapType === PCFShadowMap ) {
  11778. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11779. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11780. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11781. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11782. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11783. }
  11784. return shadowMapTypeDefine;
  11785. }
  11786. function generateEnvMapTypeDefine( parameters ) {
  11787. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11788. if ( parameters.envMap ) {
  11789. switch ( parameters.envMapMode ) {
  11790. case CubeReflectionMapping:
  11791. case CubeRefractionMapping:
  11792. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11793. break;
  11794. case CubeUVReflectionMapping:
  11795. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11796. break;
  11797. }
  11798. }
  11799. return envMapTypeDefine;
  11800. }
  11801. function generateEnvMapModeDefine( parameters ) {
  11802. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11803. if ( parameters.envMap ) {
  11804. switch ( parameters.envMapMode ) {
  11805. case CubeRefractionMapping:
  11806. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11807. break;
  11808. }
  11809. }
  11810. return envMapModeDefine;
  11811. }
  11812. function generateEnvMapBlendingDefine( parameters ) {
  11813. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11814. if ( parameters.envMap ) {
  11815. switch ( parameters.combine ) {
  11816. case MultiplyOperation:
  11817. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11818. break;
  11819. case MixOperation:
  11820. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11821. break;
  11822. case AddOperation:
  11823. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11824. break;
  11825. }
  11826. }
  11827. return envMapBlendingDefine;
  11828. }
  11829. function generateCubeUVSize( parameters ) {
  11830. const imageHeight = parameters.envMapCubeUVHeight;
  11831. if ( imageHeight === null ) return null;
  11832. const maxMip = Math.log2( imageHeight ) - 2;
  11833. const texelHeight = 1.0 / imageHeight;
  11834. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11835. return { texelWidth, texelHeight, maxMip };
  11836. }
  11837. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11838. // TODO Send this event to Three.js DevTools
  11839. // console.log( 'WebGLProgram', cacheKey );
  11840. const gl = renderer.getContext();
  11841. const defines = parameters.defines;
  11842. let vertexShader = parameters.vertexShader;
  11843. let fragmentShader = parameters.fragmentShader;
  11844. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11845. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11846. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11847. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11848. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11849. const customVertexExtensions = generateVertexExtensions( parameters );
  11850. const customDefines = generateDefines( defines );
  11851. const program = gl.createProgram();
  11852. let prefixVertex, prefixFragment;
  11853. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11854. if ( parameters.isRawShaderMaterial ) {
  11855. prefixVertex = [
  11856. '#define SHADER_TYPE ' + parameters.shaderType,
  11857. '#define SHADER_NAME ' + parameters.shaderName,
  11858. customDefines
  11859. ].filter( filterEmptyLine ).join( '\n' );
  11860. if ( prefixVertex.length > 0 ) {
  11861. prefixVertex += '\n';
  11862. }
  11863. prefixFragment = [
  11864. '#define SHADER_TYPE ' + parameters.shaderType,
  11865. '#define SHADER_NAME ' + parameters.shaderName,
  11866. customDefines
  11867. ].filter( filterEmptyLine ).join( '\n' );
  11868. if ( prefixFragment.length > 0 ) {
  11869. prefixFragment += '\n';
  11870. }
  11871. } else {
  11872. prefixVertex = [
  11873. generatePrecision( parameters ),
  11874. '#define SHADER_TYPE ' + parameters.shaderType,
  11875. '#define SHADER_NAME ' + parameters.shaderName,
  11876. customDefines,
  11877. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  11878. parameters.batching ? '#define USE_BATCHING' : '',
  11879. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  11880. parameters.instancing ? '#define USE_INSTANCING' : '',
  11881. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11882. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  11883. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11884. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11885. parameters.map ? '#define USE_MAP' : '',
  11886. parameters.envMap ? '#define USE_ENVMAP' : '',
  11887. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11888. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11889. parameters.aoMap ? '#define USE_AOMAP' : '',
  11890. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11891. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11892. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11893. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11894. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11895. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11896. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11897. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11898. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11899. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11900. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11901. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11902. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11903. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11904. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11905. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11906. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11907. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11908. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11909. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11910. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11911. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11912. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11913. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11914. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11915. //
  11916. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11917. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11918. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11919. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11920. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11921. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11922. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11923. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11924. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11925. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11926. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11927. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11928. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11929. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11930. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11931. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11932. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11933. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11934. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11935. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11936. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11937. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11938. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11939. //
  11940. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11941. parameters.vertexColors ? '#define USE_COLOR' : '',
  11942. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11943. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11944. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11945. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11946. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11947. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11948. parameters.skinning ? '#define USE_SKINNING' : '',
  11949. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11950. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11951. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  11952. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11953. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11954. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11955. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11956. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11957. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11958. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11959. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11960. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11961. 'uniform mat4 modelMatrix;',
  11962. 'uniform mat4 modelViewMatrix;',
  11963. 'uniform mat4 projectionMatrix;',
  11964. 'uniform mat4 viewMatrix;',
  11965. 'uniform mat3 normalMatrix;',
  11966. 'uniform vec3 cameraPosition;',
  11967. 'uniform bool isOrthographic;',
  11968. '#ifdef USE_INSTANCING',
  11969. ' attribute mat4 instanceMatrix;',
  11970. '#endif',
  11971. '#ifdef USE_INSTANCING_COLOR',
  11972. ' attribute vec3 instanceColor;',
  11973. '#endif',
  11974. '#ifdef USE_INSTANCING_MORPH',
  11975. ' uniform sampler2D morphTexture;',
  11976. '#endif',
  11977. 'attribute vec3 position;',
  11978. 'attribute vec3 normal;',
  11979. 'attribute vec2 uv;',
  11980. '#ifdef USE_UV1',
  11981. ' attribute vec2 uv1;',
  11982. '#endif',
  11983. '#ifdef USE_UV2',
  11984. ' attribute vec2 uv2;',
  11985. '#endif',
  11986. '#ifdef USE_UV3',
  11987. ' attribute vec2 uv3;',
  11988. '#endif',
  11989. '#ifdef USE_TANGENT',
  11990. ' attribute vec4 tangent;',
  11991. '#endif',
  11992. '#if defined( USE_COLOR_ALPHA )',
  11993. ' attribute vec4 color;',
  11994. '#elif defined( USE_COLOR )',
  11995. ' attribute vec3 color;',
  11996. '#endif',
  11997. '#ifdef USE_SKINNING',
  11998. ' attribute vec4 skinIndex;',
  11999. ' attribute vec4 skinWeight;',
  12000. '#endif',
  12001. '\n'
  12002. ].filter( filterEmptyLine ).join( '\n' );
  12003. prefixFragment = [
  12004. generatePrecision( parameters ),
  12005. '#define SHADER_TYPE ' + parameters.shaderType,
  12006. '#define SHADER_NAME ' + parameters.shaderName,
  12007. customDefines,
  12008. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  12009. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  12010. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  12011. parameters.map ? '#define USE_MAP' : '',
  12012. parameters.matcap ? '#define USE_MATCAP' : '',
  12013. parameters.envMap ? '#define USE_ENVMAP' : '',
  12014. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  12015. parameters.envMap ? '#define ' + envMapModeDefine : '',
  12016. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  12017. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  12018. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  12019. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  12020. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12021. parameters.aoMap ? '#define USE_AOMAP' : '',
  12022. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12023. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12024. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  12025. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  12026. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12027. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  12028. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  12029. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  12030. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  12031. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  12032. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  12033. parameters.dispersion ? '#define USE_DISPERSION' : '',
  12034. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  12035. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  12036. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  12037. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12038. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  12039. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  12040. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12041. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12042. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12043. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  12044. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  12045. parameters.sheen ? '#define USE_SHEEN' : '',
  12046. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  12047. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  12048. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  12049. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  12050. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  12051. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  12052. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  12053. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  12054. parameters.vertexUv1s ? '#define USE_UV1' : '',
  12055. parameters.vertexUv2s ? '#define USE_UV2' : '',
  12056. parameters.vertexUv3s ? '#define USE_UV3' : '',
  12057. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  12058. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  12059. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12060. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12061. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12062. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12063. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12064. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  12065. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  12066. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  12067. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12068. 'uniform mat4 viewMatrix;',
  12069. 'uniform vec3 cameraPosition;',
  12070. 'uniform bool isOrthographic;',
  12071. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  12072. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  12073. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  12074. parameters.dithering ? '#define DITHERING' : '',
  12075. parameters.opaque ? '#define OPAQUE' : '',
  12076. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  12077. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  12078. getLuminanceFunction(),
  12079. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  12080. '\n'
  12081. ].filter( filterEmptyLine ).join( '\n' );
  12082. }
  12083. vertexShader = resolveIncludes( vertexShader );
  12084. vertexShader = replaceLightNums( vertexShader, parameters );
  12085. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  12086. fragmentShader = resolveIncludes( fragmentShader );
  12087. fragmentShader = replaceLightNums( fragmentShader, parameters );
  12088. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  12089. vertexShader = unrollLoops( vertexShader );
  12090. fragmentShader = unrollLoops( fragmentShader );
  12091. if ( parameters.isRawShaderMaterial !== true ) {
  12092. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  12093. versionString = '#version 300 es\n';
  12094. prefixVertex = [
  12095. customVertexExtensions,
  12096. '#define attribute in',
  12097. '#define varying out',
  12098. '#define texture2D texture'
  12099. ].join( '\n' ) + '\n' + prefixVertex;
  12100. prefixFragment = [
  12101. '#define varying in',
  12102. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  12103. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  12104. '#define gl_FragDepthEXT gl_FragDepth',
  12105. '#define texture2D texture',
  12106. '#define textureCube texture',
  12107. '#define texture2DProj textureProj',
  12108. '#define texture2DLodEXT textureLod',
  12109. '#define texture2DProjLodEXT textureProjLod',
  12110. '#define textureCubeLodEXT textureLod',
  12111. '#define texture2DGradEXT textureGrad',
  12112. '#define texture2DProjGradEXT textureProjGrad',
  12113. '#define textureCubeGradEXT textureGrad'
  12114. ].join( '\n' ) + '\n' + prefixFragment;
  12115. }
  12116. const vertexGlsl = versionString + prefixVertex + vertexShader;
  12117. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  12118. // console.log( '*VERTEX*', vertexGlsl );
  12119. // console.log( '*FRAGMENT*', fragmentGlsl );
  12120. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  12121. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  12122. gl.attachShader( program, glVertexShader );
  12123. gl.attachShader( program, glFragmentShader );
  12124. // Force a particular attribute to index 0.
  12125. if ( parameters.index0AttributeName !== undefined ) {
  12126. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  12127. } else if ( parameters.morphTargets === true ) {
  12128. // programs with morphTargets displace position out of attribute 0
  12129. gl.bindAttribLocation( program, 0, 'position' );
  12130. }
  12131. gl.linkProgram( program );
  12132. function onFirstUse( self ) {
  12133. // check for link errors
  12134. if ( renderer.debug.checkShaderErrors ) {
  12135. const programLog = gl.getProgramInfoLog( program ).trim();
  12136. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  12137. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  12138. let runnable = true;
  12139. let haveDiagnostics = true;
  12140. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  12141. runnable = false;
  12142. if ( typeof renderer.debug.onShaderError === 'function' ) {
  12143. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  12144. } else {
  12145. // default error reporting
  12146. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  12147. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  12148. console.error(
  12149. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  12150. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  12151. 'Material Name: ' + self.name + '\n' +
  12152. 'Material Type: ' + self.type + '\n\n' +
  12153. 'Program Info Log: ' + programLog + '\n' +
  12154. vertexErrors + '\n' +
  12155. fragmentErrors
  12156. );
  12157. }
  12158. } else if ( programLog !== '' ) {
  12159. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  12160. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12161. haveDiagnostics = false;
  12162. }
  12163. if ( haveDiagnostics ) {
  12164. self.diagnostics = {
  12165. runnable: runnable,
  12166. programLog: programLog,
  12167. vertexShader: {
  12168. log: vertexLog,
  12169. prefix: prefixVertex
  12170. },
  12171. fragmentShader: {
  12172. log: fragmentLog,
  12173. prefix: prefixFragment
  12174. }
  12175. };
  12176. }
  12177. }
  12178. // Clean up
  12179. // Crashes in iOS9 and iOS10. #18402
  12180. // gl.detachShader( program, glVertexShader );
  12181. // gl.detachShader( program, glFragmentShader );
  12182. gl.deleteShader( glVertexShader );
  12183. gl.deleteShader( glFragmentShader );
  12184. cachedUniforms = new WebGLUniforms( gl, program );
  12185. cachedAttributes = fetchAttributeLocations( gl, program );
  12186. }
  12187. // set up caching for uniform locations
  12188. let cachedUniforms;
  12189. this.getUniforms = function () {
  12190. if ( cachedUniforms === undefined ) {
  12191. // Populates cachedUniforms and cachedAttributes
  12192. onFirstUse( this );
  12193. }
  12194. return cachedUniforms;
  12195. };
  12196. // set up caching for attribute locations
  12197. let cachedAttributes;
  12198. this.getAttributes = function () {
  12199. if ( cachedAttributes === undefined ) {
  12200. // Populates cachedAttributes and cachedUniforms
  12201. onFirstUse( this );
  12202. }
  12203. return cachedAttributes;
  12204. };
  12205. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  12206. // flag the program as ready immediately. It may cause a stall when it's first used.
  12207. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  12208. this.isReady = function () {
  12209. if ( programReady === false ) {
  12210. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  12211. }
  12212. return programReady;
  12213. };
  12214. // free resource
  12215. this.destroy = function () {
  12216. bindingStates.releaseStatesOfProgram( this );
  12217. gl.deleteProgram( program );
  12218. this.program = undefined;
  12219. };
  12220. //
  12221. this.type = parameters.shaderType;
  12222. this.name = parameters.shaderName;
  12223. this.id = programIdCount ++;
  12224. this.cacheKey = cacheKey;
  12225. this.usedTimes = 1;
  12226. this.program = program;
  12227. this.vertexShader = glVertexShader;
  12228. this.fragmentShader = glFragmentShader;
  12229. return this;
  12230. }
  12231. let _id$1 = 0;
  12232. class WebGLShaderCache {
  12233. constructor() {
  12234. this.shaderCache = new Map();
  12235. this.materialCache = new Map();
  12236. }
  12237. update( material ) {
  12238. const vertexShader = material.vertexShader;
  12239. const fragmentShader = material.fragmentShader;
  12240. const vertexShaderStage = this._getShaderStage( vertexShader );
  12241. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  12242. const materialShaders = this._getShaderCacheForMaterial( material );
  12243. if ( materialShaders.has( vertexShaderStage ) === false ) {
  12244. materialShaders.add( vertexShaderStage );
  12245. vertexShaderStage.usedTimes ++;
  12246. }
  12247. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12248. materialShaders.add( fragmentShaderStage );
  12249. fragmentShaderStage.usedTimes ++;
  12250. }
  12251. return this;
  12252. }
  12253. remove( material ) {
  12254. const materialShaders = this.materialCache.get( material );
  12255. for ( const shaderStage of materialShaders ) {
  12256. shaderStage.usedTimes --;
  12257. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12258. }
  12259. this.materialCache.delete( material );
  12260. return this;
  12261. }
  12262. getVertexShaderID( material ) {
  12263. return this._getShaderStage( material.vertexShader ).id;
  12264. }
  12265. getFragmentShaderID( material ) {
  12266. return this._getShaderStage( material.fragmentShader ).id;
  12267. }
  12268. dispose() {
  12269. this.shaderCache.clear();
  12270. this.materialCache.clear();
  12271. }
  12272. _getShaderCacheForMaterial( material ) {
  12273. const cache = this.materialCache;
  12274. let set = cache.get( material );
  12275. if ( set === undefined ) {
  12276. set = new Set();
  12277. cache.set( material, set );
  12278. }
  12279. return set;
  12280. }
  12281. _getShaderStage( code ) {
  12282. const cache = this.shaderCache;
  12283. let stage = cache.get( code );
  12284. if ( stage === undefined ) {
  12285. stage = new WebGLShaderStage( code );
  12286. cache.set( code, stage );
  12287. }
  12288. return stage;
  12289. }
  12290. }
  12291. class WebGLShaderStage {
  12292. constructor( code ) {
  12293. this.id = _id$1 ++;
  12294. this.code = code;
  12295. this.usedTimes = 0;
  12296. }
  12297. }
  12298. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12299. const _programLayers = new Layers();
  12300. const _customShaders = new WebGLShaderCache();
  12301. const _activeChannels = new Set();
  12302. const programs = [];
  12303. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12304. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12305. let precision = capabilities.precision;
  12306. const shaderIDs = {
  12307. MeshDepthMaterial: 'depth',
  12308. MeshDistanceMaterial: 'distanceRGBA',
  12309. MeshNormalMaterial: 'normal',
  12310. MeshBasicMaterial: 'basic',
  12311. MeshLambertMaterial: 'lambert',
  12312. MeshPhongMaterial: 'phong',
  12313. MeshToonMaterial: 'toon',
  12314. MeshStandardMaterial: 'physical',
  12315. MeshPhysicalMaterial: 'physical',
  12316. MeshMatcapMaterial: 'matcap',
  12317. LineBasicMaterial: 'basic',
  12318. LineDashedMaterial: 'dashed',
  12319. PointsMaterial: 'points',
  12320. ShadowMaterial: 'shadow',
  12321. SpriteMaterial: 'sprite'
  12322. };
  12323. function getChannel( value ) {
  12324. _activeChannels.add( value );
  12325. if ( value === 0 ) return 'uv';
  12326. return `uv${ value }`;
  12327. }
  12328. function getParameters( material, lights, shadows, scene, object ) {
  12329. const fog = scene.fog;
  12330. const geometry = object.geometry;
  12331. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12332. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12333. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12334. const shaderID = shaderIDs[ material.type ];
  12335. // heuristics to create shader parameters according to lights in the scene
  12336. // (not to blow over maxLights budget)
  12337. if ( material.precision !== null ) {
  12338. precision = capabilities.getMaxPrecision( material.precision );
  12339. if ( precision !== material.precision ) {
  12340. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12341. }
  12342. }
  12343. //
  12344. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12345. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12346. let morphTextureStride = 0;
  12347. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12348. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12349. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12350. //
  12351. let vertexShader, fragmentShader;
  12352. let customVertexShaderID, customFragmentShaderID;
  12353. if ( shaderID ) {
  12354. const shader = ShaderLib[ shaderID ];
  12355. vertexShader = shader.vertexShader;
  12356. fragmentShader = shader.fragmentShader;
  12357. } else {
  12358. vertexShader = material.vertexShader;
  12359. fragmentShader = material.fragmentShader;
  12360. _customShaders.update( material );
  12361. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12362. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12363. }
  12364. const currentRenderTarget = renderer.getRenderTarget();
  12365. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12366. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  12367. const HAS_MAP = !! material.map;
  12368. const HAS_MATCAP = !! material.matcap;
  12369. const HAS_ENVMAP = !! envMap;
  12370. const HAS_AOMAP = !! material.aoMap;
  12371. const HAS_LIGHTMAP = !! material.lightMap;
  12372. const HAS_BUMPMAP = !! material.bumpMap;
  12373. const HAS_NORMALMAP = !! material.normalMap;
  12374. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12375. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12376. const HAS_METALNESSMAP = !! material.metalnessMap;
  12377. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12378. const HAS_ANISOTROPY = material.anisotropy > 0;
  12379. const HAS_CLEARCOAT = material.clearcoat > 0;
  12380. const HAS_DISPERSION = material.dispersion > 0;
  12381. const HAS_IRIDESCENCE = material.iridescence > 0;
  12382. const HAS_SHEEN = material.sheen > 0;
  12383. const HAS_TRANSMISSION = material.transmission > 0;
  12384. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12385. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12386. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12387. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12388. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12389. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12390. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12391. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12392. const HAS_SPECULARMAP = !! material.specularMap;
  12393. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12394. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12395. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12396. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12397. const HAS_GRADIENTMAP = !! material.gradientMap;
  12398. const HAS_ALPHAMAP = !! material.alphaMap;
  12399. const HAS_ALPHATEST = material.alphaTest > 0;
  12400. const HAS_ALPHAHASH = !! material.alphaHash;
  12401. const HAS_EXTENSIONS = !! material.extensions;
  12402. let toneMapping = NoToneMapping;
  12403. if ( material.toneMapped ) {
  12404. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  12405. toneMapping = renderer.toneMapping;
  12406. }
  12407. }
  12408. const parameters = {
  12409. shaderID: shaderID,
  12410. shaderType: material.type,
  12411. shaderName: material.name,
  12412. vertexShader: vertexShader,
  12413. fragmentShader: fragmentShader,
  12414. defines: material.defines,
  12415. customVertexShaderID: customVertexShaderID,
  12416. customFragmentShaderID: customFragmentShaderID,
  12417. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12418. glslVersion: material.glslVersion,
  12419. precision: precision,
  12420. batching: IS_BATCHEDMESH,
  12421. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  12422. instancing: IS_INSTANCEDMESH,
  12423. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12424. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  12425. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12426. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12427. alphaToCoverage: !! material.alphaToCoverage,
  12428. map: HAS_MAP,
  12429. matcap: HAS_MATCAP,
  12430. envMap: HAS_ENVMAP,
  12431. envMapMode: HAS_ENVMAP && envMap.mapping,
  12432. envMapCubeUVHeight: envMapCubeUVHeight,
  12433. aoMap: HAS_AOMAP,
  12434. lightMap: HAS_LIGHTMAP,
  12435. bumpMap: HAS_BUMPMAP,
  12436. normalMap: HAS_NORMALMAP,
  12437. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12438. emissiveMap: HAS_EMISSIVEMAP,
  12439. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12440. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12441. metalnessMap: HAS_METALNESSMAP,
  12442. roughnessMap: HAS_ROUGHNESSMAP,
  12443. anisotropy: HAS_ANISOTROPY,
  12444. anisotropyMap: HAS_ANISOTROPYMAP,
  12445. clearcoat: HAS_CLEARCOAT,
  12446. clearcoatMap: HAS_CLEARCOATMAP,
  12447. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12448. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12449. dispersion: HAS_DISPERSION,
  12450. iridescence: HAS_IRIDESCENCE,
  12451. iridescenceMap: HAS_IRIDESCENCEMAP,
  12452. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12453. sheen: HAS_SHEEN,
  12454. sheenColorMap: HAS_SHEEN_COLORMAP,
  12455. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12456. specularMap: HAS_SPECULARMAP,
  12457. specularColorMap: HAS_SPECULAR_COLORMAP,
  12458. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12459. transmission: HAS_TRANSMISSION,
  12460. transmissionMap: HAS_TRANSMISSIONMAP,
  12461. thicknessMap: HAS_THICKNESSMAP,
  12462. gradientMap: HAS_GRADIENTMAP,
  12463. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  12464. alphaMap: HAS_ALPHAMAP,
  12465. alphaTest: HAS_ALPHATEST,
  12466. alphaHash: HAS_ALPHAHASH,
  12467. combine: material.combine,
  12468. //
  12469. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12470. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12471. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12472. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12473. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12474. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12475. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12476. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12477. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12478. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12479. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12480. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12481. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12482. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12483. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12484. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12485. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12486. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12487. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12488. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12489. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12490. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12491. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12492. //
  12493. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12494. vertexColors: material.vertexColors,
  12495. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12496. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12497. fog: !! fog,
  12498. useFog: material.fog === true,
  12499. fogExp2: ( !! fog && fog.isFogExp2 ),
  12500. flatShading: material.flatShading === true,
  12501. sizeAttenuation: material.sizeAttenuation === true,
  12502. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12503. skinning: object.isSkinnedMesh === true,
  12504. morphTargets: geometry.morphAttributes.position !== undefined,
  12505. morphNormals: geometry.morphAttributes.normal !== undefined,
  12506. morphColors: geometry.morphAttributes.color !== undefined,
  12507. morphTargetsCount: morphTargetsCount,
  12508. morphTextureStride: morphTextureStride,
  12509. numDirLights: lights.directional.length,
  12510. numPointLights: lights.point.length,
  12511. numSpotLights: lights.spot.length,
  12512. numSpotLightMaps: lights.spotLightMap.length,
  12513. numRectAreaLights: lights.rectArea.length,
  12514. numHemiLights: lights.hemi.length,
  12515. numDirLightShadows: lights.directionalShadowMap.length,
  12516. numPointLightShadows: lights.pointShadowMap.length,
  12517. numSpotLightShadows: lights.spotShadowMap.length,
  12518. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12519. numLightProbes: lights.numLightProbes,
  12520. numClippingPlanes: clipping.numPlanes,
  12521. numClipIntersection: clipping.numIntersection,
  12522. dithering: material.dithering,
  12523. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12524. shadowMapType: renderer.shadowMap.type,
  12525. toneMapping: toneMapping,
  12526. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  12527. premultipliedAlpha: material.premultipliedAlpha,
  12528. doubleSided: material.side === DoubleSide,
  12529. flipSided: material.side === BackSide,
  12530. useDepthPacking: material.depthPacking >= 0,
  12531. depthPacking: material.depthPacking || 0,
  12532. index0AttributeName: material.index0AttributeName,
  12533. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  12534. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  12535. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  12536. customProgramCacheKey: material.customProgramCacheKey()
  12537. };
  12538. // the usage of getChannel() determines the active texture channels for this shader
  12539. parameters.vertexUv1s = _activeChannels.has( 1 );
  12540. parameters.vertexUv2s = _activeChannels.has( 2 );
  12541. parameters.vertexUv3s = _activeChannels.has( 3 );
  12542. _activeChannels.clear();
  12543. return parameters;
  12544. }
  12545. function getProgramCacheKey( parameters ) {
  12546. const array = [];
  12547. if ( parameters.shaderID ) {
  12548. array.push( parameters.shaderID );
  12549. } else {
  12550. array.push( parameters.customVertexShaderID );
  12551. array.push( parameters.customFragmentShaderID );
  12552. }
  12553. if ( parameters.defines !== undefined ) {
  12554. for ( const name in parameters.defines ) {
  12555. array.push( name );
  12556. array.push( parameters.defines[ name ] );
  12557. }
  12558. }
  12559. if ( parameters.isRawShaderMaterial === false ) {
  12560. getProgramCacheKeyParameters( array, parameters );
  12561. getProgramCacheKeyBooleans( array, parameters );
  12562. array.push( renderer.outputColorSpace );
  12563. }
  12564. array.push( parameters.customProgramCacheKey );
  12565. return array.join();
  12566. }
  12567. function getProgramCacheKeyParameters( array, parameters ) {
  12568. array.push( parameters.precision );
  12569. array.push( parameters.outputColorSpace );
  12570. array.push( parameters.envMapMode );
  12571. array.push( parameters.envMapCubeUVHeight );
  12572. array.push( parameters.mapUv );
  12573. array.push( parameters.alphaMapUv );
  12574. array.push( parameters.lightMapUv );
  12575. array.push( parameters.aoMapUv );
  12576. array.push( parameters.bumpMapUv );
  12577. array.push( parameters.normalMapUv );
  12578. array.push( parameters.displacementMapUv );
  12579. array.push( parameters.emissiveMapUv );
  12580. array.push( parameters.metalnessMapUv );
  12581. array.push( parameters.roughnessMapUv );
  12582. array.push( parameters.anisotropyMapUv );
  12583. array.push( parameters.clearcoatMapUv );
  12584. array.push( parameters.clearcoatNormalMapUv );
  12585. array.push( parameters.clearcoatRoughnessMapUv );
  12586. array.push( parameters.iridescenceMapUv );
  12587. array.push( parameters.iridescenceThicknessMapUv );
  12588. array.push( parameters.sheenColorMapUv );
  12589. array.push( parameters.sheenRoughnessMapUv );
  12590. array.push( parameters.specularMapUv );
  12591. array.push( parameters.specularColorMapUv );
  12592. array.push( parameters.specularIntensityMapUv );
  12593. array.push( parameters.transmissionMapUv );
  12594. array.push( parameters.thicknessMapUv );
  12595. array.push( parameters.combine );
  12596. array.push( parameters.fogExp2 );
  12597. array.push( parameters.sizeAttenuation );
  12598. array.push( parameters.morphTargetsCount );
  12599. array.push( parameters.morphAttributeCount );
  12600. array.push( parameters.numDirLights );
  12601. array.push( parameters.numPointLights );
  12602. array.push( parameters.numSpotLights );
  12603. array.push( parameters.numSpotLightMaps );
  12604. array.push( parameters.numHemiLights );
  12605. array.push( parameters.numRectAreaLights );
  12606. array.push( parameters.numDirLightShadows );
  12607. array.push( parameters.numPointLightShadows );
  12608. array.push( parameters.numSpotLightShadows );
  12609. array.push( parameters.numSpotLightShadowsWithMaps );
  12610. array.push( parameters.numLightProbes );
  12611. array.push( parameters.shadowMapType );
  12612. array.push( parameters.toneMapping );
  12613. array.push( parameters.numClippingPlanes );
  12614. array.push( parameters.numClipIntersection );
  12615. array.push( parameters.depthPacking );
  12616. }
  12617. function getProgramCacheKeyBooleans( array, parameters ) {
  12618. _programLayers.disableAll();
  12619. if ( parameters.supportsVertexTextures )
  12620. _programLayers.enable( 0 );
  12621. if ( parameters.instancing )
  12622. _programLayers.enable( 1 );
  12623. if ( parameters.instancingColor )
  12624. _programLayers.enable( 2 );
  12625. if ( parameters.instancingMorph )
  12626. _programLayers.enable( 3 );
  12627. if ( parameters.matcap )
  12628. _programLayers.enable( 4 );
  12629. if ( parameters.envMap )
  12630. _programLayers.enable( 5 );
  12631. if ( parameters.normalMapObjectSpace )
  12632. _programLayers.enable( 6 );
  12633. if ( parameters.normalMapTangentSpace )
  12634. _programLayers.enable( 7 );
  12635. if ( parameters.clearcoat )
  12636. _programLayers.enable( 8 );
  12637. if ( parameters.iridescence )
  12638. _programLayers.enable( 9 );
  12639. if ( parameters.alphaTest )
  12640. _programLayers.enable( 10 );
  12641. if ( parameters.vertexColors )
  12642. _programLayers.enable( 11 );
  12643. if ( parameters.vertexAlphas )
  12644. _programLayers.enable( 12 );
  12645. if ( parameters.vertexUv1s )
  12646. _programLayers.enable( 13 );
  12647. if ( parameters.vertexUv2s )
  12648. _programLayers.enable( 14 );
  12649. if ( parameters.vertexUv3s )
  12650. _programLayers.enable( 15 );
  12651. if ( parameters.vertexTangents )
  12652. _programLayers.enable( 16 );
  12653. if ( parameters.anisotropy )
  12654. _programLayers.enable( 17 );
  12655. if ( parameters.alphaHash )
  12656. _programLayers.enable( 18 );
  12657. if ( parameters.batching )
  12658. _programLayers.enable( 19 );
  12659. if ( parameters.dispersion )
  12660. _programLayers.enable( 20 );
  12661. if ( parameters.batchingColor )
  12662. _programLayers.enable( 21 );
  12663. array.push( _programLayers.mask );
  12664. _programLayers.disableAll();
  12665. if ( parameters.fog )
  12666. _programLayers.enable( 0 );
  12667. if ( parameters.useFog )
  12668. _programLayers.enable( 1 );
  12669. if ( parameters.flatShading )
  12670. _programLayers.enable( 2 );
  12671. if ( parameters.logarithmicDepthBuffer )
  12672. _programLayers.enable( 3 );
  12673. if ( parameters.skinning )
  12674. _programLayers.enable( 4 );
  12675. if ( parameters.morphTargets )
  12676. _programLayers.enable( 5 );
  12677. if ( parameters.morphNormals )
  12678. _programLayers.enable( 6 );
  12679. if ( parameters.morphColors )
  12680. _programLayers.enable( 7 );
  12681. if ( parameters.premultipliedAlpha )
  12682. _programLayers.enable( 8 );
  12683. if ( parameters.shadowMapEnabled )
  12684. _programLayers.enable( 9 );
  12685. if ( parameters.doubleSided )
  12686. _programLayers.enable( 10 );
  12687. if ( parameters.flipSided )
  12688. _programLayers.enable( 11 );
  12689. if ( parameters.useDepthPacking )
  12690. _programLayers.enable( 12 );
  12691. if ( parameters.dithering )
  12692. _programLayers.enable( 13 );
  12693. if ( parameters.transmission )
  12694. _programLayers.enable( 14 );
  12695. if ( parameters.sheen )
  12696. _programLayers.enable( 15 );
  12697. if ( parameters.opaque )
  12698. _programLayers.enable( 16 );
  12699. if ( parameters.pointsUvs )
  12700. _programLayers.enable( 17 );
  12701. if ( parameters.decodeVideoTexture )
  12702. _programLayers.enable( 18 );
  12703. if ( parameters.alphaToCoverage )
  12704. _programLayers.enable( 19 );
  12705. array.push( _programLayers.mask );
  12706. }
  12707. function getUniforms( material ) {
  12708. const shaderID = shaderIDs[ material.type ];
  12709. let uniforms;
  12710. if ( shaderID ) {
  12711. const shader = ShaderLib[ shaderID ];
  12712. uniforms = UniformsUtils.clone( shader.uniforms );
  12713. } else {
  12714. uniforms = material.uniforms;
  12715. }
  12716. return uniforms;
  12717. }
  12718. function acquireProgram( parameters, cacheKey ) {
  12719. let program;
  12720. // Check if code has been already compiled
  12721. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12722. const preexistingProgram = programs[ p ];
  12723. if ( preexistingProgram.cacheKey === cacheKey ) {
  12724. program = preexistingProgram;
  12725. ++ program.usedTimes;
  12726. break;
  12727. }
  12728. }
  12729. if ( program === undefined ) {
  12730. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12731. programs.push( program );
  12732. }
  12733. return program;
  12734. }
  12735. function releaseProgram( program ) {
  12736. if ( -- program.usedTimes === 0 ) {
  12737. // Remove from unordered set
  12738. const i = programs.indexOf( program );
  12739. programs[ i ] = programs[ programs.length - 1 ];
  12740. programs.pop();
  12741. // Free WebGL resources
  12742. program.destroy();
  12743. }
  12744. }
  12745. function releaseShaderCache( material ) {
  12746. _customShaders.remove( material );
  12747. }
  12748. function dispose() {
  12749. _customShaders.dispose();
  12750. }
  12751. return {
  12752. getParameters: getParameters,
  12753. getProgramCacheKey: getProgramCacheKey,
  12754. getUniforms: getUniforms,
  12755. acquireProgram: acquireProgram,
  12756. releaseProgram: releaseProgram,
  12757. releaseShaderCache: releaseShaderCache,
  12758. // Exposed for resource monitoring & error feedback via renderer.info:
  12759. programs: programs,
  12760. dispose: dispose
  12761. };
  12762. }
  12763. function WebGLProperties() {
  12764. let properties = new WeakMap();
  12765. function has( object ) {
  12766. return properties.has( object );
  12767. }
  12768. function get( object ) {
  12769. let map = properties.get( object );
  12770. if ( map === undefined ) {
  12771. map = {};
  12772. properties.set( object, map );
  12773. }
  12774. return map;
  12775. }
  12776. function remove( object ) {
  12777. properties.delete( object );
  12778. }
  12779. function update( object, key, value ) {
  12780. properties.get( object )[ key ] = value;
  12781. }
  12782. function dispose() {
  12783. properties = new WeakMap();
  12784. }
  12785. return {
  12786. has: has,
  12787. get: get,
  12788. remove: remove,
  12789. update: update,
  12790. dispose: dispose
  12791. };
  12792. }
  12793. function painterSortStable( a, b ) {
  12794. if ( a.groupOrder !== b.groupOrder ) {
  12795. return a.groupOrder - b.groupOrder;
  12796. } else if ( a.renderOrder !== b.renderOrder ) {
  12797. return a.renderOrder - b.renderOrder;
  12798. } else if ( a.material.id !== b.material.id ) {
  12799. return a.material.id - b.material.id;
  12800. } else if ( a.z !== b.z ) {
  12801. return a.z - b.z;
  12802. } else {
  12803. return a.id - b.id;
  12804. }
  12805. }
  12806. function reversePainterSortStable( a, b ) {
  12807. if ( a.groupOrder !== b.groupOrder ) {
  12808. return a.groupOrder - b.groupOrder;
  12809. } else if ( a.renderOrder !== b.renderOrder ) {
  12810. return a.renderOrder - b.renderOrder;
  12811. } else if ( a.z !== b.z ) {
  12812. return b.z - a.z;
  12813. } else {
  12814. return a.id - b.id;
  12815. }
  12816. }
  12817. function WebGLRenderList() {
  12818. const renderItems = [];
  12819. let renderItemsIndex = 0;
  12820. const opaque = [];
  12821. const transmissive = [];
  12822. const transparent = [];
  12823. function init() {
  12824. renderItemsIndex = 0;
  12825. opaque.length = 0;
  12826. transmissive.length = 0;
  12827. transparent.length = 0;
  12828. }
  12829. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12830. let renderItem = renderItems[ renderItemsIndex ];
  12831. if ( renderItem === undefined ) {
  12832. renderItem = {
  12833. id: object.id,
  12834. object: object,
  12835. geometry: geometry,
  12836. material: material,
  12837. groupOrder: groupOrder,
  12838. renderOrder: object.renderOrder,
  12839. z: z,
  12840. group: group
  12841. };
  12842. renderItems[ renderItemsIndex ] = renderItem;
  12843. } else {
  12844. renderItem.id = object.id;
  12845. renderItem.object = object;
  12846. renderItem.geometry = geometry;
  12847. renderItem.material = material;
  12848. renderItem.groupOrder = groupOrder;
  12849. renderItem.renderOrder = object.renderOrder;
  12850. renderItem.z = z;
  12851. renderItem.group = group;
  12852. }
  12853. renderItemsIndex ++;
  12854. return renderItem;
  12855. }
  12856. function push( object, geometry, material, groupOrder, z, group ) {
  12857. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12858. if ( material.transmission > 0.0 ) {
  12859. transmissive.push( renderItem );
  12860. } else if ( material.transparent === true ) {
  12861. transparent.push( renderItem );
  12862. } else {
  12863. opaque.push( renderItem );
  12864. }
  12865. }
  12866. function unshift( object, geometry, material, groupOrder, z, group ) {
  12867. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12868. if ( material.transmission > 0.0 ) {
  12869. transmissive.unshift( renderItem );
  12870. } else if ( material.transparent === true ) {
  12871. transparent.unshift( renderItem );
  12872. } else {
  12873. opaque.unshift( renderItem );
  12874. }
  12875. }
  12876. function sort( customOpaqueSort, customTransparentSort ) {
  12877. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12878. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12879. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12880. }
  12881. function finish() {
  12882. // Clear references from inactive renderItems in the list
  12883. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12884. const renderItem = renderItems[ i ];
  12885. if ( renderItem.id === null ) break;
  12886. renderItem.id = null;
  12887. renderItem.object = null;
  12888. renderItem.geometry = null;
  12889. renderItem.material = null;
  12890. renderItem.group = null;
  12891. }
  12892. }
  12893. return {
  12894. opaque: opaque,
  12895. transmissive: transmissive,
  12896. transparent: transparent,
  12897. init: init,
  12898. push: push,
  12899. unshift: unshift,
  12900. finish: finish,
  12901. sort: sort
  12902. };
  12903. }
  12904. function WebGLRenderLists() {
  12905. let lists = new WeakMap();
  12906. function get( scene, renderCallDepth ) {
  12907. const listArray = lists.get( scene );
  12908. let list;
  12909. if ( listArray === undefined ) {
  12910. list = new WebGLRenderList();
  12911. lists.set( scene, [ list ] );
  12912. } else {
  12913. if ( renderCallDepth >= listArray.length ) {
  12914. list = new WebGLRenderList();
  12915. listArray.push( list );
  12916. } else {
  12917. list = listArray[ renderCallDepth ];
  12918. }
  12919. }
  12920. return list;
  12921. }
  12922. function dispose() {
  12923. lists = new WeakMap();
  12924. }
  12925. return {
  12926. get: get,
  12927. dispose: dispose
  12928. };
  12929. }
  12930. function UniformsCache() {
  12931. const lights = {};
  12932. return {
  12933. get: function ( light ) {
  12934. if ( lights[ light.id ] !== undefined ) {
  12935. return lights[ light.id ];
  12936. }
  12937. let uniforms;
  12938. switch ( light.type ) {
  12939. case 'DirectionalLight':
  12940. uniforms = {
  12941. direction: new Vector3(),
  12942. color: new Color()
  12943. };
  12944. break;
  12945. case 'SpotLight':
  12946. uniforms = {
  12947. position: new Vector3(),
  12948. direction: new Vector3(),
  12949. color: new Color(),
  12950. distance: 0,
  12951. coneCos: 0,
  12952. penumbraCos: 0,
  12953. decay: 0
  12954. };
  12955. break;
  12956. case 'PointLight':
  12957. uniforms = {
  12958. position: new Vector3(),
  12959. color: new Color(),
  12960. distance: 0,
  12961. decay: 0
  12962. };
  12963. break;
  12964. case 'HemisphereLight':
  12965. uniforms = {
  12966. direction: new Vector3(),
  12967. skyColor: new Color(),
  12968. groundColor: new Color()
  12969. };
  12970. break;
  12971. case 'RectAreaLight':
  12972. uniforms = {
  12973. color: new Color(),
  12974. position: new Vector3(),
  12975. halfWidth: new Vector3(),
  12976. halfHeight: new Vector3()
  12977. };
  12978. break;
  12979. }
  12980. lights[ light.id ] = uniforms;
  12981. return uniforms;
  12982. }
  12983. };
  12984. }
  12985. function ShadowUniformsCache() {
  12986. const lights = {};
  12987. return {
  12988. get: function ( light ) {
  12989. if ( lights[ light.id ] !== undefined ) {
  12990. return lights[ light.id ];
  12991. }
  12992. let uniforms;
  12993. switch ( light.type ) {
  12994. case 'DirectionalLight':
  12995. uniforms = {
  12996. shadowIntensity: 1,
  12997. shadowBias: 0,
  12998. shadowNormalBias: 0,
  12999. shadowRadius: 1,
  13000. shadowMapSize: new Vector2()
  13001. };
  13002. break;
  13003. case 'SpotLight':
  13004. uniforms = {
  13005. shadowIntensity: 1,
  13006. shadowBias: 0,
  13007. shadowNormalBias: 0,
  13008. shadowRadius: 1,
  13009. shadowMapSize: new Vector2()
  13010. };
  13011. break;
  13012. case 'PointLight':
  13013. uniforms = {
  13014. shadowIntensity: 1,
  13015. shadowBias: 0,
  13016. shadowNormalBias: 0,
  13017. shadowRadius: 1,
  13018. shadowMapSize: new Vector2(),
  13019. shadowCameraNear: 1,
  13020. shadowCameraFar: 1000
  13021. };
  13022. break;
  13023. // TODO (abelnation): set RectAreaLight shadow uniforms
  13024. }
  13025. lights[ light.id ] = uniforms;
  13026. return uniforms;
  13027. }
  13028. };
  13029. }
  13030. let nextVersion = 0;
  13031. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  13032. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  13033. }
  13034. function WebGLLights( extensions ) {
  13035. const cache = new UniformsCache();
  13036. const shadowCache = ShadowUniformsCache();
  13037. const state = {
  13038. version: 0,
  13039. hash: {
  13040. directionalLength: - 1,
  13041. pointLength: - 1,
  13042. spotLength: - 1,
  13043. rectAreaLength: - 1,
  13044. hemiLength: - 1,
  13045. numDirectionalShadows: - 1,
  13046. numPointShadows: - 1,
  13047. numSpotShadows: - 1,
  13048. numSpotMaps: - 1,
  13049. numLightProbes: - 1
  13050. },
  13051. ambient: [ 0, 0, 0 ],
  13052. probe: [],
  13053. directional: [],
  13054. directionalShadow: [],
  13055. directionalShadowMap: [],
  13056. directionalShadowMatrix: [],
  13057. spot: [],
  13058. spotLightMap: [],
  13059. spotShadow: [],
  13060. spotShadowMap: [],
  13061. spotLightMatrix: [],
  13062. rectArea: [],
  13063. rectAreaLTC1: null,
  13064. rectAreaLTC2: null,
  13065. point: [],
  13066. pointShadow: [],
  13067. pointShadowMap: [],
  13068. pointShadowMatrix: [],
  13069. hemi: [],
  13070. numSpotLightShadowsWithMaps: 0,
  13071. numLightProbes: 0
  13072. };
  13073. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  13074. const vector3 = new Vector3();
  13075. const matrix4 = new Matrix4();
  13076. const matrix42 = new Matrix4();
  13077. function setup( lights ) {
  13078. let r = 0, g = 0, b = 0;
  13079. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  13080. let directionalLength = 0;
  13081. let pointLength = 0;
  13082. let spotLength = 0;
  13083. let rectAreaLength = 0;
  13084. let hemiLength = 0;
  13085. let numDirectionalShadows = 0;
  13086. let numPointShadows = 0;
  13087. let numSpotShadows = 0;
  13088. let numSpotMaps = 0;
  13089. let numSpotShadowsWithMaps = 0;
  13090. let numLightProbes = 0;
  13091. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  13092. lights.sort( shadowCastingAndTexturingLightsFirst );
  13093. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13094. const light = lights[ i ];
  13095. const color = light.color;
  13096. const intensity = light.intensity;
  13097. const distance = light.distance;
  13098. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13099. if ( light.isAmbientLight ) {
  13100. r += color.r * intensity;
  13101. g += color.g * intensity;
  13102. b += color.b * intensity;
  13103. } else if ( light.isLightProbe ) {
  13104. for ( let j = 0; j < 9; j ++ ) {
  13105. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  13106. }
  13107. numLightProbes ++;
  13108. } else if ( light.isDirectionalLight ) {
  13109. const uniforms = cache.get( light );
  13110. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13111. if ( light.castShadow ) {
  13112. const shadow = light.shadow;
  13113. const shadowUniforms = shadowCache.get( light );
  13114. shadowUniforms.shadowIntensity = shadow.intensity;
  13115. shadowUniforms.shadowBias = shadow.bias;
  13116. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13117. shadowUniforms.shadowRadius = shadow.radius;
  13118. shadowUniforms.shadowMapSize = shadow.mapSize;
  13119. state.directionalShadow[ directionalLength ] = shadowUniforms;
  13120. state.directionalShadowMap[ directionalLength ] = shadowMap;
  13121. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13122. numDirectionalShadows ++;
  13123. }
  13124. state.directional[ directionalLength ] = uniforms;
  13125. directionalLength ++;
  13126. } else if ( light.isSpotLight ) {
  13127. const uniforms = cache.get( light );
  13128. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13129. uniforms.color.copy( color ).multiplyScalar( intensity );
  13130. uniforms.distance = distance;
  13131. uniforms.coneCos = Math.cos( light.angle );
  13132. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13133. uniforms.decay = light.decay;
  13134. state.spot[ spotLength ] = uniforms;
  13135. const shadow = light.shadow;
  13136. if ( light.map ) {
  13137. state.spotLightMap[ numSpotMaps ] = light.map;
  13138. numSpotMaps ++;
  13139. // make sure the lightMatrix is up to date
  13140. // TODO : do it if required only
  13141. shadow.updateMatrices( light );
  13142. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  13143. }
  13144. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  13145. if ( light.castShadow ) {
  13146. const shadowUniforms = shadowCache.get( light );
  13147. shadowUniforms.shadowIntensity = shadow.intensity;
  13148. shadowUniforms.shadowBias = shadow.bias;
  13149. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13150. shadowUniforms.shadowRadius = shadow.radius;
  13151. shadowUniforms.shadowMapSize = shadow.mapSize;
  13152. state.spotShadow[ spotLength ] = shadowUniforms;
  13153. state.spotShadowMap[ spotLength ] = shadowMap;
  13154. numSpotShadows ++;
  13155. }
  13156. spotLength ++;
  13157. } else if ( light.isRectAreaLight ) {
  13158. const uniforms = cache.get( light );
  13159. uniforms.color.copy( color ).multiplyScalar( intensity );
  13160. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13161. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13162. state.rectArea[ rectAreaLength ] = uniforms;
  13163. rectAreaLength ++;
  13164. } else if ( light.isPointLight ) {
  13165. const uniforms = cache.get( light );
  13166. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13167. uniforms.distance = light.distance;
  13168. uniforms.decay = light.decay;
  13169. if ( light.castShadow ) {
  13170. const shadow = light.shadow;
  13171. const shadowUniforms = shadowCache.get( light );
  13172. shadowUniforms.shadowIntensity = shadow.intensity;
  13173. shadowUniforms.shadowBias = shadow.bias;
  13174. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13175. shadowUniforms.shadowRadius = shadow.radius;
  13176. shadowUniforms.shadowMapSize = shadow.mapSize;
  13177. shadowUniforms.shadowCameraNear = shadow.camera.near;
  13178. shadowUniforms.shadowCameraFar = shadow.camera.far;
  13179. state.pointShadow[ pointLength ] = shadowUniforms;
  13180. state.pointShadowMap[ pointLength ] = shadowMap;
  13181. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13182. numPointShadows ++;
  13183. }
  13184. state.point[ pointLength ] = uniforms;
  13185. pointLength ++;
  13186. } else if ( light.isHemisphereLight ) {
  13187. const uniforms = cache.get( light );
  13188. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13189. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13190. state.hemi[ hemiLength ] = uniforms;
  13191. hemiLength ++;
  13192. }
  13193. }
  13194. if ( rectAreaLength > 0 ) {
  13195. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13196. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13197. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13198. } else {
  13199. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13200. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13201. }
  13202. }
  13203. state.ambient[ 0 ] = r;
  13204. state.ambient[ 1 ] = g;
  13205. state.ambient[ 2 ] = b;
  13206. const hash = state.hash;
  13207. if ( hash.directionalLength !== directionalLength ||
  13208. hash.pointLength !== pointLength ||
  13209. hash.spotLength !== spotLength ||
  13210. hash.rectAreaLength !== rectAreaLength ||
  13211. hash.hemiLength !== hemiLength ||
  13212. hash.numDirectionalShadows !== numDirectionalShadows ||
  13213. hash.numPointShadows !== numPointShadows ||
  13214. hash.numSpotShadows !== numSpotShadows ||
  13215. hash.numSpotMaps !== numSpotMaps ||
  13216. hash.numLightProbes !== numLightProbes ) {
  13217. state.directional.length = directionalLength;
  13218. state.spot.length = spotLength;
  13219. state.rectArea.length = rectAreaLength;
  13220. state.point.length = pointLength;
  13221. state.hemi.length = hemiLength;
  13222. state.directionalShadow.length = numDirectionalShadows;
  13223. state.directionalShadowMap.length = numDirectionalShadows;
  13224. state.pointShadow.length = numPointShadows;
  13225. state.pointShadowMap.length = numPointShadows;
  13226. state.spotShadow.length = numSpotShadows;
  13227. state.spotShadowMap.length = numSpotShadows;
  13228. state.directionalShadowMatrix.length = numDirectionalShadows;
  13229. state.pointShadowMatrix.length = numPointShadows;
  13230. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  13231. state.spotLightMap.length = numSpotMaps;
  13232. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  13233. state.numLightProbes = numLightProbes;
  13234. hash.directionalLength = directionalLength;
  13235. hash.pointLength = pointLength;
  13236. hash.spotLength = spotLength;
  13237. hash.rectAreaLength = rectAreaLength;
  13238. hash.hemiLength = hemiLength;
  13239. hash.numDirectionalShadows = numDirectionalShadows;
  13240. hash.numPointShadows = numPointShadows;
  13241. hash.numSpotShadows = numSpotShadows;
  13242. hash.numSpotMaps = numSpotMaps;
  13243. hash.numLightProbes = numLightProbes;
  13244. state.version = nextVersion ++;
  13245. }
  13246. }
  13247. function setupView( lights, camera ) {
  13248. let directionalLength = 0;
  13249. let pointLength = 0;
  13250. let spotLength = 0;
  13251. let rectAreaLength = 0;
  13252. let hemiLength = 0;
  13253. const viewMatrix = camera.matrixWorldInverse;
  13254. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13255. const light = lights[ i ];
  13256. if ( light.isDirectionalLight ) {
  13257. const uniforms = state.directional[ directionalLength ];
  13258. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13259. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13260. uniforms.direction.sub( vector3 );
  13261. uniforms.direction.transformDirection( viewMatrix );
  13262. directionalLength ++;
  13263. } else if ( light.isSpotLight ) {
  13264. const uniforms = state.spot[ spotLength ];
  13265. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13266. uniforms.position.applyMatrix4( viewMatrix );
  13267. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13268. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13269. uniforms.direction.sub( vector3 );
  13270. uniforms.direction.transformDirection( viewMatrix );
  13271. spotLength ++;
  13272. } else if ( light.isRectAreaLight ) {
  13273. const uniforms = state.rectArea[ rectAreaLength ];
  13274. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13275. uniforms.position.applyMatrix4( viewMatrix );
  13276. // extract local rotation of light to derive width/height half vectors
  13277. matrix42.identity();
  13278. matrix4.copy( light.matrixWorld );
  13279. matrix4.premultiply( viewMatrix );
  13280. matrix42.extractRotation( matrix4 );
  13281. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13282. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13283. uniforms.halfWidth.applyMatrix4( matrix42 );
  13284. uniforms.halfHeight.applyMatrix4( matrix42 );
  13285. rectAreaLength ++;
  13286. } else if ( light.isPointLight ) {
  13287. const uniforms = state.point[ pointLength ];
  13288. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13289. uniforms.position.applyMatrix4( viewMatrix );
  13290. pointLength ++;
  13291. } else if ( light.isHemisphereLight ) {
  13292. const uniforms = state.hemi[ hemiLength ];
  13293. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13294. uniforms.direction.transformDirection( viewMatrix );
  13295. hemiLength ++;
  13296. }
  13297. }
  13298. }
  13299. return {
  13300. setup: setup,
  13301. setupView: setupView,
  13302. state: state
  13303. };
  13304. }
  13305. function WebGLRenderState( extensions ) {
  13306. const lights = new WebGLLights( extensions );
  13307. const lightsArray = [];
  13308. const shadowsArray = [];
  13309. function init( camera ) {
  13310. state.camera = camera;
  13311. lightsArray.length = 0;
  13312. shadowsArray.length = 0;
  13313. }
  13314. function pushLight( light ) {
  13315. lightsArray.push( light );
  13316. }
  13317. function pushShadow( shadowLight ) {
  13318. shadowsArray.push( shadowLight );
  13319. }
  13320. function setupLights() {
  13321. lights.setup( lightsArray );
  13322. }
  13323. function setupLightsView( camera ) {
  13324. lights.setupView( lightsArray, camera );
  13325. }
  13326. const state = {
  13327. lightsArray: lightsArray,
  13328. shadowsArray: shadowsArray,
  13329. camera: null,
  13330. lights: lights,
  13331. transmissionRenderTarget: {}
  13332. };
  13333. return {
  13334. init: init,
  13335. state: state,
  13336. setupLights: setupLights,
  13337. setupLightsView: setupLightsView,
  13338. pushLight: pushLight,
  13339. pushShadow: pushShadow
  13340. };
  13341. }
  13342. function WebGLRenderStates( extensions ) {
  13343. let renderStates = new WeakMap();
  13344. function get( scene, renderCallDepth = 0 ) {
  13345. const renderStateArray = renderStates.get( scene );
  13346. let renderState;
  13347. if ( renderStateArray === undefined ) {
  13348. renderState = new WebGLRenderState( extensions );
  13349. renderStates.set( scene, [ renderState ] );
  13350. } else {
  13351. if ( renderCallDepth >= renderStateArray.length ) {
  13352. renderState = new WebGLRenderState( extensions );
  13353. renderStateArray.push( renderState );
  13354. } else {
  13355. renderState = renderStateArray[ renderCallDepth ];
  13356. }
  13357. }
  13358. return renderState;
  13359. }
  13360. function dispose() {
  13361. renderStates = new WeakMap();
  13362. }
  13363. return {
  13364. get: get,
  13365. dispose: dispose
  13366. };
  13367. }
  13368. class MeshDepthMaterial extends Material {
  13369. constructor( parameters ) {
  13370. super();
  13371. this.isMeshDepthMaterial = true;
  13372. this.type = 'MeshDepthMaterial';
  13373. this.depthPacking = BasicDepthPacking;
  13374. this.map = null;
  13375. this.alphaMap = null;
  13376. this.displacementMap = null;
  13377. this.displacementScale = 1;
  13378. this.displacementBias = 0;
  13379. this.wireframe = false;
  13380. this.wireframeLinewidth = 1;
  13381. this.setValues( parameters );
  13382. }
  13383. copy( source ) {
  13384. super.copy( source );
  13385. this.depthPacking = source.depthPacking;
  13386. this.map = source.map;
  13387. this.alphaMap = source.alphaMap;
  13388. this.displacementMap = source.displacementMap;
  13389. this.displacementScale = source.displacementScale;
  13390. this.displacementBias = source.displacementBias;
  13391. this.wireframe = source.wireframe;
  13392. this.wireframeLinewidth = source.wireframeLinewidth;
  13393. return this;
  13394. }
  13395. }
  13396. class MeshDistanceMaterial extends Material {
  13397. constructor( parameters ) {
  13398. super();
  13399. this.isMeshDistanceMaterial = true;
  13400. this.type = 'MeshDistanceMaterial';
  13401. this.map = null;
  13402. this.alphaMap = null;
  13403. this.displacementMap = null;
  13404. this.displacementScale = 1;
  13405. this.displacementBias = 0;
  13406. this.setValues( parameters );
  13407. }
  13408. copy( source ) {
  13409. super.copy( source );
  13410. this.map = source.map;
  13411. this.alphaMap = source.alphaMap;
  13412. this.displacementMap = source.displacementMap;
  13413. this.displacementScale = source.displacementScale;
  13414. this.displacementBias = source.displacementBias;
  13415. return this;
  13416. }
  13417. }
  13418. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13419. 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}";
  13420. function WebGLShadowMap( renderer, objects, capabilities ) {
  13421. let _frustum = new Frustum();
  13422. const _shadowMapSize = new Vector2(),
  13423. _viewportSize = new Vector2(),
  13424. _viewport = new Vector4(),
  13425. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13426. _distanceMaterial = new MeshDistanceMaterial(),
  13427. _materialCache = {},
  13428. _maxTextureSize = capabilities.maxTextureSize;
  13429. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13430. const shadowMaterialVertical = new ShaderMaterial( {
  13431. defines: {
  13432. VSM_SAMPLES: 8
  13433. },
  13434. uniforms: {
  13435. shadow_pass: { value: null },
  13436. resolution: { value: new Vector2() },
  13437. radius: { value: 4.0 }
  13438. },
  13439. vertexShader: vertex,
  13440. fragmentShader: fragment
  13441. } );
  13442. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13443. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13444. const fullScreenTri = new BufferGeometry();
  13445. fullScreenTri.setAttribute(
  13446. 'position',
  13447. new BufferAttribute(
  13448. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13449. 3
  13450. )
  13451. );
  13452. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13453. const scope = this;
  13454. this.enabled = false;
  13455. this.autoUpdate = true;
  13456. this.needsUpdate = false;
  13457. this.type = PCFShadowMap;
  13458. let _previousType = this.type;
  13459. this.render = function ( lights, scene, camera ) {
  13460. if ( scope.enabled === false ) return;
  13461. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13462. if ( lights.length === 0 ) return;
  13463. const currentRenderTarget = renderer.getRenderTarget();
  13464. const activeCubeFace = renderer.getActiveCubeFace();
  13465. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  13466. const _state = renderer.state;
  13467. // Set GL state for depth map.
  13468. _state.setBlending( NoBlending );
  13469. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13470. _state.buffers.depth.setTest( true );
  13471. _state.setScissorTest( false );
  13472. // check for shadow map type changes
  13473. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13474. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13475. // render depth map
  13476. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13477. const light = lights[ i ];
  13478. const shadow = light.shadow;
  13479. if ( shadow === undefined ) {
  13480. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13481. continue;
  13482. }
  13483. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13484. _shadowMapSize.copy( shadow.mapSize );
  13485. const shadowFrameExtents = shadow.getFrameExtents();
  13486. _shadowMapSize.multiply( shadowFrameExtents );
  13487. _viewportSize.copy( shadow.mapSize );
  13488. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13489. if ( _shadowMapSize.x > _maxTextureSize ) {
  13490. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13491. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13492. shadow.mapSize.x = _viewportSize.x;
  13493. }
  13494. if ( _shadowMapSize.y > _maxTextureSize ) {
  13495. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13496. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13497. shadow.mapSize.y = _viewportSize.y;
  13498. }
  13499. }
  13500. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13501. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13502. if ( shadow.map !== null ) {
  13503. shadow.map.dispose();
  13504. }
  13505. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13506. shadow.map.texture.name = light.name + '.shadowMap';
  13507. shadow.camera.updateProjectionMatrix();
  13508. }
  13509. renderer.setRenderTarget( shadow.map );
  13510. renderer.clear();
  13511. const viewportCount = shadow.getViewportCount();
  13512. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13513. const viewport = shadow.getViewport( vp );
  13514. _viewport.set(
  13515. _viewportSize.x * viewport.x,
  13516. _viewportSize.y * viewport.y,
  13517. _viewportSize.x * viewport.z,
  13518. _viewportSize.y * viewport.w
  13519. );
  13520. _state.viewport( _viewport );
  13521. shadow.updateMatrices( light, vp );
  13522. _frustum = shadow.getFrustum();
  13523. renderObject( scene, camera, shadow.camera, light, this.type );
  13524. }
  13525. // do blur pass for VSM
  13526. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13527. VSMPass( shadow, camera );
  13528. }
  13529. shadow.needsUpdate = false;
  13530. }
  13531. _previousType = this.type;
  13532. scope.needsUpdate = false;
  13533. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13534. };
  13535. function VSMPass( shadow, camera ) {
  13536. const geometry = objects.update( fullScreenMesh );
  13537. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13538. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13539. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13540. shadowMaterialVertical.needsUpdate = true;
  13541. shadowMaterialHorizontal.needsUpdate = true;
  13542. }
  13543. if ( shadow.mapPass === null ) {
  13544. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13545. }
  13546. // vertical pass
  13547. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13548. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13549. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13550. renderer.setRenderTarget( shadow.mapPass );
  13551. renderer.clear();
  13552. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13553. // horizontal pass
  13554. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13555. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13556. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13557. renderer.setRenderTarget( shadow.map );
  13558. renderer.clear();
  13559. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13560. }
  13561. function getDepthMaterial( object, material, light, type ) {
  13562. let result = null;
  13563. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13564. if ( customMaterial !== undefined ) {
  13565. result = customMaterial;
  13566. } else {
  13567. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13568. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13569. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13570. ( material.alphaMap && material.alphaTest > 0 ) ||
  13571. ( material.map && material.alphaTest > 0 ) ) {
  13572. // in this case we need a unique material instance reflecting the
  13573. // appropriate state
  13574. const keyA = result.uuid, keyB = material.uuid;
  13575. let materialsForVariant = _materialCache[ keyA ];
  13576. if ( materialsForVariant === undefined ) {
  13577. materialsForVariant = {};
  13578. _materialCache[ keyA ] = materialsForVariant;
  13579. }
  13580. let cachedMaterial = materialsForVariant[ keyB ];
  13581. if ( cachedMaterial === undefined ) {
  13582. cachedMaterial = result.clone();
  13583. materialsForVariant[ keyB ] = cachedMaterial;
  13584. material.addEventListener( 'dispose', onMaterialDispose );
  13585. }
  13586. result = cachedMaterial;
  13587. }
  13588. }
  13589. result.visible = material.visible;
  13590. result.wireframe = material.wireframe;
  13591. if ( type === VSMShadowMap ) {
  13592. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13593. } else {
  13594. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13595. }
  13596. result.alphaMap = material.alphaMap;
  13597. result.alphaTest = material.alphaTest;
  13598. result.map = material.map;
  13599. result.clipShadows = material.clipShadows;
  13600. result.clippingPlanes = material.clippingPlanes;
  13601. result.clipIntersection = material.clipIntersection;
  13602. result.displacementMap = material.displacementMap;
  13603. result.displacementScale = material.displacementScale;
  13604. result.displacementBias = material.displacementBias;
  13605. result.wireframeLinewidth = material.wireframeLinewidth;
  13606. result.linewidth = material.linewidth;
  13607. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13608. const materialProperties = renderer.properties.get( result );
  13609. materialProperties.light = light;
  13610. }
  13611. return result;
  13612. }
  13613. function renderObject( object, camera, shadowCamera, light, type ) {
  13614. if ( object.visible === false ) return;
  13615. const visible = object.layers.test( camera.layers );
  13616. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13617. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13618. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13619. const geometry = objects.update( object );
  13620. const material = object.material;
  13621. if ( Array.isArray( material ) ) {
  13622. const groups = geometry.groups;
  13623. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13624. const group = groups[ k ];
  13625. const groupMaterial = material[ group.materialIndex ];
  13626. if ( groupMaterial && groupMaterial.visible ) {
  13627. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13628. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13629. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13630. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13631. }
  13632. }
  13633. } else if ( material.visible ) {
  13634. const depthMaterial = getDepthMaterial( object, material, light, type );
  13635. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13636. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13637. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13638. }
  13639. }
  13640. }
  13641. const children = object.children;
  13642. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13643. renderObject( children[ i ], camera, shadowCamera, light, type );
  13644. }
  13645. }
  13646. function onMaterialDispose( event ) {
  13647. const material = event.target;
  13648. material.removeEventListener( 'dispose', onMaterialDispose );
  13649. // make sure to remove the unique distance/depth materials used for shadow map rendering
  13650. for ( const id in _materialCache ) {
  13651. const cache = _materialCache[ id ];
  13652. const uuid = event.target.uuid;
  13653. if ( uuid in cache ) {
  13654. const shadowMaterial = cache[ uuid ];
  13655. shadowMaterial.dispose();
  13656. delete cache[ uuid ];
  13657. }
  13658. }
  13659. }
  13660. }
  13661. function WebGLState( gl ) {
  13662. function ColorBuffer() {
  13663. let locked = false;
  13664. const color = new Vector4();
  13665. let currentColorMask = null;
  13666. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13667. return {
  13668. setMask: function ( colorMask ) {
  13669. if ( currentColorMask !== colorMask && ! locked ) {
  13670. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13671. currentColorMask = colorMask;
  13672. }
  13673. },
  13674. setLocked: function ( lock ) {
  13675. locked = lock;
  13676. },
  13677. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13678. if ( premultipliedAlpha === true ) {
  13679. r *= a; g *= a; b *= a;
  13680. }
  13681. color.set( r, g, b, a );
  13682. if ( currentColorClear.equals( color ) === false ) {
  13683. gl.clearColor( r, g, b, a );
  13684. currentColorClear.copy( color );
  13685. }
  13686. },
  13687. reset: function () {
  13688. locked = false;
  13689. currentColorMask = null;
  13690. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13691. }
  13692. };
  13693. }
  13694. function DepthBuffer() {
  13695. let locked = false;
  13696. let currentDepthMask = null;
  13697. let currentDepthFunc = null;
  13698. let currentDepthClear = null;
  13699. return {
  13700. setTest: function ( depthTest ) {
  13701. if ( depthTest ) {
  13702. enable( gl.DEPTH_TEST );
  13703. } else {
  13704. disable( gl.DEPTH_TEST );
  13705. }
  13706. },
  13707. setMask: function ( depthMask ) {
  13708. if ( currentDepthMask !== depthMask && ! locked ) {
  13709. gl.depthMask( depthMask );
  13710. currentDepthMask = depthMask;
  13711. }
  13712. },
  13713. setFunc: function ( depthFunc ) {
  13714. if ( currentDepthFunc !== depthFunc ) {
  13715. switch ( depthFunc ) {
  13716. case NeverDepth:
  13717. gl.depthFunc( gl.NEVER );
  13718. break;
  13719. case AlwaysDepth:
  13720. gl.depthFunc( gl.ALWAYS );
  13721. break;
  13722. case LessDepth:
  13723. gl.depthFunc( gl.LESS );
  13724. break;
  13725. case LessEqualDepth:
  13726. gl.depthFunc( gl.LEQUAL );
  13727. break;
  13728. case EqualDepth:
  13729. gl.depthFunc( gl.EQUAL );
  13730. break;
  13731. case GreaterEqualDepth:
  13732. gl.depthFunc( gl.GEQUAL );
  13733. break;
  13734. case GreaterDepth:
  13735. gl.depthFunc( gl.GREATER );
  13736. break;
  13737. case NotEqualDepth:
  13738. gl.depthFunc( gl.NOTEQUAL );
  13739. break;
  13740. default:
  13741. gl.depthFunc( gl.LEQUAL );
  13742. }
  13743. currentDepthFunc = depthFunc;
  13744. }
  13745. },
  13746. setLocked: function ( lock ) {
  13747. locked = lock;
  13748. },
  13749. setClear: function ( depth ) {
  13750. if ( currentDepthClear !== depth ) {
  13751. gl.clearDepth( depth );
  13752. currentDepthClear = depth;
  13753. }
  13754. },
  13755. reset: function () {
  13756. locked = false;
  13757. currentDepthMask = null;
  13758. currentDepthFunc = null;
  13759. currentDepthClear = null;
  13760. }
  13761. };
  13762. }
  13763. function StencilBuffer() {
  13764. let locked = false;
  13765. let currentStencilMask = null;
  13766. let currentStencilFunc = null;
  13767. let currentStencilRef = null;
  13768. let currentStencilFuncMask = null;
  13769. let currentStencilFail = null;
  13770. let currentStencilZFail = null;
  13771. let currentStencilZPass = null;
  13772. let currentStencilClear = null;
  13773. return {
  13774. setTest: function ( stencilTest ) {
  13775. if ( ! locked ) {
  13776. if ( stencilTest ) {
  13777. enable( gl.STENCIL_TEST );
  13778. } else {
  13779. disable( gl.STENCIL_TEST );
  13780. }
  13781. }
  13782. },
  13783. setMask: function ( stencilMask ) {
  13784. if ( currentStencilMask !== stencilMask && ! locked ) {
  13785. gl.stencilMask( stencilMask );
  13786. currentStencilMask = stencilMask;
  13787. }
  13788. },
  13789. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13790. if ( currentStencilFunc !== stencilFunc ||
  13791. currentStencilRef !== stencilRef ||
  13792. currentStencilFuncMask !== stencilMask ) {
  13793. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13794. currentStencilFunc = stencilFunc;
  13795. currentStencilRef = stencilRef;
  13796. currentStencilFuncMask = stencilMask;
  13797. }
  13798. },
  13799. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13800. if ( currentStencilFail !== stencilFail ||
  13801. currentStencilZFail !== stencilZFail ||
  13802. currentStencilZPass !== stencilZPass ) {
  13803. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13804. currentStencilFail = stencilFail;
  13805. currentStencilZFail = stencilZFail;
  13806. currentStencilZPass = stencilZPass;
  13807. }
  13808. },
  13809. setLocked: function ( lock ) {
  13810. locked = lock;
  13811. },
  13812. setClear: function ( stencil ) {
  13813. if ( currentStencilClear !== stencil ) {
  13814. gl.clearStencil( stencil );
  13815. currentStencilClear = stencil;
  13816. }
  13817. },
  13818. reset: function () {
  13819. locked = false;
  13820. currentStencilMask = null;
  13821. currentStencilFunc = null;
  13822. currentStencilRef = null;
  13823. currentStencilFuncMask = null;
  13824. currentStencilFail = null;
  13825. currentStencilZFail = null;
  13826. currentStencilZPass = null;
  13827. currentStencilClear = null;
  13828. }
  13829. };
  13830. }
  13831. //
  13832. const colorBuffer = new ColorBuffer();
  13833. const depthBuffer = new DepthBuffer();
  13834. const stencilBuffer = new StencilBuffer();
  13835. const uboBindings = new WeakMap();
  13836. const uboProgramMap = new WeakMap();
  13837. let enabledCapabilities = {};
  13838. let currentBoundFramebuffers = {};
  13839. let currentDrawbuffers = new WeakMap();
  13840. let defaultDrawbuffers = [];
  13841. let currentProgram = null;
  13842. let currentBlendingEnabled = false;
  13843. let currentBlending = null;
  13844. let currentBlendEquation = null;
  13845. let currentBlendSrc = null;
  13846. let currentBlendDst = null;
  13847. let currentBlendEquationAlpha = null;
  13848. let currentBlendSrcAlpha = null;
  13849. let currentBlendDstAlpha = null;
  13850. let currentBlendColor = new Color( 0, 0, 0 );
  13851. let currentBlendAlpha = 0;
  13852. let currentPremultipledAlpha = false;
  13853. let currentFlipSided = null;
  13854. let currentCullFace = null;
  13855. let currentLineWidth = null;
  13856. let currentPolygonOffsetFactor = null;
  13857. let currentPolygonOffsetUnits = null;
  13858. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13859. let lineWidthAvailable = false;
  13860. let version = 0;
  13861. const glVersion = gl.getParameter( gl.VERSION );
  13862. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13863. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13864. lineWidthAvailable = ( version >= 1.0 );
  13865. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13866. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13867. lineWidthAvailable = ( version >= 2.0 );
  13868. }
  13869. let currentTextureSlot = null;
  13870. let currentBoundTextures = {};
  13871. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13872. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13873. const currentScissor = new Vector4().fromArray( scissorParam );
  13874. const currentViewport = new Vector4().fromArray( viewportParam );
  13875. function createTexture( type, target, count, dimensions ) {
  13876. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13877. const texture = gl.createTexture();
  13878. gl.bindTexture( type, texture );
  13879. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13880. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13881. for ( let i = 0; i < count; i ++ ) {
  13882. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  13883. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13884. } else {
  13885. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13886. }
  13887. }
  13888. return texture;
  13889. }
  13890. const emptyTextures = {};
  13891. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13892. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13893. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13894. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13895. // init
  13896. colorBuffer.setClear( 0, 0, 0, 1 );
  13897. depthBuffer.setClear( 1 );
  13898. stencilBuffer.setClear( 0 );
  13899. enable( gl.DEPTH_TEST );
  13900. depthBuffer.setFunc( LessEqualDepth );
  13901. setFlipSided( false );
  13902. setCullFace( CullFaceBack );
  13903. enable( gl.CULL_FACE );
  13904. setBlending( NoBlending );
  13905. //
  13906. function enable( id ) {
  13907. if ( enabledCapabilities[ id ] !== true ) {
  13908. gl.enable( id );
  13909. enabledCapabilities[ id ] = true;
  13910. }
  13911. }
  13912. function disable( id ) {
  13913. if ( enabledCapabilities[ id ] !== false ) {
  13914. gl.disable( id );
  13915. enabledCapabilities[ id ] = false;
  13916. }
  13917. }
  13918. function bindFramebuffer( target, framebuffer ) {
  13919. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13920. gl.bindFramebuffer( target, framebuffer );
  13921. currentBoundFramebuffers[ target ] = framebuffer;
  13922. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13923. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13924. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13925. }
  13926. if ( target === gl.FRAMEBUFFER ) {
  13927. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13928. }
  13929. return true;
  13930. }
  13931. return false;
  13932. }
  13933. function drawBuffers( renderTarget, framebuffer ) {
  13934. let drawBuffers = defaultDrawbuffers;
  13935. let needsUpdate = false;
  13936. if ( renderTarget ) {
  13937. drawBuffers = currentDrawbuffers.get( framebuffer );
  13938. if ( drawBuffers === undefined ) {
  13939. drawBuffers = [];
  13940. currentDrawbuffers.set( framebuffer, drawBuffers );
  13941. }
  13942. const textures = renderTarget.textures;
  13943. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13944. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13945. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13946. }
  13947. drawBuffers.length = textures.length;
  13948. needsUpdate = true;
  13949. }
  13950. } else {
  13951. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13952. drawBuffers[ 0 ] = gl.BACK;
  13953. needsUpdate = true;
  13954. }
  13955. }
  13956. if ( needsUpdate ) {
  13957. gl.drawBuffers( drawBuffers );
  13958. }
  13959. }
  13960. function useProgram( program ) {
  13961. if ( currentProgram !== program ) {
  13962. gl.useProgram( program );
  13963. currentProgram = program;
  13964. return true;
  13965. }
  13966. return false;
  13967. }
  13968. const equationToGL = {
  13969. [ AddEquation ]: gl.FUNC_ADD,
  13970. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13971. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13972. };
  13973. equationToGL[ MinEquation ] = gl.MIN;
  13974. equationToGL[ MaxEquation ] = gl.MAX;
  13975. const factorToGL = {
  13976. [ ZeroFactor ]: gl.ZERO,
  13977. [ OneFactor ]: gl.ONE,
  13978. [ SrcColorFactor ]: gl.SRC_COLOR,
  13979. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13980. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13981. [ DstColorFactor ]: gl.DST_COLOR,
  13982. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13983. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13984. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13985. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13986. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  13987. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  13988. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  13989. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  13990. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  13991. };
  13992. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  13993. if ( blending === NoBlending ) {
  13994. if ( currentBlendingEnabled === true ) {
  13995. disable( gl.BLEND );
  13996. currentBlendingEnabled = false;
  13997. }
  13998. return;
  13999. }
  14000. if ( currentBlendingEnabled === false ) {
  14001. enable( gl.BLEND );
  14002. currentBlendingEnabled = true;
  14003. }
  14004. if ( blending !== CustomBlending ) {
  14005. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  14006. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  14007. gl.blendEquation( gl.FUNC_ADD );
  14008. currentBlendEquation = AddEquation;
  14009. currentBlendEquationAlpha = AddEquation;
  14010. }
  14011. if ( premultipliedAlpha ) {
  14012. switch ( blending ) {
  14013. case NormalBlending:
  14014. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14015. break;
  14016. case AdditiveBlending:
  14017. gl.blendFunc( gl.ONE, gl.ONE );
  14018. break;
  14019. case SubtractiveBlending:
  14020. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  14021. break;
  14022. case MultiplyBlending:
  14023. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  14024. break;
  14025. default:
  14026. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14027. break;
  14028. }
  14029. } else {
  14030. switch ( blending ) {
  14031. case NormalBlending:
  14032. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14033. break;
  14034. case AdditiveBlending:
  14035. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  14036. break;
  14037. case SubtractiveBlending:
  14038. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  14039. break;
  14040. case MultiplyBlending:
  14041. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  14042. break;
  14043. default:
  14044. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14045. break;
  14046. }
  14047. }
  14048. currentBlendSrc = null;
  14049. currentBlendDst = null;
  14050. currentBlendSrcAlpha = null;
  14051. currentBlendDstAlpha = null;
  14052. currentBlendColor.set( 0, 0, 0 );
  14053. currentBlendAlpha = 0;
  14054. currentBlending = blending;
  14055. currentPremultipledAlpha = premultipliedAlpha;
  14056. }
  14057. return;
  14058. }
  14059. // custom blending
  14060. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14061. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14062. blendDstAlpha = blendDstAlpha || blendDst;
  14063. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14064. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  14065. currentBlendEquation = blendEquation;
  14066. currentBlendEquationAlpha = blendEquationAlpha;
  14067. }
  14068. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14069. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  14070. currentBlendSrc = blendSrc;
  14071. currentBlendDst = blendDst;
  14072. currentBlendSrcAlpha = blendSrcAlpha;
  14073. currentBlendDstAlpha = blendDstAlpha;
  14074. }
  14075. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  14076. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  14077. currentBlendColor.copy( blendColor );
  14078. currentBlendAlpha = blendAlpha;
  14079. }
  14080. currentBlending = blending;
  14081. currentPremultipledAlpha = false;
  14082. }
  14083. function setMaterial( material, frontFaceCW ) {
  14084. material.side === DoubleSide
  14085. ? disable( gl.CULL_FACE )
  14086. : enable( gl.CULL_FACE );
  14087. let flipSided = ( material.side === BackSide );
  14088. if ( frontFaceCW ) flipSided = ! flipSided;
  14089. setFlipSided( flipSided );
  14090. ( material.blending === NormalBlending && material.transparent === false )
  14091. ? setBlending( NoBlending )
  14092. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  14093. depthBuffer.setFunc( material.depthFunc );
  14094. depthBuffer.setTest( material.depthTest );
  14095. depthBuffer.setMask( material.depthWrite );
  14096. colorBuffer.setMask( material.colorWrite );
  14097. const stencilWrite = material.stencilWrite;
  14098. stencilBuffer.setTest( stencilWrite );
  14099. if ( stencilWrite ) {
  14100. stencilBuffer.setMask( material.stencilWriteMask );
  14101. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  14102. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  14103. }
  14104. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14105. material.alphaToCoverage === true
  14106. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  14107. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14108. }
  14109. //
  14110. function setFlipSided( flipSided ) {
  14111. if ( currentFlipSided !== flipSided ) {
  14112. if ( flipSided ) {
  14113. gl.frontFace( gl.CW );
  14114. } else {
  14115. gl.frontFace( gl.CCW );
  14116. }
  14117. currentFlipSided = flipSided;
  14118. }
  14119. }
  14120. function setCullFace( cullFace ) {
  14121. if ( cullFace !== CullFaceNone ) {
  14122. enable( gl.CULL_FACE );
  14123. if ( cullFace !== currentCullFace ) {
  14124. if ( cullFace === CullFaceBack ) {
  14125. gl.cullFace( gl.BACK );
  14126. } else if ( cullFace === CullFaceFront ) {
  14127. gl.cullFace( gl.FRONT );
  14128. } else {
  14129. gl.cullFace( gl.FRONT_AND_BACK );
  14130. }
  14131. }
  14132. } else {
  14133. disable( gl.CULL_FACE );
  14134. }
  14135. currentCullFace = cullFace;
  14136. }
  14137. function setLineWidth( width ) {
  14138. if ( width !== currentLineWidth ) {
  14139. if ( lineWidthAvailable ) gl.lineWidth( width );
  14140. currentLineWidth = width;
  14141. }
  14142. }
  14143. function setPolygonOffset( polygonOffset, factor, units ) {
  14144. if ( polygonOffset ) {
  14145. enable( gl.POLYGON_OFFSET_FILL );
  14146. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  14147. gl.polygonOffset( factor, units );
  14148. currentPolygonOffsetFactor = factor;
  14149. currentPolygonOffsetUnits = units;
  14150. }
  14151. } else {
  14152. disable( gl.POLYGON_OFFSET_FILL );
  14153. }
  14154. }
  14155. function setScissorTest( scissorTest ) {
  14156. if ( scissorTest ) {
  14157. enable( gl.SCISSOR_TEST );
  14158. } else {
  14159. disable( gl.SCISSOR_TEST );
  14160. }
  14161. }
  14162. // texture
  14163. function activeTexture( webglSlot ) {
  14164. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14165. if ( currentTextureSlot !== webglSlot ) {
  14166. gl.activeTexture( webglSlot );
  14167. currentTextureSlot = webglSlot;
  14168. }
  14169. }
  14170. function bindTexture( webglType, webglTexture, webglSlot ) {
  14171. if ( webglSlot === undefined ) {
  14172. if ( currentTextureSlot === null ) {
  14173. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14174. } else {
  14175. webglSlot = currentTextureSlot;
  14176. }
  14177. }
  14178. let boundTexture = currentBoundTextures[ webglSlot ];
  14179. if ( boundTexture === undefined ) {
  14180. boundTexture = { type: undefined, texture: undefined };
  14181. currentBoundTextures[ webglSlot ] = boundTexture;
  14182. }
  14183. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14184. if ( currentTextureSlot !== webglSlot ) {
  14185. gl.activeTexture( webglSlot );
  14186. currentTextureSlot = webglSlot;
  14187. }
  14188. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14189. boundTexture.type = webglType;
  14190. boundTexture.texture = webglTexture;
  14191. }
  14192. }
  14193. function unbindTexture() {
  14194. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  14195. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  14196. gl.bindTexture( boundTexture.type, null );
  14197. boundTexture.type = undefined;
  14198. boundTexture.texture = undefined;
  14199. }
  14200. }
  14201. function compressedTexImage2D() {
  14202. try {
  14203. gl.compressedTexImage2D.apply( gl, arguments );
  14204. } catch ( error ) {
  14205. console.error( 'THREE.WebGLState:', error );
  14206. }
  14207. }
  14208. function compressedTexImage3D() {
  14209. try {
  14210. gl.compressedTexImage3D.apply( gl, arguments );
  14211. } catch ( error ) {
  14212. console.error( 'THREE.WebGLState:', error );
  14213. }
  14214. }
  14215. function texSubImage2D() {
  14216. try {
  14217. gl.texSubImage2D.apply( gl, arguments );
  14218. } catch ( error ) {
  14219. console.error( 'THREE.WebGLState:', error );
  14220. }
  14221. }
  14222. function texSubImage3D() {
  14223. try {
  14224. gl.texSubImage3D.apply( gl, arguments );
  14225. } catch ( error ) {
  14226. console.error( 'THREE.WebGLState:', error );
  14227. }
  14228. }
  14229. function compressedTexSubImage2D() {
  14230. try {
  14231. gl.compressedTexSubImage2D.apply( gl, arguments );
  14232. } catch ( error ) {
  14233. console.error( 'THREE.WebGLState:', error );
  14234. }
  14235. }
  14236. function compressedTexSubImage3D() {
  14237. try {
  14238. gl.compressedTexSubImage3D.apply( gl, arguments );
  14239. } catch ( error ) {
  14240. console.error( 'THREE.WebGLState:', error );
  14241. }
  14242. }
  14243. function texStorage2D() {
  14244. try {
  14245. gl.texStorage2D.apply( gl, arguments );
  14246. } catch ( error ) {
  14247. console.error( 'THREE.WebGLState:', error );
  14248. }
  14249. }
  14250. function texStorage3D() {
  14251. try {
  14252. gl.texStorage3D.apply( gl, arguments );
  14253. } catch ( error ) {
  14254. console.error( 'THREE.WebGLState:', error );
  14255. }
  14256. }
  14257. function texImage2D() {
  14258. try {
  14259. gl.texImage2D.apply( gl, arguments );
  14260. } catch ( error ) {
  14261. console.error( 'THREE.WebGLState:', error );
  14262. }
  14263. }
  14264. function texImage3D() {
  14265. try {
  14266. gl.texImage3D.apply( gl, arguments );
  14267. } catch ( error ) {
  14268. console.error( 'THREE.WebGLState:', error );
  14269. }
  14270. }
  14271. //
  14272. function scissor( scissor ) {
  14273. if ( currentScissor.equals( scissor ) === false ) {
  14274. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14275. currentScissor.copy( scissor );
  14276. }
  14277. }
  14278. function viewport( viewport ) {
  14279. if ( currentViewport.equals( viewport ) === false ) {
  14280. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14281. currentViewport.copy( viewport );
  14282. }
  14283. }
  14284. function updateUBOMapping( uniformsGroup, program ) {
  14285. let mapping = uboProgramMap.get( program );
  14286. if ( mapping === undefined ) {
  14287. mapping = new WeakMap();
  14288. uboProgramMap.set( program, mapping );
  14289. }
  14290. let blockIndex = mapping.get( uniformsGroup );
  14291. if ( blockIndex === undefined ) {
  14292. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14293. mapping.set( uniformsGroup, blockIndex );
  14294. }
  14295. }
  14296. function uniformBlockBinding( uniformsGroup, program ) {
  14297. const mapping = uboProgramMap.get( program );
  14298. const blockIndex = mapping.get( uniformsGroup );
  14299. if ( uboBindings.get( program ) !== blockIndex ) {
  14300. // bind shader specific block index to global block point
  14301. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14302. uboBindings.set( program, blockIndex );
  14303. }
  14304. }
  14305. //
  14306. function reset() {
  14307. // reset state
  14308. gl.disable( gl.BLEND );
  14309. gl.disable( gl.CULL_FACE );
  14310. gl.disable( gl.DEPTH_TEST );
  14311. gl.disable( gl.POLYGON_OFFSET_FILL );
  14312. gl.disable( gl.SCISSOR_TEST );
  14313. gl.disable( gl.STENCIL_TEST );
  14314. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14315. gl.blendEquation( gl.FUNC_ADD );
  14316. gl.blendFunc( gl.ONE, gl.ZERO );
  14317. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14318. gl.blendColor( 0, 0, 0, 0 );
  14319. gl.colorMask( true, true, true, true );
  14320. gl.clearColor( 0, 0, 0, 0 );
  14321. gl.depthMask( true );
  14322. gl.depthFunc( gl.LESS );
  14323. gl.clearDepth( 1 );
  14324. gl.stencilMask( 0xffffffff );
  14325. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14326. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14327. gl.clearStencil( 0 );
  14328. gl.cullFace( gl.BACK );
  14329. gl.frontFace( gl.CCW );
  14330. gl.polygonOffset( 0, 0 );
  14331. gl.activeTexture( gl.TEXTURE0 );
  14332. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14333. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14334. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14335. gl.useProgram( null );
  14336. gl.lineWidth( 1 );
  14337. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14338. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14339. // reset internals
  14340. enabledCapabilities = {};
  14341. currentTextureSlot = null;
  14342. currentBoundTextures = {};
  14343. currentBoundFramebuffers = {};
  14344. currentDrawbuffers = new WeakMap();
  14345. defaultDrawbuffers = [];
  14346. currentProgram = null;
  14347. currentBlendingEnabled = false;
  14348. currentBlending = null;
  14349. currentBlendEquation = null;
  14350. currentBlendSrc = null;
  14351. currentBlendDst = null;
  14352. currentBlendEquationAlpha = null;
  14353. currentBlendSrcAlpha = null;
  14354. currentBlendDstAlpha = null;
  14355. currentBlendColor = new Color( 0, 0, 0 );
  14356. currentBlendAlpha = 0;
  14357. currentPremultipledAlpha = false;
  14358. currentFlipSided = null;
  14359. currentCullFace = null;
  14360. currentLineWidth = null;
  14361. currentPolygonOffsetFactor = null;
  14362. currentPolygonOffsetUnits = null;
  14363. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14364. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14365. colorBuffer.reset();
  14366. depthBuffer.reset();
  14367. stencilBuffer.reset();
  14368. }
  14369. return {
  14370. buffers: {
  14371. color: colorBuffer,
  14372. depth: depthBuffer,
  14373. stencil: stencilBuffer
  14374. },
  14375. enable: enable,
  14376. disable: disable,
  14377. bindFramebuffer: bindFramebuffer,
  14378. drawBuffers: drawBuffers,
  14379. useProgram: useProgram,
  14380. setBlending: setBlending,
  14381. setMaterial: setMaterial,
  14382. setFlipSided: setFlipSided,
  14383. setCullFace: setCullFace,
  14384. setLineWidth: setLineWidth,
  14385. setPolygonOffset: setPolygonOffset,
  14386. setScissorTest: setScissorTest,
  14387. activeTexture: activeTexture,
  14388. bindTexture: bindTexture,
  14389. unbindTexture: unbindTexture,
  14390. compressedTexImage2D: compressedTexImage2D,
  14391. compressedTexImage3D: compressedTexImage3D,
  14392. texImage2D: texImage2D,
  14393. texImage3D: texImage3D,
  14394. updateUBOMapping: updateUBOMapping,
  14395. uniformBlockBinding: uniformBlockBinding,
  14396. texStorage2D: texStorage2D,
  14397. texStorage3D: texStorage3D,
  14398. texSubImage2D: texSubImage2D,
  14399. texSubImage3D: texSubImage3D,
  14400. compressedTexSubImage2D: compressedTexSubImage2D,
  14401. compressedTexSubImage3D: compressedTexSubImage3D,
  14402. scissor: scissor,
  14403. viewport: viewport,
  14404. reset: reset
  14405. };
  14406. }
  14407. function contain( texture, aspect ) {
  14408. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  14409. if ( imageAspect > aspect ) {
  14410. texture.repeat.x = 1;
  14411. texture.repeat.y = imageAspect / aspect;
  14412. texture.offset.x = 0;
  14413. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  14414. } else {
  14415. texture.repeat.x = aspect / imageAspect;
  14416. texture.repeat.y = 1;
  14417. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  14418. texture.offset.y = 0;
  14419. }
  14420. return texture;
  14421. }
  14422. function cover( texture, aspect ) {
  14423. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  14424. if ( imageAspect > aspect ) {
  14425. texture.repeat.x = aspect / imageAspect;
  14426. texture.repeat.y = 1;
  14427. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  14428. texture.offset.y = 0;
  14429. } else {
  14430. texture.repeat.x = 1;
  14431. texture.repeat.y = imageAspect / aspect;
  14432. texture.offset.x = 0;
  14433. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  14434. }
  14435. return texture;
  14436. }
  14437. function fill( texture ) {
  14438. texture.repeat.x = 1;
  14439. texture.repeat.y = 1;
  14440. texture.offset.x = 0;
  14441. texture.offset.y = 0;
  14442. return texture;
  14443. }
  14444. /**
  14445. * Given the width, height, format, and type of a texture. Determines how many
  14446. * bytes must be used to represent the texture.
  14447. */
  14448. function getByteLength( width, height, format, type ) {
  14449. const typeByteLength = getTextureTypeByteLength( type );
  14450. switch ( format ) {
  14451. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  14452. case AlphaFormat:
  14453. return width * height;
  14454. case LuminanceFormat:
  14455. return width * height;
  14456. case LuminanceAlphaFormat:
  14457. return width * height * 2;
  14458. case RedFormat:
  14459. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  14460. case RedIntegerFormat:
  14461. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  14462. case RGFormat:
  14463. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14464. case RGIntegerFormat:
  14465. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14466. case RGBFormat:
  14467. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14468. case RGBAFormat:
  14469. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14470. case RGBAIntegerFormat:
  14471. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  14472. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  14473. case RGB_S3TC_DXT1_Format:
  14474. case RGBA_S3TC_DXT1_Format:
  14475. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  14476. case RGBA_S3TC_DXT3_Format:
  14477. case RGBA_S3TC_DXT5_Format:
  14478. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  14479. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  14480. case RGB_PVRTC_2BPPV1_Format:
  14481. case RGBA_PVRTC_2BPPV1_Format:
  14482. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  14483. case RGB_PVRTC_4BPPV1_Format:
  14484. case RGBA_PVRTC_4BPPV1_Format:
  14485. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  14486. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  14487. case RGB_ETC1_Format:
  14488. case RGB_ETC2_Format:
  14489. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  14490. case RGBA_ETC2_EAC_Format:
  14491. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  14492. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  14493. case RGBA_ASTC_4x4_Format:
  14494. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  14495. case RGBA_ASTC_5x4_Format:
  14496. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  14497. case RGBA_ASTC_5x5_Format:
  14498. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  14499. case RGBA_ASTC_6x5_Format:
  14500. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  14501. case RGBA_ASTC_6x6_Format:
  14502. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  14503. case RGBA_ASTC_8x5_Format:
  14504. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  14505. case RGBA_ASTC_8x6_Format:
  14506. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  14507. case RGBA_ASTC_8x8_Format:
  14508. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  14509. case RGBA_ASTC_10x5_Format:
  14510. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  14511. case RGBA_ASTC_10x6_Format:
  14512. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  14513. case RGBA_ASTC_10x8_Format:
  14514. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  14515. case RGBA_ASTC_10x10_Format:
  14516. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  14517. case RGBA_ASTC_12x10_Format:
  14518. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  14519. case RGBA_ASTC_12x12_Format:
  14520. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  14521. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  14522. case RGBA_BPTC_Format:
  14523. case RGB_BPTC_SIGNED_Format:
  14524. case RGB_BPTC_UNSIGNED_Format:
  14525. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  14526. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  14527. case RED_RGTC1_Format:
  14528. case SIGNED_RED_RGTC1_Format:
  14529. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  14530. case RED_GREEN_RGTC2_Format:
  14531. case SIGNED_RED_GREEN_RGTC2_Format:
  14532. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  14533. }
  14534. throw new Error(
  14535. `Unable to determine texture byte length for ${format} format.`,
  14536. );
  14537. }
  14538. function getTextureTypeByteLength( type ) {
  14539. switch ( type ) {
  14540. case UnsignedByteType:
  14541. case ByteType:
  14542. return { byteLength: 1, components: 1 };
  14543. case UnsignedShortType:
  14544. case ShortType:
  14545. case HalfFloatType:
  14546. return { byteLength: 2, components: 1 };
  14547. case UnsignedShort4444Type:
  14548. case UnsignedShort5551Type:
  14549. return { byteLength: 2, components: 4 };
  14550. case UnsignedIntType:
  14551. case IntType:
  14552. case FloatType:
  14553. return { byteLength: 4, components: 1 };
  14554. case UnsignedInt5999Type:
  14555. return { byteLength: 4, components: 3 };
  14556. }
  14557. throw new Error( `Unknown texture type ${type}.` );
  14558. }
  14559. const TextureUtils = {
  14560. contain,
  14561. cover,
  14562. fill,
  14563. getByteLength
  14564. };
  14565. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14566. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14567. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14568. const _imageDimensions = new Vector2();
  14569. const _videoTextures = new WeakMap();
  14570. let _canvas;
  14571. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14572. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14573. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14574. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14575. let useOffscreenCanvas = false;
  14576. try {
  14577. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14578. // eslint-disable-next-line compat/compat
  14579. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14580. } catch ( err ) {
  14581. // Ignore any errors
  14582. }
  14583. function createCanvas( width, height ) {
  14584. // Use OffscreenCanvas when available. Specially needed in web workers
  14585. return useOffscreenCanvas ?
  14586. // eslint-disable-next-line compat/compat
  14587. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14588. }
  14589. function resizeImage( image, needsNewCanvas, maxSize ) {
  14590. let scale = 1;
  14591. const dimensions = getDimensions( image );
  14592. // handle case if texture exceeds max size
  14593. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  14594. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  14595. }
  14596. // only perform resize if necessary
  14597. if ( scale < 1 ) {
  14598. // only perform resize for certain image types
  14599. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14600. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14601. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  14602. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  14603. const width = Math.floor( scale * dimensions.width );
  14604. const height = Math.floor( scale * dimensions.height );
  14605. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14606. // cube textures can't reuse the same canvas
  14607. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14608. canvas.width = width;
  14609. canvas.height = height;
  14610. const context = canvas.getContext( '2d' );
  14611. context.drawImage( image, 0, 0, width, height );
  14612. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  14613. return canvas;
  14614. } else {
  14615. if ( 'data' in image ) {
  14616. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  14617. }
  14618. return image;
  14619. }
  14620. }
  14621. return image;
  14622. }
  14623. function textureNeedsGenerateMipmaps( texture ) {
  14624. return texture.generateMipmaps && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14625. }
  14626. function generateMipmap( target ) {
  14627. _gl.generateMipmap( target );
  14628. }
  14629. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14630. if ( internalFormatName !== null ) {
  14631. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14632. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14633. }
  14634. let internalFormat = glFormat;
  14635. if ( glFormat === _gl.RED ) {
  14636. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14637. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14638. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14639. }
  14640. if ( glFormat === _gl.RED_INTEGER ) {
  14641. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  14642. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  14643. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  14644. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  14645. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  14646. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  14647. }
  14648. if ( glFormat === _gl.RG ) {
  14649. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14650. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14651. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14652. }
  14653. if ( glFormat === _gl.RG_INTEGER ) {
  14654. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  14655. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  14656. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  14657. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  14658. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  14659. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  14660. }
  14661. if ( glFormat === _gl.RGB ) {
  14662. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  14663. }
  14664. if ( glFormat === _gl.RGBA ) {
  14665. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  14666. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14667. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14668. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14669. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14670. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14671. }
  14672. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14673. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14674. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14675. extensions.get( 'EXT_color_buffer_float' );
  14676. }
  14677. return internalFormat;
  14678. }
  14679. function getInternalDepthFormat( useStencil, depthType ) {
  14680. let glInternalFormat;
  14681. if ( useStencil ) {
  14682. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  14683. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14684. } else if ( depthType === FloatType ) {
  14685. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  14686. } else if ( depthType === UnsignedShortType ) {
  14687. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14688. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  14689. }
  14690. } else {
  14691. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  14692. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14693. } else if ( depthType === FloatType ) {
  14694. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14695. } else if ( depthType === UnsignedShortType ) {
  14696. glInternalFormat = _gl.DEPTH_COMPONENT16;
  14697. }
  14698. }
  14699. return glInternalFormat;
  14700. }
  14701. function getMipLevels( texture, image ) {
  14702. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14703. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14704. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14705. // user-defined mipmaps
  14706. return texture.mipmaps.length;
  14707. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14708. return image.mipmaps.length;
  14709. } else {
  14710. // texture without mipmaps (only base level)
  14711. return 1;
  14712. }
  14713. }
  14714. //
  14715. function onTextureDispose( event ) {
  14716. const texture = event.target;
  14717. texture.removeEventListener( 'dispose', onTextureDispose );
  14718. deallocateTexture( texture );
  14719. if ( texture.isVideoTexture ) {
  14720. _videoTextures.delete( texture );
  14721. }
  14722. }
  14723. function onRenderTargetDispose( event ) {
  14724. const renderTarget = event.target;
  14725. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14726. deallocateRenderTarget( renderTarget );
  14727. }
  14728. //
  14729. function deallocateTexture( texture ) {
  14730. const textureProperties = properties.get( texture );
  14731. if ( textureProperties.__webglInit === undefined ) return;
  14732. // check if it's necessary to remove the WebGLTexture object
  14733. const source = texture.source;
  14734. const webglTextures = _sources.get( source );
  14735. if ( webglTextures ) {
  14736. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14737. webglTexture.usedTimes --;
  14738. // the WebGLTexture object is not used anymore, remove it
  14739. if ( webglTexture.usedTimes === 0 ) {
  14740. deleteTexture( texture );
  14741. }
  14742. // remove the weak map entry if no WebGLTexture uses the source anymore
  14743. if ( Object.keys( webglTextures ).length === 0 ) {
  14744. _sources.delete( source );
  14745. }
  14746. }
  14747. properties.remove( texture );
  14748. }
  14749. function deleteTexture( texture ) {
  14750. const textureProperties = properties.get( texture );
  14751. _gl.deleteTexture( textureProperties.__webglTexture );
  14752. const source = texture.source;
  14753. const webglTextures = _sources.get( source );
  14754. delete webglTextures[ textureProperties.__cacheKey ];
  14755. info.memory.textures --;
  14756. }
  14757. function deallocateRenderTarget( renderTarget ) {
  14758. const renderTargetProperties = properties.get( renderTarget );
  14759. if ( renderTarget.depthTexture ) {
  14760. renderTarget.depthTexture.dispose();
  14761. }
  14762. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14763. for ( let i = 0; i < 6; i ++ ) {
  14764. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  14765. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  14766. } else {
  14767. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14768. }
  14769. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14770. }
  14771. } else {
  14772. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  14773. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  14774. } else {
  14775. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14776. }
  14777. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14778. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14779. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14780. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14781. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14782. }
  14783. }
  14784. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14785. }
  14786. const textures = renderTarget.textures;
  14787. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14788. const attachmentProperties = properties.get( textures[ i ] );
  14789. if ( attachmentProperties.__webglTexture ) {
  14790. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14791. info.memory.textures --;
  14792. }
  14793. properties.remove( textures[ i ] );
  14794. }
  14795. properties.remove( renderTarget );
  14796. }
  14797. //
  14798. let textureUnits = 0;
  14799. function resetTextureUnits() {
  14800. textureUnits = 0;
  14801. }
  14802. function allocateTextureUnit() {
  14803. const textureUnit = textureUnits;
  14804. if ( textureUnit >= capabilities.maxTextures ) {
  14805. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  14806. }
  14807. textureUnits += 1;
  14808. return textureUnit;
  14809. }
  14810. function getTextureCacheKey( texture ) {
  14811. const array = [];
  14812. array.push( texture.wrapS );
  14813. array.push( texture.wrapT );
  14814. array.push( texture.wrapR || 0 );
  14815. array.push( texture.magFilter );
  14816. array.push( texture.minFilter );
  14817. array.push( texture.anisotropy );
  14818. array.push( texture.internalFormat );
  14819. array.push( texture.format );
  14820. array.push( texture.type );
  14821. array.push( texture.generateMipmaps );
  14822. array.push( texture.premultiplyAlpha );
  14823. array.push( texture.flipY );
  14824. array.push( texture.unpackAlignment );
  14825. array.push( texture.colorSpace );
  14826. return array.join();
  14827. }
  14828. //
  14829. function setTexture2D( texture, slot ) {
  14830. const textureProperties = properties.get( texture );
  14831. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14832. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14833. const image = texture.image;
  14834. if ( image === null ) {
  14835. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14836. } else if ( image.complete === false ) {
  14837. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14838. } else {
  14839. uploadTexture( textureProperties, texture, slot );
  14840. return;
  14841. }
  14842. }
  14843. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14844. }
  14845. function setTexture2DArray( texture, slot ) {
  14846. const textureProperties = properties.get( texture );
  14847. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14848. uploadTexture( textureProperties, texture, slot );
  14849. return;
  14850. }
  14851. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14852. }
  14853. function setTexture3D( texture, slot ) {
  14854. const textureProperties = properties.get( texture );
  14855. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14856. uploadTexture( textureProperties, texture, slot );
  14857. return;
  14858. }
  14859. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14860. }
  14861. function setTextureCube( texture, slot ) {
  14862. const textureProperties = properties.get( texture );
  14863. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14864. uploadCubeTexture( textureProperties, texture, slot );
  14865. return;
  14866. }
  14867. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14868. }
  14869. const wrappingToGL = {
  14870. [ RepeatWrapping ]: _gl.REPEAT,
  14871. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14872. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14873. };
  14874. const filterToGL = {
  14875. [ NearestFilter ]: _gl.NEAREST,
  14876. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14877. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14878. [ LinearFilter ]: _gl.LINEAR,
  14879. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14880. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14881. };
  14882. const compareToGL = {
  14883. [ NeverCompare ]: _gl.NEVER,
  14884. [ AlwaysCompare ]: _gl.ALWAYS,
  14885. [ LessCompare ]: _gl.LESS,
  14886. [ LessEqualCompare ]: _gl.LEQUAL,
  14887. [ EqualCompare ]: _gl.EQUAL,
  14888. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14889. [ GreaterCompare ]: _gl.GREATER,
  14890. [ NotEqualCompare ]: _gl.NOTEQUAL
  14891. };
  14892. function setTextureParameters( textureType, texture ) {
  14893. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  14894. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  14895. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  14896. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  14897. }
  14898. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14899. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14900. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14901. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14902. }
  14903. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14904. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14905. if ( texture.compareFunction ) {
  14906. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14907. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14908. }
  14909. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14910. if ( texture.magFilter === NearestFilter ) return;
  14911. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14912. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  14913. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14914. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14915. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14916. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14917. }
  14918. }
  14919. }
  14920. function initTexture( textureProperties, texture ) {
  14921. let forceUpload = false;
  14922. if ( textureProperties.__webglInit === undefined ) {
  14923. textureProperties.__webglInit = true;
  14924. texture.addEventListener( 'dispose', onTextureDispose );
  14925. }
  14926. // create Source <-> WebGLTextures mapping if necessary
  14927. const source = texture.source;
  14928. let webglTextures = _sources.get( source );
  14929. if ( webglTextures === undefined ) {
  14930. webglTextures = {};
  14931. _sources.set( source, webglTextures );
  14932. }
  14933. // check if there is already a WebGLTexture object for the given texture parameters
  14934. const textureCacheKey = getTextureCacheKey( texture );
  14935. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14936. // if not, create a new instance of WebGLTexture
  14937. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14938. // create new entry
  14939. webglTextures[ textureCacheKey ] = {
  14940. texture: _gl.createTexture(),
  14941. usedTimes: 0
  14942. };
  14943. info.memory.textures ++;
  14944. // when a new instance of WebGLTexture was created, a texture upload is required
  14945. // even if the image contents are identical
  14946. forceUpload = true;
  14947. }
  14948. webglTextures[ textureCacheKey ].usedTimes ++;
  14949. // every time the texture cache key changes, it's necessary to check if an instance of
  14950. // WebGLTexture can be deleted in order to avoid a memory leak.
  14951. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14952. if ( webglTexture !== undefined ) {
  14953. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14954. if ( webglTexture.usedTimes === 0 ) {
  14955. deleteTexture( texture );
  14956. }
  14957. }
  14958. // store references to cache key and WebGLTexture object
  14959. textureProperties.__cacheKey = textureCacheKey;
  14960. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14961. }
  14962. return forceUpload;
  14963. }
  14964. function uploadTexture( textureProperties, texture, slot ) {
  14965. let textureType = _gl.TEXTURE_2D;
  14966. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14967. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14968. const forceUpload = initTexture( textureProperties, texture );
  14969. const source = texture.source;
  14970. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14971. const sourceProperties = properties.get( source );
  14972. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14973. state.activeTexture( _gl.TEXTURE0 + slot );
  14974. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14975. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14976. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14977. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14978. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14979. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14980. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14981. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  14982. image = verifyColorSpace( texture, image );
  14983. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14984. const glType = utils.convert( texture.type );
  14985. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  14986. setTextureParameters( textureType, texture );
  14987. let mipmap;
  14988. const mipmaps = texture.mipmaps;
  14989. const useTexStorage = ( texture.isVideoTexture !== true );
  14990. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14991. const dataReady = source.dataReady;
  14992. const levels = getMipLevels( texture, image );
  14993. if ( texture.isDepthTexture ) {
  14994. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  14995. //
  14996. if ( allocateMemory ) {
  14997. if ( useTexStorage ) {
  14998. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14999. } else {
  15000. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  15001. }
  15002. }
  15003. } else if ( texture.isDataTexture ) {
  15004. // use manually created mipmaps if available
  15005. // if there are no manual mipmaps
  15006. // set 0 level mipmap and then use GL to generate other mipmap levels
  15007. if ( mipmaps.length > 0 ) {
  15008. if ( useTexStorage && allocateMemory ) {
  15009. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  15010. }
  15011. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15012. mipmap = mipmaps[ i ];
  15013. if ( useTexStorage ) {
  15014. if ( dataReady ) {
  15015. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15016. }
  15017. } else {
  15018. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15019. }
  15020. }
  15021. texture.generateMipmaps = false;
  15022. } else {
  15023. if ( useTexStorage ) {
  15024. if ( allocateMemory ) {
  15025. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  15026. }
  15027. if ( dataReady ) {
  15028. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  15029. }
  15030. } else {
  15031. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15032. }
  15033. }
  15034. } else if ( texture.isCompressedTexture ) {
  15035. if ( texture.isCompressedArrayTexture ) {
  15036. if ( useTexStorage && allocateMemory ) {
  15037. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  15038. }
  15039. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15040. mipmap = mipmaps[ i ];
  15041. if ( texture.format !== RGBAFormat ) {
  15042. if ( glFormat !== null ) {
  15043. if ( useTexStorage ) {
  15044. if ( dataReady ) {
  15045. if ( texture.layerUpdates.size > 0 ) {
  15046. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  15047. for ( const layerIndex of texture.layerUpdates ) {
  15048. const layerData = mipmap.data.subarray(
  15049. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  15050. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  15051. );
  15052. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData, 0, 0 );
  15053. }
  15054. texture.clearLayerUpdates();
  15055. } else {
  15056. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  15057. }
  15058. }
  15059. } else {
  15060. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  15061. }
  15062. } else {
  15063. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  15064. }
  15065. } else {
  15066. if ( useTexStorage ) {
  15067. if ( dataReady ) {
  15068. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  15069. }
  15070. } else {
  15071. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  15072. }
  15073. }
  15074. }
  15075. } else {
  15076. if ( useTexStorage && allocateMemory ) {
  15077. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  15078. }
  15079. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15080. mipmap = mipmaps[ i ];
  15081. if ( texture.format !== RGBAFormat ) {
  15082. if ( glFormat !== null ) {
  15083. if ( useTexStorage ) {
  15084. if ( dataReady ) {
  15085. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  15086. }
  15087. } else {
  15088. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15089. }
  15090. } else {
  15091. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  15092. }
  15093. } else {
  15094. if ( useTexStorage ) {
  15095. if ( dataReady ) {
  15096. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15097. }
  15098. } else {
  15099. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15100. }
  15101. }
  15102. }
  15103. }
  15104. } else if ( texture.isDataArrayTexture ) {
  15105. if ( useTexStorage ) {
  15106. if ( allocateMemory ) {
  15107. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  15108. }
  15109. if ( dataReady ) {
  15110. if ( texture.layerUpdates.size > 0 ) {
  15111. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  15112. for ( const layerIndex of texture.layerUpdates ) {
  15113. const layerData = image.data.subarray(
  15114. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  15115. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  15116. );
  15117. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  15118. }
  15119. texture.clearLayerUpdates();
  15120. } else {
  15121. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  15122. }
  15123. }
  15124. } else {
  15125. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  15126. }
  15127. } else if ( texture.isData3DTexture ) {
  15128. if ( useTexStorage ) {
  15129. if ( allocateMemory ) {
  15130. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  15131. }
  15132. if ( dataReady ) {
  15133. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  15134. }
  15135. } else {
  15136. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  15137. }
  15138. } else if ( texture.isFramebufferTexture ) {
  15139. if ( allocateMemory ) {
  15140. if ( useTexStorage ) {
  15141. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  15142. } else {
  15143. let width = image.width, height = image.height;
  15144. for ( let i = 0; i < levels; i ++ ) {
  15145. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  15146. width >>= 1;
  15147. height >>= 1;
  15148. }
  15149. }
  15150. }
  15151. } else {
  15152. // regular Texture (image, video, canvas)
  15153. // use manually created mipmaps if available
  15154. // if there are no manual mipmaps
  15155. // set 0 level mipmap and then use GL to generate other mipmap levels
  15156. if ( mipmaps.length > 0 ) {
  15157. if ( useTexStorage && allocateMemory ) {
  15158. const dimensions = getDimensions( mipmaps[ 0 ] );
  15159. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  15160. }
  15161. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15162. mipmap = mipmaps[ i ];
  15163. if ( useTexStorage ) {
  15164. if ( dataReady ) {
  15165. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  15166. }
  15167. } else {
  15168. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  15169. }
  15170. }
  15171. texture.generateMipmaps = false;
  15172. } else {
  15173. if ( useTexStorage ) {
  15174. if ( allocateMemory ) {
  15175. const dimensions = getDimensions( image );
  15176. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  15177. }
  15178. if ( dataReady ) {
  15179. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  15180. }
  15181. } else {
  15182. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  15183. }
  15184. }
  15185. }
  15186. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15187. generateMipmap( textureType );
  15188. }
  15189. sourceProperties.__version = source.version;
  15190. if ( texture.onUpdate ) texture.onUpdate( texture );
  15191. }
  15192. textureProperties.__version = texture.version;
  15193. }
  15194. function uploadCubeTexture( textureProperties, texture, slot ) {
  15195. if ( texture.image.length !== 6 ) return;
  15196. const forceUpload = initTexture( textureProperties, texture );
  15197. const source = texture.source;
  15198. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  15199. const sourceProperties = properties.get( source );
  15200. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  15201. state.activeTexture( _gl.TEXTURE0 + slot );
  15202. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  15203. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  15204. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  15205. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15206. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15207. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15208. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  15209. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  15210. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15211. const cubeImage = [];
  15212. for ( let i = 0; i < 6; i ++ ) {
  15213. if ( ! isCompressed && ! isDataTexture ) {
  15214. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  15215. } else {
  15216. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15217. }
  15218. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  15219. }
  15220. const image = cubeImage[ 0 ],
  15221. glFormat = utils.convert( texture.format, texture.colorSpace ),
  15222. glType = utils.convert( texture.type ),
  15223. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15224. const useTexStorage = ( texture.isVideoTexture !== true );
  15225. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  15226. const dataReady = source.dataReady;
  15227. let levels = getMipLevels( texture, image );
  15228. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  15229. let mipmaps;
  15230. if ( isCompressed ) {
  15231. if ( useTexStorage && allocateMemory ) {
  15232. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  15233. }
  15234. for ( let i = 0; i < 6; i ++ ) {
  15235. mipmaps = cubeImage[ i ].mipmaps;
  15236. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15237. const mipmap = mipmaps[ j ];
  15238. if ( texture.format !== RGBAFormat ) {
  15239. if ( glFormat !== null ) {
  15240. if ( useTexStorage ) {
  15241. if ( dataReady ) {
  15242. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  15243. }
  15244. } else {
  15245. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15246. }
  15247. } else {
  15248. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  15249. }
  15250. } else {
  15251. if ( useTexStorage ) {
  15252. if ( dataReady ) {
  15253. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15254. }
  15255. } else {
  15256. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15257. }
  15258. }
  15259. }
  15260. }
  15261. } else {
  15262. mipmaps = texture.mipmaps;
  15263. if ( useTexStorage && allocateMemory ) {
  15264. // TODO: Uniformly handle mipmap definitions
  15265. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  15266. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  15267. if ( mipmaps.length > 0 ) levels ++;
  15268. const dimensions = getDimensions( cubeImage[ 0 ] );
  15269. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  15270. }
  15271. for ( let i = 0; i < 6; i ++ ) {
  15272. if ( isDataTexture ) {
  15273. if ( useTexStorage ) {
  15274. if ( dataReady ) {
  15275. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  15276. }
  15277. } else {
  15278. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15279. }
  15280. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15281. const mipmap = mipmaps[ j ];
  15282. const mipmapImage = mipmap.image[ i ].image;
  15283. if ( useTexStorage ) {
  15284. if ( dataReady ) {
  15285. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  15286. }
  15287. } else {
  15288. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  15289. }
  15290. }
  15291. } else {
  15292. if ( useTexStorage ) {
  15293. if ( dataReady ) {
  15294. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  15295. }
  15296. } else {
  15297. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  15298. }
  15299. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15300. const mipmap = mipmaps[ j ];
  15301. if ( useTexStorage ) {
  15302. if ( dataReady ) {
  15303. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  15304. }
  15305. } else {
  15306. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  15307. }
  15308. }
  15309. }
  15310. }
  15311. }
  15312. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15313. // We assume images for cube map have the same size.
  15314. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15315. }
  15316. sourceProperties.__version = source.version;
  15317. if ( texture.onUpdate ) texture.onUpdate( texture );
  15318. }
  15319. textureProperties.__version = texture.version;
  15320. }
  15321. // Render targets
  15322. // Setup storage for target texture and bind it to correct framebuffer
  15323. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  15324. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15325. const glType = utils.convert( texture.type );
  15326. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15327. const renderTargetProperties = properties.get( renderTarget );
  15328. if ( ! renderTargetProperties.__hasExternalTextures ) {
  15329. const width = Math.max( 1, renderTarget.width >> level );
  15330. const height = Math.max( 1, renderTarget.height >> level );
  15331. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  15332. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  15333. } else {
  15334. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  15335. }
  15336. }
  15337. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15338. if ( useMultisampledRTT( renderTarget ) ) {
  15339. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  15340. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  15341. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, level );
  15342. }
  15343. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15344. }
  15345. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15346. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  15347. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15348. if ( renderTarget.depthBuffer ) {
  15349. // retrieve the depth attachment types
  15350. const depthTexture = renderTarget.depthTexture;
  15351. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  15352. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  15353. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15354. // set up the attachment
  15355. const samples = getRenderTargetSamples( renderTarget );
  15356. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  15357. if ( isUseMultisampledRTT ) {
  15358. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15359. } else if ( isMultisample ) {
  15360. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15361. } else {
  15362. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15363. }
  15364. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  15365. } else {
  15366. const textures = renderTarget.textures;
  15367. for ( let i = 0; i < textures.length; i ++ ) {
  15368. const texture = textures[ i ];
  15369. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15370. const glType = utils.convert( texture.type );
  15371. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15372. const samples = getRenderTargetSamples( renderTarget );
  15373. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15374. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15375. } else if ( useMultisampledRTT( renderTarget ) ) {
  15376. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15377. } else {
  15378. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15379. }
  15380. }
  15381. }
  15382. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15383. }
  15384. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15385. function setupDepthTexture( framebuffer, renderTarget ) {
  15386. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  15387. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15388. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15389. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15390. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15391. }
  15392. // upload an empty depth texture with framebuffer size
  15393. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  15394. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15395. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15396. renderTarget.depthTexture.image.width = renderTarget.width;
  15397. renderTarget.depthTexture.image.height = renderTarget.height;
  15398. renderTarget.depthTexture.needsUpdate = true;
  15399. }
  15400. setTexture2D( renderTarget.depthTexture, 0 );
  15401. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15402. const samples = getRenderTargetSamples( renderTarget );
  15403. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15404. if ( useMultisampledRTT( renderTarget ) ) {
  15405. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15406. } else {
  15407. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15408. }
  15409. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15410. if ( useMultisampledRTT( renderTarget ) ) {
  15411. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15412. } else {
  15413. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15414. }
  15415. } else {
  15416. throw new Error( 'Unknown depthTexture format' );
  15417. }
  15418. }
  15419. // Setup GL resources for a non-texture depth buffer
  15420. function setupDepthRenderbuffer( renderTarget ) {
  15421. const renderTargetProperties = properties.get( renderTarget );
  15422. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15423. // if the bound depth texture has changed
  15424. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  15425. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  15426. const depthTexture = renderTarget.depthTexture;
  15427. if ( renderTargetProperties.__depthDisposeCallback ) {
  15428. renderTargetProperties.__depthDisposeCallback();
  15429. }
  15430. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  15431. if ( depthTexture ) {
  15432. const disposeEvent = () => {
  15433. delete renderTargetProperties.__boundDepthTexture;
  15434. delete renderTargetProperties.__depthDisposeCallback;
  15435. depthTexture.removeEventListener( 'dispose', disposeEvent );
  15436. };
  15437. depthTexture.addEventListener( 'dispose', disposeEvent );
  15438. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  15439. }
  15440. renderTargetProperties.__boundDepthTexture = depthTexture;
  15441. }
  15442. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  15443. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15444. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15445. } else {
  15446. if ( isCube ) {
  15447. renderTargetProperties.__webglDepthbuffer = [];
  15448. for ( let i = 0; i < 6; i ++ ) {
  15449. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15450. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  15451. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15452. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  15453. } else {
  15454. // attach buffer if it's been created already
  15455. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15456. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  15457. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15458. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  15459. }
  15460. }
  15461. } else {
  15462. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15463. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  15464. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15465. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  15466. } else {
  15467. // attach buffer if it's been created already
  15468. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15469. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  15470. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15471. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  15472. }
  15473. }
  15474. }
  15475. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15476. }
  15477. // rebind framebuffer with external textures
  15478. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  15479. const renderTargetProperties = properties.get( renderTarget );
  15480. if ( colorTexture !== undefined ) {
  15481. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  15482. }
  15483. if ( depthTexture !== undefined ) {
  15484. setupDepthRenderbuffer( renderTarget );
  15485. }
  15486. }
  15487. // Set up GL resources for the render target
  15488. function setupRenderTarget( renderTarget ) {
  15489. const texture = renderTarget.texture;
  15490. const renderTargetProperties = properties.get( renderTarget );
  15491. const textureProperties = properties.get( texture );
  15492. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15493. const textures = renderTarget.textures;
  15494. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15495. const isMultipleRenderTargets = ( textures.length > 1 );
  15496. if ( ! isMultipleRenderTargets ) {
  15497. if ( textureProperties.__webglTexture === undefined ) {
  15498. textureProperties.__webglTexture = _gl.createTexture();
  15499. }
  15500. textureProperties.__version = texture.version;
  15501. info.memory.textures ++;
  15502. }
  15503. // Setup framebuffer
  15504. if ( isCube ) {
  15505. renderTargetProperties.__webglFramebuffer = [];
  15506. for ( let i = 0; i < 6; i ++ ) {
  15507. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15508. renderTargetProperties.__webglFramebuffer[ i ] = [];
  15509. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15510. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  15511. }
  15512. } else {
  15513. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15514. }
  15515. }
  15516. } else {
  15517. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15518. renderTargetProperties.__webglFramebuffer = [];
  15519. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15520. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  15521. }
  15522. } else {
  15523. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15524. }
  15525. if ( isMultipleRenderTargets ) {
  15526. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15527. const attachmentProperties = properties.get( textures[ i ] );
  15528. if ( attachmentProperties.__webglTexture === undefined ) {
  15529. attachmentProperties.__webglTexture = _gl.createTexture();
  15530. info.memory.textures ++;
  15531. }
  15532. }
  15533. }
  15534. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15535. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15536. renderTargetProperties.__webglColorRenderbuffer = [];
  15537. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15538. for ( let i = 0; i < textures.length; i ++ ) {
  15539. const texture = textures[ i ];
  15540. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15541. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15542. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15543. const glType = utils.convert( texture.type );
  15544. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15545. const samples = getRenderTargetSamples( renderTarget );
  15546. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15547. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15548. }
  15549. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15550. if ( renderTarget.depthBuffer ) {
  15551. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15552. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15553. }
  15554. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15555. }
  15556. }
  15557. // Setup color buffer
  15558. if ( isCube ) {
  15559. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15560. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  15561. for ( let i = 0; i < 6; i ++ ) {
  15562. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15563. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15564. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  15565. }
  15566. } else {
  15567. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  15568. }
  15569. }
  15570. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15571. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15572. }
  15573. state.unbindTexture();
  15574. } else if ( isMultipleRenderTargets ) {
  15575. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15576. const attachment = textures[ i ];
  15577. const attachmentProperties = properties.get( attachment );
  15578. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15579. setTextureParameters( _gl.TEXTURE_2D, attachment );
  15580. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  15581. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  15582. generateMipmap( _gl.TEXTURE_2D );
  15583. }
  15584. }
  15585. state.unbindTexture();
  15586. } else {
  15587. let glTextureType = _gl.TEXTURE_2D;
  15588. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15589. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15590. }
  15591. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15592. setTextureParameters( glTextureType, texture );
  15593. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15594. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15595. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  15596. }
  15597. } else {
  15598. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  15599. }
  15600. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15601. generateMipmap( glTextureType );
  15602. }
  15603. state.unbindTexture();
  15604. }
  15605. // Setup depth and stencil buffers
  15606. if ( renderTarget.depthBuffer ) {
  15607. setupDepthRenderbuffer( renderTarget );
  15608. }
  15609. }
  15610. function updateRenderTargetMipmap( renderTarget ) {
  15611. const textures = renderTarget.textures;
  15612. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15613. const texture = textures[ i ];
  15614. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15615. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15616. const webglTexture = properties.get( texture ).__webglTexture;
  15617. state.bindTexture( target, webglTexture );
  15618. generateMipmap( target );
  15619. state.unbindTexture();
  15620. }
  15621. }
  15622. }
  15623. const invalidationArrayRead = [];
  15624. const invalidationArrayDraw = [];
  15625. function updateMultisampleRenderTarget( renderTarget ) {
  15626. if ( renderTarget.samples > 0 ) {
  15627. if ( useMultisampledRTT( renderTarget ) === false ) {
  15628. const textures = renderTarget.textures;
  15629. const width = renderTarget.width;
  15630. const height = renderTarget.height;
  15631. let mask = _gl.COLOR_BUFFER_BIT;
  15632. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15633. const renderTargetProperties = properties.get( renderTarget );
  15634. const isMultipleRenderTargets = ( textures.length > 1 );
  15635. // If MRT we need to remove FBO attachments
  15636. if ( isMultipleRenderTargets ) {
  15637. for ( let i = 0; i < textures.length; i ++ ) {
  15638. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15639. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15640. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15641. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15642. }
  15643. }
  15644. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15645. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15646. for ( let i = 0; i < textures.length; i ++ ) {
  15647. if ( renderTarget.resolveDepthBuffer ) {
  15648. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15649. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  15650. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  15651. }
  15652. if ( isMultipleRenderTargets ) {
  15653. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15654. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15655. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15656. }
  15657. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15658. if ( supportsInvalidateFramebuffer === true ) {
  15659. invalidationArrayRead.length = 0;
  15660. invalidationArrayDraw.length = 0;
  15661. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  15662. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  15663. invalidationArrayRead.push( depthStyle );
  15664. invalidationArrayDraw.push( depthStyle );
  15665. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  15666. }
  15667. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  15668. }
  15669. }
  15670. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15671. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15672. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15673. if ( isMultipleRenderTargets ) {
  15674. for ( let i = 0; i < textures.length; i ++ ) {
  15675. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15676. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15677. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15678. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15679. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15680. }
  15681. }
  15682. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15683. } else {
  15684. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  15685. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15686. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15687. }
  15688. }
  15689. }
  15690. }
  15691. function getRenderTargetSamples( renderTarget ) {
  15692. return Math.min( capabilities.maxSamples, renderTarget.samples );
  15693. }
  15694. function useMultisampledRTT( renderTarget ) {
  15695. const renderTargetProperties = properties.get( renderTarget );
  15696. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15697. }
  15698. function updateVideoTexture( texture ) {
  15699. const frame = info.render.frame;
  15700. // Check the last frame we updated the VideoTexture
  15701. if ( _videoTextures.get( texture ) !== frame ) {
  15702. _videoTextures.set( texture, frame );
  15703. texture.update();
  15704. }
  15705. }
  15706. function verifyColorSpace( texture, image ) {
  15707. const colorSpace = texture.colorSpace;
  15708. const format = texture.format;
  15709. const type = texture.type;
  15710. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  15711. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15712. // sRGB
  15713. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  15714. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15715. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15716. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15717. }
  15718. } else {
  15719. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15720. }
  15721. }
  15722. return image;
  15723. }
  15724. function getDimensions( image ) {
  15725. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  15726. // if intrinsic data are not available, fallback to width/height
  15727. _imageDimensions.width = image.naturalWidth || image.width;
  15728. _imageDimensions.height = image.naturalHeight || image.height;
  15729. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  15730. _imageDimensions.width = image.displayWidth;
  15731. _imageDimensions.height = image.displayHeight;
  15732. } else {
  15733. _imageDimensions.width = image.width;
  15734. _imageDimensions.height = image.height;
  15735. }
  15736. return _imageDimensions;
  15737. }
  15738. //
  15739. this.allocateTextureUnit = allocateTextureUnit;
  15740. this.resetTextureUnits = resetTextureUnits;
  15741. this.setTexture2D = setTexture2D;
  15742. this.setTexture2DArray = setTexture2DArray;
  15743. this.setTexture3D = setTexture3D;
  15744. this.setTextureCube = setTextureCube;
  15745. this.rebindTextures = rebindTextures;
  15746. this.setupRenderTarget = setupRenderTarget;
  15747. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15748. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15749. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15750. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15751. this.useMultisampledRTT = useMultisampledRTT;
  15752. }
  15753. function WebGLUtils( gl, extensions ) {
  15754. function convert( p, colorSpace = NoColorSpace ) {
  15755. let extension;
  15756. const transfer = ColorManagement.getTransfer( colorSpace );
  15757. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15758. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15759. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15760. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  15761. if ( p === ByteType ) return gl.BYTE;
  15762. if ( p === ShortType ) return gl.SHORT;
  15763. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15764. if ( p === IntType ) return gl.INT;
  15765. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15766. if ( p === FloatType ) return gl.FLOAT;
  15767. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  15768. if ( p === AlphaFormat ) return gl.ALPHA;
  15769. if ( p === RGBFormat ) return gl.RGB;
  15770. if ( p === RGBAFormat ) return gl.RGBA;
  15771. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15772. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15773. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15774. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15775. // WebGL2 formats.
  15776. if ( p === RedFormat ) return gl.RED;
  15777. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15778. if ( p === RGFormat ) return gl.RG;
  15779. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15780. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15781. // S3TC
  15782. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15783. if ( transfer === SRGBTransfer ) {
  15784. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15785. if ( extension !== null ) {
  15786. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15787. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15788. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15789. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15790. } else {
  15791. return null;
  15792. }
  15793. } else {
  15794. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15795. if ( extension !== null ) {
  15796. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15797. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15798. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15799. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15800. } else {
  15801. return null;
  15802. }
  15803. }
  15804. }
  15805. // PVRTC
  15806. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15807. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15808. if ( extension !== null ) {
  15809. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15810. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15811. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15812. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15813. } else {
  15814. return null;
  15815. }
  15816. }
  15817. // ETC
  15818. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15819. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15820. if ( extension !== null ) {
  15821. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15822. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15823. } else {
  15824. return null;
  15825. }
  15826. }
  15827. // ASTC
  15828. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15829. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15830. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15831. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15832. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15833. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15834. if ( extension !== null ) {
  15835. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15836. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15837. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15838. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15839. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15840. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15841. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15842. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15843. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15844. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15845. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15846. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15847. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15848. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15849. } else {
  15850. return null;
  15851. }
  15852. }
  15853. // BPTC
  15854. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  15855. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15856. if ( extension !== null ) {
  15857. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15858. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  15859. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  15860. } else {
  15861. return null;
  15862. }
  15863. }
  15864. // RGTC
  15865. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15866. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15867. if ( extension !== null ) {
  15868. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15869. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15870. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15871. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15872. } else {
  15873. return null;
  15874. }
  15875. }
  15876. //
  15877. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  15878. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15879. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15880. }
  15881. return { convert: convert };
  15882. }
  15883. class ArrayCamera extends PerspectiveCamera {
  15884. constructor( array = [] ) {
  15885. super();
  15886. this.isArrayCamera = true;
  15887. this.cameras = array;
  15888. }
  15889. }
  15890. class Group extends Object3D {
  15891. constructor() {
  15892. super();
  15893. this.isGroup = true;
  15894. this.type = 'Group';
  15895. }
  15896. }
  15897. const _moveEvent = { type: 'move' };
  15898. class WebXRController {
  15899. constructor() {
  15900. this._targetRay = null;
  15901. this._grip = null;
  15902. this._hand = null;
  15903. }
  15904. getHandSpace() {
  15905. if ( this._hand === null ) {
  15906. this._hand = new Group();
  15907. this._hand.matrixAutoUpdate = false;
  15908. this._hand.visible = false;
  15909. this._hand.joints = {};
  15910. this._hand.inputState = { pinching: false };
  15911. }
  15912. return this._hand;
  15913. }
  15914. getTargetRaySpace() {
  15915. if ( this._targetRay === null ) {
  15916. this._targetRay = new Group();
  15917. this._targetRay.matrixAutoUpdate = false;
  15918. this._targetRay.visible = false;
  15919. this._targetRay.hasLinearVelocity = false;
  15920. this._targetRay.linearVelocity = new Vector3();
  15921. this._targetRay.hasAngularVelocity = false;
  15922. this._targetRay.angularVelocity = new Vector3();
  15923. }
  15924. return this._targetRay;
  15925. }
  15926. getGripSpace() {
  15927. if ( this._grip === null ) {
  15928. this._grip = new Group();
  15929. this._grip.matrixAutoUpdate = false;
  15930. this._grip.visible = false;
  15931. this._grip.hasLinearVelocity = false;
  15932. this._grip.linearVelocity = new Vector3();
  15933. this._grip.hasAngularVelocity = false;
  15934. this._grip.angularVelocity = new Vector3();
  15935. }
  15936. return this._grip;
  15937. }
  15938. dispatchEvent( event ) {
  15939. if ( this._targetRay !== null ) {
  15940. this._targetRay.dispatchEvent( event );
  15941. }
  15942. if ( this._grip !== null ) {
  15943. this._grip.dispatchEvent( event );
  15944. }
  15945. if ( this._hand !== null ) {
  15946. this._hand.dispatchEvent( event );
  15947. }
  15948. return this;
  15949. }
  15950. connect( inputSource ) {
  15951. if ( inputSource && inputSource.hand ) {
  15952. const hand = this._hand;
  15953. if ( hand ) {
  15954. for ( const inputjoint of inputSource.hand.values() ) {
  15955. // Initialize hand with joints when connected
  15956. this._getHandJoint( hand, inputjoint );
  15957. }
  15958. }
  15959. }
  15960. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15961. return this;
  15962. }
  15963. disconnect( inputSource ) {
  15964. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15965. if ( this._targetRay !== null ) {
  15966. this._targetRay.visible = false;
  15967. }
  15968. if ( this._grip !== null ) {
  15969. this._grip.visible = false;
  15970. }
  15971. if ( this._hand !== null ) {
  15972. this._hand.visible = false;
  15973. }
  15974. return this;
  15975. }
  15976. update( inputSource, frame, referenceSpace ) {
  15977. let inputPose = null;
  15978. let gripPose = null;
  15979. let handPose = null;
  15980. const targetRay = this._targetRay;
  15981. const grip = this._grip;
  15982. const hand = this._hand;
  15983. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15984. if ( hand && inputSource.hand ) {
  15985. handPose = true;
  15986. for ( const inputjoint of inputSource.hand.values() ) {
  15987. // Update the joints groups with the XRJoint poses
  15988. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15989. // The transform of this joint will be updated with the joint pose on each frame
  15990. const joint = this._getHandJoint( hand, inputjoint );
  15991. if ( jointPose !== null ) {
  15992. joint.matrix.fromArray( jointPose.transform.matrix );
  15993. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15994. joint.matrixWorldNeedsUpdate = true;
  15995. joint.jointRadius = jointPose.radius;
  15996. }
  15997. joint.visible = jointPose !== null;
  15998. }
  15999. // Custom events
  16000. // Check pinchz
  16001. const indexTip = hand.joints[ 'index-finger-tip' ];
  16002. const thumbTip = hand.joints[ 'thumb-tip' ];
  16003. const distance = indexTip.position.distanceTo( thumbTip.position );
  16004. const distanceToPinch = 0.02;
  16005. const threshold = 0.005;
  16006. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16007. hand.inputState.pinching = false;
  16008. this.dispatchEvent( {
  16009. type: 'pinchend',
  16010. handedness: inputSource.handedness,
  16011. target: this
  16012. } );
  16013. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16014. hand.inputState.pinching = true;
  16015. this.dispatchEvent( {
  16016. type: 'pinchstart',
  16017. handedness: inputSource.handedness,
  16018. target: this
  16019. } );
  16020. }
  16021. } else {
  16022. if ( grip !== null && inputSource.gripSpace ) {
  16023. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16024. if ( gripPose !== null ) {
  16025. grip.matrix.fromArray( gripPose.transform.matrix );
  16026. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16027. grip.matrixWorldNeedsUpdate = true;
  16028. if ( gripPose.linearVelocity ) {
  16029. grip.hasLinearVelocity = true;
  16030. grip.linearVelocity.copy( gripPose.linearVelocity );
  16031. } else {
  16032. grip.hasLinearVelocity = false;
  16033. }
  16034. if ( gripPose.angularVelocity ) {
  16035. grip.hasAngularVelocity = true;
  16036. grip.angularVelocity.copy( gripPose.angularVelocity );
  16037. } else {
  16038. grip.hasAngularVelocity = false;
  16039. }
  16040. }
  16041. }
  16042. }
  16043. if ( targetRay !== null ) {
  16044. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16045. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16046. if ( inputPose === null && gripPose !== null ) {
  16047. inputPose = gripPose;
  16048. }
  16049. if ( inputPose !== null ) {
  16050. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16051. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16052. targetRay.matrixWorldNeedsUpdate = true;
  16053. if ( inputPose.linearVelocity ) {
  16054. targetRay.hasLinearVelocity = true;
  16055. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16056. } else {
  16057. targetRay.hasLinearVelocity = false;
  16058. }
  16059. if ( inputPose.angularVelocity ) {
  16060. targetRay.hasAngularVelocity = true;
  16061. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16062. } else {
  16063. targetRay.hasAngularVelocity = false;
  16064. }
  16065. this.dispatchEvent( _moveEvent );
  16066. }
  16067. }
  16068. }
  16069. if ( targetRay !== null ) {
  16070. targetRay.visible = ( inputPose !== null );
  16071. }
  16072. if ( grip !== null ) {
  16073. grip.visible = ( gripPose !== null );
  16074. }
  16075. if ( hand !== null ) {
  16076. hand.visible = ( handPose !== null );
  16077. }
  16078. return this;
  16079. }
  16080. // private method
  16081. _getHandJoint( hand, inputjoint ) {
  16082. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16083. const joint = new Group();
  16084. joint.matrixAutoUpdate = false;
  16085. joint.visible = false;
  16086. hand.joints[ inputjoint.jointName ] = joint;
  16087. hand.add( joint );
  16088. }
  16089. return hand.joints[ inputjoint.jointName ];
  16090. }
  16091. }
  16092. const _occlusion_vertex = `
  16093. void main() {
  16094. gl_Position = vec4( position, 1.0 );
  16095. }`;
  16096. const _occlusion_fragment = `
  16097. uniform sampler2DArray depthColor;
  16098. uniform float depthWidth;
  16099. uniform float depthHeight;
  16100. void main() {
  16101. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  16102. if ( coord.x >= 1.0 ) {
  16103. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  16104. } else {
  16105. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  16106. }
  16107. }`;
  16108. class WebXRDepthSensing {
  16109. constructor() {
  16110. this.texture = null;
  16111. this.mesh = null;
  16112. this.depthNear = 0;
  16113. this.depthFar = 0;
  16114. }
  16115. init( renderer, depthData, renderState ) {
  16116. if ( this.texture === null ) {
  16117. const texture = new Texture();
  16118. const texProps = renderer.properties.get( texture );
  16119. texProps.__webglTexture = depthData.texture;
  16120. if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) {
  16121. this.depthNear = depthData.depthNear;
  16122. this.depthFar = depthData.depthFar;
  16123. }
  16124. this.texture = texture;
  16125. }
  16126. }
  16127. getMesh( cameraXR ) {
  16128. if ( this.texture !== null ) {
  16129. if ( this.mesh === null ) {
  16130. const viewport = cameraXR.cameras[ 0 ].viewport;
  16131. const material = new ShaderMaterial( {
  16132. vertexShader: _occlusion_vertex,
  16133. fragmentShader: _occlusion_fragment,
  16134. uniforms: {
  16135. depthColor: { value: this.texture },
  16136. depthWidth: { value: viewport.z },
  16137. depthHeight: { value: viewport.w }
  16138. }
  16139. } );
  16140. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  16141. }
  16142. }
  16143. return this.mesh;
  16144. }
  16145. reset() {
  16146. this.texture = null;
  16147. this.mesh = null;
  16148. }
  16149. getDepthTexture() {
  16150. return this.texture;
  16151. }
  16152. }
  16153. class WebXRManager extends EventDispatcher {
  16154. constructor( renderer, gl ) {
  16155. super();
  16156. const scope = this;
  16157. let session = null;
  16158. let framebufferScaleFactor = 1.0;
  16159. let referenceSpace = null;
  16160. let referenceSpaceType = 'local-floor';
  16161. // Set default foveation to maximum.
  16162. let foveation = 1.0;
  16163. let customReferenceSpace = null;
  16164. let pose = null;
  16165. let glBinding = null;
  16166. let glProjLayer = null;
  16167. let glBaseLayer = null;
  16168. let xrFrame = null;
  16169. const depthSensing = new WebXRDepthSensing();
  16170. const attributes = gl.getContextAttributes();
  16171. let initialRenderTarget = null;
  16172. let newRenderTarget = null;
  16173. const controllers = [];
  16174. const controllerInputSources = [];
  16175. const currentSize = new Vector2();
  16176. let currentPixelRatio = null;
  16177. //
  16178. const cameraL = new PerspectiveCamera();
  16179. cameraL.layers.enable( 1 );
  16180. cameraL.viewport = new Vector4();
  16181. const cameraR = new PerspectiveCamera();
  16182. cameraR.layers.enable( 2 );
  16183. cameraR.viewport = new Vector4();
  16184. const cameras = [ cameraL, cameraR ];
  16185. const cameraXR = new ArrayCamera();
  16186. cameraXR.layers.enable( 1 );
  16187. cameraXR.layers.enable( 2 );
  16188. let _currentDepthNear = null;
  16189. let _currentDepthFar = null;
  16190. //
  16191. this.cameraAutoUpdate = true;
  16192. this.enabled = false;
  16193. this.isPresenting = false;
  16194. this.getController = function ( index ) {
  16195. let controller = controllers[ index ];
  16196. if ( controller === undefined ) {
  16197. controller = new WebXRController();
  16198. controllers[ index ] = controller;
  16199. }
  16200. return controller.getTargetRaySpace();
  16201. };
  16202. this.getControllerGrip = function ( index ) {
  16203. let controller = controllers[ index ];
  16204. if ( controller === undefined ) {
  16205. controller = new WebXRController();
  16206. controllers[ index ] = controller;
  16207. }
  16208. return controller.getGripSpace();
  16209. };
  16210. this.getHand = function ( index ) {
  16211. let controller = controllers[ index ];
  16212. if ( controller === undefined ) {
  16213. controller = new WebXRController();
  16214. controllers[ index ] = controller;
  16215. }
  16216. return controller.getHandSpace();
  16217. };
  16218. //
  16219. function onSessionEvent( event ) {
  16220. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  16221. if ( controllerIndex === - 1 ) {
  16222. return;
  16223. }
  16224. const controller = controllers[ controllerIndex ];
  16225. if ( controller !== undefined ) {
  16226. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  16227. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  16228. }
  16229. }
  16230. function onSessionEnd() {
  16231. session.removeEventListener( 'select', onSessionEvent );
  16232. session.removeEventListener( 'selectstart', onSessionEvent );
  16233. session.removeEventListener( 'selectend', onSessionEvent );
  16234. session.removeEventListener( 'squeeze', onSessionEvent );
  16235. session.removeEventListener( 'squeezestart', onSessionEvent );
  16236. session.removeEventListener( 'squeezeend', onSessionEvent );
  16237. session.removeEventListener( 'end', onSessionEnd );
  16238. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  16239. for ( let i = 0; i < controllers.length; i ++ ) {
  16240. const inputSource = controllerInputSources[ i ];
  16241. if ( inputSource === null ) continue;
  16242. controllerInputSources[ i ] = null;
  16243. controllers[ i ].disconnect( inputSource );
  16244. }
  16245. _currentDepthNear = null;
  16246. _currentDepthFar = null;
  16247. depthSensing.reset();
  16248. // restore framebuffer/rendering state
  16249. renderer.setRenderTarget( initialRenderTarget );
  16250. glBaseLayer = null;
  16251. glProjLayer = null;
  16252. glBinding = null;
  16253. session = null;
  16254. newRenderTarget = null;
  16255. //
  16256. animation.stop();
  16257. scope.isPresenting = false;
  16258. renderer.setPixelRatio( currentPixelRatio );
  16259. renderer.setSize( currentSize.width, currentSize.height, false );
  16260. scope.dispatchEvent( { type: 'sessionend' } );
  16261. }
  16262. this.setFramebufferScaleFactor = function ( value ) {
  16263. framebufferScaleFactor = value;
  16264. if ( scope.isPresenting === true ) {
  16265. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  16266. }
  16267. };
  16268. this.setReferenceSpaceType = function ( value ) {
  16269. referenceSpaceType = value;
  16270. if ( scope.isPresenting === true ) {
  16271. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  16272. }
  16273. };
  16274. this.getReferenceSpace = function () {
  16275. return customReferenceSpace || referenceSpace;
  16276. };
  16277. this.setReferenceSpace = function ( space ) {
  16278. customReferenceSpace = space;
  16279. };
  16280. this.getBaseLayer = function () {
  16281. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  16282. };
  16283. this.getBinding = function () {
  16284. return glBinding;
  16285. };
  16286. this.getFrame = function () {
  16287. return xrFrame;
  16288. };
  16289. this.getSession = function () {
  16290. return session;
  16291. };
  16292. this.setSession = async function ( value ) {
  16293. session = value;
  16294. if ( session !== null ) {
  16295. initialRenderTarget = renderer.getRenderTarget();
  16296. session.addEventListener( 'select', onSessionEvent );
  16297. session.addEventListener( 'selectstart', onSessionEvent );
  16298. session.addEventListener( 'selectend', onSessionEvent );
  16299. session.addEventListener( 'squeeze', onSessionEvent );
  16300. session.addEventListener( 'squeezestart', onSessionEvent );
  16301. session.addEventListener( 'squeezeend', onSessionEvent );
  16302. session.addEventListener( 'end', onSessionEnd );
  16303. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  16304. if ( attributes.xrCompatible !== true ) {
  16305. await gl.makeXRCompatible();
  16306. }
  16307. currentPixelRatio = renderer.getPixelRatio();
  16308. renderer.getSize( currentSize );
  16309. if ( session.renderState.layers === undefined ) {
  16310. const layerInit = {
  16311. antialias: attributes.antialias,
  16312. alpha: true,
  16313. depth: attributes.depth,
  16314. stencil: attributes.stencil,
  16315. framebufferScaleFactor: framebufferScaleFactor
  16316. };
  16317. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  16318. session.updateRenderState( { baseLayer: glBaseLayer } );
  16319. renderer.setPixelRatio( 1 );
  16320. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  16321. newRenderTarget = new WebGLRenderTarget(
  16322. glBaseLayer.framebufferWidth,
  16323. glBaseLayer.framebufferHeight,
  16324. {
  16325. format: RGBAFormat,
  16326. type: UnsignedByteType,
  16327. colorSpace: renderer.outputColorSpace,
  16328. stencilBuffer: attributes.stencil
  16329. }
  16330. );
  16331. } else {
  16332. let depthFormat = null;
  16333. let depthType = null;
  16334. let glDepthFormat = null;
  16335. if ( attributes.depth ) {
  16336. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  16337. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  16338. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  16339. }
  16340. const projectionlayerInit = {
  16341. colorFormat: gl.RGBA8,
  16342. depthFormat: glDepthFormat,
  16343. scaleFactor: framebufferScaleFactor
  16344. };
  16345. glBinding = new XRWebGLBinding( session, gl );
  16346. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  16347. session.updateRenderState( { layers: [ glProjLayer ] } );
  16348. renderer.setPixelRatio( 1 );
  16349. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  16350. newRenderTarget = new WebGLRenderTarget(
  16351. glProjLayer.textureWidth,
  16352. glProjLayer.textureHeight,
  16353. {
  16354. format: RGBAFormat,
  16355. type: UnsignedByteType,
  16356. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  16357. stencilBuffer: attributes.stencil,
  16358. colorSpace: renderer.outputColorSpace,
  16359. samples: attributes.antialias ? 4 : 0,
  16360. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false )
  16361. } );
  16362. }
  16363. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  16364. this.setFoveation( foveation );
  16365. customReferenceSpace = null;
  16366. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  16367. animation.setContext( session );
  16368. animation.start();
  16369. scope.isPresenting = true;
  16370. scope.dispatchEvent( { type: 'sessionstart' } );
  16371. }
  16372. };
  16373. this.getEnvironmentBlendMode = function () {
  16374. if ( session !== null ) {
  16375. return session.environmentBlendMode;
  16376. }
  16377. };
  16378. this.getDepthTexture = function () {
  16379. return depthSensing.getDepthTexture();
  16380. };
  16381. function onInputSourcesChange( event ) {
  16382. // Notify disconnected
  16383. for ( let i = 0; i < event.removed.length; i ++ ) {
  16384. const inputSource = event.removed[ i ];
  16385. const index = controllerInputSources.indexOf( inputSource );
  16386. if ( index >= 0 ) {
  16387. controllerInputSources[ index ] = null;
  16388. controllers[ index ].disconnect( inputSource );
  16389. }
  16390. }
  16391. // Notify connected
  16392. for ( let i = 0; i < event.added.length; i ++ ) {
  16393. const inputSource = event.added[ i ];
  16394. let controllerIndex = controllerInputSources.indexOf( inputSource );
  16395. if ( controllerIndex === - 1 ) {
  16396. // Assign input source a controller that currently has no input source
  16397. for ( let i = 0; i < controllers.length; i ++ ) {
  16398. if ( i >= controllerInputSources.length ) {
  16399. controllerInputSources.push( inputSource );
  16400. controllerIndex = i;
  16401. break;
  16402. } else if ( controllerInputSources[ i ] === null ) {
  16403. controllerInputSources[ i ] = inputSource;
  16404. controllerIndex = i;
  16405. break;
  16406. }
  16407. }
  16408. // If all controllers do currently receive input we ignore new ones
  16409. if ( controllerIndex === - 1 ) break;
  16410. }
  16411. const controller = controllers[ controllerIndex ];
  16412. if ( controller ) {
  16413. controller.connect( inputSource );
  16414. }
  16415. }
  16416. }
  16417. //
  16418. const cameraLPos = new Vector3();
  16419. const cameraRPos = new Vector3();
  16420. /**
  16421. * Assumes 2 cameras that are parallel and share an X-axis, and that
  16422. * the cameras' projection and world matrices have already been set.
  16423. * And that near and far planes are identical for both cameras.
  16424. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  16425. */
  16426. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  16427. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  16428. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  16429. const ipd = cameraLPos.distanceTo( cameraRPos );
  16430. const projL = cameraL.projectionMatrix.elements;
  16431. const projR = cameraR.projectionMatrix.elements;
  16432. // VR systems will have identical far and near planes, and
  16433. // most likely identical top and bottom frustum extents.
  16434. // Use the left camera for these values.
  16435. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  16436. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  16437. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  16438. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  16439. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  16440. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  16441. const left = near * leftFov;
  16442. const right = near * rightFov;
  16443. // Calculate the new camera's position offset from the
  16444. // left camera. xOffset should be roughly half `ipd`.
  16445. const zOffset = ipd / ( - leftFov + rightFov );
  16446. const xOffset = zOffset * - leftFov;
  16447. // TODO: Better way to apply this offset?
  16448. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  16449. camera.translateX( xOffset );
  16450. camera.translateZ( zOffset );
  16451. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  16452. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16453. // Check if the projection uses an infinite far plane.
  16454. if ( projL[ 10 ] === - 1.0 ) {
  16455. // Use the projection matrix from the left eye.
  16456. // The camera offset is sufficient to include the view volumes
  16457. // of both eyes (assuming symmetric projections).
  16458. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  16459. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  16460. } else {
  16461. // Find the union of the frustum values of the cameras and scale
  16462. // the values so that the near plane's position does not change in world space,
  16463. // although must now be relative to the new union camera.
  16464. const near2 = near + zOffset;
  16465. const far2 = far + zOffset;
  16466. const left2 = left - xOffset;
  16467. const right2 = right + ( ipd - xOffset );
  16468. const top2 = topFov * far / far2 * near2;
  16469. const bottom2 = bottomFov * far / far2 * near2;
  16470. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  16471. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16472. }
  16473. }
  16474. function updateCamera( camera, parent ) {
  16475. if ( parent === null ) {
  16476. camera.matrixWorld.copy( camera.matrix );
  16477. } else {
  16478. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16479. }
  16480. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16481. }
  16482. this.updateCamera = function ( camera ) {
  16483. if ( session === null ) return;
  16484. let depthNear = camera.near;
  16485. let depthFar = camera.far;
  16486. if ( depthSensing.texture !== null ) {
  16487. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  16488. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  16489. }
  16490. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  16491. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  16492. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  16493. // Note that the new renderState won't apply until the next frame. See #18320
  16494. session.updateRenderState( {
  16495. depthNear: cameraXR.near,
  16496. depthFar: cameraXR.far
  16497. } );
  16498. _currentDepthNear = cameraXR.near;
  16499. _currentDepthFar = cameraXR.far;
  16500. }
  16501. const parent = camera.parent;
  16502. const cameras = cameraXR.cameras;
  16503. updateCamera( cameraXR, parent );
  16504. for ( let i = 0; i < cameras.length; i ++ ) {
  16505. updateCamera( cameras[ i ], parent );
  16506. }
  16507. // update projection matrix for proper view frustum culling
  16508. if ( cameras.length === 2 ) {
  16509. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  16510. } else {
  16511. // assume single camera setup (AR)
  16512. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  16513. }
  16514. // update user camera and its children
  16515. updateUserCamera( camera, cameraXR, parent );
  16516. };
  16517. function updateUserCamera( camera, cameraXR, parent ) {
  16518. if ( parent === null ) {
  16519. camera.matrix.copy( cameraXR.matrixWorld );
  16520. } else {
  16521. camera.matrix.copy( parent.matrixWorld );
  16522. camera.matrix.invert();
  16523. camera.matrix.multiply( cameraXR.matrixWorld );
  16524. }
  16525. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16526. camera.updateMatrixWorld( true );
  16527. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  16528. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  16529. if ( camera.isPerspectiveCamera ) {
  16530. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  16531. camera.zoom = 1;
  16532. }
  16533. }
  16534. this.getCamera = function () {
  16535. return cameraXR;
  16536. };
  16537. this.getFoveation = function () {
  16538. if ( glProjLayer === null && glBaseLayer === null ) {
  16539. return undefined;
  16540. }
  16541. return foveation;
  16542. };
  16543. this.setFoveation = function ( value ) {
  16544. // 0 = no foveation = full resolution
  16545. // 1 = maximum foveation = the edges render at lower resolution
  16546. foveation = value;
  16547. if ( glProjLayer !== null ) {
  16548. glProjLayer.fixedFoveation = value;
  16549. }
  16550. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16551. glBaseLayer.fixedFoveation = value;
  16552. }
  16553. };
  16554. this.hasDepthSensing = function () {
  16555. return depthSensing.texture !== null;
  16556. };
  16557. this.getDepthSensingMesh = function () {
  16558. return depthSensing.getMesh( cameraXR );
  16559. };
  16560. // Animation Loop
  16561. let onAnimationFrameCallback = null;
  16562. function onAnimationFrame( time, frame ) {
  16563. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16564. xrFrame = frame;
  16565. if ( pose !== null ) {
  16566. const views = pose.views;
  16567. if ( glBaseLayer !== null ) {
  16568. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16569. renderer.setRenderTarget( newRenderTarget );
  16570. }
  16571. let cameraXRNeedsUpdate = false;
  16572. // check if it's necessary to rebuild cameraXR's camera list
  16573. if ( views.length !== cameraXR.cameras.length ) {
  16574. cameraXR.cameras.length = 0;
  16575. cameraXRNeedsUpdate = true;
  16576. }
  16577. for ( let i = 0; i < views.length; i ++ ) {
  16578. const view = views[ i ];
  16579. let viewport = null;
  16580. if ( glBaseLayer !== null ) {
  16581. viewport = glBaseLayer.getViewport( view );
  16582. } else {
  16583. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16584. viewport = glSubImage.viewport;
  16585. // For side-by-side projection, we only produce a single texture for both eyes.
  16586. if ( i === 0 ) {
  16587. renderer.setRenderTargetTextures(
  16588. newRenderTarget,
  16589. glSubImage.colorTexture,
  16590. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16591. renderer.setRenderTarget( newRenderTarget );
  16592. }
  16593. }
  16594. let camera = cameras[ i ];
  16595. if ( camera === undefined ) {
  16596. camera = new PerspectiveCamera();
  16597. camera.layers.enable( i );
  16598. camera.viewport = new Vector4();
  16599. cameras[ i ] = camera;
  16600. }
  16601. camera.matrix.fromArray( view.transform.matrix );
  16602. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16603. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16604. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16605. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16606. if ( i === 0 ) {
  16607. cameraXR.matrix.copy( camera.matrix );
  16608. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16609. }
  16610. if ( cameraXRNeedsUpdate === true ) {
  16611. cameraXR.cameras.push( camera );
  16612. }
  16613. }
  16614. //
  16615. const enabledFeatures = session.enabledFeatures;
  16616. if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) {
  16617. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  16618. if ( depthData && depthData.isValid && depthData.texture ) {
  16619. depthSensing.init( renderer, depthData, session.renderState );
  16620. }
  16621. }
  16622. }
  16623. //
  16624. for ( let i = 0; i < controllers.length; i ++ ) {
  16625. const inputSource = controllerInputSources[ i ];
  16626. const controller = controllers[ i ];
  16627. if ( inputSource !== null && controller !== undefined ) {
  16628. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16629. }
  16630. }
  16631. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16632. if ( frame.detectedPlanes ) {
  16633. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16634. }
  16635. xrFrame = null;
  16636. }
  16637. const animation = new WebGLAnimation();
  16638. animation.setAnimationLoop( onAnimationFrame );
  16639. this.setAnimationLoop = function ( callback ) {
  16640. onAnimationFrameCallback = callback;
  16641. };
  16642. this.dispose = function () {};
  16643. }
  16644. }
  16645. const _e1 = /*@__PURE__*/ new Euler();
  16646. const _m1 = /*@__PURE__*/ new Matrix4();
  16647. function WebGLMaterials( renderer, properties ) {
  16648. function refreshTransformUniform( map, uniform ) {
  16649. if ( map.matrixAutoUpdate === true ) {
  16650. map.updateMatrix();
  16651. }
  16652. uniform.value.copy( map.matrix );
  16653. }
  16654. function refreshFogUniforms( uniforms, fog ) {
  16655. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16656. if ( fog.isFog ) {
  16657. uniforms.fogNear.value = fog.near;
  16658. uniforms.fogFar.value = fog.far;
  16659. } else if ( fog.isFogExp2 ) {
  16660. uniforms.fogDensity.value = fog.density;
  16661. }
  16662. }
  16663. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16664. if ( material.isMeshBasicMaterial ) {
  16665. refreshUniformsCommon( uniforms, material );
  16666. } else if ( material.isMeshLambertMaterial ) {
  16667. refreshUniformsCommon( uniforms, material );
  16668. } else if ( material.isMeshToonMaterial ) {
  16669. refreshUniformsCommon( uniforms, material );
  16670. refreshUniformsToon( uniforms, material );
  16671. } else if ( material.isMeshPhongMaterial ) {
  16672. refreshUniformsCommon( uniforms, material );
  16673. refreshUniformsPhong( uniforms, material );
  16674. } else if ( material.isMeshStandardMaterial ) {
  16675. refreshUniformsCommon( uniforms, material );
  16676. refreshUniformsStandard( uniforms, material );
  16677. if ( material.isMeshPhysicalMaterial ) {
  16678. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16679. }
  16680. } else if ( material.isMeshMatcapMaterial ) {
  16681. refreshUniformsCommon( uniforms, material );
  16682. refreshUniformsMatcap( uniforms, material );
  16683. } else if ( material.isMeshDepthMaterial ) {
  16684. refreshUniformsCommon( uniforms, material );
  16685. } else if ( material.isMeshDistanceMaterial ) {
  16686. refreshUniformsCommon( uniforms, material );
  16687. refreshUniformsDistance( uniforms, material );
  16688. } else if ( material.isMeshNormalMaterial ) {
  16689. refreshUniformsCommon( uniforms, material );
  16690. } else if ( material.isLineBasicMaterial ) {
  16691. refreshUniformsLine( uniforms, material );
  16692. if ( material.isLineDashedMaterial ) {
  16693. refreshUniformsDash( uniforms, material );
  16694. }
  16695. } else if ( material.isPointsMaterial ) {
  16696. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16697. } else if ( material.isSpriteMaterial ) {
  16698. refreshUniformsSprites( uniforms, material );
  16699. } else if ( material.isShadowMaterial ) {
  16700. uniforms.color.value.copy( material.color );
  16701. uniforms.opacity.value = material.opacity;
  16702. } else if ( material.isShaderMaterial ) {
  16703. material.uniformsNeedUpdate = false; // #15581
  16704. }
  16705. }
  16706. function refreshUniformsCommon( uniforms, material ) {
  16707. uniforms.opacity.value = material.opacity;
  16708. if ( material.color ) {
  16709. uniforms.diffuse.value.copy( material.color );
  16710. }
  16711. if ( material.emissive ) {
  16712. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16713. }
  16714. if ( material.map ) {
  16715. uniforms.map.value = material.map;
  16716. refreshTransformUniform( material.map, uniforms.mapTransform );
  16717. }
  16718. if ( material.alphaMap ) {
  16719. uniforms.alphaMap.value = material.alphaMap;
  16720. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16721. }
  16722. if ( material.bumpMap ) {
  16723. uniforms.bumpMap.value = material.bumpMap;
  16724. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16725. uniforms.bumpScale.value = material.bumpScale;
  16726. if ( material.side === BackSide ) {
  16727. uniforms.bumpScale.value *= - 1;
  16728. }
  16729. }
  16730. if ( material.normalMap ) {
  16731. uniforms.normalMap.value = material.normalMap;
  16732. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16733. uniforms.normalScale.value.copy( material.normalScale );
  16734. if ( material.side === BackSide ) {
  16735. uniforms.normalScale.value.negate();
  16736. }
  16737. }
  16738. if ( material.displacementMap ) {
  16739. uniforms.displacementMap.value = material.displacementMap;
  16740. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16741. uniforms.displacementScale.value = material.displacementScale;
  16742. uniforms.displacementBias.value = material.displacementBias;
  16743. }
  16744. if ( material.emissiveMap ) {
  16745. uniforms.emissiveMap.value = material.emissiveMap;
  16746. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16747. }
  16748. if ( material.specularMap ) {
  16749. uniforms.specularMap.value = material.specularMap;
  16750. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16751. }
  16752. if ( material.alphaTest > 0 ) {
  16753. uniforms.alphaTest.value = material.alphaTest;
  16754. }
  16755. const materialProperties = properties.get( material );
  16756. const envMap = materialProperties.envMap;
  16757. const envMapRotation = materialProperties.envMapRotation;
  16758. if ( envMap ) {
  16759. uniforms.envMap.value = envMap;
  16760. _e1.copy( envMapRotation );
  16761. // accommodate left-handed frame
  16762. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  16763. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  16764. // environment maps which are not cube render targets or PMREMs follow a different convention
  16765. _e1.y *= - 1;
  16766. _e1.z *= - 1;
  16767. }
  16768. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  16769. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16770. uniforms.reflectivity.value = material.reflectivity;
  16771. uniforms.ior.value = material.ior;
  16772. uniforms.refractionRatio.value = material.refractionRatio;
  16773. }
  16774. if ( material.lightMap ) {
  16775. uniforms.lightMap.value = material.lightMap;
  16776. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16777. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16778. }
  16779. if ( material.aoMap ) {
  16780. uniforms.aoMap.value = material.aoMap;
  16781. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16782. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16783. }
  16784. }
  16785. function refreshUniformsLine( uniforms, material ) {
  16786. uniforms.diffuse.value.copy( material.color );
  16787. uniforms.opacity.value = material.opacity;
  16788. if ( material.map ) {
  16789. uniforms.map.value = material.map;
  16790. refreshTransformUniform( material.map, uniforms.mapTransform );
  16791. }
  16792. }
  16793. function refreshUniformsDash( uniforms, material ) {
  16794. uniforms.dashSize.value = material.dashSize;
  16795. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16796. uniforms.scale.value = material.scale;
  16797. }
  16798. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16799. uniforms.diffuse.value.copy( material.color );
  16800. uniforms.opacity.value = material.opacity;
  16801. uniforms.size.value = material.size * pixelRatio;
  16802. uniforms.scale.value = height * 0.5;
  16803. if ( material.map ) {
  16804. uniforms.map.value = material.map;
  16805. refreshTransformUniform( material.map, uniforms.uvTransform );
  16806. }
  16807. if ( material.alphaMap ) {
  16808. uniforms.alphaMap.value = material.alphaMap;
  16809. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16810. }
  16811. if ( material.alphaTest > 0 ) {
  16812. uniforms.alphaTest.value = material.alphaTest;
  16813. }
  16814. }
  16815. function refreshUniformsSprites( uniforms, material ) {
  16816. uniforms.diffuse.value.copy( material.color );
  16817. uniforms.opacity.value = material.opacity;
  16818. uniforms.rotation.value = material.rotation;
  16819. if ( material.map ) {
  16820. uniforms.map.value = material.map;
  16821. refreshTransformUniform( material.map, uniforms.mapTransform );
  16822. }
  16823. if ( material.alphaMap ) {
  16824. uniforms.alphaMap.value = material.alphaMap;
  16825. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16826. }
  16827. if ( material.alphaTest > 0 ) {
  16828. uniforms.alphaTest.value = material.alphaTest;
  16829. }
  16830. }
  16831. function refreshUniformsPhong( uniforms, material ) {
  16832. uniforms.specular.value.copy( material.specular );
  16833. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16834. }
  16835. function refreshUniformsToon( uniforms, material ) {
  16836. if ( material.gradientMap ) {
  16837. uniforms.gradientMap.value = material.gradientMap;
  16838. }
  16839. }
  16840. function refreshUniformsStandard( uniforms, material ) {
  16841. uniforms.metalness.value = material.metalness;
  16842. if ( material.metalnessMap ) {
  16843. uniforms.metalnessMap.value = material.metalnessMap;
  16844. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16845. }
  16846. uniforms.roughness.value = material.roughness;
  16847. if ( material.roughnessMap ) {
  16848. uniforms.roughnessMap.value = material.roughnessMap;
  16849. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16850. }
  16851. if ( material.envMap ) {
  16852. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16853. uniforms.envMapIntensity.value = material.envMapIntensity;
  16854. }
  16855. }
  16856. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16857. uniforms.ior.value = material.ior; // also part of uniforms common
  16858. if ( material.sheen > 0 ) {
  16859. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16860. uniforms.sheenRoughness.value = material.sheenRoughness;
  16861. if ( material.sheenColorMap ) {
  16862. uniforms.sheenColorMap.value = material.sheenColorMap;
  16863. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16864. }
  16865. if ( material.sheenRoughnessMap ) {
  16866. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16867. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16868. }
  16869. }
  16870. if ( material.clearcoat > 0 ) {
  16871. uniforms.clearcoat.value = material.clearcoat;
  16872. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16873. if ( material.clearcoatMap ) {
  16874. uniforms.clearcoatMap.value = material.clearcoatMap;
  16875. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16876. }
  16877. if ( material.clearcoatRoughnessMap ) {
  16878. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16879. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16880. }
  16881. if ( material.clearcoatNormalMap ) {
  16882. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16883. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16884. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16885. if ( material.side === BackSide ) {
  16886. uniforms.clearcoatNormalScale.value.negate();
  16887. }
  16888. }
  16889. }
  16890. if ( material.dispersion > 0 ) {
  16891. uniforms.dispersion.value = material.dispersion;
  16892. }
  16893. if ( material.iridescence > 0 ) {
  16894. uniforms.iridescence.value = material.iridescence;
  16895. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16896. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16897. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16898. if ( material.iridescenceMap ) {
  16899. uniforms.iridescenceMap.value = material.iridescenceMap;
  16900. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16901. }
  16902. if ( material.iridescenceThicknessMap ) {
  16903. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16904. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16905. }
  16906. }
  16907. if ( material.transmission > 0 ) {
  16908. uniforms.transmission.value = material.transmission;
  16909. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16910. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16911. if ( material.transmissionMap ) {
  16912. uniforms.transmissionMap.value = material.transmissionMap;
  16913. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16914. }
  16915. uniforms.thickness.value = material.thickness;
  16916. if ( material.thicknessMap ) {
  16917. uniforms.thicknessMap.value = material.thicknessMap;
  16918. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16919. }
  16920. uniforms.attenuationDistance.value = material.attenuationDistance;
  16921. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16922. }
  16923. if ( material.anisotropy > 0 ) {
  16924. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16925. if ( material.anisotropyMap ) {
  16926. uniforms.anisotropyMap.value = material.anisotropyMap;
  16927. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16928. }
  16929. }
  16930. uniforms.specularIntensity.value = material.specularIntensity;
  16931. uniforms.specularColor.value.copy( material.specularColor );
  16932. if ( material.specularColorMap ) {
  16933. uniforms.specularColorMap.value = material.specularColorMap;
  16934. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16935. }
  16936. if ( material.specularIntensityMap ) {
  16937. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16938. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16939. }
  16940. }
  16941. function refreshUniformsMatcap( uniforms, material ) {
  16942. if ( material.matcap ) {
  16943. uniforms.matcap.value = material.matcap;
  16944. }
  16945. }
  16946. function refreshUniformsDistance( uniforms, material ) {
  16947. const light = properties.get( material ).light;
  16948. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16949. uniforms.nearDistance.value = light.shadow.camera.near;
  16950. uniforms.farDistance.value = light.shadow.camera.far;
  16951. }
  16952. return {
  16953. refreshFogUniforms: refreshFogUniforms,
  16954. refreshMaterialUniforms: refreshMaterialUniforms
  16955. };
  16956. }
  16957. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16958. let buffers = {};
  16959. let updateList = {};
  16960. let allocatedBindingPoints = [];
  16961. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  16962. function bind( uniformsGroup, program ) {
  16963. const webglProgram = program.program;
  16964. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16965. }
  16966. function update( uniformsGroup, program ) {
  16967. let buffer = buffers[ uniformsGroup.id ];
  16968. if ( buffer === undefined ) {
  16969. prepareUniformsGroup( uniformsGroup );
  16970. buffer = createBuffer( uniformsGroup );
  16971. buffers[ uniformsGroup.id ] = buffer;
  16972. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16973. }
  16974. // ensure to update the binding points/block indices mapping for this program
  16975. const webglProgram = program.program;
  16976. state.updateUBOMapping( uniformsGroup, webglProgram );
  16977. // update UBO once per frame
  16978. const frame = info.render.frame;
  16979. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16980. updateBufferData( uniformsGroup );
  16981. updateList[ uniformsGroup.id ] = frame;
  16982. }
  16983. }
  16984. function createBuffer( uniformsGroup ) {
  16985. // the setup of an UBO is independent of a particular shader program but global
  16986. const bindingPointIndex = allocateBindingPointIndex();
  16987. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16988. const buffer = gl.createBuffer();
  16989. const size = uniformsGroup.__size;
  16990. const usage = uniformsGroup.usage;
  16991. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16992. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16993. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16994. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16995. return buffer;
  16996. }
  16997. function allocateBindingPointIndex() {
  16998. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16999. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  17000. allocatedBindingPoints.push( i );
  17001. return i;
  17002. }
  17003. }
  17004. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  17005. return 0;
  17006. }
  17007. function updateBufferData( uniformsGroup ) {
  17008. const buffer = buffers[ uniformsGroup.id ];
  17009. const uniforms = uniformsGroup.uniforms;
  17010. const cache = uniformsGroup.__cache;
  17011. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  17012. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  17013. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  17014. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  17015. const uniform = uniformArray[ j ];
  17016. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  17017. const offset = uniform.__offset;
  17018. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  17019. let arrayOffset = 0;
  17020. for ( let k = 0; k < values.length; k ++ ) {
  17021. const value = values[ k ];
  17022. const info = getUniformSize( value );
  17023. // TODO add integer and struct support
  17024. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  17025. uniform.__data[ 0 ] = value;
  17026. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  17027. } else if ( value.isMatrix3 ) {
  17028. // manually converting 3x3 to 3x4
  17029. uniform.__data[ 0 ] = value.elements[ 0 ];
  17030. uniform.__data[ 1 ] = value.elements[ 1 ];
  17031. uniform.__data[ 2 ] = value.elements[ 2 ];
  17032. uniform.__data[ 3 ] = 0;
  17033. uniform.__data[ 4 ] = value.elements[ 3 ];
  17034. uniform.__data[ 5 ] = value.elements[ 4 ];
  17035. uniform.__data[ 6 ] = value.elements[ 5 ];
  17036. uniform.__data[ 7 ] = 0;
  17037. uniform.__data[ 8 ] = value.elements[ 6 ];
  17038. uniform.__data[ 9 ] = value.elements[ 7 ];
  17039. uniform.__data[ 10 ] = value.elements[ 8 ];
  17040. uniform.__data[ 11 ] = 0;
  17041. } else {
  17042. value.toArray( uniform.__data, arrayOffset );
  17043. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  17044. }
  17045. }
  17046. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  17047. }
  17048. }
  17049. }
  17050. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  17051. }
  17052. function hasUniformChanged( uniform, index, indexArray, cache ) {
  17053. const value = uniform.value;
  17054. const indexString = index + '_' + indexArray;
  17055. if ( cache[ indexString ] === undefined ) {
  17056. // cache entry does not exist so far
  17057. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  17058. cache[ indexString ] = value;
  17059. } else {
  17060. cache[ indexString ] = value.clone();
  17061. }
  17062. return true;
  17063. } else {
  17064. const cachedObject = cache[ indexString ];
  17065. // compare current value with cached entry
  17066. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  17067. if ( cachedObject !== value ) {
  17068. cache[ indexString ] = value;
  17069. return true;
  17070. }
  17071. } else {
  17072. if ( cachedObject.equals( value ) === false ) {
  17073. cachedObject.copy( value );
  17074. return true;
  17075. }
  17076. }
  17077. }
  17078. return false;
  17079. }
  17080. function prepareUniformsGroup( uniformsGroup ) {
  17081. // determine total buffer size according to the STD140 layout
  17082. // Hint: STD140 is the only supported layout in WebGL 2
  17083. const uniforms = uniformsGroup.uniforms;
  17084. let offset = 0; // global buffer offset in bytes
  17085. const chunkSize = 16; // size of a chunk in bytes
  17086. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  17087. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  17088. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  17089. const uniform = uniformArray[ j ];
  17090. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  17091. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  17092. const value = values[ k ];
  17093. const info = getUniformSize( value );
  17094. const chunkOffset = offset % chunkSize; // offset in the current chunk
  17095. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  17096. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  17097. offset += chunkPadding;
  17098. // Check for chunk overflow
  17099. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  17100. // Add padding and adjust offset
  17101. offset += ( chunkSize - chunkStart );
  17102. }
  17103. // the following two properties will be used for partial buffer updates
  17104. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  17105. uniform.__offset = offset;
  17106. // Update the global offset
  17107. offset += info.storage;
  17108. }
  17109. }
  17110. }
  17111. // ensure correct final padding
  17112. const chunkOffset = offset % chunkSize;
  17113. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  17114. //
  17115. uniformsGroup.__size = offset;
  17116. uniformsGroup.__cache = {};
  17117. return this;
  17118. }
  17119. function getUniformSize( value ) {
  17120. const info = {
  17121. boundary: 0, // bytes
  17122. storage: 0 // bytes
  17123. };
  17124. // determine sizes according to STD140
  17125. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  17126. // float/int/bool
  17127. info.boundary = 4;
  17128. info.storage = 4;
  17129. } else if ( value.isVector2 ) {
  17130. // vec2
  17131. info.boundary = 8;
  17132. info.storage = 8;
  17133. } else if ( value.isVector3 || value.isColor ) {
  17134. // vec3
  17135. info.boundary = 16;
  17136. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  17137. } else if ( value.isVector4 ) {
  17138. // vec4
  17139. info.boundary = 16;
  17140. info.storage = 16;
  17141. } else if ( value.isMatrix3 ) {
  17142. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  17143. info.boundary = 48;
  17144. info.storage = 48;
  17145. } else if ( value.isMatrix4 ) {
  17146. // mat4
  17147. info.boundary = 64;
  17148. info.storage = 64;
  17149. } else if ( value.isTexture ) {
  17150. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  17151. } else {
  17152. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  17153. }
  17154. return info;
  17155. }
  17156. function onUniformsGroupsDispose( event ) {
  17157. const uniformsGroup = event.target;
  17158. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  17159. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  17160. allocatedBindingPoints.splice( index, 1 );
  17161. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  17162. delete buffers[ uniformsGroup.id ];
  17163. delete updateList[ uniformsGroup.id ];
  17164. }
  17165. function dispose() {
  17166. for ( const id in buffers ) {
  17167. gl.deleteBuffer( buffers[ id ] );
  17168. }
  17169. allocatedBindingPoints = [];
  17170. buffers = {};
  17171. updateList = {};
  17172. }
  17173. return {
  17174. bind: bind,
  17175. update: update,
  17176. dispose: dispose
  17177. };
  17178. }
  17179. class WebGLRenderer {
  17180. constructor( parameters = {} ) {
  17181. const {
  17182. canvas = createCanvasElement(),
  17183. context = null,
  17184. depth = true,
  17185. stencil = false,
  17186. alpha = false,
  17187. antialias = false,
  17188. premultipliedAlpha = true,
  17189. preserveDrawingBuffer = false,
  17190. powerPreference = 'default',
  17191. failIfMajorPerformanceCaveat = false,
  17192. } = parameters;
  17193. this.isWebGLRenderer = true;
  17194. let _alpha;
  17195. if ( context !== null ) {
  17196. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  17197. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  17198. }
  17199. _alpha = context.getContextAttributes().alpha;
  17200. } else {
  17201. _alpha = alpha;
  17202. }
  17203. const uintClearColor = new Uint32Array( 4 );
  17204. const intClearColor = new Int32Array( 4 );
  17205. let currentRenderList = null;
  17206. let currentRenderState = null;
  17207. // render() can be called from within a callback triggered by another render.
  17208. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  17209. const renderListStack = [];
  17210. const renderStateStack = [];
  17211. // public properties
  17212. this.domElement = canvas;
  17213. // Debug configuration container
  17214. this.debug = {
  17215. /**
  17216. * Enables error checking and reporting when shader programs are being compiled
  17217. * @type {boolean}
  17218. */
  17219. checkShaderErrors: true,
  17220. /**
  17221. * Callback for custom error reporting.
  17222. * @type {?Function}
  17223. */
  17224. onShaderError: null
  17225. };
  17226. // clearing
  17227. this.autoClear = true;
  17228. this.autoClearColor = true;
  17229. this.autoClearDepth = true;
  17230. this.autoClearStencil = true;
  17231. // scene graph
  17232. this.sortObjects = true;
  17233. // user-defined clipping
  17234. this.clippingPlanes = [];
  17235. this.localClippingEnabled = false;
  17236. // physically based shading
  17237. this._outputColorSpace = SRGBColorSpace;
  17238. // tone mapping
  17239. this.toneMapping = NoToneMapping;
  17240. this.toneMappingExposure = 1.0;
  17241. // internal properties
  17242. const _this = this;
  17243. let _isContextLost = false;
  17244. // internal state cache
  17245. let _currentActiveCubeFace = 0;
  17246. let _currentActiveMipmapLevel = 0;
  17247. let _currentRenderTarget = null;
  17248. let _currentMaterialId = - 1;
  17249. let _currentCamera = null;
  17250. const _currentViewport = new Vector4();
  17251. const _currentScissor = new Vector4();
  17252. let _currentScissorTest = null;
  17253. const _currentClearColor = new Color( 0x000000 );
  17254. let _currentClearAlpha = 0;
  17255. //
  17256. let _width = canvas.width;
  17257. let _height = canvas.height;
  17258. let _pixelRatio = 1;
  17259. let _opaqueSort = null;
  17260. let _transparentSort = null;
  17261. const _viewport = new Vector4( 0, 0, _width, _height );
  17262. const _scissor = new Vector4( 0, 0, _width, _height );
  17263. let _scissorTest = false;
  17264. // frustum
  17265. const _frustum = new Frustum();
  17266. // clipping
  17267. let _clippingEnabled = false;
  17268. let _localClippingEnabled = false;
  17269. // camera matrices cache
  17270. const _projScreenMatrix = new Matrix4();
  17271. const _vector3 = new Vector3();
  17272. const _vector4 = new Vector4();
  17273. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  17274. let _renderBackground = false;
  17275. function getTargetPixelRatio() {
  17276. return _currentRenderTarget === null ? _pixelRatio : 1;
  17277. }
  17278. // initialize
  17279. let _gl = context;
  17280. function getContext( contextName, contextAttributes ) {
  17281. return canvas.getContext( contextName, contextAttributes );
  17282. }
  17283. try {
  17284. const contextAttributes = {
  17285. alpha: true,
  17286. depth,
  17287. stencil,
  17288. antialias,
  17289. premultipliedAlpha,
  17290. preserveDrawingBuffer,
  17291. powerPreference,
  17292. failIfMajorPerformanceCaveat,
  17293. };
  17294. // OffscreenCanvas does not have setAttribute, see #22811
  17295. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  17296. // event listeners must be registered before WebGL context is created, see #12753
  17297. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  17298. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  17299. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17300. if ( _gl === null ) {
  17301. const contextName = 'webgl2';
  17302. _gl = getContext( contextName, contextAttributes );
  17303. if ( _gl === null ) {
  17304. if ( getContext( contextName ) ) {
  17305. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  17306. } else {
  17307. throw new Error( 'Error creating WebGL context.' );
  17308. }
  17309. }
  17310. }
  17311. } catch ( error ) {
  17312. console.error( 'THREE.WebGLRenderer: ' + error.message );
  17313. throw error;
  17314. }
  17315. let extensions, capabilities, state, info;
  17316. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  17317. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  17318. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  17319. let utils, bindingStates, uniformsGroups;
  17320. function initGLContext() {
  17321. extensions = new WebGLExtensions( _gl );
  17322. extensions.init();
  17323. utils = new WebGLUtils( _gl, extensions );
  17324. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  17325. state = new WebGLState( _gl );
  17326. info = new WebGLInfo( _gl );
  17327. properties = new WebGLProperties();
  17328. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  17329. cubemaps = new WebGLCubeMaps( _this );
  17330. cubeuvmaps = new WebGLCubeUVMaps( _this );
  17331. attributes = new WebGLAttributes( _gl );
  17332. bindingStates = new WebGLBindingStates( _gl, attributes );
  17333. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  17334. objects = new WebGLObjects( _gl, geometries, attributes, info );
  17335. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  17336. clipping = new WebGLClipping( properties );
  17337. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  17338. materials = new WebGLMaterials( _this, properties );
  17339. renderLists = new WebGLRenderLists();
  17340. renderStates = new WebGLRenderStates( extensions );
  17341. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  17342. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  17343. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  17344. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  17345. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  17346. info.programs = programCache.programs;
  17347. _this.capabilities = capabilities;
  17348. _this.extensions = extensions;
  17349. _this.properties = properties;
  17350. _this.renderLists = renderLists;
  17351. _this.shadowMap = shadowMap;
  17352. _this.state = state;
  17353. _this.info = info;
  17354. }
  17355. initGLContext();
  17356. // xr
  17357. const xr = new WebXRManager( _this, _gl );
  17358. this.xr = xr;
  17359. // API
  17360. this.getContext = function () {
  17361. return _gl;
  17362. };
  17363. this.getContextAttributes = function () {
  17364. return _gl.getContextAttributes();
  17365. };
  17366. this.forceContextLoss = function () {
  17367. const extension = extensions.get( 'WEBGL_lose_context' );
  17368. if ( extension ) extension.loseContext();
  17369. };
  17370. this.forceContextRestore = function () {
  17371. const extension = extensions.get( 'WEBGL_lose_context' );
  17372. if ( extension ) extension.restoreContext();
  17373. };
  17374. this.getPixelRatio = function () {
  17375. return _pixelRatio;
  17376. };
  17377. this.setPixelRatio = function ( value ) {
  17378. if ( value === undefined ) return;
  17379. _pixelRatio = value;
  17380. this.setSize( _width, _height, false );
  17381. };
  17382. this.getSize = function ( target ) {
  17383. return target.set( _width, _height );
  17384. };
  17385. this.setSize = function ( width, height, updateStyle = true ) {
  17386. if ( xr.isPresenting ) {
  17387. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17388. return;
  17389. }
  17390. _width = width;
  17391. _height = height;
  17392. canvas.width = Math.floor( width * _pixelRatio );
  17393. canvas.height = Math.floor( height * _pixelRatio );
  17394. if ( updateStyle === true ) {
  17395. canvas.style.width = width + 'px';
  17396. canvas.style.height = height + 'px';
  17397. }
  17398. this.setViewport( 0, 0, width, height );
  17399. };
  17400. this.getDrawingBufferSize = function ( target ) {
  17401. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  17402. };
  17403. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17404. _width = width;
  17405. _height = height;
  17406. _pixelRatio = pixelRatio;
  17407. canvas.width = Math.floor( width * pixelRatio );
  17408. canvas.height = Math.floor( height * pixelRatio );
  17409. this.setViewport( 0, 0, width, height );
  17410. };
  17411. this.getCurrentViewport = function ( target ) {
  17412. return target.copy( _currentViewport );
  17413. };
  17414. this.getViewport = function ( target ) {
  17415. return target.copy( _viewport );
  17416. };
  17417. this.setViewport = function ( x, y, width, height ) {
  17418. if ( x.isVector4 ) {
  17419. _viewport.set( x.x, x.y, x.z, x.w );
  17420. } else {
  17421. _viewport.set( x, y, width, height );
  17422. }
  17423. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  17424. };
  17425. this.getScissor = function ( target ) {
  17426. return target.copy( _scissor );
  17427. };
  17428. this.setScissor = function ( x, y, width, height ) {
  17429. if ( x.isVector4 ) {
  17430. _scissor.set( x.x, x.y, x.z, x.w );
  17431. } else {
  17432. _scissor.set( x, y, width, height );
  17433. }
  17434. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  17435. };
  17436. this.getScissorTest = function () {
  17437. return _scissorTest;
  17438. };
  17439. this.setScissorTest = function ( boolean ) {
  17440. state.setScissorTest( _scissorTest = boolean );
  17441. };
  17442. this.setOpaqueSort = function ( method ) {
  17443. _opaqueSort = method;
  17444. };
  17445. this.setTransparentSort = function ( method ) {
  17446. _transparentSort = method;
  17447. };
  17448. // Clearing
  17449. this.getClearColor = function ( target ) {
  17450. return target.copy( background.getClearColor() );
  17451. };
  17452. this.setClearColor = function () {
  17453. background.setClearColor.apply( background, arguments );
  17454. };
  17455. this.getClearAlpha = function () {
  17456. return background.getClearAlpha();
  17457. };
  17458. this.setClearAlpha = function () {
  17459. background.setClearAlpha.apply( background, arguments );
  17460. };
  17461. this.clear = function ( color = true, depth = true, stencil = true ) {
  17462. let bits = 0;
  17463. if ( color ) {
  17464. // check if we're trying to clear an integer target
  17465. let isIntegerFormat = false;
  17466. if ( _currentRenderTarget !== null ) {
  17467. const targetFormat = _currentRenderTarget.texture.format;
  17468. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  17469. targetFormat === RGIntegerFormat ||
  17470. targetFormat === RedIntegerFormat;
  17471. }
  17472. // use the appropriate clear functions to clear the target if it's a signed
  17473. // or unsigned integer target
  17474. if ( isIntegerFormat ) {
  17475. const targetType = _currentRenderTarget.texture.type;
  17476. const isUnsignedType = targetType === UnsignedByteType ||
  17477. targetType === UnsignedIntType ||
  17478. targetType === UnsignedShortType ||
  17479. targetType === UnsignedInt248Type ||
  17480. targetType === UnsignedShort4444Type ||
  17481. targetType === UnsignedShort5551Type;
  17482. const clearColor = background.getClearColor();
  17483. const a = background.getClearAlpha();
  17484. const r = clearColor.r;
  17485. const g = clearColor.g;
  17486. const b = clearColor.b;
  17487. if ( isUnsignedType ) {
  17488. uintClearColor[ 0 ] = r;
  17489. uintClearColor[ 1 ] = g;
  17490. uintClearColor[ 2 ] = b;
  17491. uintClearColor[ 3 ] = a;
  17492. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  17493. } else {
  17494. intClearColor[ 0 ] = r;
  17495. intClearColor[ 1 ] = g;
  17496. intClearColor[ 2 ] = b;
  17497. intClearColor[ 3 ] = a;
  17498. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  17499. }
  17500. } else {
  17501. bits |= _gl.COLOR_BUFFER_BIT;
  17502. }
  17503. }
  17504. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17505. if ( stencil ) {
  17506. bits |= _gl.STENCIL_BUFFER_BIT;
  17507. this.state.buffers.stencil.setMask( 0xffffffff );
  17508. }
  17509. _gl.clear( bits );
  17510. };
  17511. this.clearColor = function () {
  17512. this.clear( true, false, false );
  17513. };
  17514. this.clearDepth = function () {
  17515. this.clear( false, true, false );
  17516. };
  17517. this.clearStencil = function () {
  17518. this.clear( false, false, true );
  17519. };
  17520. //
  17521. this.dispose = function () {
  17522. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17523. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17524. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17525. renderLists.dispose();
  17526. renderStates.dispose();
  17527. properties.dispose();
  17528. cubemaps.dispose();
  17529. cubeuvmaps.dispose();
  17530. objects.dispose();
  17531. bindingStates.dispose();
  17532. uniformsGroups.dispose();
  17533. programCache.dispose();
  17534. xr.dispose();
  17535. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  17536. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  17537. animation.stop();
  17538. };
  17539. // Events
  17540. function onContextLost( event ) {
  17541. event.preventDefault();
  17542. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17543. _isContextLost = true;
  17544. }
  17545. function onContextRestore( /* event */ ) {
  17546. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17547. _isContextLost = false;
  17548. const infoAutoReset = info.autoReset;
  17549. const shadowMapEnabled = shadowMap.enabled;
  17550. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17551. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17552. const shadowMapType = shadowMap.type;
  17553. initGLContext();
  17554. info.autoReset = infoAutoReset;
  17555. shadowMap.enabled = shadowMapEnabled;
  17556. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17557. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17558. shadowMap.type = shadowMapType;
  17559. }
  17560. function onContextCreationError( event ) {
  17561. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17562. }
  17563. function onMaterialDispose( event ) {
  17564. const material = event.target;
  17565. material.removeEventListener( 'dispose', onMaterialDispose );
  17566. deallocateMaterial( material );
  17567. }
  17568. // Buffer deallocation
  17569. function deallocateMaterial( material ) {
  17570. releaseMaterialProgramReferences( material );
  17571. properties.remove( material );
  17572. }
  17573. function releaseMaterialProgramReferences( material ) {
  17574. const programs = properties.get( material ).programs;
  17575. if ( programs !== undefined ) {
  17576. programs.forEach( function ( program ) {
  17577. programCache.releaseProgram( program );
  17578. } );
  17579. if ( material.isShaderMaterial ) {
  17580. programCache.releaseShaderCache( material );
  17581. }
  17582. }
  17583. }
  17584. // Buffer rendering
  17585. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17586. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17587. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17588. const program = setProgram( camera, scene, geometry, material, object );
  17589. state.setMaterial( material, frontFaceCW );
  17590. //
  17591. let index = geometry.index;
  17592. let rangeFactor = 1;
  17593. if ( material.wireframe === true ) {
  17594. index = geometries.getWireframeAttribute( geometry );
  17595. if ( index === undefined ) return;
  17596. rangeFactor = 2;
  17597. }
  17598. //
  17599. const drawRange = geometry.drawRange;
  17600. const position = geometry.attributes.position;
  17601. let drawStart = drawRange.start * rangeFactor;
  17602. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17603. if ( group !== null ) {
  17604. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17605. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17606. }
  17607. if ( index !== null ) {
  17608. drawStart = Math.max( drawStart, 0 );
  17609. drawEnd = Math.min( drawEnd, index.count );
  17610. } else if ( position !== undefined && position !== null ) {
  17611. drawStart = Math.max( drawStart, 0 );
  17612. drawEnd = Math.min( drawEnd, position.count );
  17613. }
  17614. const drawCount = drawEnd - drawStart;
  17615. if ( drawCount < 0 || drawCount === Infinity ) return;
  17616. //
  17617. bindingStates.setup( object, material, program, geometry, index );
  17618. let attribute;
  17619. let renderer = bufferRenderer;
  17620. if ( index !== null ) {
  17621. attribute = attributes.get( index );
  17622. renderer = indexedBufferRenderer;
  17623. renderer.setIndex( attribute );
  17624. }
  17625. //
  17626. if ( object.isMesh ) {
  17627. if ( material.wireframe === true ) {
  17628. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17629. renderer.setMode( _gl.LINES );
  17630. } else {
  17631. renderer.setMode( _gl.TRIANGLES );
  17632. }
  17633. } else if ( object.isLine ) {
  17634. let lineWidth = material.linewidth;
  17635. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17636. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17637. if ( object.isLineSegments ) {
  17638. renderer.setMode( _gl.LINES );
  17639. } else if ( object.isLineLoop ) {
  17640. renderer.setMode( _gl.LINE_LOOP );
  17641. } else {
  17642. renderer.setMode( _gl.LINE_STRIP );
  17643. }
  17644. } else if ( object.isPoints ) {
  17645. renderer.setMode( _gl.POINTS );
  17646. } else if ( object.isSprite ) {
  17647. renderer.setMode( _gl.TRIANGLES );
  17648. }
  17649. if ( object.isBatchedMesh ) {
  17650. if ( object._multiDrawInstances !== null ) {
  17651. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  17652. } else {
  17653. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  17654. const starts = object._multiDrawStarts;
  17655. const counts = object._multiDrawCounts;
  17656. const drawCount = object._multiDrawCount;
  17657. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  17658. const uniforms = properties.get( material ).currentProgram.getUniforms();
  17659. for ( let i = 0; i < drawCount; i ++ ) {
  17660. uniforms.setValue( _gl, '_gl_DrawID', i );
  17661. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  17662. }
  17663. } else {
  17664. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  17665. }
  17666. }
  17667. } else if ( object.isInstancedMesh ) {
  17668. renderer.renderInstances( drawStart, drawCount, object.count );
  17669. } else if ( geometry.isInstancedBufferGeometry ) {
  17670. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17671. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17672. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17673. } else {
  17674. renderer.render( drawStart, drawCount );
  17675. }
  17676. };
  17677. // Compile
  17678. function prepareMaterial( material, scene, object ) {
  17679. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17680. material.side = BackSide;
  17681. material.needsUpdate = true;
  17682. getProgram( material, scene, object );
  17683. material.side = FrontSide;
  17684. material.needsUpdate = true;
  17685. getProgram( material, scene, object );
  17686. material.side = DoubleSide;
  17687. } else {
  17688. getProgram( material, scene, object );
  17689. }
  17690. }
  17691. this.compile = function ( scene, camera, targetScene = null ) {
  17692. if ( targetScene === null ) targetScene = scene;
  17693. currentRenderState = renderStates.get( targetScene );
  17694. currentRenderState.init( camera );
  17695. renderStateStack.push( currentRenderState );
  17696. // gather lights from both the target scene and the new object that will be added to the scene.
  17697. targetScene.traverseVisible( function ( object ) {
  17698. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17699. currentRenderState.pushLight( object );
  17700. if ( object.castShadow ) {
  17701. currentRenderState.pushShadow( object );
  17702. }
  17703. }
  17704. } );
  17705. if ( scene !== targetScene ) {
  17706. scene.traverseVisible( function ( object ) {
  17707. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17708. currentRenderState.pushLight( object );
  17709. if ( object.castShadow ) {
  17710. currentRenderState.pushShadow( object );
  17711. }
  17712. }
  17713. } );
  17714. }
  17715. currentRenderState.setupLights();
  17716. // Only initialize materials in the new scene, not the targetScene.
  17717. const materials = new Set();
  17718. scene.traverse( function ( object ) {
  17719. const material = object.material;
  17720. if ( material ) {
  17721. if ( Array.isArray( material ) ) {
  17722. for ( let i = 0; i < material.length; i ++ ) {
  17723. const material2 = material[ i ];
  17724. prepareMaterial( material2, targetScene, object );
  17725. materials.add( material2 );
  17726. }
  17727. } else {
  17728. prepareMaterial( material, targetScene, object );
  17729. materials.add( material );
  17730. }
  17731. }
  17732. } );
  17733. renderStateStack.pop();
  17734. currentRenderState = null;
  17735. return materials;
  17736. };
  17737. // compileAsync
  17738. this.compileAsync = function ( scene, camera, targetScene = null ) {
  17739. const materials = this.compile( scene, camera, targetScene );
  17740. // Wait for all the materials in the new object to indicate that they're
  17741. // ready to be used before resolving the promise.
  17742. return new Promise( ( resolve ) => {
  17743. function checkMaterialsReady() {
  17744. materials.forEach( function ( material ) {
  17745. const materialProperties = properties.get( material );
  17746. const program = materialProperties.currentProgram;
  17747. if ( program.isReady() ) {
  17748. // remove any programs that report they're ready to use from the list
  17749. materials.delete( material );
  17750. }
  17751. } );
  17752. // once the list of compiling materials is empty, call the callback
  17753. if ( materials.size === 0 ) {
  17754. resolve( scene );
  17755. return;
  17756. }
  17757. // if some materials are still not ready, wait a bit and check again
  17758. setTimeout( checkMaterialsReady, 10 );
  17759. }
  17760. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  17761. // If we can check the compilation status of the materials without
  17762. // blocking then do so right away.
  17763. checkMaterialsReady();
  17764. } else {
  17765. // Otherwise start by waiting a bit to give the materials we just
  17766. // initialized a chance to finish.
  17767. setTimeout( checkMaterialsReady, 10 );
  17768. }
  17769. } );
  17770. };
  17771. // Animation Loop
  17772. let onAnimationFrameCallback = null;
  17773. function onAnimationFrame( time ) {
  17774. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17775. }
  17776. function onXRSessionStart() {
  17777. animation.stop();
  17778. }
  17779. function onXRSessionEnd() {
  17780. animation.start();
  17781. }
  17782. const animation = new WebGLAnimation();
  17783. animation.setAnimationLoop( onAnimationFrame );
  17784. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17785. this.setAnimationLoop = function ( callback ) {
  17786. onAnimationFrameCallback = callback;
  17787. xr.setAnimationLoop( callback );
  17788. ( callback === null ) ? animation.stop() : animation.start();
  17789. };
  17790. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17791. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17792. // Rendering
  17793. this.render = function ( scene, camera ) {
  17794. if ( camera !== undefined && camera.isCamera !== true ) {
  17795. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17796. return;
  17797. }
  17798. if ( _isContextLost === true ) return;
  17799. // update scene graph
  17800. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17801. // update camera matrices and frustum
  17802. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17803. if ( xr.enabled === true && xr.isPresenting === true ) {
  17804. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  17805. camera = xr.getCamera(); // use XR camera for rendering
  17806. }
  17807. //
  17808. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17809. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17810. currentRenderState.init( camera );
  17811. renderStateStack.push( currentRenderState );
  17812. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17813. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17814. _localClippingEnabled = this.localClippingEnabled;
  17815. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17816. currentRenderList = renderLists.get( scene, renderListStack.length );
  17817. currentRenderList.init();
  17818. renderListStack.push( currentRenderList );
  17819. if ( xr.enabled === true && xr.isPresenting === true ) {
  17820. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  17821. if ( depthSensingMesh !== null ) {
  17822. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  17823. }
  17824. }
  17825. projectObject( scene, camera, 0, _this.sortObjects );
  17826. currentRenderList.finish();
  17827. if ( _this.sortObjects === true ) {
  17828. currentRenderList.sort( _opaqueSort, _transparentSort );
  17829. }
  17830. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  17831. if ( _renderBackground ) {
  17832. background.addToRenderList( currentRenderList, scene );
  17833. }
  17834. //
  17835. this.info.render.frame ++;
  17836. if ( _clippingEnabled === true ) clipping.beginShadows();
  17837. const shadowsArray = currentRenderState.state.shadowsArray;
  17838. shadowMap.render( shadowsArray, scene, camera );
  17839. if ( _clippingEnabled === true ) clipping.endShadows();
  17840. //
  17841. if ( this.info.autoReset === true ) this.info.reset();
  17842. // render scene
  17843. const opaqueObjects = currentRenderList.opaque;
  17844. const transmissiveObjects = currentRenderList.transmissive;
  17845. currentRenderState.setupLights();
  17846. if ( camera.isArrayCamera ) {
  17847. const cameras = camera.cameras;
  17848. if ( transmissiveObjects.length > 0 ) {
  17849. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17850. const camera2 = cameras[ i ];
  17851. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  17852. }
  17853. }
  17854. if ( _renderBackground ) background.render( scene );
  17855. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17856. const camera2 = cameras[ i ];
  17857. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17858. }
  17859. } else {
  17860. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17861. if ( _renderBackground ) background.render( scene );
  17862. renderScene( currentRenderList, scene, camera );
  17863. }
  17864. //
  17865. if ( _currentRenderTarget !== null ) {
  17866. // resolve multisample renderbuffers to a single-sample texture if necessary
  17867. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17868. // Generate mipmap if we're using any kind of mipmap filtering
  17869. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17870. }
  17871. //
  17872. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17873. // _gl.finish();
  17874. bindingStates.resetDefaultState();
  17875. _currentMaterialId = - 1;
  17876. _currentCamera = null;
  17877. renderStateStack.pop();
  17878. if ( renderStateStack.length > 0 ) {
  17879. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17880. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  17881. } else {
  17882. currentRenderState = null;
  17883. }
  17884. renderListStack.pop();
  17885. if ( renderListStack.length > 0 ) {
  17886. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17887. } else {
  17888. currentRenderList = null;
  17889. }
  17890. };
  17891. function projectObject( object, camera, groupOrder, sortObjects ) {
  17892. if ( object.visible === false ) return;
  17893. const visible = object.layers.test( camera.layers );
  17894. if ( visible ) {
  17895. if ( object.isGroup ) {
  17896. groupOrder = object.renderOrder;
  17897. } else if ( object.isLOD ) {
  17898. if ( object.autoUpdate === true ) object.update( camera );
  17899. } else if ( object.isLight ) {
  17900. currentRenderState.pushLight( object );
  17901. if ( object.castShadow ) {
  17902. currentRenderState.pushShadow( object );
  17903. }
  17904. } else if ( object.isSprite ) {
  17905. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17906. if ( sortObjects ) {
  17907. _vector4.setFromMatrixPosition( object.matrixWorld )
  17908. .applyMatrix4( _projScreenMatrix );
  17909. }
  17910. const geometry = objects.update( object );
  17911. const material = object.material;
  17912. if ( material.visible ) {
  17913. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  17914. }
  17915. }
  17916. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17917. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17918. const geometry = objects.update( object );
  17919. const material = object.material;
  17920. if ( sortObjects ) {
  17921. if ( object.boundingSphere !== undefined ) {
  17922. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17923. _vector4.copy( object.boundingSphere.center );
  17924. } else {
  17925. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17926. _vector4.copy( geometry.boundingSphere.center );
  17927. }
  17928. _vector4
  17929. .applyMatrix4( object.matrixWorld )
  17930. .applyMatrix4( _projScreenMatrix );
  17931. }
  17932. if ( Array.isArray( material ) ) {
  17933. const groups = geometry.groups;
  17934. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17935. const group = groups[ i ];
  17936. const groupMaterial = material[ group.materialIndex ];
  17937. if ( groupMaterial && groupMaterial.visible ) {
  17938. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  17939. }
  17940. }
  17941. } else if ( material.visible ) {
  17942. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  17943. }
  17944. }
  17945. }
  17946. }
  17947. const children = object.children;
  17948. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17949. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17950. }
  17951. }
  17952. function renderScene( currentRenderList, scene, camera, viewport ) {
  17953. const opaqueObjects = currentRenderList.opaque;
  17954. const transmissiveObjects = currentRenderList.transmissive;
  17955. const transparentObjects = currentRenderList.transparent;
  17956. currentRenderState.setupLightsView( camera );
  17957. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17958. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17959. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17960. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17961. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17962. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17963. state.buffers.depth.setTest( true );
  17964. state.buffers.depth.setMask( true );
  17965. state.buffers.color.setMask( true );
  17966. state.setPolygonOffset( false );
  17967. }
  17968. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17969. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17970. if ( overrideMaterial !== null ) {
  17971. return;
  17972. }
  17973. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  17974. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  17975. generateMipmaps: true,
  17976. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  17977. minFilter: LinearMipmapLinearFilter,
  17978. samples: 4,
  17979. stencilBuffer: stencil,
  17980. resolveDepthBuffer: false,
  17981. resolveStencilBuffer: false,
  17982. colorSpace: ColorManagement.workingColorSpace,
  17983. } );
  17984. // debug
  17985. /*
  17986. const geometry = new PlaneGeometry();
  17987. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17988. const mesh = new Mesh( geometry, material );
  17989. scene.add( mesh );
  17990. */
  17991. }
  17992. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  17993. const activeViewport = camera.viewport || _currentViewport;
  17994. transmissionRenderTarget.setSize( activeViewport.z, activeViewport.w );
  17995. //
  17996. const currentRenderTarget = _this.getRenderTarget();
  17997. _this.setRenderTarget( transmissionRenderTarget );
  17998. _this.getClearColor( _currentClearColor );
  17999. _currentClearAlpha = _this.getClearAlpha();
  18000. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  18001. _this.clear();
  18002. if ( _renderBackground ) background.render( scene );
  18003. // Turn off the features which can affect the frag color for opaque objects pass.
  18004. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  18005. const currentToneMapping = _this.toneMapping;
  18006. _this.toneMapping = NoToneMapping;
  18007. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  18008. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  18009. const currentCameraViewport = camera.viewport;
  18010. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  18011. currentRenderState.setupLightsView( camera );
  18012. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  18013. renderObjects( opaqueObjects, scene, camera );
  18014. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  18015. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  18016. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  18017. let renderTargetNeedsUpdate = false;
  18018. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  18019. const renderItem = transmissiveObjects[ i ];
  18020. const object = renderItem.object;
  18021. const geometry = renderItem.geometry;
  18022. const material = renderItem.material;
  18023. const group = renderItem.group;
  18024. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  18025. const currentSide = material.side;
  18026. material.side = BackSide;
  18027. material.needsUpdate = true;
  18028. renderObject( object, scene, camera, geometry, material, group );
  18029. material.side = currentSide;
  18030. material.needsUpdate = true;
  18031. renderTargetNeedsUpdate = true;
  18032. }
  18033. }
  18034. if ( renderTargetNeedsUpdate === true ) {
  18035. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  18036. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  18037. }
  18038. }
  18039. _this.setRenderTarget( currentRenderTarget );
  18040. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  18041. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  18042. _this.toneMapping = currentToneMapping;
  18043. }
  18044. function renderObjects( renderList, scene, camera ) {
  18045. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  18046. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  18047. const renderItem = renderList[ i ];
  18048. const object = renderItem.object;
  18049. const geometry = renderItem.geometry;
  18050. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  18051. const group = renderItem.group;
  18052. if ( object.layers.test( camera.layers ) ) {
  18053. renderObject( object, scene, camera, geometry, material, group );
  18054. }
  18055. }
  18056. }
  18057. function renderObject( object, scene, camera, geometry, material, group ) {
  18058. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  18059. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  18060. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  18061. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  18062. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  18063. material.side = BackSide;
  18064. material.needsUpdate = true;
  18065. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  18066. material.side = FrontSide;
  18067. material.needsUpdate = true;
  18068. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  18069. material.side = DoubleSide;
  18070. } else {
  18071. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  18072. }
  18073. object.onAfterRender( _this, scene, camera, geometry, material, group );
  18074. }
  18075. function getProgram( material, scene, object ) {
  18076. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  18077. const materialProperties = properties.get( material );
  18078. const lights = currentRenderState.state.lights;
  18079. const shadowsArray = currentRenderState.state.shadowsArray;
  18080. const lightsStateVersion = lights.state.version;
  18081. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  18082. const programCacheKey = programCache.getProgramCacheKey( parameters );
  18083. let programs = materialProperties.programs;
  18084. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  18085. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  18086. materialProperties.fog = scene.fog;
  18087. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  18088. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  18089. if ( programs === undefined ) {
  18090. // new material
  18091. material.addEventListener( 'dispose', onMaterialDispose );
  18092. programs = new Map();
  18093. materialProperties.programs = programs;
  18094. }
  18095. let program = programs.get( programCacheKey );
  18096. if ( program !== undefined ) {
  18097. // early out if program and light state is identical
  18098. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  18099. updateCommonMaterialProperties( material, parameters );
  18100. return program;
  18101. }
  18102. } else {
  18103. parameters.uniforms = programCache.getUniforms( material );
  18104. material.onBeforeCompile( parameters, _this );
  18105. program = programCache.acquireProgram( parameters, programCacheKey );
  18106. programs.set( programCacheKey, program );
  18107. materialProperties.uniforms = parameters.uniforms;
  18108. }
  18109. const uniforms = materialProperties.uniforms;
  18110. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  18111. uniforms.clippingPlanes = clipping.uniform;
  18112. }
  18113. updateCommonMaterialProperties( material, parameters );
  18114. // store the light setup it was created for
  18115. materialProperties.needsLights = materialNeedsLights( material );
  18116. materialProperties.lightsStateVersion = lightsStateVersion;
  18117. if ( materialProperties.needsLights ) {
  18118. // wire up the material to this renderer's lighting state
  18119. uniforms.ambientLightColor.value = lights.state.ambient;
  18120. uniforms.lightProbe.value = lights.state.probe;
  18121. uniforms.directionalLights.value = lights.state.directional;
  18122. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  18123. uniforms.spotLights.value = lights.state.spot;
  18124. uniforms.spotLightShadows.value = lights.state.spotShadow;
  18125. uniforms.rectAreaLights.value = lights.state.rectArea;
  18126. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  18127. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  18128. uniforms.pointLights.value = lights.state.point;
  18129. uniforms.pointLightShadows.value = lights.state.pointShadow;
  18130. uniforms.hemisphereLights.value = lights.state.hemi;
  18131. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  18132. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  18133. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  18134. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  18135. uniforms.spotLightMap.value = lights.state.spotLightMap;
  18136. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  18137. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  18138. // TODO (abelnation): add area lights shadow info to uniforms
  18139. }
  18140. materialProperties.currentProgram = program;
  18141. materialProperties.uniformsList = null;
  18142. return program;
  18143. }
  18144. function getUniformList( materialProperties ) {
  18145. if ( materialProperties.uniformsList === null ) {
  18146. const progUniforms = materialProperties.currentProgram.getUniforms();
  18147. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  18148. }
  18149. return materialProperties.uniformsList;
  18150. }
  18151. function updateCommonMaterialProperties( material, parameters ) {
  18152. const materialProperties = properties.get( material );
  18153. materialProperties.outputColorSpace = parameters.outputColorSpace;
  18154. materialProperties.batching = parameters.batching;
  18155. materialProperties.batchingColor = parameters.batchingColor;
  18156. materialProperties.instancing = parameters.instancing;
  18157. materialProperties.instancingColor = parameters.instancingColor;
  18158. materialProperties.instancingMorph = parameters.instancingMorph;
  18159. materialProperties.skinning = parameters.skinning;
  18160. materialProperties.morphTargets = parameters.morphTargets;
  18161. materialProperties.morphNormals = parameters.morphNormals;
  18162. materialProperties.morphColors = parameters.morphColors;
  18163. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  18164. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  18165. materialProperties.numIntersection = parameters.numClipIntersection;
  18166. materialProperties.vertexAlphas = parameters.vertexAlphas;
  18167. materialProperties.vertexTangents = parameters.vertexTangents;
  18168. materialProperties.toneMapping = parameters.toneMapping;
  18169. }
  18170. function setProgram( camera, scene, geometry, material, object ) {
  18171. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  18172. textures.resetTextureUnits();
  18173. const fog = scene.fog;
  18174. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  18175. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  18176. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  18177. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  18178. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  18179. const morphTargets = !! geometry.morphAttributes.position;
  18180. const morphNormals = !! geometry.morphAttributes.normal;
  18181. const morphColors = !! geometry.morphAttributes.color;
  18182. let toneMapping = NoToneMapping;
  18183. if ( material.toneMapped ) {
  18184. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  18185. toneMapping = _this.toneMapping;
  18186. }
  18187. }
  18188. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  18189. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  18190. const materialProperties = properties.get( material );
  18191. const lights = currentRenderState.state.lights;
  18192. if ( _clippingEnabled === true ) {
  18193. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  18194. const useCache =
  18195. camera === _currentCamera &&
  18196. material.id === _currentMaterialId;
  18197. // we might want to call this function with some ClippingGroup
  18198. // object instead of the material, once it becomes feasible
  18199. // (#8465, #8379)
  18200. clipping.setState( material, camera, useCache );
  18201. }
  18202. }
  18203. //
  18204. let needsProgramChange = false;
  18205. if ( material.version === materialProperties.__version ) {
  18206. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  18207. needsProgramChange = true;
  18208. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  18209. needsProgramChange = true;
  18210. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  18211. needsProgramChange = true;
  18212. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  18213. needsProgramChange = true;
  18214. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  18215. needsProgramChange = true;
  18216. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  18217. needsProgramChange = true;
  18218. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  18219. needsProgramChange = true;
  18220. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  18221. needsProgramChange = true;
  18222. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  18223. needsProgramChange = true;
  18224. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  18225. needsProgramChange = true;
  18226. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  18227. needsProgramChange = true;
  18228. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  18229. needsProgramChange = true;
  18230. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  18231. needsProgramChange = true;
  18232. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  18233. needsProgramChange = true;
  18234. } else if ( materialProperties.envMap !== envMap ) {
  18235. needsProgramChange = true;
  18236. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  18237. needsProgramChange = true;
  18238. } else if ( materialProperties.numClippingPlanes !== undefined &&
  18239. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  18240. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  18241. needsProgramChange = true;
  18242. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  18243. needsProgramChange = true;
  18244. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  18245. needsProgramChange = true;
  18246. } else if ( materialProperties.morphTargets !== morphTargets ) {
  18247. needsProgramChange = true;
  18248. } else if ( materialProperties.morphNormals !== morphNormals ) {
  18249. needsProgramChange = true;
  18250. } else if ( materialProperties.morphColors !== morphColors ) {
  18251. needsProgramChange = true;
  18252. } else if ( materialProperties.toneMapping !== toneMapping ) {
  18253. needsProgramChange = true;
  18254. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  18255. needsProgramChange = true;
  18256. }
  18257. } else {
  18258. needsProgramChange = true;
  18259. materialProperties.__version = material.version;
  18260. }
  18261. //
  18262. let program = materialProperties.currentProgram;
  18263. if ( needsProgramChange === true ) {
  18264. program = getProgram( material, scene, object );
  18265. }
  18266. let refreshProgram = false;
  18267. let refreshMaterial = false;
  18268. let refreshLights = false;
  18269. const p_uniforms = program.getUniforms(),
  18270. m_uniforms = materialProperties.uniforms;
  18271. if ( state.useProgram( program.program ) ) {
  18272. refreshProgram = true;
  18273. refreshMaterial = true;
  18274. refreshLights = true;
  18275. }
  18276. if ( material.id !== _currentMaterialId ) {
  18277. _currentMaterialId = material.id;
  18278. refreshMaterial = true;
  18279. }
  18280. if ( refreshProgram || _currentCamera !== camera ) {
  18281. // common camera uniforms
  18282. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  18283. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  18284. const uCamPos = p_uniforms.map.cameraPosition;
  18285. if ( uCamPos !== undefined ) {
  18286. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  18287. }
  18288. if ( capabilities.logarithmicDepthBuffer ) {
  18289. p_uniforms.setValue( _gl, 'logDepthBufFC',
  18290. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  18291. }
  18292. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  18293. if ( material.isMeshPhongMaterial ||
  18294. material.isMeshToonMaterial ||
  18295. material.isMeshLambertMaterial ||
  18296. material.isMeshBasicMaterial ||
  18297. material.isMeshStandardMaterial ||
  18298. material.isShaderMaterial ) {
  18299. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  18300. }
  18301. if ( _currentCamera !== camera ) {
  18302. _currentCamera = camera;
  18303. // lighting uniforms depend on the camera so enforce an update
  18304. // now, in case this material supports lights - or later, when
  18305. // the next material that does gets activated:
  18306. refreshMaterial = true; // set to true on material change
  18307. refreshLights = true; // remains set until update done
  18308. }
  18309. }
  18310. // skinning and morph target uniforms must be set even if material didn't change
  18311. // auto-setting of texture unit for bone and morph texture must go before other textures
  18312. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  18313. if ( object.isSkinnedMesh ) {
  18314. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  18315. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  18316. const skeleton = object.skeleton;
  18317. if ( skeleton ) {
  18318. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  18319. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  18320. }
  18321. }
  18322. if ( object.isBatchedMesh ) {
  18323. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  18324. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  18325. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  18326. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  18327. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  18328. if ( object._colorsTexture !== null ) {
  18329. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  18330. }
  18331. }
  18332. const morphAttributes = geometry.morphAttributes;
  18333. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  18334. morphtargets.update( object, geometry, program );
  18335. }
  18336. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  18337. materialProperties.receiveShadow = object.receiveShadow;
  18338. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  18339. }
  18340. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  18341. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  18342. m_uniforms.envMap.value = envMap;
  18343. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  18344. }
  18345. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  18346. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  18347. }
  18348. if ( refreshMaterial ) {
  18349. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  18350. if ( materialProperties.needsLights ) {
  18351. // the current material requires lighting info
  18352. // note: all lighting uniforms are always set correctly
  18353. // they simply reference the renderer's state for their
  18354. // values
  18355. //
  18356. // use the current material's .needsUpdate flags to set
  18357. // the GL state when required
  18358. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  18359. }
  18360. // refresh uniforms common to several materials
  18361. if ( fog && material.fog === true ) {
  18362. materials.refreshFogUniforms( m_uniforms, fog );
  18363. }
  18364. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  18365. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18366. }
  18367. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  18368. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18369. material.uniformsNeedUpdate = false;
  18370. }
  18371. if ( material.isSpriteMaterial ) {
  18372. p_uniforms.setValue( _gl, 'center', object.center );
  18373. }
  18374. // common matrices
  18375. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  18376. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  18377. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  18378. // UBOs
  18379. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  18380. const groups = material.uniformsGroups;
  18381. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  18382. const group = groups[ i ];
  18383. uniformsGroups.update( group, program );
  18384. uniformsGroups.bind( group, program );
  18385. }
  18386. }
  18387. return program;
  18388. }
  18389. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18390. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18391. uniforms.ambientLightColor.needsUpdate = value;
  18392. uniforms.lightProbe.needsUpdate = value;
  18393. uniforms.directionalLights.needsUpdate = value;
  18394. uniforms.directionalLightShadows.needsUpdate = value;
  18395. uniforms.pointLights.needsUpdate = value;
  18396. uniforms.pointLightShadows.needsUpdate = value;
  18397. uniforms.spotLights.needsUpdate = value;
  18398. uniforms.spotLightShadows.needsUpdate = value;
  18399. uniforms.rectAreaLights.needsUpdate = value;
  18400. uniforms.hemisphereLights.needsUpdate = value;
  18401. }
  18402. function materialNeedsLights( material ) {
  18403. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  18404. material.isMeshStandardMaterial || material.isShadowMaterial ||
  18405. ( material.isShaderMaterial && material.lights === true );
  18406. }
  18407. this.getActiveCubeFace = function () {
  18408. return _currentActiveCubeFace;
  18409. };
  18410. this.getActiveMipmapLevel = function () {
  18411. return _currentActiveMipmapLevel;
  18412. };
  18413. this.getRenderTarget = function () {
  18414. return _currentRenderTarget;
  18415. };
  18416. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  18417. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  18418. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  18419. const renderTargetProperties = properties.get( renderTarget );
  18420. renderTargetProperties.__hasExternalTextures = true;
  18421. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  18422. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  18423. // The multisample_render_to_texture extension doesn't work properly if there
  18424. // are midframe flushes and an external depth buffer. Disable use of the extension.
  18425. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  18426. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  18427. renderTargetProperties.__useRenderToTexture = false;
  18428. }
  18429. }
  18430. };
  18431. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  18432. const renderTargetProperties = properties.get( renderTarget );
  18433. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  18434. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  18435. };
  18436. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  18437. _currentRenderTarget = renderTarget;
  18438. _currentActiveCubeFace = activeCubeFace;
  18439. _currentActiveMipmapLevel = activeMipmapLevel;
  18440. let useDefaultFramebuffer = true;
  18441. let framebuffer = null;
  18442. let isCube = false;
  18443. let isRenderTarget3D = false;
  18444. if ( renderTarget ) {
  18445. const renderTargetProperties = properties.get( renderTarget );
  18446. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  18447. // We need to make sure to rebind the framebuffer.
  18448. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  18449. useDefaultFramebuffer = false;
  18450. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  18451. textures.setupRenderTarget( renderTarget );
  18452. } else if ( renderTargetProperties.__hasExternalTextures ) {
  18453. // Color and depth texture must be rebound in order for the swapchain to update.
  18454. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  18455. } else if ( renderTarget.depthBuffer ) {
  18456. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  18457. const depthTexture = renderTarget.depthTexture;
  18458. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  18459. // check if the depth texture is compatible
  18460. if (
  18461. depthTexture !== null &&
  18462. properties.has( depthTexture ) &&
  18463. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  18464. ) {
  18465. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  18466. }
  18467. // Swap the depth buffer to the currently attached one
  18468. textures.setupDepthRenderbuffer( renderTarget );
  18469. }
  18470. }
  18471. const texture = renderTarget.texture;
  18472. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18473. isRenderTarget3D = true;
  18474. }
  18475. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18476. if ( renderTarget.isWebGLCubeRenderTarget ) {
  18477. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  18478. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  18479. } else {
  18480. framebuffer = __webglFramebuffer[ activeCubeFace ];
  18481. }
  18482. isCube = true;
  18483. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  18484. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  18485. } else {
  18486. if ( Array.isArray( __webglFramebuffer ) ) {
  18487. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  18488. } else {
  18489. framebuffer = __webglFramebuffer;
  18490. }
  18491. }
  18492. _currentViewport.copy( renderTarget.viewport );
  18493. _currentScissor.copy( renderTarget.scissor );
  18494. _currentScissorTest = renderTarget.scissorTest;
  18495. } else {
  18496. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  18497. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  18498. _currentScissorTest = _scissorTest;
  18499. }
  18500. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18501. if ( framebufferBound && useDefaultFramebuffer ) {
  18502. state.drawBuffers( renderTarget, framebuffer );
  18503. }
  18504. state.viewport( _currentViewport );
  18505. state.scissor( _currentScissor );
  18506. state.setScissorTest( _currentScissorTest );
  18507. if ( isCube ) {
  18508. const textureProperties = properties.get( renderTarget.texture );
  18509. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  18510. } else if ( isRenderTarget3D ) {
  18511. const textureProperties = properties.get( renderTarget.texture );
  18512. const layer = activeCubeFace || 0;
  18513. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  18514. }
  18515. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  18516. };
  18517. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18518. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18519. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18520. return;
  18521. }
  18522. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18523. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18524. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18525. }
  18526. if ( framebuffer ) {
  18527. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18528. try {
  18529. const texture = renderTarget.texture;
  18530. const textureFormat = texture.format;
  18531. const textureType = texture.type;
  18532. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  18533. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18534. return;
  18535. }
  18536. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  18537. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18538. return;
  18539. }
  18540. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18541. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18542. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18543. }
  18544. } finally {
  18545. // restore framebuffer of current render target if necessary
  18546. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18547. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18548. }
  18549. }
  18550. };
  18551. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18552. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18553. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18554. }
  18555. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18556. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18557. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18558. }
  18559. if ( framebuffer ) {
  18560. const texture = renderTarget.texture;
  18561. const textureFormat = texture.format;
  18562. const textureType = texture.type;
  18563. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  18564. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  18565. }
  18566. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  18567. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18568. }
  18569. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18570. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18571. // set the active frame buffer to the one we want to read
  18572. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18573. const glBuffer = _gl.createBuffer();
  18574. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  18575. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  18576. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  18577. _gl.flush();
  18578. // reset the frame buffer to the currently set buffer before waiting
  18579. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18580. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  18581. // check if the commands have finished every 8 ms
  18582. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  18583. await probeAsync( _gl, sync, 4 );
  18584. // read the data and delete the buffer
  18585. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  18586. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  18587. _gl.deleteBuffer( glBuffer );
  18588. _gl.deleteSync( sync );
  18589. return buffer;
  18590. } else {
  18591. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  18592. }
  18593. }
  18594. };
  18595. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  18596. // support previous signature with position first
  18597. if ( texture.isTexture !== true ) {
  18598. // @deprecated, r165
  18599. warnOnce( 'WebGLRenderer: copyFramebufferToTexture function signature has changed.' );
  18600. position = arguments[ 0 ] || null;
  18601. texture = arguments[ 1 ];
  18602. }
  18603. const levelScale = Math.pow( 2, - level );
  18604. const width = Math.floor( texture.image.width * levelScale );
  18605. const height = Math.floor( texture.image.height * levelScale );
  18606. const x = position !== null ? position.x : 0;
  18607. const y = position !== null ? position.y : 0;
  18608. textures.setTexture2D( texture, 0 );
  18609. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  18610. state.unbindTexture();
  18611. };
  18612. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  18613. // support previous signature with dstPosition first
  18614. if ( srcTexture.isTexture !== true ) {
  18615. // @deprecated, r165
  18616. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  18617. dstPosition = arguments[ 0 ] || null;
  18618. srcTexture = arguments[ 1 ];
  18619. dstTexture = arguments[ 2 ];
  18620. level = arguments[ 3 ] || 0;
  18621. srcRegion = null;
  18622. }
  18623. let width, height, minX, minY;
  18624. let dstX, dstY;
  18625. if ( srcRegion !== null ) {
  18626. width = srcRegion.max.x - srcRegion.min.x;
  18627. height = srcRegion.max.y - srcRegion.min.y;
  18628. minX = srcRegion.min.x;
  18629. minY = srcRegion.min.y;
  18630. } else {
  18631. width = srcTexture.image.width;
  18632. height = srcTexture.image.height;
  18633. minX = 0;
  18634. minY = 0;
  18635. }
  18636. if ( dstPosition !== null ) {
  18637. dstX = dstPosition.x;
  18638. dstY = dstPosition.y;
  18639. } else {
  18640. dstX = 0;
  18641. dstY = 0;
  18642. }
  18643. const glFormat = utils.convert( dstTexture.format );
  18644. const glType = utils.convert( dstTexture.type );
  18645. textures.setTexture2D( dstTexture, 0 );
  18646. // As another texture upload may have changed pixelStorei
  18647. // parameters, make sure they are correct for the dstTexture
  18648. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18649. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18650. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18651. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18652. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18653. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18654. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18655. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18656. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18657. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18658. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18659. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  18660. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  18661. if ( srcTexture.isDataTexture ) {
  18662. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  18663. } else {
  18664. if ( srcTexture.isCompressedTexture ) {
  18665. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  18666. } else {
  18667. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  18668. }
  18669. }
  18670. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  18671. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  18672. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  18673. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  18674. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  18675. // Generate mipmaps only when copying level 0
  18676. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  18677. state.unbindTexture();
  18678. };
  18679. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  18680. // support previous signature with source box first
  18681. if ( srcTexture.isTexture !== true ) {
  18682. // @deprecated, r165
  18683. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  18684. srcRegion = arguments[ 0 ] || null;
  18685. dstPosition = arguments[ 1 ] || null;
  18686. srcTexture = arguments[ 2 ];
  18687. dstTexture = arguments[ 3 ];
  18688. level = arguments[ 4 ] || 0;
  18689. }
  18690. let width, height, depth, minX, minY, minZ;
  18691. let dstX, dstY, dstZ;
  18692. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18693. if ( srcRegion !== null ) {
  18694. width = srcRegion.max.x - srcRegion.min.x;
  18695. height = srcRegion.max.y - srcRegion.min.y;
  18696. depth = srcRegion.max.z - srcRegion.min.z;
  18697. minX = srcRegion.min.x;
  18698. minY = srcRegion.min.y;
  18699. minZ = srcRegion.min.z;
  18700. } else {
  18701. width = image.width;
  18702. height = image.height;
  18703. depth = image.depth;
  18704. minX = 0;
  18705. minY = 0;
  18706. minZ = 0;
  18707. }
  18708. if ( dstPosition !== null ) {
  18709. dstX = dstPosition.x;
  18710. dstY = dstPosition.y;
  18711. dstZ = dstPosition.z;
  18712. } else {
  18713. dstX = 0;
  18714. dstY = 0;
  18715. dstZ = 0;
  18716. }
  18717. const glFormat = utils.convert( dstTexture.format );
  18718. const glType = utils.convert( dstTexture.type );
  18719. let glTarget;
  18720. if ( dstTexture.isData3DTexture ) {
  18721. textures.setTexture3D( dstTexture, 0 );
  18722. glTarget = _gl.TEXTURE_3D;
  18723. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  18724. textures.setTexture2DArray( dstTexture, 0 );
  18725. glTarget = _gl.TEXTURE_2D_ARRAY;
  18726. } else {
  18727. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  18728. return;
  18729. }
  18730. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18731. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18732. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18733. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18734. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18735. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18736. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18737. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18738. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18739. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18740. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  18741. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  18742. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  18743. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  18744. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  18745. } else {
  18746. if ( dstTexture.isCompressedArrayTexture ) {
  18747. _gl.compressedTexSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  18748. } else {
  18749. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  18750. }
  18751. }
  18752. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  18753. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  18754. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  18755. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  18756. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  18757. // Generate mipmaps only when copying level 0
  18758. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  18759. state.unbindTexture();
  18760. };
  18761. this.initRenderTarget = function ( target ) {
  18762. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  18763. textures.setupRenderTarget( target );
  18764. }
  18765. };
  18766. this.initTexture = function ( texture ) {
  18767. if ( texture.isCubeTexture ) {
  18768. textures.setTextureCube( texture, 0 );
  18769. } else if ( texture.isData3DTexture ) {
  18770. textures.setTexture3D( texture, 0 );
  18771. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18772. textures.setTexture2DArray( texture, 0 );
  18773. } else {
  18774. textures.setTexture2D( texture, 0 );
  18775. }
  18776. state.unbindTexture();
  18777. };
  18778. this.resetState = function () {
  18779. _currentActiveCubeFace = 0;
  18780. _currentActiveMipmapLevel = 0;
  18781. _currentRenderTarget = null;
  18782. state.reset();
  18783. bindingStates.reset();
  18784. };
  18785. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18786. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18787. }
  18788. }
  18789. get coordinateSystem() {
  18790. return WebGLCoordinateSystem;
  18791. }
  18792. get outputColorSpace() {
  18793. return this._outputColorSpace;
  18794. }
  18795. set outputColorSpace( colorSpace ) {
  18796. this._outputColorSpace = colorSpace;
  18797. const gl = this.getContext();
  18798. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18799. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18800. }
  18801. }
  18802. class FogExp2 {
  18803. constructor( color, density = 0.00025 ) {
  18804. this.isFogExp2 = true;
  18805. this.name = '';
  18806. this.color = new Color( color );
  18807. this.density = density;
  18808. }
  18809. clone() {
  18810. return new FogExp2( this.color, this.density );
  18811. }
  18812. toJSON( /* meta */ ) {
  18813. return {
  18814. type: 'FogExp2',
  18815. name: this.name,
  18816. color: this.color.getHex(),
  18817. density: this.density
  18818. };
  18819. }
  18820. }
  18821. class Fog {
  18822. constructor( color, near = 1, far = 1000 ) {
  18823. this.isFog = true;
  18824. this.name = '';
  18825. this.color = new Color( color );
  18826. this.near = near;
  18827. this.far = far;
  18828. }
  18829. clone() {
  18830. return new Fog( this.color, this.near, this.far );
  18831. }
  18832. toJSON( /* meta */ ) {
  18833. return {
  18834. type: 'Fog',
  18835. name: this.name,
  18836. color: this.color.getHex(),
  18837. near: this.near,
  18838. far: this.far
  18839. };
  18840. }
  18841. }
  18842. class Scene extends Object3D {
  18843. constructor() {
  18844. super();
  18845. this.isScene = true;
  18846. this.type = 'Scene';
  18847. this.background = null;
  18848. this.environment = null;
  18849. this.fog = null;
  18850. this.backgroundBlurriness = 0;
  18851. this.backgroundIntensity = 1;
  18852. this.backgroundRotation = new Euler();
  18853. this.environmentIntensity = 1;
  18854. this.environmentRotation = new Euler();
  18855. this.overrideMaterial = null;
  18856. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18857. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18858. }
  18859. }
  18860. copy( source, recursive ) {
  18861. super.copy( source, recursive );
  18862. if ( source.background !== null ) this.background = source.background.clone();
  18863. if ( source.environment !== null ) this.environment = source.environment.clone();
  18864. if ( source.fog !== null ) this.fog = source.fog.clone();
  18865. this.backgroundBlurriness = source.backgroundBlurriness;
  18866. this.backgroundIntensity = source.backgroundIntensity;
  18867. this.backgroundRotation.copy( source.backgroundRotation );
  18868. this.environmentIntensity = source.environmentIntensity;
  18869. this.environmentRotation.copy( source.environmentRotation );
  18870. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18871. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18872. return this;
  18873. }
  18874. toJSON( meta ) {
  18875. const data = super.toJSON( meta );
  18876. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18877. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18878. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18879. data.object.backgroundRotation = this.backgroundRotation.toArray();
  18880. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  18881. data.object.environmentRotation = this.environmentRotation.toArray();
  18882. return data;
  18883. }
  18884. }
  18885. class InterleavedBuffer {
  18886. constructor( array, stride ) {
  18887. this.isInterleavedBuffer = true;
  18888. this.array = array;
  18889. this.stride = stride;
  18890. this.count = array !== undefined ? array.length / stride : 0;
  18891. this.usage = StaticDrawUsage;
  18892. this.updateRanges = [];
  18893. this.version = 0;
  18894. this.uuid = generateUUID();
  18895. }
  18896. onUploadCallback() {}
  18897. set needsUpdate( value ) {
  18898. if ( value === true ) this.version ++;
  18899. }
  18900. setUsage( value ) {
  18901. this.usage = value;
  18902. return this;
  18903. }
  18904. addUpdateRange( start, count ) {
  18905. this.updateRanges.push( { start, count } );
  18906. }
  18907. clearUpdateRanges() {
  18908. this.updateRanges.length = 0;
  18909. }
  18910. copy( source ) {
  18911. this.array = new source.array.constructor( source.array );
  18912. this.count = source.count;
  18913. this.stride = source.stride;
  18914. this.usage = source.usage;
  18915. return this;
  18916. }
  18917. copyAt( index1, attribute, index2 ) {
  18918. index1 *= this.stride;
  18919. index2 *= attribute.stride;
  18920. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18921. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18922. }
  18923. return this;
  18924. }
  18925. set( value, offset = 0 ) {
  18926. this.array.set( value, offset );
  18927. return this;
  18928. }
  18929. clone( data ) {
  18930. if ( data.arrayBuffers === undefined ) {
  18931. data.arrayBuffers = {};
  18932. }
  18933. if ( this.array.buffer._uuid === undefined ) {
  18934. this.array.buffer._uuid = generateUUID();
  18935. }
  18936. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18937. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18938. }
  18939. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18940. const ib = new this.constructor( array, this.stride );
  18941. ib.setUsage( this.usage );
  18942. return ib;
  18943. }
  18944. onUpload( callback ) {
  18945. this.onUploadCallback = callback;
  18946. return this;
  18947. }
  18948. toJSON( data ) {
  18949. if ( data.arrayBuffers === undefined ) {
  18950. data.arrayBuffers = {};
  18951. }
  18952. // generate UUID for array buffer if necessary
  18953. if ( this.array.buffer._uuid === undefined ) {
  18954. this.array.buffer._uuid = generateUUID();
  18955. }
  18956. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18957. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18958. }
  18959. //
  18960. return {
  18961. uuid: this.uuid,
  18962. buffer: this.array.buffer._uuid,
  18963. type: this.array.constructor.name,
  18964. stride: this.stride
  18965. };
  18966. }
  18967. }
  18968. const _vector$6 = /*@__PURE__*/ new Vector3();
  18969. class InterleavedBufferAttribute {
  18970. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18971. this.isInterleavedBufferAttribute = true;
  18972. this.name = '';
  18973. this.data = interleavedBuffer;
  18974. this.itemSize = itemSize;
  18975. this.offset = offset;
  18976. this.normalized = normalized;
  18977. }
  18978. get count() {
  18979. return this.data.count;
  18980. }
  18981. get array() {
  18982. return this.data.array;
  18983. }
  18984. set needsUpdate( value ) {
  18985. this.data.needsUpdate = value;
  18986. }
  18987. applyMatrix4( m ) {
  18988. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18989. _vector$6.fromBufferAttribute( this, i );
  18990. _vector$6.applyMatrix4( m );
  18991. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18992. }
  18993. return this;
  18994. }
  18995. applyNormalMatrix( m ) {
  18996. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18997. _vector$6.fromBufferAttribute( this, i );
  18998. _vector$6.applyNormalMatrix( m );
  18999. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  19000. }
  19001. return this;
  19002. }
  19003. transformDirection( m ) {
  19004. for ( let i = 0, l = this.count; i < l; i ++ ) {
  19005. _vector$6.fromBufferAttribute( this, i );
  19006. _vector$6.transformDirection( m );
  19007. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  19008. }
  19009. return this;
  19010. }
  19011. getComponent( index, component ) {
  19012. let value = this.array[ index * this.data.stride + this.offset + component ];
  19013. if ( this.normalized ) value = denormalize( value, this.array );
  19014. return value;
  19015. }
  19016. setComponent( index, component, value ) {
  19017. if ( this.normalized ) value = normalize( value, this.array );
  19018. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  19019. return this;
  19020. }
  19021. setX( index, x ) {
  19022. if ( this.normalized ) x = normalize( x, this.array );
  19023. this.data.array[ index * this.data.stride + this.offset ] = x;
  19024. return this;
  19025. }
  19026. setY( index, y ) {
  19027. if ( this.normalized ) y = normalize( y, this.array );
  19028. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  19029. return this;
  19030. }
  19031. setZ( index, z ) {
  19032. if ( this.normalized ) z = normalize( z, this.array );
  19033. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  19034. return this;
  19035. }
  19036. setW( index, w ) {
  19037. if ( this.normalized ) w = normalize( w, this.array );
  19038. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  19039. return this;
  19040. }
  19041. getX( index ) {
  19042. let x = this.data.array[ index * this.data.stride + this.offset ];
  19043. if ( this.normalized ) x = denormalize( x, this.array );
  19044. return x;
  19045. }
  19046. getY( index ) {
  19047. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  19048. if ( this.normalized ) y = denormalize( y, this.array );
  19049. return y;
  19050. }
  19051. getZ( index ) {
  19052. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  19053. if ( this.normalized ) z = denormalize( z, this.array );
  19054. return z;
  19055. }
  19056. getW( index ) {
  19057. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  19058. if ( this.normalized ) w = denormalize( w, this.array );
  19059. return w;
  19060. }
  19061. setXY( index, x, y ) {
  19062. index = index * this.data.stride + this.offset;
  19063. if ( this.normalized ) {
  19064. x = normalize( x, this.array );
  19065. y = normalize( y, this.array );
  19066. }
  19067. this.data.array[ index + 0 ] = x;
  19068. this.data.array[ index + 1 ] = y;
  19069. return this;
  19070. }
  19071. setXYZ( index, x, y, z ) {
  19072. index = index * this.data.stride + this.offset;
  19073. if ( this.normalized ) {
  19074. x = normalize( x, this.array );
  19075. y = normalize( y, this.array );
  19076. z = normalize( z, this.array );
  19077. }
  19078. this.data.array[ index + 0 ] = x;
  19079. this.data.array[ index + 1 ] = y;
  19080. this.data.array[ index + 2 ] = z;
  19081. return this;
  19082. }
  19083. setXYZW( index, x, y, z, w ) {
  19084. index = index * this.data.stride + this.offset;
  19085. if ( this.normalized ) {
  19086. x = normalize( x, this.array );
  19087. y = normalize( y, this.array );
  19088. z = normalize( z, this.array );
  19089. w = normalize( w, this.array );
  19090. }
  19091. this.data.array[ index + 0 ] = x;
  19092. this.data.array[ index + 1 ] = y;
  19093. this.data.array[ index + 2 ] = z;
  19094. this.data.array[ index + 3 ] = w;
  19095. return this;
  19096. }
  19097. clone( data ) {
  19098. if ( data === undefined ) {
  19099. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  19100. const array = [];
  19101. for ( let i = 0; i < this.count; i ++ ) {
  19102. const index = i * this.data.stride + this.offset;
  19103. for ( let j = 0; j < this.itemSize; j ++ ) {
  19104. array.push( this.data.array[ index + j ] );
  19105. }
  19106. }
  19107. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  19108. } else {
  19109. if ( data.interleavedBuffers === undefined ) {
  19110. data.interleavedBuffers = {};
  19111. }
  19112. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  19113. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  19114. }
  19115. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  19116. }
  19117. }
  19118. toJSON( data ) {
  19119. if ( data === undefined ) {
  19120. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  19121. const array = [];
  19122. for ( let i = 0; i < this.count; i ++ ) {
  19123. const index = i * this.data.stride + this.offset;
  19124. for ( let j = 0; j < this.itemSize; j ++ ) {
  19125. array.push( this.data.array[ index + j ] );
  19126. }
  19127. }
  19128. // de-interleave data and save it as an ordinary buffer attribute for now
  19129. return {
  19130. itemSize: this.itemSize,
  19131. type: this.array.constructor.name,
  19132. array: array,
  19133. normalized: this.normalized
  19134. };
  19135. } else {
  19136. // save as true interleaved attribute
  19137. if ( data.interleavedBuffers === undefined ) {
  19138. data.interleavedBuffers = {};
  19139. }
  19140. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  19141. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  19142. }
  19143. return {
  19144. isInterleavedBufferAttribute: true,
  19145. itemSize: this.itemSize,
  19146. data: this.data.uuid,
  19147. offset: this.offset,
  19148. normalized: this.normalized
  19149. };
  19150. }
  19151. }
  19152. }
  19153. class SpriteMaterial extends Material {
  19154. constructor( parameters ) {
  19155. super();
  19156. this.isSpriteMaterial = true;
  19157. this.type = 'SpriteMaterial';
  19158. this.color = new Color( 0xffffff );
  19159. this.map = null;
  19160. this.alphaMap = null;
  19161. this.rotation = 0;
  19162. this.sizeAttenuation = true;
  19163. this.transparent = true;
  19164. this.fog = true;
  19165. this.setValues( parameters );
  19166. }
  19167. copy( source ) {
  19168. super.copy( source );
  19169. this.color.copy( source.color );
  19170. this.map = source.map;
  19171. this.alphaMap = source.alphaMap;
  19172. this.rotation = source.rotation;
  19173. this.sizeAttenuation = source.sizeAttenuation;
  19174. this.fog = source.fog;
  19175. return this;
  19176. }
  19177. }
  19178. let _geometry;
  19179. const _intersectPoint = /*@__PURE__*/ new Vector3();
  19180. const _worldScale = /*@__PURE__*/ new Vector3();
  19181. const _mvPosition = /*@__PURE__*/ new Vector3();
  19182. const _alignedPosition = /*@__PURE__*/ new Vector2();
  19183. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  19184. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  19185. const _vA = /*@__PURE__*/ new Vector3();
  19186. const _vB = /*@__PURE__*/ new Vector3();
  19187. const _vC = /*@__PURE__*/ new Vector3();
  19188. const _uvA = /*@__PURE__*/ new Vector2();
  19189. const _uvB = /*@__PURE__*/ new Vector2();
  19190. const _uvC = /*@__PURE__*/ new Vector2();
  19191. class Sprite extends Object3D {
  19192. constructor( material = new SpriteMaterial() ) {
  19193. super();
  19194. this.isSprite = true;
  19195. this.type = 'Sprite';
  19196. if ( _geometry === undefined ) {
  19197. _geometry = new BufferGeometry();
  19198. const float32Array = new Float32Array( [
  19199. - 0.5, - 0.5, 0, 0, 0,
  19200. 0.5, - 0.5, 0, 1, 0,
  19201. 0.5, 0.5, 0, 1, 1,
  19202. - 0.5, 0.5, 0, 0, 1
  19203. ] );
  19204. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  19205. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  19206. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  19207. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  19208. }
  19209. this.geometry = _geometry;
  19210. this.material = material;
  19211. this.center = new Vector2( 0.5, 0.5 );
  19212. }
  19213. raycast( raycaster, intersects ) {
  19214. if ( raycaster.camera === null ) {
  19215. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  19216. }
  19217. _worldScale.setFromMatrixScale( this.matrixWorld );
  19218. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  19219. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  19220. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  19221. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  19222. _worldScale.multiplyScalar( - _mvPosition.z );
  19223. }
  19224. const rotation = this.material.rotation;
  19225. let sin, cos;
  19226. if ( rotation !== 0 ) {
  19227. cos = Math.cos( rotation );
  19228. sin = Math.sin( rotation );
  19229. }
  19230. const center = this.center;
  19231. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  19232. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  19233. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  19234. _uvA.set( 0, 0 );
  19235. _uvB.set( 1, 0 );
  19236. _uvC.set( 1, 1 );
  19237. // check first triangle
  19238. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  19239. if ( intersect === null ) {
  19240. // check second triangle
  19241. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  19242. _uvB.set( 0, 1 );
  19243. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  19244. if ( intersect === null ) {
  19245. return;
  19246. }
  19247. }
  19248. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  19249. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19250. intersects.push( {
  19251. distance: distance,
  19252. point: _intersectPoint.clone(),
  19253. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  19254. face: null,
  19255. object: this
  19256. } );
  19257. }
  19258. copy( source, recursive ) {
  19259. super.copy( source, recursive );
  19260. if ( source.center !== undefined ) this.center.copy( source.center );
  19261. this.material = source.material;
  19262. return this;
  19263. }
  19264. }
  19265. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  19266. // compute position in camera space
  19267. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  19268. // to check if rotation is not zero
  19269. if ( sin !== undefined ) {
  19270. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  19271. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  19272. } else {
  19273. _rotatedPosition.copy( _alignedPosition );
  19274. }
  19275. vertexPosition.copy( mvPosition );
  19276. vertexPosition.x += _rotatedPosition.x;
  19277. vertexPosition.y += _rotatedPosition.y;
  19278. // transform to world space
  19279. vertexPosition.applyMatrix4( _viewWorldMatrix );
  19280. }
  19281. const _v1$2 = /*@__PURE__*/ new Vector3();
  19282. const _v2$1 = /*@__PURE__*/ new Vector3();
  19283. class LOD extends Object3D {
  19284. constructor() {
  19285. super();
  19286. this._currentLevel = 0;
  19287. this.type = 'LOD';
  19288. Object.defineProperties( this, {
  19289. levels: {
  19290. enumerable: true,
  19291. value: []
  19292. },
  19293. isLOD: {
  19294. value: true,
  19295. }
  19296. } );
  19297. this.autoUpdate = true;
  19298. }
  19299. copy( source ) {
  19300. super.copy( source, false );
  19301. const levels = source.levels;
  19302. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  19303. const level = levels[ i ];
  19304. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  19305. }
  19306. this.autoUpdate = source.autoUpdate;
  19307. return this;
  19308. }
  19309. addLevel( object, distance = 0, hysteresis = 0 ) {
  19310. distance = Math.abs( distance );
  19311. const levels = this.levels;
  19312. let l;
  19313. for ( l = 0; l < levels.length; l ++ ) {
  19314. if ( distance < levels[ l ].distance ) {
  19315. break;
  19316. }
  19317. }
  19318. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  19319. this.add( object );
  19320. return this;
  19321. }
  19322. getCurrentLevel() {
  19323. return this._currentLevel;
  19324. }
  19325. getObjectForDistance( distance ) {
  19326. const levels = this.levels;
  19327. if ( levels.length > 0 ) {
  19328. let i, l;
  19329. for ( i = 1, l = levels.length; i < l; i ++ ) {
  19330. let levelDistance = levels[ i ].distance;
  19331. if ( levels[ i ].object.visible ) {
  19332. levelDistance -= levelDistance * levels[ i ].hysteresis;
  19333. }
  19334. if ( distance < levelDistance ) {
  19335. break;
  19336. }
  19337. }
  19338. return levels[ i - 1 ].object;
  19339. }
  19340. return null;
  19341. }
  19342. raycast( raycaster, intersects ) {
  19343. const levels = this.levels;
  19344. if ( levels.length > 0 ) {
  19345. _v1$2.setFromMatrixPosition( this.matrixWorld );
  19346. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  19347. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  19348. }
  19349. }
  19350. update( camera ) {
  19351. const levels = this.levels;
  19352. if ( levels.length > 1 ) {
  19353. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  19354. _v2$1.setFromMatrixPosition( this.matrixWorld );
  19355. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  19356. levels[ 0 ].object.visible = true;
  19357. let i, l;
  19358. for ( i = 1, l = levels.length; i < l; i ++ ) {
  19359. let levelDistance = levels[ i ].distance;
  19360. if ( levels[ i ].object.visible ) {
  19361. levelDistance -= levelDistance * levels[ i ].hysteresis;
  19362. }
  19363. if ( distance >= levelDistance ) {
  19364. levels[ i - 1 ].object.visible = false;
  19365. levels[ i ].object.visible = true;
  19366. } else {
  19367. break;
  19368. }
  19369. }
  19370. this._currentLevel = i - 1;
  19371. for ( ; i < l; i ++ ) {
  19372. levels[ i ].object.visible = false;
  19373. }
  19374. }
  19375. }
  19376. toJSON( meta ) {
  19377. const data = super.toJSON( meta );
  19378. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  19379. data.object.levels = [];
  19380. const levels = this.levels;
  19381. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  19382. const level = levels[ i ];
  19383. data.object.levels.push( {
  19384. object: level.object.uuid,
  19385. distance: level.distance,
  19386. hysteresis: level.hysteresis
  19387. } );
  19388. }
  19389. return data;
  19390. }
  19391. }
  19392. const _basePosition = /*@__PURE__*/ new Vector3();
  19393. const _skinIndex = /*@__PURE__*/ new Vector4();
  19394. const _skinWeight = /*@__PURE__*/ new Vector4();
  19395. const _vector3 = /*@__PURE__*/ new Vector3();
  19396. const _matrix4 = /*@__PURE__*/ new Matrix4();
  19397. const _vertex = /*@__PURE__*/ new Vector3();
  19398. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19399. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  19400. const _ray$2 = /*@__PURE__*/ new Ray();
  19401. class SkinnedMesh extends Mesh {
  19402. constructor( geometry, material ) {
  19403. super( geometry, material );
  19404. this.isSkinnedMesh = true;
  19405. this.type = 'SkinnedMesh';
  19406. this.bindMode = AttachedBindMode;
  19407. this.bindMatrix = new Matrix4();
  19408. this.bindMatrixInverse = new Matrix4();
  19409. this.boundingBox = null;
  19410. this.boundingSphere = null;
  19411. }
  19412. computeBoundingBox() {
  19413. const geometry = this.geometry;
  19414. if ( this.boundingBox === null ) {
  19415. this.boundingBox = new Box3();
  19416. }
  19417. this.boundingBox.makeEmpty();
  19418. const positionAttribute = geometry.getAttribute( 'position' );
  19419. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19420. this.getVertexPosition( i, _vertex );
  19421. this.boundingBox.expandByPoint( _vertex );
  19422. }
  19423. }
  19424. computeBoundingSphere() {
  19425. const geometry = this.geometry;
  19426. if ( this.boundingSphere === null ) {
  19427. this.boundingSphere = new Sphere();
  19428. }
  19429. this.boundingSphere.makeEmpty();
  19430. const positionAttribute = geometry.getAttribute( 'position' );
  19431. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19432. this.getVertexPosition( i, _vertex );
  19433. this.boundingSphere.expandByPoint( _vertex );
  19434. }
  19435. }
  19436. copy( source, recursive ) {
  19437. super.copy( source, recursive );
  19438. this.bindMode = source.bindMode;
  19439. this.bindMatrix.copy( source.bindMatrix );
  19440. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  19441. this.skeleton = source.skeleton;
  19442. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19443. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19444. return this;
  19445. }
  19446. raycast( raycaster, intersects ) {
  19447. const material = this.material;
  19448. const matrixWorld = this.matrixWorld;
  19449. if ( material === undefined ) return;
  19450. // test with bounding sphere in world space
  19451. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19452. _sphere$4.copy( this.boundingSphere );
  19453. _sphere$4.applyMatrix4( matrixWorld );
  19454. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19455. // convert ray to local space of skinned mesh
  19456. _inverseMatrix$2.copy( matrixWorld ).invert();
  19457. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  19458. // test with bounding box in local space
  19459. if ( this.boundingBox !== null ) {
  19460. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  19461. }
  19462. // test for intersections with geometry
  19463. this._computeIntersections( raycaster, intersects, _ray$2 );
  19464. }
  19465. getVertexPosition( index, target ) {
  19466. super.getVertexPosition( index, target );
  19467. this.applyBoneTransform( index, target );
  19468. return target;
  19469. }
  19470. bind( skeleton, bindMatrix ) {
  19471. this.skeleton = skeleton;
  19472. if ( bindMatrix === undefined ) {
  19473. this.updateMatrixWorld( true );
  19474. this.skeleton.calculateInverses();
  19475. bindMatrix = this.matrixWorld;
  19476. }
  19477. this.bindMatrix.copy( bindMatrix );
  19478. this.bindMatrixInverse.copy( bindMatrix ).invert();
  19479. }
  19480. pose() {
  19481. this.skeleton.pose();
  19482. }
  19483. normalizeSkinWeights() {
  19484. const vector = new Vector4();
  19485. const skinWeight = this.geometry.attributes.skinWeight;
  19486. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  19487. vector.fromBufferAttribute( skinWeight, i );
  19488. const scale = 1.0 / vector.manhattanLength();
  19489. if ( scale !== Infinity ) {
  19490. vector.multiplyScalar( scale );
  19491. } else {
  19492. vector.set( 1, 0, 0, 0 ); // do something reasonable
  19493. }
  19494. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  19495. }
  19496. }
  19497. updateMatrixWorld( force ) {
  19498. super.updateMatrixWorld( force );
  19499. if ( this.bindMode === AttachedBindMode ) {
  19500. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  19501. } else if ( this.bindMode === DetachedBindMode ) {
  19502. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  19503. } else {
  19504. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  19505. }
  19506. }
  19507. applyBoneTransform( index, vector ) {
  19508. const skeleton = this.skeleton;
  19509. const geometry = this.geometry;
  19510. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  19511. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  19512. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  19513. vector.set( 0, 0, 0 );
  19514. for ( let i = 0; i < 4; i ++ ) {
  19515. const weight = _skinWeight.getComponent( i );
  19516. if ( weight !== 0 ) {
  19517. const boneIndex = _skinIndex.getComponent( i );
  19518. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  19519. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  19520. }
  19521. }
  19522. return vector.applyMatrix4( this.bindMatrixInverse );
  19523. }
  19524. }
  19525. class Bone extends Object3D {
  19526. constructor() {
  19527. super();
  19528. this.isBone = true;
  19529. this.type = 'Bone';
  19530. }
  19531. }
  19532. class DataTexture extends Texture {
  19533. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  19534. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  19535. this.isDataTexture = true;
  19536. this.image = { data: data, width: width, height: height };
  19537. this.generateMipmaps = false;
  19538. this.flipY = false;
  19539. this.unpackAlignment = 1;
  19540. }
  19541. }
  19542. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  19543. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  19544. class Skeleton {
  19545. constructor( bones = [], boneInverses = [] ) {
  19546. this.uuid = generateUUID();
  19547. this.bones = bones.slice( 0 );
  19548. this.boneInverses = boneInverses;
  19549. this.boneMatrices = null;
  19550. this.boneTexture = null;
  19551. this.init();
  19552. }
  19553. init() {
  19554. const bones = this.bones;
  19555. const boneInverses = this.boneInverses;
  19556. this.boneMatrices = new Float32Array( bones.length * 16 );
  19557. // calculate inverse bone matrices if necessary
  19558. if ( boneInverses.length === 0 ) {
  19559. this.calculateInverses();
  19560. } else {
  19561. // handle special case
  19562. if ( bones.length !== boneInverses.length ) {
  19563. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19564. this.boneInverses = [];
  19565. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19566. this.boneInverses.push( new Matrix4() );
  19567. }
  19568. }
  19569. }
  19570. }
  19571. calculateInverses() {
  19572. this.boneInverses.length = 0;
  19573. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19574. const inverse = new Matrix4();
  19575. if ( this.bones[ i ] ) {
  19576. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19577. }
  19578. this.boneInverses.push( inverse );
  19579. }
  19580. }
  19581. pose() {
  19582. // recover the bind-time world matrices
  19583. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19584. const bone = this.bones[ i ];
  19585. if ( bone ) {
  19586. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19587. }
  19588. }
  19589. // compute the local matrices, positions, rotations and scales
  19590. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19591. const bone = this.bones[ i ];
  19592. if ( bone ) {
  19593. if ( bone.parent && bone.parent.isBone ) {
  19594. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19595. bone.matrix.multiply( bone.matrixWorld );
  19596. } else {
  19597. bone.matrix.copy( bone.matrixWorld );
  19598. }
  19599. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19600. }
  19601. }
  19602. }
  19603. update() {
  19604. const bones = this.bones;
  19605. const boneInverses = this.boneInverses;
  19606. const boneMatrices = this.boneMatrices;
  19607. const boneTexture = this.boneTexture;
  19608. // flatten bone matrices to array
  19609. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19610. // compute the offset between the current and the original transform
  19611. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  19612. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19613. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19614. }
  19615. if ( boneTexture !== null ) {
  19616. boneTexture.needsUpdate = true;
  19617. }
  19618. }
  19619. clone() {
  19620. return new Skeleton( this.bones, this.boneInverses );
  19621. }
  19622. computeBoneTexture() {
  19623. // layout (1 matrix = 4 pixels)
  19624. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19625. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19626. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19627. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19628. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19629. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19630. size = Math.ceil( size / 4 ) * 4;
  19631. size = Math.max( size, 4 );
  19632. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19633. boneMatrices.set( this.boneMatrices ); // copy current values
  19634. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19635. boneTexture.needsUpdate = true;
  19636. this.boneMatrices = boneMatrices;
  19637. this.boneTexture = boneTexture;
  19638. return this;
  19639. }
  19640. getBoneByName( name ) {
  19641. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19642. const bone = this.bones[ i ];
  19643. if ( bone.name === name ) {
  19644. return bone;
  19645. }
  19646. }
  19647. return undefined;
  19648. }
  19649. dispose( ) {
  19650. if ( this.boneTexture !== null ) {
  19651. this.boneTexture.dispose();
  19652. this.boneTexture = null;
  19653. }
  19654. }
  19655. fromJSON( json, bones ) {
  19656. this.uuid = json.uuid;
  19657. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19658. const uuid = json.bones[ i ];
  19659. let bone = bones[ uuid ];
  19660. if ( bone === undefined ) {
  19661. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  19662. bone = new Bone();
  19663. }
  19664. this.bones.push( bone );
  19665. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19666. }
  19667. this.init();
  19668. return this;
  19669. }
  19670. toJSON() {
  19671. const data = {
  19672. metadata: {
  19673. version: 4.6,
  19674. type: 'Skeleton',
  19675. generator: 'Skeleton.toJSON'
  19676. },
  19677. bones: [],
  19678. boneInverses: []
  19679. };
  19680. data.uuid = this.uuid;
  19681. const bones = this.bones;
  19682. const boneInverses = this.boneInverses;
  19683. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19684. const bone = bones[ i ];
  19685. data.bones.push( bone.uuid );
  19686. const boneInverse = boneInverses[ i ];
  19687. data.boneInverses.push( boneInverse.toArray() );
  19688. }
  19689. return data;
  19690. }
  19691. }
  19692. class InstancedBufferAttribute extends BufferAttribute {
  19693. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19694. super( array, itemSize, normalized );
  19695. this.isInstancedBufferAttribute = true;
  19696. this.meshPerAttribute = meshPerAttribute;
  19697. }
  19698. copy( source ) {
  19699. super.copy( source );
  19700. this.meshPerAttribute = source.meshPerAttribute;
  19701. return this;
  19702. }
  19703. toJSON() {
  19704. const data = super.toJSON();
  19705. data.meshPerAttribute = this.meshPerAttribute;
  19706. data.isInstancedBufferAttribute = true;
  19707. return data;
  19708. }
  19709. }
  19710. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19711. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19712. const _instanceIntersects = [];
  19713. const _box3 = /*@__PURE__*/ new Box3();
  19714. const _identity = /*@__PURE__*/ new Matrix4();
  19715. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19716. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19717. class InstancedMesh extends Mesh {
  19718. constructor( geometry, material, count ) {
  19719. super( geometry, material );
  19720. this.isInstancedMesh = true;
  19721. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19722. this.instanceColor = null;
  19723. this.morphTexture = null;
  19724. this.count = count;
  19725. this.boundingBox = null;
  19726. this.boundingSphere = null;
  19727. for ( let i = 0; i < count; i ++ ) {
  19728. this.setMatrixAt( i, _identity );
  19729. }
  19730. }
  19731. computeBoundingBox() {
  19732. const geometry = this.geometry;
  19733. const count = this.count;
  19734. if ( this.boundingBox === null ) {
  19735. this.boundingBox = new Box3();
  19736. }
  19737. if ( geometry.boundingBox === null ) {
  19738. geometry.computeBoundingBox();
  19739. }
  19740. this.boundingBox.makeEmpty();
  19741. for ( let i = 0; i < count; i ++ ) {
  19742. this.getMatrixAt( i, _instanceLocalMatrix );
  19743. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19744. this.boundingBox.union( _box3 );
  19745. }
  19746. }
  19747. computeBoundingSphere() {
  19748. const geometry = this.geometry;
  19749. const count = this.count;
  19750. if ( this.boundingSphere === null ) {
  19751. this.boundingSphere = new Sphere();
  19752. }
  19753. if ( geometry.boundingSphere === null ) {
  19754. geometry.computeBoundingSphere();
  19755. }
  19756. this.boundingSphere.makeEmpty();
  19757. for ( let i = 0; i < count; i ++ ) {
  19758. this.getMatrixAt( i, _instanceLocalMatrix );
  19759. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19760. this.boundingSphere.union( _sphere$3 );
  19761. }
  19762. }
  19763. copy( source, recursive ) {
  19764. super.copy( source, recursive );
  19765. this.instanceMatrix.copy( source.instanceMatrix );
  19766. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19767. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19768. this.count = source.count;
  19769. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19770. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19771. return this;
  19772. }
  19773. getColorAt( index, color ) {
  19774. color.fromArray( this.instanceColor.array, index * 3 );
  19775. }
  19776. getMatrixAt( index, matrix ) {
  19777. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19778. }
  19779. getMorphAt( index, object ) {
  19780. const objectInfluences = object.morphTargetInfluences;
  19781. const array = this.morphTexture.source.data.data;
  19782. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19783. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19784. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19785. objectInfluences[ i ] = array[ dataIndex + i ];
  19786. }
  19787. }
  19788. raycast( raycaster, intersects ) {
  19789. const matrixWorld = this.matrixWorld;
  19790. const raycastTimes = this.count;
  19791. _mesh$1.geometry = this.geometry;
  19792. _mesh$1.material = this.material;
  19793. if ( _mesh$1.material === undefined ) return;
  19794. // test with bounding sphere first
  19795. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19796. _sphere$3.copy( this.boundingSphere );
  19797. _sphere$3.applyMatrix4( matrixWorld );
  19798. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  19799. // now test each instance
  19800. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19801. // calculate the world matrix for each instance
  19802. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19803. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19804. // the mesh represents this single instance
  19805. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19806. _mesh$1.raycast( raycaster, _instanceIntersects );
  19807. // process the result of raycast
  19808. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19809. const intersect = _instanceIntersects[ i ];
  19810. intersect.instanceId = instanceId;
  19811. intersect.object = this;
  19812. intersects.push( intersect );
  19813. }
  19814. _instanceIntersects.length = 0;
  19815. }
  19816. }
  19817. setColorAt( index, color ) {
  19818. if ( this.instanceColor === null ) {
  19819. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19820. }
  19821. color.toArray( this.instanceColor.array, index * 3 );
  19822. }
  19823. setMatrixAt( index, matrix ) {
  19824. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19825. }
  19826. setMorphAt( index, object ) {
  19827. const objectInfluences = object.morphTargetInfluences;
  19828. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19829. if ( this.morphTexture === null ) {
  19830. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19831. }
  19832. const array = this.morphTexture.source.data.data;
  19833. let morphInfluencesSum = 0;
  19834. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19835. morphInfluencesSum += objectInfluences[ i ];
  19836. }
  19837. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19838. const dataIndex = len * index;
  19839. array[ dataIndex ] = morphBaseInfluence;
  19840. array.set( objectInfluences, dataIndex + 1 );
  19841. }
  19842. updateMorphTargets() {
  19843. }
  19844. dispose() {
  19845. this.dispatchEvent( { type: 'dispose' } );
  19846. if ( this.morphTexture !== null ) {
  19847. this.morphTexture.dispose();
  19848. this.morphTexture = null;
  19849. }
  19850. return this;
  19851. }
  19852. }
  19853. function sortOpaque( a, b ) {
  19854. return a.z - b.z;
  19855. }
  19856. function sortTransparent( a, b ) {
  19857. return b.z - a.z;
  19858. }
  19859. class MultiDrawRenderList {
  19860. constructor() {
  19861. this.index = 0;
  19862. this.pool = [];
  19863. this.list = [];
  19864. }
  19865. push( drawRange, z, index ) {
  19866. const pool = this.pool;
  19867. const list = this.list;
  19868. if ( this.index >= pool.length ) {
  19869. pool.push( {
  19870. start: - 1,
  19871. count: - 1,
  19872. z: - 1,
  19873. index: - 1,
  19874. } );
  19875. }
  19876. const item = pool[ this.index ];
  19877. list.push( item );
  19878. this.index ++;
  19879. item.start = drawRange.start;
  19880. item.count = drawRange.count;
  19881. item.z = z;
  19882. item.index = index;
  19883. }
  19884. reset() {
  19885. this.list.length = 0;
  19886. this.index = 0;
  19887. }
  19888. }
  19889. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19890. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  19891. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  19892. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19893. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19894. const _frustum = /*@__PURE__*/ new Frustum();
  19895. const _box$1 = /*@__PURE__*/ new Box3();
  19896. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19897. const _vector$5 = /*@__PURE__*/ new Vector3();
  19898. const _forward = /*@__PURE__*/ new Vector3();
  19899. const _temp = /*@__PURE__*/ new Vector3();
  19900. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19901. const _mesh = /*@__PURE__*/ new Mesh();
  19902. const _batchIntersects = [];
  19903. // @TODO: SkinnedMesh support?
  19904. // @TODO: geometry.groups support?
  19905. // @TODO: geometry.drawRange support?
  19906. // @TODO: geometry.morphAttributes support?
  19907. // @TODO: Support uniform parameter per geometry
  19908. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  19909. // copies data from attribute "src" into "target" starting at "targetOffset"
  19910. function copyAttributeData( src, target, targetOffset = 0 ) {
  19911. const itemSize = target.itemSize;
  19912. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19913. // use the component getters and setters if the array data cannot
  19914. // be copied directly
  19915. const vertexCount = src.count;
  19916. for ( let i = 0; i < vertexCount; i ++ ) {
  19917. for ( let c = 0; c < itemSize; c ++ ) {
  19918. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19919. }
  19920. }
  19921. } else {
  19922. // faster copy approach using typed array set function
  19923. target.array.set( src.array, targetOffset * itemSize );
  19924. }
  19925. target.needsUpdate = true;
  19926. }
  19927. class BatchedMesh extends Mesh {
  19928. get maxInstanceCount() {
  19929. return this._maxInstanceCount;
  19930. }
  19931. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19932. super( new BufferGeometry(), material );
  19933. this.isBatchedMesh = true;
  19934. this.perObjectFrustumCulled = true;
  19935. this.sortObjects = true;
  19936. this.boundingBox = null;
  19937. this.boundingSphere = null;
  19938. this.customSort = null;
  19939. // stores visible, active, and geometry id per object
  19940. this._drawInfo = [];
  19941. // geometry information
  19942. this._drawRanges = [];
  19943. this._reservedRanges = [];
  19944. this._bounds = [];
  19945. this._maxInstanceCount = maxInstanceCount;
  19946. this._maxVertexCount = maxVertexCount;
  19947. this._maxIndexCount = maxIndexCount;
  19948. this._geometryInitialized = false;
  19949. this._geometryCount = 0;
  19950. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19951. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19952. this._multiDrawCount = 0;
  19953. this._multiDrawInstances = null;
  19954. this._visibilityChanged = true;
  19955. // Local matrix per geometry by using data texture
  19956. this._matricesTexture = null;
  19957. this._indirectTexture = null;
  19958. this._colorsTexture = null;
  19959. this._initMatricesTexture();
  19960. this._initIndirectTexture();
  19961. }
  19962. _initMatricesTexture() {
  19963. // layout (1 matrix = 4 pixels)
  19964. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19965. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19966. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19967. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19968. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19969. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19970. size = Math.ceil( size / 4 ) * 4;
  19971. size = Math.max( size, 4 );
  19972. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19973. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19974. this._matricesTexture = matricesTexture;
  19975. }
  19976. _initIndirectTexture() {
  19977. let size = Math.sqrt( this._maxInstanceCount );
  19978. size = Math.ceil( size );
  19979. const indirectArray = new Uint32Array( size * size );
  19980. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19981. this._indirectTexture = indirectTexture;
  19982. }
  19983. _initColorsTexture() {
  19984. let size = Math.sqrt( this._maxInstanceCount );
  19985. size = Math.ceil( size );
  19986. // 4 floats per RGBA pixel initialized to white
  19987. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19988. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19989. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19990. this._colorsTexture = colorsTexture;
  19991. }
  19992. _initializeGeometry( reference ) {
  19993. const geometry = this.geometry;
  19994. const maxVertexCount = this._maxVertexCount;
  19995. const maxIndexCount = this._maxIndexCount;
  19996. if ( this._geometryInitialized === false ) {
  19997. for ( const attributeName in reference.attributes ) {
  19998. const srcAttribute = reference.getAttribute( attributeName );
  19999. const { array, itemSize, normalized } = srcAttribute;
  20000. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20001. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20002. geometry.setAttribute( attributeName, dstAttribute );
  20003. }
  20004. if ( reference.getIndex() !== null ) {
  20005. // Reserve last u16 index for primitive restart.
  20006. const indexArray = maxVertexCount > 65535
  20007. ? new Uint32Array( maxIndexCount )
  20008. : new Uint16Array( maxIndexCount );
  20009. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20010. }
  20011. this._geometryInitialized = true;
  20012. }
  20013. }
  20014. // Make sure the geometry is compatible with the existing combined geometry attributes
  20015. _validateGeometry( geometry ) {
  20016. // check to ensure the geometries are using consistent attributes and indices
  20017. const batchGeometry = this.geometry;
  20018. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20019. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  20020. }
  20021. for ( const attributeName in batchGeometry.attributes ) {
  20022. if ( ! geometry.hasAttribute( attributeName ) ) {
  20023. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20024. }
  20025. const srcAttribute = geometry.getAttribute( attributeName );
  20026. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20027. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20028. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20029. }
  20030. }
  20031. }
  20032. setCustomSort( func ) {
  20033. this.customSort = func;
  20034. return this;
  20035. }
  20036. computeBoundingBox() {
  20037. if ( this.boundingBox === null ) {
  20038. this.boundingBox = new Box3();
  20039. }
  20040. const boundingBox = this.boundingBox;
  20041. const drawInfo = this._drawInfo;
  20042. boundingBox.makeEmpty();
  20043. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  20044. if ( drawInfo[ i ].active === false ) continue;
  20045. const geometryId = drawInfo[ i ].geometryIndex;
  20046. this.getMatrixAt( i, _matrix$1 );
  20047. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20048. boundingBox.union( _box$1 );
  20049. }
  20050. }
  20051. computeBoundingSphere() {
  20052. if ( this.boundingSphere === null ) {
  20053. this.boundingSphere = new Sphere();
  20054. }
  20055. const boundingSphere = this.boundingSphere;
  20056. const drawInfo = this._drawInfo;
  20057. boundingSphere.makeEmpty();
  20058. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  20059. if ( drawInfo[ i ].active === false ) continue;
  20060. const geometryId = drawInfo[ i ].geometryIndex;
  20061. this.getMatrixAt( i, _matrix$1 );
  20062. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20063. boundingSphere.union( _sphere$2 );
  20064. }
  20065. }
  20066. addInstance( geometryId ) {
  20067. // ensure we're not over geometry
  20068. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  20069. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  20070. }
  20071. this._drawInfo.push( {
  20072. visible: true,
  20073. active: true,
  20074. geometryIndex: geometryId,
  20075. } );
  20076. // initialize the matrix
  20077. const drawId = this._drawInfo.length - 1;
  20078. const matricesTexture = this._matricesTexture;
  20079. const matricesArray = matricesTexture.image.data;
  20080. _identityMatrix.toArray( matricesArray, drawId * 16 );
  20081. matricesTexture.needsUpdate = true;
  20082. const colorsTexture = this._colorsTexture;
  20083. if ( colorsTexture ) {
  20084. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20085. colorsTexture.needsUpdate = true;
  20086. }
  20087. return drawId;
  20088. }
  20089. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  20090. this._initializeGeometry( geometry );
  20091. this._validateGeometry( geometry );
  20092. // ensure we're not over geometry
  20093. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  20094. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  20095. }
  20096. // get the necessary range fo the geometry
  20097. const reservedRange = {
  20098. vertexStart: - 1,
  20099. vertexCount: - 1,
  20100. indexStart: - 1,
  20101. indexCount: - 1,
  20102. };
  20103. let lastRange = null;
  20104. const reservedRanges = this._reservedRanges;
  20105. const drawRanges = this._drawRanges;
  20106. const bounds = this._bounds;
  20107. if ( this._geometryCount !== 0 ) {
  20108. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  20109. }
  20110. if ( vertexCount === - 1 ) {
  20111. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  20112. } else {
  20113. reservedRange.vertexCount = vertexCount;
  20114. }
  20115. if ( lastRange === null ) {
  20116. reservedRange.vertexStart = 0;
  20117. } else {
  20118. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  20119. }
  20120. const index = geometry.getIndex();
  20121. const hasIndex = index !== null;
  20122. if ( hasIndex ) {
  20123. if ( indexCount === - 1 ) {
  20124. reservedRange.indexCount = index.count;
  20125. } else {
  20126. reservedRange.indexCount = indexCount;
  20127. }
  20128. if ( lastRange === null ) {
  20129. reservedRange.indexStart = 0;
  20130. } else {
  20131. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  20132. }
  20133. }
  20134. if (
  20135. reservedRange.indexStart !== - 1 &&
  20136. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  20137. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  20138. ) {
  20139. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20140. }
  20141. // update id
  20142. const geometryId = this._geometryCount;
  20143. this._geometryCount ++;
  20144. // add the reserved range and draw range objects
  20145. reservedRanges.push( reservedRange );
  20146. drawRanges.push( {
  20147. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  20148. count: - 1
  20149. } );
  20150. bounds.push( {
  20151. boxInitialized: false,
  20152. box: new Box3(),
  20153. sphereInitialized: false,
  20154. sphere: new Sphere()
  20155. } );
  20156. // update the geometry
  20157. this.setGeometryAt( geometryId, geometry );
  20158. return geometryId;
  20159. }
  20160. setGeometryAt( geometryId, geometry ) {
  20161. if ( geometryId >= this._geometryCount ) {
  20162. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  20163. }
  20164. this._validateGeometry( geometry );
  20165. const batchGeometry = this.geometry;
  20166. const hasIndex = batchGeometry.getIndex() !== null;
  20167. const dstIndex = batchGeometry.getIndex();
  20168. const srcIndex = geometry.getIndex();
  20169. const reservedRange = this._reservedRanges[ geometryId ];
  20170. if (
  20171. hasIndex &&
  20172. srcIndex.count > reservedRange.indexCount ||
  20173. geometry.attributes.position.count > reservedRange.vertexCount
  20174. ) {
  20175. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  20176. }
  20177. // copy geometry over
  20178. const vertexStart = reservedRange.vertexStart;
  20179. const vertexCount = reservedRange.vertexCount;
  20180. for ( const attributeName in batchGeometry.attributes ) {
  20181. // copy attribute data
  20182. const srcAttribute = geometry.getAttribute( attributeName );
  20183. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20184. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20185. // fill the rest in with zeroes
  20186. const itemSize = srcAttribute.itemSize;
  20187. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  20188. const index = vertexStart + i;
  20189. for ( let c = 0; c < itemSize; c ++ ) {
  20190. dstAttribute.setComponent( index, c, 0 );
  20191. }
  20192. }
  20193. dstAttribute.needsUpdate = true;
  20194. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  20195. }
  20196. // copy index
  20197. if ( hasIndex ) {
  20198. const indexStart = reservedRange.indexStart;
  20199. // copy index data over
  20200. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20201. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20202. }
  20203. // fill the rest in with zeroes
  20204. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  20205. dstIndex.setX( indexStart + i, vertexStart );
  20206. }
  20207. dstIndex.needsUpdate = true;
  20208. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  20209. }
  20210. // store the bounding boxes
  20211. const bound = this._bounds[ geometryId ];
  20212. if ( geometry.boundingBox !== null ) {
  20213. bound.box.copy( geometry.boundingBox );
  20214. bound.boxInitialized = true;
  20215. } else {
  20216. bound.boxInitialized = false;
  20217. }
  20218. if ( geometry.boundingSphere !== null ) {
  20219. bound.sphere.copy( geometry.boundingSphere );
  20220. bound.sphereInitialized = true;
  20221. } else {
  20222. bound.sphereInitialized = false;
  20223. }
  20224. // set drawRange count
  20225. const drawRange = this._drawRanges[ geometryId ];
  20226. const posAttr = geometry.getAttribute( 'position' );
  20227. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  20228. this._visibilityChanged = true;
  20229. return geometryId;
  20230. }
  20231. /*
  20232. deleteGeometry( geometryId ) {
  20233. // TODO: delete geometry and associated instances
  20234. }
  20235. */
  20236. /*
  20237. deleteInstance( instanceId ) {
  20238. // Note: User needs to call optimize() afterward to pack the data.
  20239. const drawInfo = this._drawInfo;
  20240. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20241. return this;
  20242. }
  20243. drawInfo[ instanceId ].active = false;
  20244. this._visibilityChanged = true;
  20245. return this;
  20246. }
  20247. */
  20248. // get bounding box and compute it if it doesn't exist
  20249. getBoundingBoxAt( geometryId, target ) {
  20250. if ( geometryId >= this._geometryCount ) {
  20251. return null;
  20252. }
  20253. // compute bounding box
  20254. const bound = this._bounds[ geometryId ];
  20255. const box = bound.box;
  20256. const geometry = this.geometry;
  20257. if ( bound.boxInitialized === false ) {
  20258. box.makeEmpty();
  20259. const index = geometry.index;
  20260. const position = geometry.attributes.position;
  20261. const drawRange = this._drawRanges[ geometryId ];
  20262. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  20263. let iv = i;
  20264. if ( index ) {
  20265. iv = index.getX( iv );
  20266. }
  20267. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20268. }
  20269. bound.boxInitialized = true;
  20270. }
  20271. target.copy( box );
  20272. return target;
  20273. }
  20274. // get bounding sphere and compute it if it doesn't exist
  20275. getBoundingSphereAt( geometryId, target ) {
  20276. if ( geometryId >= this._geometryCount ) {
  20277. return null;
  20278. }
  20279. // compute bounding sphere
  20280. const bound = this._bounds[ geometryId ];
  20281. const sphere = bound.sphere;
  20282. const geometry = this.geometry;
  20283. if ( bound.sphereInitialized === false ) {
  20284. sphere.makeEmpty();
  20285. this.getBoundingBoxAt( geometryId, _box$1 );
  20286. _box$1.getCenter( sphere.center );
  20287. const index = geometry.index;
  20288. const position = geometry.attributes.position;
  20289. const drawRange = this._drawRanges[ geometryId ];
  20290. let maxRadiusSq = 0;
  20291. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  20292. let iv = i;
  20293. if ( index ) {
  20294. iv = index.getX( iv );
  20295. }
  20296. _vector$5.fromBufferAttribute( position, iv );
  20297. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20298. }
  20299. sphere.radius = Math.sqrt( maxRadiusSq );
  20300. bound.sphereInitialized = true;
  20301. }
  20302. target.copy( sphere );
  20303. return target;
  20304. }
  20305. setMatrixAt( instanceId, matrix ) {
  20306. // @TODO: Map geometryId to index of the arrays because
  20307. // optimize() can make geometryId mismatch the index
  20308. const drawInfo = this._drawInfo;
  20309. const matricesTexture = this._matricesTexture;
  20310. const matricesArray = this._matricesTexture.image.data;
  20311. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20312. return this;
  20313. }
  20314. matrix.toArray( matricesArray, instanceId * 16 );
  20315. matricesTexture.needsUpdate = true;
  20316. return this;
  20317. }
  20318. getMatrixAt( instanceId, matrix ) {
  20319. const drawInfo = this._drawInfo;
  20320. const matricesArray = this._matricesTexture.image.data;
  20321. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20322. return null;
  20323. }
  20324. return matrix.fromArray( matricesArray, instanceId * 16 );
  20325. }
  20326. setColorAt( instanceId, color ) {
  20327. if ( this._colorsTexture === null ) {
  20328. this._initColorsTexture();
  20329. }
  20330. // @TODO: Map id to index of the arrays because
  20331. // optimize() can make id mismatch the index
  20332. const colorsTexture = this._colorsTexture;
  20333. const colorsArray = this._colorsTexture.image.data;
  20334. const drawInfo = this._drawInfo;
  20335. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20336. return this;
  20337. }
  20338. color.toArray( colorsArray, instanceId * 4 );
  20339. colorsTexture.needsUpdate = true;
  20340. return this;
  20341. }
  20342. getColorAt( instanceId, color ) {
  20343. const colorsArray = this._colorsTexture.image.data;
  20344. const drawInfo = this._drawInfo;
  20345. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20346. return null;
  20347. }
  20348. return color.fromArray( colorsArray, instanceId * 4 );
  20349. }
  20350. setVisibleAt( instanceId, value ) {
  20351. // if the geometry is out of range, not active, or visibility state
  20352. // does not change then return early
  20353. const drawInfo = this._drawInfo;
  20354. if (
  20355. instanceId >= drawInfo.length ||
  20356. drawInfo[ instanceId ].active === false ||
  20357. drawInfo[ instanceId ].visible === value
  20358. ) {
  20359. return this;
  20360. }
  20361. drawInfo[ instanceId ].visible = value;
  20362. this._visibilityChanged = true;
  20363. return this;
  20364. }
  20365. getVisibleAt( instanceId ) {
  20366. // return early if the geometry is out of range or not active
  20367. const drawInfo = this._drawInfo;
  20368. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  20369. return false;
  20370. }
  20371. return drawInfo[ instanceId ].visible;
  20372. }
  20373. raycast( raycaster, intersects ) {
  20374. const drawInfo = this._drawInfo;
  20375. const drawRanges = this._drawRanges;
  20376. const matrixWorld = this.matrixWorld;
  20377. const batchGeometry = this.geometry;
  20378. // iterate over each geometry
  20379. _mesh.material = this.material;
  20380. _mesh.geometry.index = batchGeometry.index;
  20381. _mesh.geometry.attributes = batchGeometry.attributes;
  20382. if ( _mesh.geometry.boundingBox === null ) {
  20383. _mesh.geometry.boundingBox = new Box3();
  20384. }
  20385. if ( _mesh.geometry.boundingSphere === null ) {
  20386. _mesh.geometry.boundingSphere = new Sphere();
  20387. }
  20388. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  20389. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  20390. continue;
  20391. }
  20392. const geometryId = drawInfo[ i ].geometryIndex;
  20393. const drawRange = drawRanges[ geometryId ];
  20394. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  20395. // ge the intersects
  20396. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20397. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20398. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20399. _mesh.raycast( raycaster, _batchIntersects );
  20400. // add batch id to the intersects
  20401. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20402. const intersect = _batchIntersects[ j ];
  20403. intersect.object = this;
  20404. intersect.batchId = i;
  20405. intersects.push( intersect );
  20406. }
  20407. _batchIntersects.length = 0;
  20408. }
  20409. _mesh.material = null;
  20410. _mesh.geometry.index = null;
  20411. _mesh.geometry.attributes = {};
  20412. _mesh.geometry.setDrawRange( 0, Infinity );
  20413. }
  20414. copy( source ) {
  20415. super.copy( source );
  20416. this.geometry = source.geometry.clone();
  20417. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20418. this.sortObjects = source.sortObjects;
  20419. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20420. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20421. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  20422. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  20423. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  20424. this._bounds = source._bounds.map( bound => ( {
  20425. boxInitialized: bound.boxInitialized,
  20426. box: bound.box.clone(),
  20427. sphereInitialized: bound.sphereInitialized,
  20428. sphere: bound.sphere.clone()
  20429. } ) );
  20430. this._maxInstanceCount = source._maxInstanceCount;
  20431. this._maxVertexCount = source._maxVertexCount;
  20432. this._maxIndexCount = source._maxIndexCount;
  20433. this._geometryInitialized = source._geometryInitialized;
  20434. this._geometryCount = source._geometryCount;
  20435. this._multiDrawCounts = source._multiDrawCounts.slice();
  20436. this._multiDrawStarts = source._multiDrawStarts.slice();
  20437. this._matricesTexture = source._matricesTexture.clone();
  20438. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20439. if ( this._colorsTexture !== null ) {
  20440. this._colorsTexture = source._colorsTexture.clone();
  20441. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20442. }
  20443. return this;
  20444. }
  20445. dispose() {
  20446. // Assuming the geometry is not shared with other meshes
  20447. this.geometry.dispose();
  20448. this._matricesTexture.dispose();
  20449. this._matricesTexture = null;
  20450. this._indirectTexture.dispose();
  20451. this._indirectTexture = null;
  20452. if ( this._colorsTexture !== null ) {
  20453. this._colorsTexture.dispose();
  20454. this._colorsTexture = null;
  20455. }
  20456. return this;
  20457. }
  20458. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20459. // if visibility has not changed and frustum culling and object sorting is not required
  20460. // then skip iterating over all items
  20461. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20462. return;
  20463. }
  20464. // the indexed version of the multi draw function requires specifying the start
  20465. // offset in bytes.
  20466. const index = geometry.getIndex();
  20467. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20468. const drawInfo = this._drawInfo;
  20469. const multiDrawStarts = this._multiDrawStarts;
  20470. const multiDrawCounts = this._multiDrawCounts;
  20471. const drawRanges = this._drawRanges;
  20472. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20473. const indirectTexture = this._indirectTexture;
  20474. const indirectArray = indirectTexture.image.data;
  20475. // prepare the frustum in the local frame
  20476. if ( perObjectFrustumCulled ) {
  20477. _projScreenMatrix$2
  20478. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20479. .multiply( this.matrixWorld );
  20480. _frustum.setFromProjectionMatrix(
  20481. _projScreenMatrix$2,
  20482. renderer.coordinateSystem
  20483. );
  20484. }
  20485. let count = 0;
  20486. if ( this.sortObjects ) {
  20487. // get the camera position in the local frame
  20488. _invMatrixWorld.copy( this.matrixWorld ).invert();
  20489. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  20490. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  20491. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  20492. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  20493. const geometryId = drawInfo[ i ].geometryIndex;
  20494. // get the bounds in world space
  20495. this.getMatrixAt( i, _matrix$1 );
  20496. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20497. // determine whether the batched geometry is within the frustum
  20498. let culled = false;
  20499. if ( perObjectFrustumCulled ) {
  20500. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20501. }
  20502. if ( ! culled ) {
  20503. // get the distance from camera used for sorting
  20504. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  20505. _renderList.push( drawRanges[ geometryId ], z, i );
  20506. }
  20507. }
  20508. }
  20509. // Sort the draw ranges and prep for rendering
  20510. const list = _renderList.list;
  20511. const customSort = this.customSort;
  20512. if ( customSort === null ) {
  20513. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20514. } else {
  20515. customSort.call( this, list, camera );
  20516. }
  20517. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20518. const item = list[ i ];
  20519. multiDrawStarts[ count ] = item.start * bytesPerElement;
  20520. multiDrawCounts[ count ] = item.count;
  20521. indirectArray[ count ] = item.index;
  20522. count ++;
  20523. }
  20524. _renderList.reset();
  20525. } else {
  20526. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  20527. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  20528. const geometryId = drawInfo[ i ].geometryIndex;
  20529. // determine whether the batched geometry is within the frustum
  20530. let culled = false;
  20531. if ( perObjectFrustumCulled ) {
  20532. // get the bounds in world space
  20533. this.getMatrixAt( i, _matrix$1 );
  20534. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20535. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20536. }
  20537. if ( ! culled ) {
  20538. const range = drawRanges[ geometryId ];
  20539. multiDrawStarts[ count ] = range.start * bytesPerElement;
  20540. multiDrawCounts[ count ] = range.count;
  20541. indirectArray[ count ] = i;
  20542. count ++;
  20543. }
  20544. }
  20545. }
  20546. }
  20547. indirectTexture.needsUpdate = true;
  20548. this._multiDrawCount = count;
  20549. this._visibilityChanged = false;
  20550. }
  20551. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20552. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20553. }
  20554. }
  20555. class LineBasicMaterial extends Material {
  20556. constructor( parameters ) {
  20557. super();
  20558. this.isLineBasicMaterial = true;
  20559. this.type = 'LineBasicMaterial';
  20560. this.color = new Color( 0xffffff );
  20561. this.map = null;
  20562. this.linewidth = 1;
  20563. this.linecap = 'round';
  20564. this.linejoin = 'round';
  20565. this.fog = true;
  20566. this.setValues( parameters );
  20567. }
  20568. copy( source ) {
  20569. super.copy( source );
  20570. this.color.copy( source.color );
  20571. this.map = source.map;
  20572. this.linewidth = source.linewidth;
  20573. this.linecap = source.linecap;
  20574. this.linejoin = source.linejoin;
  20575. this.fog = source.fog;
  20576. return this;
  20577. }
  20578. }
  20579. const _vStart = /*@__PURE__*/ new Vector3();
  20580. const _vEnd = /*@__PURE__*/ new Vector3();
  20581. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20582. const _ray$1 = /*@__PURE__*/ new Ray();
  20583. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20584. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20585. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20586. class Line extends Object3D {
  20587. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20588. super();
  20589. this.isLine = true;
  20590. this.type = 'Line';
  20591. this.geometry = geometry;
  20592. this.material = material;
  20593. this.updateMorphTargets();
  20594. }
  20595. copy( source, recursive ) {
  20596. super.copy( source, recursive );
  20597. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20598. this.geometry = source.geometry;
  20599. return this;
  20600. }
  20601. computeLineDistances() {
  20602. const geometry = this.geometry;
  20603. // we assume non-indexed geometry
  20604. if ( geometry.index === null ) {
  20605. const positionAttribute = geometry.attributes.position;
  20606. const lineDistances = [ 0 ];
  20607. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20608. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20609. _vEnd.fromBufferAttribute( positionAttribute, i );
  20610. lineDistances[ i ] = lineDistances[ i - 1 ];
  20611. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20612. }
  20613. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20614. } else {
  20615. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20616. }
  20617. return this;
  20618. }
  20619. raycast( raycaster, intersects ) {
  20620. const geometry = this.geometry;
  20621. const matrixWorld = this.matrixWorld;
  20622. const threshold = raycaster.params.Line.threshold;
  20623. const drawRange = geometry.drawRange;
  20624. // Checking boundingSphere distance to ray
  20625. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20626. _sphere$1.copy( geometry.boundingSphere );
  20627. _sphere$1.applyMatrix4( matrixWorld );
  20628. _sphere$1.radius += threshold;
  20629. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20630. //
  20631. _inverseMatrix$1.copy( matrixWorld ).invert();
  20632. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20633. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20634. const localThresholdSq = localThreshold * localThreshold;
  20635. const step = this.isLineSegments ? 2 : 1;
  20636. const index = geometry.index;
  20637. const attributes = geometry.attributes;
  20638. const positionAttribute = attributes.position;
  20639. if ( index !== null ) {
  20640. const start = Math.max( 0, drawRange.start );
  20641. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20642. for ( let i = start, l = end - 1; i < l; i += step ) {
  20643. const a = index.getX( i );
  20644. const b = index.getX( i + 1 );
  20645. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  20646. if ( intersect ) {
  20647. intersects.push( intersect );
  20648. }
  20649. }
  20650. if ( this.isLineLoop ) {
  20651. const a = index.getX( end - 1 );
  20652. const b = index.getX( start );
  20653. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  20654. if ( intersect ) {
  20655. intersects.push( intersect );
  20656. }
  20657. }
  20658. } else {
  20659. const start = Math.max( 0, drawRange.start );
  20660. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20661. for ( let i = start, l = end - 1; i < l; i += step ) {
  20662. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  20663. if ( intersect ) {
  20664. intersects.push( intersect );
  20665. }
  20666. }
  20667. if ( this.isLineLoop ) {
  20668. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  20669. if ( intersect ) {
  20670. intersects.push( intersect );
  20671. }
  20672. }
  20673. }
  20674. }
  20675. updateMorphTargets() {
  20676. const geometry = this.geometry;
  20677. const morphAttributes = geometry.morphAttributes;
  20678. const keys = Object.keys( morphAttributes );
  20679. if ( keys.length > 0 ) {
  20680. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20681. if ( morphAttribute !== undefined ) {
  20682. this.morphTargetInfluences = [];
  20683. this.morphTargetDictionary = {};
  20684. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20685. const name = morphAttribute[ m ].name || String( m );
  20686. this.morphTargetInfluences.push( 0 );
  20687. this.morphTargetDictionary[ name ] = m;
  20688. }
  20689. }
  20690. }
  20691. }
  20692. }
  20693. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  20694. const positionAttribute = object.geometry.attributes.position;
  20695. _vStart.fromBufferAttribute( positionAttribute, a );
  20696. _vEnd.fromBufferAttribute( positionAttribute, b );
  20697. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20698. if ( distSq > thresholdSq ) return;
  20699. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20700. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20701. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20702. return {
  20703. distance: distance,
  20704. // What do we want? intersection point on the ray or on the segment??
  20705. // point: raycaster.ray.at( distance ),
  20706. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20707. index: a,
  20708. face: null,
  20709. faceIndex: null,
  20710. object: object
  20711. };
  20712. }
  20713. const _start = /*@__PURE__*/ new Vector3();
  20714. const _end = /*@__PURE__*/ new Vector3();
  20715. class LineSegments extends Line {
  20716. constructor( geometry, material ) {
  20717. super( geometry, material );
  20718. this.isLineSegments = true;
  20719. this.type = 'LineSegments';
  20720. }
  20721. computeLineDistances() {
  20722. const geometry = this.geometry;
  20723. // we assume non-indexed geometry
  20724. if ( geometry.index === null ) {
  20725. const positionAttribute = geometry.attributes.position;
  20726. const lineDistances = [];
  20727. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20728. _start.fromBufferAttribute( positionAttribute, i );
  20729. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20730. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20731. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20732. }
  20733. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20734. } else {
  20735. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20736. }
  20737. return this;
  20738. }
  20739. }
  20740. class LineLoop extends Line {
  20741. constructor( geometry, material ) {
  20742. super( geometry, material );
  20743. this.isLineLoop = true;
  20744. this.type = 'LineLoop';
  20745. }
  20746. }
  20747. class PointsMaterial extends Material {
  20748. constructor( parameters ) {
  20749. super();
  20750. this.isPointsMaterial = true;
  20751. this.type = 'PointsMaterial';
  20752. this.color = new Color( 0xffffff );
  20753. this.map = null;
  20754. this.alphaMap = null;
  20755. this.size = 1;
  20756. this.sizeAttenuation = true;
  20757. this.fog = true;
  20758. this.setValues( parameters );
  20759. }
  20760. copy( source ) {
  20761. super.copy( source );
  20762. this.color.copy( source.color );
  20763. this.map = source.map;
  20764. this.alphaMap = source.alphaMap;
  20765. this.size = source.size;
  20766. this.sizeAttenuation = source.sizeAttenuation;
  20767. this.fog = source.fog;
  20768. return this;
  20769. }
  20770. }
  20771. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20772. const _ray = /*@__PURE__*/ new Ray();
  20773. const _sphere = /*@__PURE__*/ new Sphere();
  20774. const _position$2 = /*@__PURE__*/ new Vector3();
  20775. class Points extends Object3D {
  20776. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20777. super();
  20778. this.isPoints = true;
  20779. this.type = 'Points';
  20780. this.geometry = geometry;
  20781. this.material = material;
  20782. this.updateMorphTargets();
  20783. }
  20784. copy( source, recursive ) {
  20785. super.copy( source, recursive );
  20786. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20787. this.geometry = source.geometry;
  20788. return this;
  20789. }
  20790. raycast( raycaster, intersects ) {
  20791. const geometry = this.geometry;
  20792. const matrixWorld = this.matrixWorld;
  20793. const threshold = raycaster.params.Points.threshold;
  20794. const drawRange = geometry.drawRange;
  20795. // Checking boundingSphere distance to ray
  20796. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20797. _sphere.copy( geometry.boundingSphere );
  20798. _sphere.applyMatrix4( matrixWorld );
  20799. _sphere.radius += threshold;
  20800. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20801. //
  20802. _inverseMatrix.copy( matrixWorld ).invert();
  20803. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20804. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20805. const localThresholdSq = localThreshold * localThreshold;
  20806. const index = geometry.index;
  20807. const attributes = geometry.attributes;
  20808. const positionAttribute = attributes.position;
  20809. if ( index !== null ) {
  20810. const start = Math.max( 0, drawRange.start );
  20811. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20812. for ( let i = start, il = end; i < il; i ++ ) {
  20813. const a = index.getX( i );
  20814. _position$2.fromBufferAttribute( positionAttribute, a );
  20815. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20816. }
  20817. } else {
  20818. const start = Math.max( 0, drawRange.start );
  20819. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20820. for ( let i = start, l = end; i < l; i ++ ) {
  20821. _position$2.fromBufferAttribute( positionAttribute, i );
  20822. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20823. }
  20824. }
  20825. }
  20826. updateMorphTargets() {
  20827. const geometry = this.geometry;
  20828. const morphAttributes = geometry.morphAttributes;
  20829. const keys = Object.keys( morphAttributes );
  20830. if ( keys.length > 0 ) {
  20831. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20832. if ( morphAttribute !== undefined ) {
  20833. this.morphTargetInfluences = [];
  20834. this.morphTargetDictionary = {};
  20835. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20836. const name = morphAttribute[ m ].name || String( m );
  20837. this.morphTargetInfluences.push( 0 );
  20838. this.morphTargetDictionary[ name ] = m;
  20839. }
  20840. }
  20841. }
  20842. }
  20843. }
  20844. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20845. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20846. if ( rayPointDistanceSq < localThresholdSq ) {
  20847. const intersectPoint = new Vector3();
  20848. _ray.closestPointToPoint( point, intersectPoint );
  20849. intersectPoint.applyMatrix4( matrixWorld );
  20850. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20851. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20852. intersects.push( {
  20853. distance: distance,
  20854. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20855. point: intersectPoint,
  20856. index: index,
  20857. face: null,
  20858. object: object
  20859. } );
  20860. }
  20861. }
  20862. class VideoTexture extends Texture {
  20863. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20864. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20865. this.isVideoTexture = true;
  20866. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  20867. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  20868. this.generateMipmaps = false;
  20869. const scope = this;
  20870. function updateVideo() {
  20871. scope.needsUpdate = true;
  20872. video.requestVideoFrameCallback( updateVideo );
  20873. }
  20874. if ( 'requestVideoFrameCallback' in video ) {
  20875. video.requestVideoFrameCallback( updateVideo );
  20876. }
  20877. }
  20878. clone() {
  20879. return new this.constructor( this.image ).copy( this );
  20880. }
  20881. update() {
  20882. const video = this.image;
  20883. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20884. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20885. this.needsUpdate = true;
  20886. }
  20887. }
  20888. }
  20889. class FramebufferTexture extends Texture {
  20890. constructor( width, height ) {
  20891. super( { width, height } );
  20892. this.isFramebufferTexture = true;
  20893. this.magFilter = NearestFilter;
  20894. this.minFilter = NearestFilter;
  20895. this.generateMipmaps = false;
  20896. this.needsUpdate = true;
  20897. }
  20898. }
  20899. class CompressedTexture extends Texture {
  20900. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  20901. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  20902. this.isCompressedTexture = true;
  20903. this.image = { width: width, height: height };
  20904. this.mipmaps = mipmaps;
  20905. // no flipping for cube textures
  20906. // (also flipping doesn't work for compressed textures )
  20907. this.flipY = false;
  20908. // can't generate mipmaps for compressed textures
  20909. // mips must be embedded in DDS files
  20910. this.generateMipmaps = false;
  20911. }
  20912. }
  20913. class CompressedArrayTexture extends CompressedTexture {
  20914. constructor( mipmaps, width, height, depth, format, type ) {
  20915. super( mipmaps, width, height, format, type );
  20916. this.isCompressedArrayTexture = true;
  20917. this.image.depth = depth;
  20918. this.wrapR = ClampToEdgeWrapping;
  20919. this.layerUpdates = new Set();
  20920. }
  20921. addLayerUpdate( layerIndex ) {
  20922. this.layerUpdates.add( layerIndex );
  20923. }
  20924. clearLayerUpdates() {
  20925. this.layerUpdates.clear();
  20926. }
  20927. }
  20928. class CompressedCubeTexture extends CompressedTexture {
  20929. constructor( images, format, type ) {
  20930. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  20931. this.isCompressedCubeTexture = true;
  20932. this.isCubeTexture = true;
  20933. this.image = images;
  20934. }
  20935. }
  20936. class CanvasTexture extends Texture {
  20937. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20938. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20939. this.isCanvasTexture = true;
  20940. this.needsUpdate = true;
  20941. }
  20942. }
  20943. /**
  20944. * Extensible curve object.
  20945. *
  20946. * Some common of curve methods:
  20947. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20948. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20949. * .getPoints(), .getSpacedPoints()
  20950. * .getLength()
  20951. * .updateArcLengths()
  20952. *
  20953. * This following curves inherit from THREE.Curve:
  20954. *
  20955. * -- 2D curves --
  20956. * THREE.ArcCurve
  20957. * THREE.CubicBezierCurve
  20958. * THREE.EllipseCurve
  20959. * THREE.LineCurve
  20960. * THREE.QuadraticBezierCurve
  20961. * THREE.SplineCurve
  20962. *
  20963. * -- 3D curves --
  20964. * THREE.CatmullRomCurve3
  20965. * THREE.CubicBezierCurve3
  20966. * THREE.LineCurve3
  20967. * THREE.QuadraticBezierCurve3
  20968. *
  20969. * A series of curves can be represented as a THREE.CurvePath.
  20970. *
  20971. **/
  20972. class Curve {
  20973. constructor() {
  20974. this.type = 'Curve';
  20975. this.arcLengthDivisions = 200;
  20976. }
  20977. // Virtual base class method to overwrite and implement in subclasses
  20978. // - t [0 .. 1]
  20979. getPoint( /* t, optionalTarget */ ) {
  20980. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20981. return null;
  20982. }
  20983. // Get point at relative position in curve according to arc length
  20984. // - u [0 .. 1]
  20985. getPointAt( u, optionalTarget ) {
  20986. const t = this.getUtoTmapping( u );
  20987. return this.getPoint( t, optionalTarget );
  20988. }
  20989. // Get sequence of points using getPoint( t )
  20990. getPoints( divisions = 5 ) {
  20991. const points = [];
  20992. for ( let d = 0; d <= divisions; d ++ ) {
  20993. points.push( this.getPoint( d / divisions ) );
  20994. }
  20995. return points;
  20996. }
  20997. // Get sequence of points using getPointAt( u )
  20998. getSpacedPoints( divisions = 5 ) {
  20999. const points = [];
  21000. for ( let d = 0; d <= divisions; d ++ ) {
  21001. points.push( this.getPointAt( d / divisions ) );
  21002. }
  21003. return points;
  21004. }
  21005. // Get total curve arc length
  21006. getLength() {
  21007. const lengths = this.getLengths();
  21008. return lengths[ lengths.length - 1 ];
  21009. }
  21010. // Get list of cumulative segment lengths
  21011. getLengths( divisions = this.arcLengthDivisions ) {
  21012. if ( this.cacheArcLengths &&
  21013. ( this.cacheArcLengths.length === divisions + 1 ) &&
  21014. ! this.needsUpdate ) {
  21015. return this.cacheArcLengths;
  21016. }
  21017. this.needsUpdate = false;
  21018. const cache = [];
  21019. let current, last = this.getPoint( 0 );
  21020. let sum = 0;
  21021. cache.push( 0 );
  21022. for ( let p = 1; p <= divisions; p ++ ) {
  21023. current = this.getPoint( p / divisions );
  21024. sum += current.distanceTo( last );
  21025. cache.push( sum );
  21026. last = current;
  21027. }
  21028. this.cacheArcLengths = cache;
  21029. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21030. }
  21031. updateArcLengths() {
  21032. this.needsUpdate = true;
  21033. this.getLengths();
  21034. }
  21035. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  21036. getUtoTmapping( u, distance ) {
  21037. const arcLengths = this.getLengths();
  21038. let i = 0;
  21039. const il = arcLengths.length;
  21040. let targetArcLength; // The targeted u distance value to get
  21041. if ( distance ) {
  21042. targetArcLength = distance;
  21043. } else {
  21044. targetArcLength = u * arcLengths[ il - 1 ];
  21045. }
  21046. // binary search for the index with largest value smaller than target u distance
  21047. let low = 0, high = il - 1, comparison;
  21048. while ( low <= high ) {
  21049. 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
  21050. comparison = arcLengths[ i ] - targetArcLength;
  21051. if ( comparison < 0 ) {
  21052. low = i + 1;
  21053. } else if ( comparison > 0 ) {
  21054. high = i - 1;
  21055. } else {
  21056. high = i;
  21057. break;
  21058. // DONE
  21059. }
  21060. }
  21061. i = high;
  21062. if ( arcLengths[ i ] === targetArcLength ) {
  21063. return i / ( il - 1 );
  21064. }
  21065. // we could get finer grain at lengths, or use simple interpolation between two points
  21066. const lengthBefore = arcLengths[ i ];
  21067. const lengthAfter = arcLengths[ i + 1 ];
  21068. const segmentLength = lengthAfter - lengthBefore;
  21069. // determine where we are between the 'before' and 'after' points
  21070. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  21071. // add that fractional amount to t
  21072. const t = ( i + segmentFraction ) / ( il - 1 );
  21073. return t;
  21074. }
  21075. // Returns a unit vector tangent at t
  21076. // In case any sub curve does not implement its tangent derivation,
  21077. // 2 points a small delta apart will be used to find its gradient
  21078. // which seems to give a reasonable approximation
  21079. getTangent( t, optionalTarget ) {
  21080. const delta = 0.0001;
  21081. let t1 = t - delta;
  21082. let t2 = t + delta;
  21083. // Capping in case of danger
  21084. if ( t1 < 0 ) t1 = 0;
  21085. if ( t2 > 1 ) t2 = 1;
  21086. const pt1 = this.getPoint( t1 );
  21087. const pt2 = this.getPoint( t2 );
  21088. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  21089. tangent.copy( pt2 ).sub( pt1 ).normalize();
  21090. return tangent;
  21091. }
  21092. getTangentAt( u, optionalTarget ) {
  21093. const t = this.getUtoTmapping( u );
  21094. return this.getTangent( t, optionalTarget );
  21095. }
  21096. computeFrenetFrames( segments, closed ) {
  21097. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21098. const normal = new Vector3();
  21099. const tangents = [];
  21100. const normals = [];
  21101. const binormals = [];
  21102. const vec = new Vector3();
  21103. const mat = new Matrix4();
  21104. // compute the tangent vectors for each segment on the curve
  21105. for ( let i = 0; i <= segments; i ++ ) {
  21106. const u = i / segments;
  21107. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  21108. }
  21109. // select an initial normal vector perpendicular to the first tangent vector,
  21110. // and in the direction of the minimum tangent xyz component
  21111. normals[ 0 ] = new Vector3();
  21112. binormals[ 0 ] = new Vector3();
  21113. let min = Number.MAX_VALUE;
  21114. const tx = Math.abs( tangents[ 0 ].x );
  21115. const ty = Math.abs( tangents[ 0 ].y );
  21116. const tz = Math.abs( tangents[ 0 ].z );
  21117. if ( tx <= min ) {
  21118. min = tx;
  21119. normal.set( 1, 0, 0 );
  21120. }
  21121. if ( ty <= min ) {
  21122. min = ty;
  21123. normal.set( 0, 1, 0 );
  21124. }
  21125. if ( tz <= min ) {
  21126. normal.set( 0, 0, 1 );
  21127. }
  21128. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21129. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21130. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21131. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21132. for ( let i = 1; i <= segments; i ++ ) {
  21133. normals[ i ] = normals[ i - 1 ].clone();
  21134. binormals[ i ] = binormals[ i - 1 ].clone();
  21135. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21136. if ( vec.length() > Number.EPSILON ) {
  21137. vec.normalize();
  21138. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  21139. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21140. }
  21141. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21142. }
  21143. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21144. if ( closed === true ) {
  21145. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  21146. theta /= segments;
  21147. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21148. theta = - theta;
  21149. }
  21150. for ( let i = 1; i <= segments; i ++ ) {
  21151. // twist a little...
  21152. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21153. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21154. }
  21155. }
  21156. return {
  21157. tangents: tangents,
  21158. normals: normals,
  21159. binormals: binormals
  21160. };
  21161. }
  21162. clone() {
  21163. return new this.constructor().copy( this );
  21164. }
  21165. copy( source ) {
  21166. this.arcLengthDivisions = source.arcLengthDivisions;
  21167. return this;
  21168. }
  21169. toJSON() {
  21170. const data = {
  21171. metadata: {
  21172. version: 4.6,
  21173. type: 'Curve',
  21174. generator: 'Curve.toJSON'
  21175. }
  21176. };
  21177. data.arcLengthDivisions = this.arcLengthDivisions;
  21178. data.type = this.type;
  21179. return data;
  21180. }
  21181. fromJSON( json ) {
  21182. this.arcLengthDivisions = json.arcLengthDivisions;
  21183. return this;
  21184. }
  21185. }
  21186. class EllipseCurve extends Curve {
  21187. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  21188. super();
  21189. this.isEllipseCurve = true;
  21190. this.type = 'EllipseCurve';
  21191. this.aX = aX;
  21192. this.aY = aY;
  21193. this.xRadius = xRadius;
  21194. this.yRadius = yRadius;
  21195. this.aStartAngle = aStartAngle;
  21196. this.aEndAngle = aEndAngle;
  21197. this.aClockwise = aClockwise;
  21198. this.aRotation = aRotation;
  21199. }
  21200. getPoint( t, optionalTarget = new Vector2() ) {
  21201. const point = optionalTarget;
  21202. const twoPi = Math.PI * 2;
  21203. let deltaAngle = this.aEndAngle - this.aStartAngle;
  21204. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  21205. // ensures that deltaAngle is 0 .. 2 PI
  21206. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  21207. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  21208. if ( deltaAngle < Number.EPSILON ) {
  21209. if ( samePoints ) {
  21210. deltaAngle = 0;
  21211. } else {
  21212. deltaAngle = twoPi;
  21213. }
  21214. }
  21215. if ( this.aClockwise === true && ! samePoints ) {
  21216. if ( deltaAngle === twoPi ) {
  21217. deltaAngle = - twoPi;
  21218. } else {
  21219. deltaAngle = deltaAngle - twoPi;
  21220. }
  21221. }
  21222. const angle = this.aStartAngle + t * deltaAngle;
  21223. let x = this.aX + this.xRadius * Math.cos( angle );
  21224. let y = this.aY + this.yRadius * Math.sin( angle );
  21225. if ( this.aRotation !== 0 ) {
  21226. const cos = Math.cos( this.aRotation );
  21227. const sin = Math.sin( this.aRotation );
  21228. const tx = x - this.aX;
  21229. const ty = y - this.aY;
  21230. // Rotate the point about the center of the ellipse.
  21231. x = tx * cos - ty * sin + this.aX;
  21232. y = tx * sin + ty * cos + this.aY;
  21233. }
  21234. return point.set( x, y );
  21235. }
  21236. copy( source ) {
  21237. super.copy( source );
  21238. this.aX = source.aX;
  21239. this.aY = source.aY;
  21240. this.xRadius = source.xRadius;
  21241. this.yRadius = source.yRadius;
  21242. this.aStartAngle = source.aStartAngle;
  21243. this.aEndAngle = source.aEndAngle;
  21244. this.aClockwise = source.aClockwise;
  21245. this.aRotation = source.aRotation;
  21246. return this;
  21247. }
  21248. toJSON() {
  21249. const data = super.toJSON();
  21250. data.aX = this.aX;
  21251. data.aY = this.aY;
  21252. data.xRadius = this.xRadius;
  21253. data.yRadius = this.yRadius;
  21254. data.aStartAngle = this.aStartAngle;
  21255. data.aEndAngle = this.aEndAngle;
  21256. data.aClockwise = this.aClockwise;
  21257. data.aRotation = this.aRotation;
  21258. return data;
  21259. }
  21260. fromJSON( json ) {
  21261. super.fromJSON( json );
  21262. this.aX = json.aX;
  21263. this.aY = json.aY;
  21264. this.xRadius = json.xRadius;
  21265. this.yRadius = json.yRadius;
  21266. this.aStartAngle = json.aStartAngle;
  21267. this.aEndAngle = json.aEndAngle;
  21268. this.aClockwise = json.aClockwise;
  21269. this.aRotation = json.aRotation;
  21270. return this;
  21271. }
  21272. }
  21273. class ArcCurve extends EllipseCurve {
  21274. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21275. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21276. this.isArcCurve = true;
  21277. this.type = 'ArcCurve';
  21278. }
  21279. }
  21280. /**
  21281. * Centripetal CatmullRom Curve - which is useful for avoiding
  21282. * cusps and self-intersections in non-uniform catmull rom curves.
  21283. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21284. *
  21285. * curve.type accepts centripetal(default), chordal and catmullrom
  21286. * curve.tension is used for catmullrom which defaults to 0.5
  21287. */
  21288. /*
  21289. Based on an optimized c++ solution in
  21290. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21291. - http://ideone.com/NoEbVM
  21292. This CubicPoly class could be used for reusing some variables and calculations,
  21293. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21294. which can be placed in CurveUtils.
  21295. */
  21296. function CubicPoly() {
  21297. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  21298. /*
  21299. * Compute coefficients for a cubic polynomial
  21300. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21301. * such that
  21302. * p(0) = x0, p(1) = x1
  21303. * and
  21304. * p'(0) = t0, p'(1) = t1.
  21305. */
  21306. function init( x0, x1, t0, t1 ) {
  21307. c0 = x0;
  21308. c1 = t0;
  21309. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  21310. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21311. }
  21312. return {
  21313. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  21314. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  21315. },
  21316. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  21317. // compute tangents when parameterized in [t1,t2]
  21318. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  21319. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  21320. // rescale tangents for parametrization in [0,1]
  21321. t1 *= dt1;
  21322. t2 *= dt1;
  21323. init( x1, x2, t1, t2 );
  21324. },
  21325. calc: function ( t ) {
  21326. const t2 = t * t;
  21327. const t3 = t2 * t;
  21328. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21329. }
  21330. };
  21331. }
  21332. //
  21333. const tmp = /*@__PURE__*/ new Vector3();
  21334. const px = /*@__PURE__*/ new CubicPoly();
  21335. const py = /*@__PURE__*/ new CubicPoly();
  21336. const pz = /*@__PURE__*/ new CubicPoly();
  21337. class CatmullRomCurve3 extends Curve {
  21338. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  21339. super();
  21340. this.isCatmullRomCurve3 = true;
  21341. this.type = 'CatmullRomCurve3';
  21342. this.points = points;
  21343. this.closed = closed;
  21344. this.curveType = curveType;
  21345. this.tension = tension;
  21346. }
  21347. getPoint( t, optionalTarget = new Vector3() ) {
  21348. const point = optionalTarget;
  21349. const points = this.points;
  21350. const l = points.length;
  21351. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  21352. let intPoint = Math.floor( p );
  21353. let weight = p - intPoint;
  21354. if ( this.closed ) {
  21355. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  21356. } else if ( weight === 0 && intPoint === l - 1 ) {
  21357. intPoint = l - 2;
  21358. weight = 1;
  21359. }
  21360. let p0, p3; // 4 points (p1 & p2 defined below)
  21361. if ( this.closed || intPoint > 0 ) {
  21362. p0 = points[ ( intPoint - 1 ) % l ];
  21363. } else {
  21364. // extrapolate first point
  21365. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21366. p0 = tmp;
  21367. }
  21368. const p1 = points[ intPoint % l ];
  21369. const p2 = points[ ( intPoint + 1 ) % l ];
  21370. if ( this.closed || intPoint + 2 < l ) {
  21371. p3 = points[ ( intPoint + 2 ) % l ];
  21372. } else {
  21373. // extrapolate last point
  21374. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  21375. p3 = tmp;
  21376. }
  21377. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  21378. // init Centripetal / Chordal Catmull-Rom
  21379. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21380. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21381. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21382. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21383. // safety check for repeated points
  21384. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21385. if ( dt0 < 1e-4 ) dt0 = dt1;
  21386. if ( dt2 < 1e-4 ) dt2 = dt1;
  21387. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21388. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21389. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21390. } else if ( this.curveType === 'catmullrom' ) {
  21391. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  21392. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  21393. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  21394. }
  21395. point.set(
  21396. px.calc( weight ),
  21397. py.calc( weight ),
  21398. pz.calc( weight )
  21399. );
  21400. return point;
  21401. }
  21402. copy( source ) {
  21403. super.copy( source );
  21404. this.points = [];
  21405. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21406. const point = source.points[ i ];
  21407. this.points.push( point.clone() );
  21408. }
  21409. this.closed = source.closed;
  21410. this.curveType = source.curveType;
  21411. this.tension = source.tension;
  21412. return this;
  21413. }
  21414. toJSON() {
  21415. const data = super.toJSON();
  21416. data.points = [];
  21417. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21418. const point = this.points[ i ];
  21419. data.points.push( point.toArray() );
  21420. }
  21421. data.closed = this.closed;
  21422. data.curveType = this.curveType;
  21423. data.tension = this.tension;
  21424. return data;
  21425. }
  21426. fromJSON( json ) {
  21427. super.fromJSON( json );
  21428. this.points = [];
  21429. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21430. const point = json.points[ i ];
  21431. this.points.push( new Vector3().fromArray( point ) );
  21432. }
  21433. this.closed = json.closed;
  21434. this.curveType = json.curveType;
  21435. this.tension = json.tension;
  21436. return this;
  21437. }
  21438. }
  21439. /**
  21440. * Bezier Curves formulas obtained from
  21441. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  21442. */
  21443. function CatmullRom( t, p0, p1, p2, p3 ) {
  21444. const v0 = ( p2 - p0 ) * 0.5;
  21445. const v1 = ( p3 - p1 ) * 0.5;
  21446. const t2 = t * t;
  21447. const t3 = t * t2;
  21448. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  21449. }
  21450. //
  21451. function QuadraticBezierP0( t, p ) {
  21452. const k = 1 - t;
  21453. return k * k * p;
  21454. }
  21455. function QuadraticBezierP1( t, p ) {
  21456. return 2 * ( 1 - t ) * t * p;
  21457. }
  21458. function QuadraticBezierP2( t, p ) {
  21459. return t * t * p;
  21460. }
  21461. function QuadraticBezier( t, p0, p1, p2 ) {
  21462. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  21463. QuadraticBezierP2( t, p2 );
  21464. }
  21465. //
  21466. function CubicBezierP0( t, p ) {
  21467. const k = 1 - t;
  21468. return k * k * k * p;
  21469. }
  21470. function CubicBezierP1( t, p ) {
  21471. const k = 1 - t;
  21472. return 3 * k * k * t * p;
  21473. }
  21474. function CubicBezierP2( t, p ) {
  21475. return 3 * ( 1 - t ) * t * t * p;
  21476. }
  21477. function CubicBezierP3( t, p ) {
  21478. return t * t * t * p;
  21479. }
  21480. function CubicBezier( t, p0, p1, p2, p3 ) {
  21481. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  21482. CubicBezierP3( t, p3 );
  21483. }
  21484. class CubicBezierCurve extends Curve {
  21485. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  21486. super();
  21487. this.isCubicBezierCurve = true;
  21488. this.type = 'CubicBezierCurve';
  21489. this.v0 = v0;
  21490. this.v1 = v1;
  21491. this.v2 = v2;
  21492. this.v3 = v3;
  21493. }
  21494. getPoint( t, optionalTarget = new Vector2() ) {
  21495. const point = optionalTarget;
  21496. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21497. point.set(
  21498. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21499. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21500. );
  21501. return point;
  21502. }
  21503. copy( source ) {
  21504. super.copy( source );
  21505. this.v0.copy( source.v0 );
  21506. this.v1.copy( source.v1 );
  21507. this.v2.copy( source.v2 );
  21508. this.v3.copy( source.v3 );
  21509. return this;
  21510. }
  21511. toJSON() {
  21512. const data = super.toJSON();
  21513. data.v0 = this.v0.toArray();
  21514. data.v1 = this.v1.toArray();
  21515. data.v2 = this.v2.toArray();
  21516. data.v3 = this.v3.toArray();
  21517. return data;
  21518. }
  21519. fromJSON( json ) {
  21520. super.fromJSON( json );
  21521. this.v0.fromArray( json.v0 );
  21522. this.v1.fromArray( json.v1 );
  21523. this.v2.fromArray( json.v2 );
  21524. this.v3.fromArray( json.v3 );
  21525. return this;
  21526. }
  21527. }
  21528. class CubicBezierCurve3 extends Curve {
  21529. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  21530. super();
  21531. this.isCubicBezierCurve3 = true;
  21532. this.type = 'CubicBezierCurve3';
  21533. this.v0 = v0;
  21534. this.v1 = v1;
  21535. this.v2 = v2;
  21536. this.v3 = v3;
  21537. }
  21538. getPoint( t, optionalTarget = new Vector3() ) {
  21539. const point = optionalTarget;
  21540. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21541. point.set(
  21542. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21543. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  21544. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  21545. );
  21546. return point;
  21547. }
  21548. copy( source ) {
  21549. super.copy( source );
  21550. this.v0.copy( source.v0 );
  21551. this.v1.copy( source.v1 );
  21552. this.v2.copy( source.v2 );
  21553. this.v3.copy( source.v3 );
  21554. return this;
  21555. }
  21556. toJSON() {
  21557. const data = super.toJSON();
  21558. data.v0 = this.v0.toArray();
  21559. data.v1 = this.v1.toArray();
  21560. data.v2 = this.v2.toArray();
  21561. data.v3 = this.v3.toArray();
  21562. return data;
  21563. }
  21564. fromJSON( json ) {
  21565. super.fromJSON( json );
  21566. this.v0.fromArray( json.v0 );
  21567. this.v1.fromArray( json.v1 );
  21568. this.v2.fromArray( json.v2 );
  21569. this.v3.fromArray( json.v3 );
  21570. return this;
  21571. }
  21572. }
  21573. class LineCurve extends Curve {
  21574. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  21575. super();
  21576. this.isLineCurve = true;
  21577. this.type = 'LineCurve';
  21578. this.v1 = v1;
  21579. this.v2 = v2;
  21580. }
  21581. getPoint( t, optionalTarget = new Vector2() ) {
  21582. const point = optionalTarget;
  21583. if ( t === 1 ) {
  21584. point.copy( this.v2 );
  21585. } else {
  21586. point.copy( this.v2 ).sub( this.v1 );
  21587. point.multiplyScalar( t ).add( this.v1 );
  21588. }
  21589. return point;
  21590. }
  21591. // Line curve is linear, so we can overwrite default getPointAt
  21592. getPointAt( u, optionalTarget ) {
  21593. return this.getPoint( u, optionalTarget );
  21594. }
  21595. getTangent( t, optionalTarget = new Vector2() ) {
  21596. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21597. }
  21598. getTangentAt( u, optionalTarget ) {
  21599. return this.getTangent( u, optionalTarget );
  21600. }
  21601. copy( source ) {
  21602. super.copy( source );
  21603. this.v1.copy( source.v1 );
  21604. this.v2.copy( source.v2 );
  21605. return this;
  21606. }
  21607. toJSON() {
  21608. const data = super.toJSON();
  21609. data.v1 = this.v1.toArray();
  21610. data.v2 = this.v2.toArray();
  21611. return data;
  21612. }
  21613. fromJSON( json ) {
  21614. super.fromJSON( json );
  21615. this.v1.fromArray( json.v1 );
  21616. this.v2.fromArray( json.v2 );
  21617. return this;
  21618. }
  21619. }
  21620. class LineCurve3 extends Curve {
  21621. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  21622. super();
  21623. this.isLineCurve3 = true;
  21624. this.type = 'LineCurve3';
  21625. this.v1 = v1;
  21626. this.v2 = v2;
  21627. }
  21628. getPoint( t, optionalTarget = new Vector3() ) {
  21629. const point = optionalTarget;
  21630. if ( t === 1 ) {
  21631. point.copy( this.v2 );
  21632. } else {
  21633. point.copy( this.v2 ).sub( this.v1 );
  21634. point.multiplyScalar( t ).add( this.v1 );
  21635. }
  21636. return point;
  21637. }
  21638. // Line curve is linear, so we can overwrite default getPointAt
  21639. getPointAt( u, optionalTarget ) {
  21640. return this.getPoint( u, optionalTarget );
  21641. }
  21642. getTangent( t, optionalTarget = new Vector3() ) {
  21643. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21644. }
  21645. getTangentAt( u, optionalTarget ) {
  21646. return this.getTangent( u, optionalTarget );
  21647. }
  21648. copy( source ) {
  21649. super.copy( source );
  21650. this.v1.copy( source.v1 );
  21651. this.v2.copy( source.v2 );
  21652. return this;
  21653. }
  21654. toJSON() {
  21655. const data = super.toJSON();
  21656. data.v1 = this.v1.toArray();
  21657. data.v2 = this.v2.toArray();
  21658. return data;
  21659. }
  21660. fromJSON( json ) {
  21661. super.fromJSON( json );
  21662. this.v1.fromArray( json.v1 );
  21663. this.v2.fromArray( json.v2 );
  21664. return this;
  21665. }
  21666. }
  21667. class QuadraticBezierCurve extends Curve {
  21668. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  21669. super();
  21670. this.isQuadraticBezierCurve = true;
  21671. this.type = 'QuadraticBezierCurve';
  21672. this.v0 = v0;
  21673. this.v1 = v1;
  21674. this.v2 = v2;
  21675. }
  21676. getPoint( t, optionalTarget = new Vector2() ) {
  21677. const point = optionalTarget;
  21678. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21679. point.set(
  21680. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21681. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21682. );
  21683. return point;
  21684. }
  21685. copy( source ) {
  21686. super.copy( source );
  21687. this.v0.copy( source.v0 );
  21688. this.v1.copy( source.v1 );
  21689. this.v2.copy( source.v2 );
  21690. return this;
  21691. }
  21692. toJSON() {
  21693. const data = super.toJSON();
  21694. data.v0 = this.v0.toArray();
  21695. data.v1 = this.v1.toArray();
  21696. data.v2 = this.v2.toArray();
  21697. return data;
  21698. }
  21699. fromJSON( json ) {
  21700. super.fromJSON( json );
  21701. this.v0.fromArray( json.v0 );
  21702. this.v1.fromArray( json.v1 );
  21703. this.v2.fromArray( json.v2 );
  21704. return this;
  21705. }
  21706. }
  21707. class QuadraticBezierCurve3 extends Curve {
  21708. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  21709. super();
  21710. this.isQuadraticBezierCurve3 = true;
  21711. this.type = 'QuadraticBezierCurve3';
  21712. this.v0 = v0;
  21713. this.v1 = v1;
  21714. this.v2 = v2;
  21715. }
  21716. getPoint( t, optionalTarget = new Vector3() ) {
  21717. const point = optionalTarget;
  21718. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21719. point.set(
  21720. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21721. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  21722. QuadraticBezier( t, v0.z, v1.z, v2.z )
  21723. );
  21724. return point;
  21725. }
  21726. copy( source ) {
  21727. super.copy( source );
  21728. this.v0.copy( source.v0 );
  21729. this.v1.copy( source.v1 );
  21730. this.v2.copy( source.v2 );
  21731. return this;
  21732. }
  21733. toJSON() {
  21734. const data = super.toJSON();
  21735. data.v0 = this.v0.toArray();
  21736. data.v1 = this.v1.toArray();
  21737. data.v2 = this.v2.toArray();
  21738. return data;
  21739. }
  21740. fromJSON( json ) {
  21741. super.fromJSON( json );
  21742. this.v0.fromArray( json.v0 );
  21743. this.v1.fromArray( json.v1 );
  21744. this.v2.fromArray( json.v2 );
  21745. return this;
  21746. }
  21747. }
  21748. class SplineCurve extends Curve {
  21749. constructor( points = [] ) {
  21750. super();
  21751. this.isSplineCurve = true;
  21752. this.type = 'SplineCurve';
  21753. this.points = points;
  21754. }
  21755. getPoint( t, optionalTarget = new Vector2() ) {
  21756. const point = optionalTarget;
  21757. const points = this.points;
  21758. const p = ( points.length - 1 ) * t;
  21759. const intPoint = Math.floor( p );
  21760. const weight = p - intPoint;
  21761. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21762. const p1 = points[ intPoint ];
  21763. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21764. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21765. point.set(
  21766. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  21767. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  21768. );
  21769. return point;
  21770. }
  21771. copy( source ) {
  21772. super.copy( source );
  21773. this.points = [];
  21774. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21775. const point = source.points[ i ];
  21776. this.points.push( point.clone() );
  21777. }
  21778. return this;
  21779. }
  21780. toJSON() {
  21781. const data = super.toJSON();
  21782. data.points = [];
  21783. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21784. const point = this.points[ i ];
  21785. data.points.push( point.toArray() );
  21786. }
  21787. return data;
  21788. }
  21789. fromJSON( json ) {
  21790. super.fromJSON( json );
  21791. this.points = [];
  21792. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21793. const point = json.points[ i ];
  21794. this.points.push( new Vector2().fromArray( point ) );
  21795. }
  21796. return this;
  21797. }
  21798. }
  21799. var Curves = /*#__PURE__*/Object.freeze({
  21800. __proto__: null,
  21801. ArcCurve: ArcCurve,
  21802. CatmullRomCurve3: CatmullRomCurve3,
  21803. CubicBezierCurve: CubicBezierCurve,
  21804. CubicBezierCurve3: CubicBezierCurve3,
  21805. EllipseCurve: EllipseCurve,
  21806. LineCurve: LineCurve,
  21807. LineCurve3: LineCurve3,
  21808. QuadraticBezierCurve: QuadraticBezierCurve,
  21809. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21810. SplineCurve: SplineCurve
  21811. });
  21812. /**************************************************************
  21813. * Curved Path - a curve path is simply a array of connected
  21814. * curves, but retains the api of a curve
  21815. **************************************************************/
  21816. class CurvePath extends Curve {
  21817. constructor() {
  21818. super();
  21819. this.type = 'CurvePath';
  21820. this.curves = [];
  21821. this.autoClose = false; // Automatically closes the path
  21822. }
  21823. add( curve ) {
  21824. this.curves.push( curve );
  21825. }
  21826. closePath() {
  21827. // Add a line curve if start and end of lines are not connected
  21828. const startPoint = this.curves[ 0 ].getPoint( 0 );
  21829. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21830. if ( ! startPoint.equals( endPoint ) ) {
  21831. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  21832. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  21833. }
  21834. return this;
  21835. }
  21836. // To get accurate point with reference to
  21837. // entire path distance at time t,
  21838. // following has to be done:
  21839. // 1. Length of each sub path have to be known
  21840. // 2. Locate and identify type of curve
  21841. // 3. Get t for the curve
  21842. // 4. Return curve.getPointAt(t')
  21843. getPoint( t, optionalTarget ) {
  21844. const d = t * this.getLength();
  21845. const curveLengths = this.getCurveLengths();
  21846. let i = 0;
  21847. // To think about boundaries points.
  21848. while ( i < curveLengths.length ) {
  21849. if ( curveLengths[ i ] >= d ) {
  21850. const diff = curveLengths[ i ] - d;
  21851. const curve = this.curves[ i ];
  21852. const segmentLength = curve.getLength();
  21853. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21854. return curve.getPointAt( u, optionalTarget );
  21855. }
  21856. i ++;
  21857. }
  21858. return null;
  21859. // loop where sum != 0, sum > d , sum+1 <d
  21860. }
  21861. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21862. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21863. // getPoint() depends on getLength
  21864. getLength() {
  21865. const lens = this.getCurveLengths();
  21866. return lens[ lens.length - 1 ];
  21867. }
  21868. // cacheLengths must be recalculated.
  21869. updateArcLengths() {
  21870. this.needsUpdate = true;
  21871. this.cacheLengths = null;
  21872. this.getCurveLengths();
  21873. }
  21874. // Compute lengths and cache them
  21875. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21876. getCurveLengths() {
  21877. // We use cache values if curves and cache array are same length
  21878. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21879. return this.cacheLengths;
  21880. }
  21881. // Get length of sub-curve
  21882. // Push sums into cached array
  21883. const lengths = [];
  21884. let sums = 0;
  21885. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21886. sums += this.curves[ i ].getLength();
  21887. lengths.push( sums );
  21888. }
  21889. this.cacheLengths = lengths;
  21890. return lengths;
  21891. }
  21892. getSpacedPoints( divisions = 40 ) {
  21893. const points = [];
  21894. for ( let i = 0; i <= divisions; i ++ ) {
  21895. points.push( this.getPoint( i / divisions ) );
  21896. }
  21897. if ( this.autoClose ) {
  21898. points.push( points[ 0 ] );
  21899. }
  21900. return points;
  21901. }
  21902. getPoints( divisions = 12 ) {
  21903. const points = [];
  21904. let last;
  21905. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21906. const curve = curves[ i ];
  21907. const resolution = curve.isEllipseCurve ? divisions * 2
  21908. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  21909. : curve.isSplineCurve ? divisions * curve.points.length
  21910. : divisions;
  21911. const pts = curve.getPoints( resolution );
  21912. for ( let j = 0; j < pts.length; j ++ ) {
  21913. const point = pts[ j ];
  21914. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21915. points.push( point );
  21916. last = point;
  21917. }
  21918. }
  21919. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21920. points.push( points[ 0 ] );
  21921. }
  21922. return points;
  21923. }
  21924. copy( source ) {
  21925. super.copy( source );
  21926. this.curves = [];
  21927. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  21928. const curve = source.curves[ i ];
  21929. this.curves.push( curve.clone() );
  21930. }
  21931. this.autoClose = source.autoClose;
  21932. return this;
  21933. }
  21934. toJSON() {
  21935. const data = super.toJSON();
  21936. data.autoClose = this.autoClose;
  21937. data.curves = [];
  21938. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21939. const curve = this.curves[ i ];
  21940. data.curves.push( curve.toJSON() );
  21941. }
  21942. return data;
  21943. }
  21944. fromJSON( json ) {
  21945. super.fromJSON( json );
  21946. this.autoClose = json.autoClose;
  21947. this.curves = [];
  21948. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  21949. const curve = json.curves[ i ];
  21950. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  21951. }
  21952. return this;
  21953. }
  21954. }
  21955. class Path extends CurvePath {
  21956. constructor( points ) {
  21957. super();
  21958. this.type = 'Path';
  21959. this.currentPoint = new Vector2();
  21960. if ( points ) {
  21961. this.setFromPoints( points );
  21962. }
  21963. }
  21964. setFromPoints( points ) {
  21965. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  21966. for ( let i = 1, l = points.length; i < l; i ++ ) {
  21967. this.lineTo( points[ i ].x, points[ i ].y );
  21968. }
  21969. return this;
  21970. }
  21971. moveTo( x, y ) {
  21972. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21973. return this;
  21974. }
  21975. lineTo( x, y ) {
  21976. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21977. this.curves.push( curve );
  21978. this.currentPoint.set( x, y );
  21979. return this;
  21980. }
  21981. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21982. const curve = new QuadraticBezierCurve(
  21983. this.currentPoint.clone(),
  21984. new Vector2( aCPx, aCPy ),
  21985. new Vector2( aX, aY )
  21986. );
  21987. this.curves.push( curve );
  21988. this.currentPoint.set( aX, aY );
  21989. return this;
  21990. }
  21991. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21992. const curve = new CubicBezierCurve(
  21993. this.currentPoint.clone(),
  21994. new Vector2( aCP1x, aCP1y ),
  21995. new Vector2( aCP2x, aCP2y ),
  21996. new Vector2( aX, aY )
  21997. );
  21998. this.curves.push( curve );
  21999. this.currentPoint.set( aX, aY );
  22000. return this;
  22001. }
  22002. splineThru( pts /*Array of Vector*/ ) {
  22003. const npts = [ this.currentPoint.clone() ].concat( pts );
  22004. const curve = new SplineCurve( npts );
  22005. this.curves.push( curve );
  22006. this.currentPoint.copy( pts[ pts.length - 1 ] );
  22007. return this;
  22008. }
  22009. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22010. const x0 = this.currentPoint.x;
  22011. const y0 = this.currentPoint.y;
  22012. this.absarc( aX + x0, aY + y0, aRadius,
  22013. aStartAngle, aEndAngle, aClockwise );
  22014. return this;
  22015. }
  22016. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22017. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  22018. return this;
  22019. }
  22020. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  22021. const x0 = this.currentPoint.x;
  22022. const y0 = this.currentPoint.y;
  22023. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  22024. return this;
  22025. }
  22026. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  22027. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  22028. if ( this.curves.length > 0 ) {
  22029. // if a previous curve is present, attempt to join
  22030. const firstPoint = curve.getPoint( 0 );
  22031. if ( ! firstPoint.equals( this.currentPoint ) ) {
  22032. this.lineTo( firstPoint.x, firstPoint.y );
  22033. }
  22034. }
  22035. this.curves.push( curve );
  22036. const lastPoint = curve.getPoint( 1 );
  22037. this.currentPoint.copy( lastPoint );
  22038. return this;
  22039. }
  22040. copy( source ) {
  22041. super.copy( source );
  22042. this.currentPoint.copy( source.currentPoint );
  22043. return this;
  22044. }
  22045. toJSON() {
  22046. const data = super.toJSON();
  22047. data.currentPoint = this.currentPoint.toArray();
  22048. return data;
  22049. }
  22050. fromJSON( json ) {
  22051. super.fromJSON( json );
  22052. this.currentPoint.fromArray( json.currentPoint );
  22053. return this;
  22054. }
  22055. }
  22056. class LatheGeometry extends BufferGeometry {
  22057. 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 ) {
  22058. super();
  22059. this.type = 'LatheGeometry';
  22060. this.parameters = {
  22061. points: points,
  22062. segments: segments,
  22063. phiStart: phiStart,
  22064. phiLength: phiLength
  22065. };
  22066. segments = Math.floor( segments );
  22067. // clamp phiLength so it's in range of [ 0, 2PI ]
  22068. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  22069. // buffers
  22070. const indices = [];
  22071. const vertices = [];
  22072. const uvs = [];
  22073. const initNormals = [];
  22074. const normals = [];
  22075. // helper variables
  22076. const inverseSegments = 1.0 / segments;
  22077. const vertex = new Vector3();
  22078. const uv = new Vector2();
  22079. const normal = new Vector3();
  22080. const curNormal = new Vector3();
  22081. const prevNormal = new Vector3();
  22082. let dx = 0;
  22083. let dy = 0;
  22084. // pre-compute normals for initial "meridian"
  22085. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  22086. switch ( j ) {
  22087. case 0: // special handling for 1st vertex on path
  22088. dx = points[ j + 1 ].x - points[ j ].x;
  22089. dy = points[ j + 1 ].y - points[ j ].y;
  22090. normal.x = dy * 1.0;
  22091. normal.y = - dx;
  22092. normal.z = dy * 0.0;
  22093. prevNormal.copy( normal );
  22094. normal.normalize();
  22095. initNormals.push( normal.x, normal.y, normal.z );
  22096. break;
  22097. case ( points.length - 1 ): // special handling for last Vertex on path
  22098. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  22099. break;
  22100. default: // default handling for all vertices in between
  22101. dx = points[ j + 1 ].x - points[ j ].x;
  22102. dy = points[ j + 1 ].y - points[ j ].y;
  22103. normal.x = dy * 1.0;
  22104. normal.y = - dx;
  22105. normal.z = dy * 0.0;
  22106. curNormal.copy( normal );
  22107. normal.x += prevNormal.x;
  22108. normal.y += prevNormal.y;
  22109. normal.z += prevNormal.z;
  22110. normal.normalize();
  22111. initNormals.push( normal.x, normal.y, normal.z );
  22112. prevNormal.copy( curNormal );
  22113. }
  22114. }
  22115. // generate vertices, uvs and normals
  22116. for ( let i = 0; i <= segments; i ++ ) {
  22117. const phi = phiStart + i * inverseSegments * phiLength;
  22118. const sin = Math.sin( phi );
  22119. const cos = Math.cos( phi );
  22120. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  22121. // vertex
  22122. vertex.x = points[ j ].x * sin;
  22123. vertex.y = points[ j ].y;
  22124. vertex.z = points[ j ].x * cos;
  22125. vertices.push( vertex.x, vertex.y, vertex.z );
  22126. // uv
  22127. uv.x = i / segments;
  22128. uv.y = j / ( points.length - 1 );
  22129. uvs.push( uv.x, uv.y );
  22130. // normal
  22131. const x = initNormals[ 3 * j + 0 ] * sin;
  22132. const y = initNormals[ 3 * j + 1 ];
  22133. const z = initNormals[ 3 * j + 0 ] * cos;
  22134. normals.push( x, y, z );
  22135. }
  22136. }
  22137. // indices
  22138. for ( let i = 0; i < segments; i ++ ) {
  22139. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  22140. const base = j + i * points.length;
  22141. const a = base;
  22142. const b = base + points.length;
  22143. const c = base + points.length + 1;
  22144. const d = base + 1;
  22145. // faces
  22146. indices.push( a, b, d );
  22147. indices.push( c, d, b );
  22148. }
  22149. }
  22150. // build geometry
  22151. this.setIndex( indices );
  22152. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22153. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22154. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22155. }
  22156. copy( source ) {
  22157. super.copy( source );
  22158. this.parameters = Object.assign( {}, source.parameters );
  22159. return this;
  22160. }
  22161. static fromJSON( data ) {
  22162. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  22163. }
  22164. }
  22165. class CapsuleGeometry extends LatheGeometry {
  22166. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  22167. const path = new Path();
  22168. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  22169. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  22170. super( path.getPoints( capSegments ), radialSegments );
  22171. this.type = 'CapsuleGeometry';
  22172. this.parameters = {
  22173. radius: radius,
  22174. length: length,
  22175. capSegments: capSegments,
  22176. radialSegments: radialSegments,
  22177. };
  22178. }
  22179. static fromJSON( data ) {
  22180. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  22181. }
  22182. }
  22183. class CircleGeometry extends BufferGeometry {
  22184. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22185. super();
  22186. this.type = 'CircleGeometry';
  22187. this.parameters = {
  22188. radius: radius,
  22189. segments: segments,
  22190. thetaStart: thetaStart,
  22191. thetaLength: thetaLength
  22192. };
  22193. segments = Math.max( 3, segments );
  22194. // buffers
  22195. const indices = [];
  22196. const vertices = [];
  22197. const normals = [];
  22198. const uvs = [];
  22199. // helper variables
  22200. const vertex = new Vector3();
  22201. const uv = new Vector2();
  22202. // center point
  22203. vertices.push( 0, 0, 0 );
  22204. normals.push( 0, 0, 1 );
  22205. uvs.push( 0.5, 0.5 );
  22206. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22207. const segment = thetaStart + s / segments * thetaLength;
  22208. // vertex
  22209. vertex.x = radius * Math.cos( segment );
  22210. vertex.y = radius * Math.sin( segment );
  22211. vertices.push( vertex.x, vertex.y, vertex.z );
  22212. // normal
  22213. normals.push( 0, 0, 1 );
  22214. // uvs
  22215. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22216. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22217. uvs.push( uv.x, uv.y );
  22218. }
  22219. // indices
  22220. for ( let i = 1; i <= segments; i ++ ) {
  22221. indices.push( i, i + 1, 0 );
  22222. }
  22223. // build geometry
  22224. this.setIndex( indices );
  22225. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22226. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22227. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22228. }
  22229. copy( source ) {
  22230. super.copy( source );
  22231. this.parameters = Object.assign( {}, source.parameters );
  22232. return this;
  22233. }
  22234. static fromJSON( data ) {
  22235. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22236. }
  22237. }
  22238. class CylinderGeometry extends BufferGeometry {
  22239. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22240. super();
  22241. this.type = 'CylinderGeometry';
  22242. this.parameters = {
  22243. radiusTop: radiusTop,
  22244. radiusBottom: radiusBottom,
  22245. height: height,
  22246. radialSegments: radialSegments,
  22247. heightSegments: heightSegments,
  22248. openEnded: openEnded,
  22249. thetaStart: thetaStart,
  22250. thetaLength: thetaLength
  22251. };
  22252. const scope = this;
  22253. radialSegments = Math.floor( radialSegments );
  22254. heightSegments = Math.floor( heightSegments );
  22255. // buffers
  22256. const indices = [];
  22257. const vertices = [];
  22258. const normals = [];
  22259. const uvs = [];
  22260. // helper variables
  22261. let index = 0;
  22262. const indexArray = [];
  22263. const halfHeight = height / 2;
  22264. let groupStart = 0;
  22265. // generate geometry
  22266. generateTorso();
  22267. if ( openEnded === false ) {
  22268. if ( radiusTop > 0 ) generateCap( true );
  22269. if ( radiusBottom > 0 ) generateCap( false );
  22270. }
  22271. // build geometry
  22272. this.setIndex( indices );
  22273. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22274. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22275. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22276. function generateTorso() {
  22277. const normal = new Vector3();
  22278. const vertex = new Vector3();
  22279. let groupCount = 0;
  22280. // this will be used to calculate the normal
  22281. const slope = ( radiusBottom - radiusTop ) / height;
  22282. // generate vertices, normals and uvs
  22283. for ( let y = 0; y <= heightSegments; y ++ ) {
  22284. const indexRow = [];
  22285. const v = y / heightSegments;
  22286. // calculate the radius of the current row
  22287. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22288. for ( let x = 0; x <= radialSegments; x ++ ) {
  22289. const u = x / radialSegments;
  22290. const theta = u * thetaLength + thetaStart;
  22291. const sinTheta = Math.sin( theta );
  22292. const cosTheta = Math.cos( theta );
  22293. // vertex
  22294. vertex.x = radius * sinTheta;
  22295. vertex.y = - v * height + halfHeight;
  22296. vertex.z = radius * cosTheta;
  22297. vertices.push( vertex.x, vertex.y, vertex.z );
  22298. // normal
  22299. normal.set( sinTheta, slope, cosTheta ).normalize();
  22300. normals.push( normal.x, normal.y, normal.z );
  22301. // uv
  22302. uvs.push( u, 1 - v );
  22303. // save index of vertex in respective row
  22304. indexRow.push( index ++ );
  22305. }
  22306. // now save vertices of the row in our index array
  22307. indexArray.push( indexRow );
  22308. }
  22309. // generate indices
  22310. for ( let x = 0; x < radialSegments; x ++ ) {
  22311. for ( let y = 0; y < heightSegments; y ++ ) {
  22312. // we use the index array to access the correct indices
  22313. const a = indexArray[ y ][ x ];
  22314. const b = indexArray[ y + 1 ][ x ];
  22315. const c = indexArray[ y + 1 ][ x + 1 ];
  22316. const d = indexArray[ y ][ x + 1 ];
  22317. // faces
  22318. indices.push( a, b, d );
  22319. indices.push( b, c, d );
  22320. // update group counter
  22321. groupCount += 6;
  22322. }
  22323. }
  22324. // add a group to the geometry. this will ensure multi material support
  22325. scope.addGroup( groupStart, groupCount, 0 );
  22326. // calculate new start value for groups
  22327. groupStart += groupCount;
  22328. }
  22329. function generateCap( top ) {
  22330. // save the index of the first center vertex
  22331. const centerIndexStart = index;
  22332. const uv = new Vector2();
  22333. const vertex = new Vector3();
  22334. let groupCount = 0;
  22335. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22336. const sign = ( top === true ) ? 1 : - 1;
  22337. // first we generate the center vertex data of the cap.
  22338. // because the geometry needs one set of uvs per face,
  22339. // we must generate a center vertex per face/segment
  22340. for ( let x = 1; x <= radialSegments; x ++ ) {
  22341. // vertex
  22342. vertices.push( 0, halfHeight * sign, 0 );
  22343. // normal
  22344. normals.push( 0, sign, 0 );
  22345. // uv
  22346. uvs.push( 0.5, 0.5 );
  22347. // increase index
  22348. index ++;
  22349. }
  22350. // save the index of the last center vertex
  22351. const centerIndexEnd = index;
  22352. // now we generate the surrounding vertices, normals and uvs
  22353. for ( let x = 0; x <= radialSegments; x ++ ) {
  22354. const u = x / radialSegments;
  22355. const theta = u * thetaLength + thetaStart;
  22356. const cosTheta = Math.cos( theta );
  22357. const sinTheta = Math.sin( theta );
  22358. // vertex
  22359. vertex.x = radius * sinTheta;
  22360. vertex.y = halfHeight * sign;
  22361. vertex.z = radius * cosTheta;
  22362. vertices.push( vertex.x, vertex.y, vertex.z );
  22363. // normal
  22364. normals.push( 0, sign, 0 );
  22365. // uv
  22366. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22367. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22368. uvs.push( uv.x, uv.y );
  22369. // increase index
  22370. index ++;
  22371. }
  22372. // generate indices
  22373. for ( let x = 0; x < radialSegments; x ++ ) {
  22374. const c = centerIndexStart + x;
  22375. const i = centerIndexEnd + x;
  22376. if ( top === true ) {
  22377. // face top
  22378. indices.push( i, i + 1, c );
  22379. } else {
  22380. // face bottom
  22381. indices.push( i + 1, i, c );
  22382. }
  22383. groupCount += 3;
  22384. }
  22385. // add a group to the geometry. this will ensure multi material support
  22386. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22387. // calculate new start value for groups
  22388. groupStart += groupCount;
  22389. }
  22390. }
  22391. copy( source ) {
  22392. super.copy( source );
  22393. this.parameters = Object.assign( {}, source.parameters );
  22394. return this;
  22395. }
  22396. static fromJSON( data ) {
  22397. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22398. }
  22399. }
  22400. class ConeGeometry extends CylinderGeometry {
  22401. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22402. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22403. this.type = 'ConeGeometry';
  22404. this.parameters = {
  22405. radius: radius,
  22406. height: height,
  22407. radialSegments: radialSegments,
  22408. heightSegments: heightSegments,
  22409. openEnded: openEnded,
  22410. thetaStart: thetaStart,
  22411. thetaLength: thetaLength
  22412. };
  22413. }
  22414. static fromJSON( data ) {
  22415. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22416. }
  22417. }
  22418. class PolyhedronGeometry extends BufferGeometry {
  22419. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22420. super();
  22421. this.type = 'PolyhedronGeometry';
  22422. this.parameters = {
  22423. vertices: vertices,
  22424. indices: indices,
  22425. radius: radius,
  22426. detail: detail
  22427. };
  22428. // default buffer data
  22429. const vertexBuffer = [];
  22430. const uvBuffer = [];
  22431. // the subdivision creates the vertex buffer data
  22432. subdivide( detail );
  22433. // all vertices should lie on a conceptual sphere with a given radius
  22434. applyRadius( radius );
  22435. // finally, create the uv data
  22436. generateUVs();
  22437. // build non-indexed geometry
  22438. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22439. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22440. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22441. if ( detail === 0 ) {
  22442. this.computeVertexNormals(); // flat normals
  22443. } else {
  22444. this.normalizeNormals(); // smooth normals
  22445. }
  22446. // helper functions
  22447. function subdivide( detail ) {
  22448. const a = new Vector3();
  22449. const b = new Vector3();
  22450. const c = new Vector3();
  22451. // iterate over all faces and apply a subdivision with the given detail value
  22452. for ( let i = 0; i < indices.length; i += 3 ) {
  22453. // get the vertices of the face
  22454. getVertexByIndex( indices[ i + 0 ], a );
  22455. getVertexByIndex( indices[ i + 1 ], b );
  22456. getVertexByIndex( indices[ i + 2 ], c );
  22457. // perform subdivision
  22458. subdivideFace( a, b, c, detail );
  22459. }
  22460. }
  22461. function subdivideFace( a, b, c, detail ) {
  22462. const cols = detail + 1;
  22463. // we use this multidimensional array as a data structure for creating the subdivision
  22464. const v = [];
  22465. // construct all of the vertices for this subdivision
  22466. for ( let i = 0; i <= cols; i ++ ) {
  22467. v[ i ] = [];
  22468. const aj = a.clone().lerp( c, i / cols );
  22469. const bj = b.clone().lerp( c, i / cols );
  22470. const rows = cols - i;
  22471. for ( let j = 0; j <= rows; j ++ ) {
  22472. if ( j === 0 && i === cols ) {
  22473. v[ i ][ j ] = aj;
  22474. } else {
  22475. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22476. }
  22477. }
  22478. }
  22479. // construct all of the faces
  22480. for ( let i = 0; i < cols; i ++ ) {
  22481. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22482. const k = Math.floor( j / 2 );
  22483. if ( j % 2 === 0 ) {
  22484. pushVertex( v[ i ][ k + 1 ] );
  22485. pushVertex( v[ i + 1 ][ k ] );
  22486. pushVertex( v[ i ][ k ] );
  22487. } else {
  22488. pushVertex( v[ i ][ k + 1 ] );
  22489. pushVertex( v[ i + 1 ][ k + 1 ] );
  22490. pushVertex( v[ i + 1 ][ k ] );
  22491. }
  22492. }
  22493. }
  22494. }
  22495. function applyRadius( radius ) {
  22496. const vertex = new Vector3();
  22497. // iterate over the entire buffer and apply the radius to each vertex
  22498. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22499. vertex.x = vertexBuffer[ i + 0 ];
  22500. vertex.y = vertexBuffer[ i + 1 ];
  22501. vertex.z = vertexBuffer[ i + 2 ];
  22502. vertex.normalize().multiplyScalar( radius );
  22503. vertexBuffer[ i + 0 ] = vertex.x;
  22504. vertexBuffer[ i + 1 ] = vertex.y;
  22505. vertexBuffer[ i + 2 ] = vertex.z;
  22506. }
  22507. }
  22508. function generateUVs() {
  22509. const vertex = new Vector3();
  22510. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22511. vertex.x = vertexBuffer[ i + 0 ];
  22512. vertex.y = vertexBuffer[ i + 1 ];
  22513. vertex.z = vertexBuffer[ i + 2 ];
  22514. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22515. const v = inclination( vertex ) / Math.PI + 0.5;
  22516. uvBuffer.push( u, 1 - v );
  22517. }
  22518. correctUVs();
  22519. correctSeam();
  22520. }
  22521. function correctSeam() {
  22522. // handle case when face straddles the seam, see #3269
  22523. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22524. // uv data of a single face
  22525. const x0 = uvBuffer[ i + 0 ];
  22526. const x1 = uvBuffer[ i + 2 ];
  22527. const x2 = uvBuffer[ i + 4 ];
  22528. const max = Math.max( x0, x1, x2 );
  22529. const min = Math.min( x0, x1, x2 );
  22530. // 0.9 is somewhat arbitrary
  22531. if ( max > 0.9 && min < 0.1 ) {
  22532. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22533. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22534. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22535. }
  22536. }
  22537. }
  22538. function pushVertex( vertex ) {
  22539. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22540. }
  22541. function getVertexByIndex( index, vertex ) {
  22542. const stride = index * 3;
  22543. vertex.x = vertices[ stride + 0 ];
  22544. vertex.y = vertices[ stride + 1 ];
  22545. vertex.z = vertices[ stride + 2 ];
  22546. }
  22547. function correctUVs() {
  22548. const a = new Vector3();
  22549. const b = new Vector3();
  22550. const c = new Vector3();
  22551. const centroid = new Vector3();
  22552. const uvA = new Vector2();
  22553. const uvB = new Vector2();
  22554. const uvC = new Vector2();
  22555. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22556. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22557. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22558. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22559. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22560. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22561. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22562. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22563. const azi = azimuth( centroid );
  22564. correctUV( uvA, j + 0, a, azi );
  22565. correctUV( uvB, j + 2, b, azi );
  22566. correctUV( uvC, j + 4, c, azi );
  22567. }
  22568. }
  22569. function correctUV( uv, stride, vector, azimuth ) {
  22570. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22571. uvBuffer[ stride ] = uv.x - 1;
  22572. }
  22573. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22574. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22575. }
  22576. }
  22577. // Angle around the Y axis, counter-clockwise when looking from above.
  22578. function azimuth( vector ) {
  22579. return Math.atan2( vector.z, - vector.x );
  22580. }
  22581. // Angle above the XZ plane.
  22582. function inclination( vector ) {
  22583. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22584. }
  22585. }
  22586. copy( source ) {
  22587. super.copy( source );
  22588. this.parameters = Object.assign( {}, source.parameters );
  22589. return this;
  22590. }
  22591. static fromJSON( data ) {
  22592. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22593. }
  22594. }
  22595. class DodecahedronGeometry extends PolyhedronGeometry {
  22596. constructor( radius = 1, detail = 0 ) {
  22597. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22598. const r = 1 / t;
  22599. const vertices = [
  22600. // (±1, ±1, ±1)
  22601. - 1, - 1, - 1, - 1, - 1, 1,
  22602. - 1, 1, - 1, - 1, 1, 1,
  22603. 1, - 1, - 1, 1, - 1, 1,
  22604. 1, 1, - 1, 1, 1, 1,
  22605. // (0, ±1/φ, ±φ)
  22606. 0, - r, - t, 0, - r, t,
  22607. 0, r, - t, 0, r, t,
  22608. // (±1/φ, ±φ, 0)
  22609. - r, - t, 0, - r, t, 0,
  22610. r, - t, 0, r, t, 0,
  22611. // (±φ, 0, ±1/φ)
  22612. - t, 0, - r, t, 0, - r,
  22613. - t, 0, r, t, 0, r
  22614. ];
  22615. const indices = [
  22616. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22617. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22618. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22619. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22620. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22621. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22622. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22623. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22624. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22625. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22626. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22627. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22628. ];
  22629. super( vertices, indices, radius, detail );
  22630. this.type = 'DodecahedronGeometry';
  22631. this.parameters = {
  22632. radius: radius,
  22633. detail: detail
  22634. };
  22635. }
  22636. static fromJSON( data ) {
  22637. return new DodecahedronGeometry( data.radius, data.detail );
  22638. }
  22639. }
  22640. const _v0 = /*@__PURE__*/ new Vector3();
  22641. const _v1$1 = /*@__PURE__*/ new Vector3();
  22642. const _normal = /*@__PURE__*/ new Vector3();
  22643. const _triangle = /*@__PURE__*/ new Triangle();
  22644. class EdgesGeometry extends BufferGeometry {
  22645. constructor( geometry = null, thresholdAngle = 1 ) {
  22646. super();
  22647. this.type = 'EdgesGeometry';
  22648. this.parameters = {
  22649. geometry: geometry,
  22650. thresholdAngle: thresholdAngle
  22651. };
  22652. if ( geometry !== null ) {
  22653. const precisionPoints = 4;
  22654. const precision = Math.pow( 10, precisionPoints );
  22655. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22656. const indexAttr = geometry.getIndex();
  22657. const positionAttr = geometry.getAttribute( 'position' );
  22658. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22659. const indexArr = [ 0, 0, 0 ];
  22660. const vertKeys = [ 'a', 'b', 'c' ];
  22661. const hashes = new Array( 3 );
  22662. const edgeData = {};
  22663. const vertices = [];
  22664. for ( let i = 0; i < indexCount; i += 3 ) {
  22665. if ( indexAttr ) {
  22666. indexArr[ 0 ] = indexAttr.getX( i );
  22667. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22668. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22669. } else {
  22670. indexArr[ 0 ] = i;
  22671. indexArr[ 1 ] = i + 1;
  22672. indexArr[ 2 ] = i + 2;
  22673. }
  22674. const { a, b, c } = _triangle;
  22675. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22676. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22677. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22678. _triangle.getNormal( _normal );
  22679. // create hashes for the edge from the vertices
  22680. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22681. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22682. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22683. // skip degenerate triangles
  22684. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22685. continue;
  22686. }
  22687. // iterate over every edge
  22688. for ( let j = 0; j < 3; j ++ ) {
  22689. // get the first and next vertex making up the edge
  22690. const jNext = ( j + 1 ) % 3;
  22691. const vecHash0 = hashes[ j ];
  22692. const vecHash1 = hashes[ jNext ];
  22693. const v0 = _triangle[ vertKeys[ j ] ];
  22694. const v1 = _triangle[ vertKeys[ jNext ] ];
  22695. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22696. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22697. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22698. // if we found a sibling edge add it into the vertex array if
  22699. // it meets the angle threshold and delete the edge from the map.
  22700. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22701. vertices.push( v0.x, v0.y, v0.z );
  22702. vertices.push( v1.x, v1.y, v1.z );
  22703. }
  22704. edgeData[ reverseHash ] = null;
  22705. } else if ( ! ( hash in edgeData ) ) {
  22706. // if we've already got an edge here then skip adding a new one
  22707. edgeData[ hash ] = {
  22708. index0: indexArr[ j ],
  22709. index1: indexArr[ jNext ],
  22710. normal: _normal.clone(),
  22711. };
  22712. }
  22713. }
  22714. }
  22715. // iterate over all remaining, unmatched edges and add them to the vertex array
  22716. for ( const key in edgeData ) {
  22717. if ( edgeData[ key ] ) {
  22718. const { index0, index1 } = edgeData[ key ];
  22719. _v0.fromBufferAttribute( positionAttr, index0 );
  22720. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22721. vertices.push( _v0.x, _v0.y, _v0.z );
  22722. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22723. }
  22724. }
  22725. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22726. }
  22727. }
  22728. copy( source ) {
  22729. super.copy( source );
  22730. this.parameters = Object.assign( {}, source.parameters );
  22731. return this;
  22732. }
  22733. }
  22734. class Shape extends Path {
  22735. constructor( points ) {
  22736. super( points );
  22737. this.uuid = generateUUID();
  22738. this.type = 'Shape';
  22739. this.holes = [];
  22740. }
  22741. getPointsHoles( divisions ) {
  22742. const holesPts = [];
  22743. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22744. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  22745. }
  22746. return holesPts;
  22747. }
  22748. // get points of shape and holes (keypoints based on segments parameter)
  22749. extractPoints( divisions ) {
  22750. return {
  22751. shape: this.getPoints( divisions ),
  22752. holes: this.getPointsHoles( divisions )
  22753. };
  22754. }
  22755. copy( source ) {
  22756. super.copy( source );
  22757. this.holes = [];
  22758. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  22759. const hole = source.holes[ i ];
  22760. this.holes.push( hole.clone() );
  22761. }
  22762. return this;
  22763. }
  22764. toJSON() {
  22765. const data = super.toJSON();
  22766. data.uuid = this.uuid;
  22767. data.holes = [];
  22768. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22769. const hole = this.holes[ i ];
  22770. data.holes.push( hole.toJSON() );
  22771. }
  22772. return data;
  22773. }
  22774. fromJSON( json ) {
  22775. super.fromJSON( json );
  22776. this.uuid = json.uuid;
  22777. this.holes = [];
  22778. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  22779. const hole = json.holes[ i ];
  22780. this.holes.push( new Path().fromJSON( hole ) );
  22781. }
  22782. return this;
  22783. }
  22784. }
  22785. /**
  22786. * Port from https://github.com/mapbox/earcut (v2.2.4)
  22787. */
  22788. const Earcut = {
  22789. triangulate: function ( data, holeIndices, dim = 2 ) {
  22790. const hasHoles = holeIndices && holeIndices.length;
  22791. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  22792. let outerNode = linkedList( data, 0, outerLen, dim, true );
  22793. const triangles = [];
  22794. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  22795. let minX, minY, maxX, maxY, x, y, invSize;
  22796. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  22797. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  22798. if ( data.length > 80 * dim ) {
  22799. minX = maxX = data[ 0 ];
  22800. minY = maxY = data[ 1 ];
  22801. for ( let i = dim; i < outerLen; i += dim ) {
  22802. x = data[ i ];
  22803. y = data[ i + 1 ];
  22804. if ( x < minX ) minX = x;
  22805. if ( y < minY ) minY = y;
  22806. if ( x > maxX ) maxX = x;
  22807. if ( y > maxY ) maxY = y;
  22808. }
  22809. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  22810. invSize = Math.max( maxX - minX, maxY - minY );
  22811. invSize = invSize !== 0 ? 32767 / invSize : 0;
  22812. }
  22813. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  22814. return triangles;
  22815. }
  22816. };
  22817. // create a circular doubly linked list from polygon points in the specified winding order
  22818. function linkedList( data, start, end, dim, clockwise ) {
  22819. let i, last;
  22820. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  22821. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22822. } else {
  22823. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22824. }
  22825. if ( last && equals( last, last.next ) ) {
  22826. removeNode( last );
  22827. last = last.next;
  22828. }
  22829. return last;
  22830. }
  22831. // eliminate colinear or duplicate points
  22832. function filterPoints( start, end ) {
  22833. if ( ! start ) return start;
  22834. if ( ! end ) end = start;
  22835. let p = start,
  22836. again;
  22837. do {
  22838. again = false;
  22839. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  22840. removeNode( p );
  22841. p = end = p.prev;
  22842. if ( p === p.next ) break;
  22843. again = true;
  22844. } else {
  22845. p = p.next;
  22846. }
  22847. } while ( again || p !== end );
  22848. return end;
  22849. }
  22850. // main ear slicing loop which triangulates a polygon (given as a linked list)
  22851. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  22852. if ( ! ear ) return;
  22853. // interlink polygon nodes in z-order
  22854. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  22855. let stop = ear,
  22856. prev, next;
  22857. // iterate through ears, slicing them one by one
  22858. while ( ear.prev !== ear.next ) {
  22859. prev = ear.prev;
  22860. next = ear.next;
  22861. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  22862. // cut off the triangle
  22863. triangles.push( prev.i / dim | 0 );
  22864. triangles.push( ear.i / dim | 0 );
  22865. triangles.push( next.i / dim | 0 );
  22866. removeNode( ear );
  22867. // skipping the next vertex leads to less sliver triangles
  22868. ear = next.next;
  22869. stop = next.next;
  22870. continue;
  22871. }
  22872. ear = next;
  22873. // if we looped through the whole remaining polygon and can't find any more ears
  22874. if ( ear === stop ) {
  22875. // try filtering points and slicing again
  22876. if ( ! pass ) {
  22877. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  22878. // if this didn't work, try curing all small self-intersections locally
  22879. } else if ( pass === 1 ) {
  22880. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  22881. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  22882. // as a last resort, try splitting the remaining polygon into two
  22883. } else if ( pass === 2 ) {
  22884. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  22885. }
  22886. break;
  22887. }
  22888. }
  22889. }
  22890. // check whether a polygon node forms a valid ear with adjacent nodes
  22891. function isEar( ear ) {
  22892. const a = ear.prev,
  22893. b = ear,
  22894. c = ear.next;
  22895. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22896. // now make sure we don't have other points inside the potential ear
  22897. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22898. // triangle bbox; min & max are calculated like this for speed
  22899. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22900. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22901. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22902. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22903. let p = c.next;
  22904. while ( p !== a ) {
  22905. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  22906. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  22907. area( p.prev, p, p.next ) >= 0 ) return false;
  22908. p = p.next;
  22909. }
  22910. return true;
  22911. }
  22912. function isEarHashed( ear, minX, minY, invSize ) {
  22913. const a = ear.prev,
  22914. b = ear,
  22915. c = ear.next;
  22916. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22917. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22918. // triangle bbox; min & max are calculated like this for speed
  22919. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22920. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22921. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22922. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22923. // z-order range for the current triangle bbox;
  22924. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  22925. maxZ = zOrder( x1, y1, minX, minY, invSize );
  22926. let p = ear.prevZ,
  22927. n = ear.nextZ;
  22928. // look for points inside the triangle in both directions
  22929. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  22930. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22931. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22932. p = p.prevZ;
  22933. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22934. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22935. n = n.nextZ;
  22936. }
  22937. // look for remaining points in decreasing z-order
  22938. while ( p && p.z >= minZ ) {
  22939. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22940. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22941. p = p.prevZ;
  22942. }
  22943. // look for remaining points in increasing z-order
  22944. while ( n && n.z <= maxZ ) {
  22945. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22946. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22947. n = n.nextZ;
  22948. }
  22949. return true;
  22950. }
  22951. // go through all polygon nodes and cure small local self-intersections
  22952. function cureLocalIntersections( start, triangles, dim ) {
  22953. let p = start;
  22954. do {
  22955. const a = p.prev,
  22956. b = p.next.next;
  22957. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  22958. triangles.push( a.i / dim | 0 );
  22959. triangles.push( p.i / dim | 0 );
  22960. triangles.push( b.i / dim | 0 );
  22961. // remove two nodes involved
  22962. removeNode( p );
  22963. removeNode( p.next );
  22964. p = start = b;
  22965. }
  22966. p = p.next;
  22967. } while ( p !== start );
  22968. return filterPoints( p );
  22969. }
  22970. // try splitting polygon into two and triangulate them independently
  22971. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  22972. // look for a valid diagonal that divides the polygon into two
  22973. let a = start;
  22974. do {
  22975. let b = a.next.next;
  22976. while ( b !== a.prev ) {
  22977. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  22978. // split the polygon in two by the diagonal
  22979. let c = splitPolygon( a, b );
  22980. // filter colinear points around the cuts
  22981. a = filterPoints( a, a.next );
  22982. c = filterPoints( c, c.next );
  22983. // run earcut on each half
  22984. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  22985. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  22986. return;
  22987. }
  22988. b = b.next;
  22989. }
  22990. a = a.next;
  22991. } while ( a !== start );
  22992. }
  22993. // link every hole into the outer loop, producing a single-ring polygon without holes
  22994. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  22995. const queue = [];
  22996. let i, len, start, end, list;
  22997. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  22998. start = holeIndices[ i ] * dim;
  22999. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  23000. list = linkedList( data, start, end, dim, false );
  23001. if ( list === list.next ) list.steiner = true;
  23002. queue.push( getLeftmost( list ) );
  23003. }
  23004. queue.sort( compareX );
  23005. // process holes from left to right
  23006. for ( i = 0; i < queue.length; i ++ ) {
  23007. outerNode = eliminateHole( queue[ i ], outerNode );
  23008. }
  23009. return outerNode;
  23010. }
  23011. function compareX( a, b ) {
  23012. return a.x - b.x;
  23013. }
  23014. // find a bridge between vertices that connects hole with an outer ring and link it
  23015. function eliminateHole( hole, outerNode ) {
  23016. const bridge = findHoleBridge( hole, outerNode );
  23017. if ( ! bridge ) {
  23018. return outerNode;
  23019. }
  23020. const bridgeReverse = splitPolygon( bridge, hole );
  23021. // filter collinear points around the cuts
  23022. filterPoints( bridgeReverse, bridgeReverse.next );
  23023. return filterPoints( bridge, bridge.next );
  23024. }
  23025. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  23026. function findHoleBridge( hole, outerNode ) {
  23027. let p = outerNode,
  23028. qx = - Infinity,
  23029. m;
  23030. const hx = hole.x, hy = hole.y;
  23031. // find a segment intersected by a ray from the hole's leftmost point to the left;
  23032. // segment's endpoint with lesser x will be potential connection point
  23033. do {
  23034. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  23035. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  23036. if ( x <= hx && x > qx ) {
  23037. qx = x;
  23038. m = p.x < p.next.x ? p : p.next;
  23039. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  23040. }
  23041. }
  23042. p = p.next;
  23043. } while ( p !== outerNode );
  23044. if ( ! m ) return null;
  23045. // look for points inside the triangle of hole point, segment intersection and endpoint;
  23046. // if there are no points found, we have a valid connection;
  23047. // otherwise choose the point of the minimum angle with the ray as connection point
  23048. const stop = m,
  23049. mx = m.x,
  23050. my = m.y;
  23051. let tanMin = Infinity, tan;
  23052. p = m;
  23053. do {
  23054. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  23055. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  23056. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  23057. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  23058. m = p;
  23059. tanMin = tan;
  23060. }
  23061. }
  23062. p = p.next;
  23063. } while ( p !== stop );
  23064. return m;
  23065. }
  23066. // whether sector in vertex m contains sector in vertex p in the same coordinates
  23067. function sectorContainsSector( m, p ) {
  23068. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  23069. }
  23070. // interlink polygon nodes in z-order
  23071. function indexCurve( start, minX, minY, invSize ) {
  23072. let p = start;
  23073. do {
  23074. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  23075. p.prevZ = p.prev;
  23076. p.nextZ = p.next;
  23077. p = p.next;
  23078. } while ( p !== start );
  23079. p.prevZ.nextZ = null;
  23080. p.prevZ = null;
  23081. sortLinked( p );
  23082. }
  23083. // Simon Tatham's linked list merge sort algorithm
  23084. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  23085. function sortLinked( list ) {
  23086. let i, p, q, e, tail, numMerges, pSize, qSize,
  23087. inSize = 1;
  23088. do {
  23089. p = list;
  23090. list = null;
  23091. tail = null;
  23092. numMerges = 0;
  23093. while ( p ) {
  23094. numMerges ++;
  23095. q = p;
  23096. pSize = 0;
  23097. for ( i = 0; i < inSize; i ++ ) {
  23098. pSize ++;
  23099. q = q.nextZ;
  23100. if ( ! q ) break;
  23101. }
  23102. qSize = inSize;
  23103. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  23104. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  23105. e = p;
  23106. p = p.nextZ;
  23107. pSize --;
  23108. } else {
  23109. e = q;
  23110. q = q.nextZ;
  23111. qSize --;
  23112. }
  23113. if ( tail ) tail.nextZ = e;
  23114. else list = e;
  23115. e.prevZ = tail;
  23116. tail = e;
  23117. }
  23118. p = q;
  23119. }
  23120. tail.nextZ = null;
  23121. inSize *= 2;
  23122. } while ( numMerges > 1 );
  23123. return list;
  23124. }
  23125. // z-order of a point given coords and inverse of the longer side of data bbox
  23126. function zOrder( x, y, minX, minY, invSize ) {
  23127. // coords are transformed into non-negative 15-bit integer range
  23128. x = ( x - minX ) * invSize | 0;
  23129. y = ( y - minY ) * invSize | 0;
  23130. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  23131. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  23132. x = ( x | ( x << 2 ) ) & 0x33333333;
  23133. x = ( x | ( x << 1 ) ) & 0x55555555;
  23134. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  23135. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  23136. y = ( y | ( y << 2 ) ) & 0x33333333;
  23137. y = ( y | ( y << 1 ) ) & 0x55555555;
  23138. return x | ( y << 1 );
  23139. }
  23140. // find the leftmost node of a polygon ring
  23141. function getLeftmost( start ) {
  23142. let p = start,
  23143. leftmost = start;
  23144. do {
  23145. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  23146. p = p.next;
  23147. } while ( p !== start );
  23148. return leftmost;
  23149. }
  23150. // check if a point lies within a convex triangle
  23151. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  23152. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  23153. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  23154. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  23155. }
  23156. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  23157. function isValidDiagonal( a, b ) {
  23158. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  23159. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  23160. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  23161. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  23162. }
  23163. // signed area of a triangle
  23164. function area( p, q, r ) {
  23165. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  23166. }
  23167. // check if two points are equal
  23168. function equals( p1, p2 ) {
  23169. return p1.x === p2.x && p1.y === p2.y;
  23170. }
  23171. // check if two segments intersect
  23172. function intersects( p1, q1, p2, q2 ) {
  23173. const o1 = sign( area( p1, q1, p2 ) );
  23174. const o2 = sign( area( p1, q1, q2 ) );
  23175. const o3 = sign( area( p2, q2, p1 ) );
  23176. const o4 = sign( area( p2, q2, q1 ) );
  23177. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  23178. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  23179. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  23180. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  23181. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  23182. return false;
  23183. }
  23184. // for collinear points p, q, r, check if point q lies on segment pr
  23185. function onSegment( p, q, r ) {
  23186. 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 );
  23187. }
  23188. function sign( num ) {
  23189. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  23190. }
  23191. // check if a polygon diagonal intersects any polygon segments
  23192. function intersectsPolygon( a, b ) {
  23193. let p = a;
  23194. do {
  23195. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  23196. intersects( p, p.next, a, b ) ) return true;
  23197. p = p.next;
  23198. } while ( p !== a );
  23199. return false;
  23200. }
  23201. // check if a polygon diagonal is locally inside the polygon
  23202. function locallyInside( a, b ) {
  23203. return area( a.prev, a, a.next ) < 0 ?
  23204. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  23205. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  23206. }
  23207. // check if the middle point of a polygon diagonal is inside the polygon
  23208. function middleInside( a, b ) {
  23209. let p = a,
  23210. inside = false;
  23211. const px = ( a.x + b.x ) / 2,
  23212. py = ( a.y + b.y ) / 2;
  23213. do {
  23214. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  23215. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  23216. inside = ! inside;
  23217. p = p.next;
  23218. } while ( p !== a );
  23219. return inside;
  23220. }
  23221. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  23222. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  23223. function splitPolygon( a, b ) {
  23224. const a2 = new Node( a.i, a.x, a.y ),
  23225. b2 = new Node( b.i, b.x, b.y ),
  23226. an = a.next,
  23227. bp = b.prev;
  23228. a.next = b;
  23229. b.prev = a;
  23230. a2.next = an;
  23231. an.prev = a2;
  23232. b2.next = a2;
  23233. a2.prev = b2;
  23234. bp.next = b2;
  23235. b2.prev = bp;
  23236. return b2;
  23237. }
  23238. // create a node and optionally link it with previous one (in a circular doubly linked list)
  23239. function insertNode( i, x, y, last ) {
  23240. const p = new Node( i, x, y );
  23241. if ( ! last ) {
  23242. p.prev = p;
  23243. p.next = p;
  23244. } else {
  23245. p.next = last.next;
  23246. p.prev = last;
  23247. last.next.prev = p;
  23248. last.next = p;
  23249. }
  23250. return p;
  23251. }
  23252. function removeNode( p ) {
  23253. p.next.prev = p.prev;
  23254. p.prev.next = p.next;
  23255. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  23256. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  23257. }
  23258. function Node( i, x, y ) {
  23259. // vertex index in coordinates array
  23260. this.i = i;
  23261. // vertex coordinates
  23262. this.x = x;
  23263. this.y = y;
  23264. // previous and next vertex nodes in a polygon ring
  23265. this.prev = null;
  23266. this.next = null;
  23267. // z-order curve value
  23268. this.z = 0;
  23269. // previous and next nodes in z-order
  23270. this.prevZ = null;
  23271. this.nextZ = null;
  23272. // indicates whether this is a steiner point
  23273. this.steiner = false;
  23274. }
  23275. function signedArea( data, start, end, dim ) {
  23276. let sum = 0;
  23277. for ( let i = start, j = end - dim; i < end; i += dim ) {
  23278. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  23279. j = i;
  23280. }
  23281. return sum;
  23282. }
  23283. class ShapeUtils {
  23284. // calculate area of the contour polygon
  23285. static area( contour ) {
  23286. const n = contour.length;
  23287. let a = 0.0;
  23288. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  23289. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  23290. }
  23291. return a * 0.5;
  23292. }
  23293. static isClockWise( pts ) {
  23294. return ShapeUtils.area( pts ) < 0;
  23295. }
  23296. static triangulateShape( contour, holes ) {
  23297. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  23298. const holeIndices = []; // array of hole indices
  23299. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  23300. removeDupEndPts( contour );
  23301. addContour( vertices, contour );
  23302. //
  23303. let holeIndex = contour.length;
  23304. holes.forEach( removeDupEndPts );
  23305. for ( let i = 0; i < holes.length; i ++ ) {
  23306. holeIndices.push( holeIndex );
  23307. holeIndex += holes[ i ].length;
  23308. addContour( vertices, holes[ i ] );
  23309. }
  23310. //
  23311. const triangles = Earcut.triangulate( vertices, holeIndices );
  23312. //
  23313. for ( let i = 0; i < triangles.length; i += 3 ) {
  23314. faces.push( triangles.slice( i, i + 3 ) );
  23315. }
  23316. return faces;
  23317. }
  23318. }
  23319. function removeDupEndPts( points ) {
  23320. const l = points.length;
  23321. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  23322. points.pop();
  23323. }
  23324. }
  23325. function addContour( vertices, contour ) {
  23326. for ( let i = 0; i < contour.length; i ++ ) {
  23327. vertices.push( contour[ i ].x );
  23328. vertices.push( contour[ i ].y );
  23329. }
  23330. }
  23331. /**
  23332. * Creates extruded geometry from a path shape.
  23333. *
  23334. * parameters = {
  23335. *
  23336. * curveSegments: <int>, // number of points on the curves
  23337. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  23338. * depth: <float>, // Depth to extrude the shape
  23339. *
  23340. * bevelEnabled: <bool>, // turn on bevel
  23341. * bevelThickness: <float>, // how deep into the original shape bevel goes
  23342. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  23343. * bevelOffset: <float>, // how far from shape outline does bevel start
  23344. * bevelSegments: <int>, // number of bevel layers
  23345. *
  23346. * extrudePath: <THREE.Curve> // curve to extrude shape along
  23347. *
  23348. * UVGenerator: <Object> // object that provides UV generator functions
  23349. *
  23350. * }
  23351. */
  23352. class ExtrudeGeometry extends BufferGeometry {
  23353. 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 = {} ) {
  23354. super();
  23355. this.type = 'ExtrudeGeometry';
  23356. this.parameters = {
  23357. shapes: shapes,
  23358. options: options
  23359. };
  23360. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  23361. const scope = this;
  23362. const verticesArray = [];
  23363. const uvArray = [];
  23364. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23365. const shape = shapes[ i ];
  23366. addShape( shape );
  23367. }
  23368. // build geometry
  23369. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  23370. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  23371. this.computeVertexNormals();
  23372. // functions
  23373. function addShape( shape ) {
  23374. const placeholder = [];
  23375. // options
  23376. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  23377. const steps = options.steps !== undefined ? options.steps : 1;
  23378. const depth = options.depth !== undefined ? options.depth : 1;
  23379. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  23380. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  23381. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  23382. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  23383. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  23384. const extrudePath = options.extrudePath;
  23385. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  23386. //
  23387. let extrudePts, extrudeByPath = false;
  23388. let splineTube, binormal, normal, position2;
  23389. if ( extrudePath ) {
  23390. extrudePts = extrudePath.getSpacedPoints( steps );
  23391. extrudeByPath = true;
  23392. bevelEnabled = false; // bevels not supported for path extrusion
  23393. // SETUP TNB variables
  23394. // TODO1 - have a .isClosed in spline?
  23395. splineTube = extrudePath.computeFrenetFrames( steps, false );
  23396. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  23397. binormal = new Vector3();
  23398. normal = new Vector3();
  23399. position2 = new Vector3();
  23400. }
  23401. // Safeguards if bevels are not enabled
  23402. if ( ! bevelEnabled ) {
  23403. bevelSegments = 0;
  23404. bevelThickness = 0;
  23405. bevelSize = 0;
  23406. bevelOffset = 0;
  23407. }
  23408. // Variables initialization
  23409. const shapePoints = shape.extractPoints( curveSegments );
  23410. let vertices = shapePoints.shape;
  23411. const holes = shapePoints.holes;
  23412. const reverse = ! ShapeUtils.isClockWise( vertices );
  23413. if ( reverse ) {
  23414. vertices = vertices.reverse();
  23415. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  23416. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23417. const ahole = holes[ h ];
  23418. if ( ShapeUtils.isClockWise( ahole ) ) {
  23419. holes[ h ] = ahole.reverse();
  23420. }
  23421. }
  23422. }
  23423. const faces = ShapeUtils.triangulateShape( vertices, holes );
  23424. /* Vertices */
  23425. const contour = vertices; // vertices has all points but contour has only points of circumference
  23426. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23427. const ahole = holes[ h ];
  23428. vertices = vertices.concat( ahole );
  23429. }
  23430. function scalePt2( pt, vec, size ) {
  23431. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  23432. return pt.clone().addScaledVector( vec, size );
  23433. }
  23434. const vlen = vertices.length, flen = faces.length;
  23435. // Find directions for point movement
  23436. function getBevelVec( inPt, inPrev, inNext ) {
  23437. // computes for inPt the corresponding point inPt' on a new contour
  23438. // shifted by 1 unit (length of normalized vector) to the left
  23439. // if we walk along contour clockwise, this new contour is outside the old one
  23440. //
  23441. // inPt' is the intersection of the two lines parallel to the two
  23442. // adjacent edges of inPt at a distance of 1 unit on the left side.
  23443. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  23444. // good reading for geometry algorithms (here: line-line intersection)
  23445. // http://geomalgorithms.com/a05-_intersect-1.html
  23446. const v_prev_x = inPt.x - inPrev.x,
  23447. v_prev_y = inPt.y - inPrev.y;
  23448. const v_next_x = inNext.x - inPt.x,
  23449. v_next_y = inNext.y - inPt.y;
  23450. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  23451. // check for collinear edges
  23452. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23453. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  23454. // not collinear
  23455. // length of vectors for normalizing
  23456. const v_prev_len = Math.sqrt( v_prev_lensq );
  23457. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  23458. // shift adjacent points by unit vectors to the left
  23459. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  23460. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  23461. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  23462. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  23463. // scaling factor for v_prev to intersection point
  23464. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  23465. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  23466. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23467. // vector from inPt to intersection point
  23468. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  23469. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  23470. // Don't normalize!, otherwise sharp corners become ugly
  23471. // but prevent crazy spikes
  23472. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  23473. if ( v_trans_lensq <= 2 ) {
  23474. return new Vector2( v_trans_x, v_trans_y );
  23475. } else {
  23476. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  23477. }
  23478. } else {
  23479. // handle special case of collinear edges
  23480. let direction_eq = false; // assumes: opposite
  23481. if ( v_prev_x > Number.EPSILON ) {
  23482. if ( v_next_x > Number.EPSILON ) {
  23483. direction_eq = true;
  23484. }
  23485. } else {
  23486. if ( v_prev_x < - Number.EPSILON ) {
  23487. if ( v_next_x < - Number.EPSILON ) {
  23488. direction_eq = true;
  23489. }
  23490. } else {
  23491. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  23492. direction_eq = true;
  23493. }
  23494. }
  23495. }
  23496. if ( direction_eq ) {
  23497. // console.log("Warning: lines are a straight sequence");
  23498. v_trans_x = - v_prev_y;
  23499. v_trans_y = v_prev_x;
  23500. shrink_by = Math.sqrt( v_prev_lensq );
  23501. } else {
  23502. // console.log("Warning: lines are a straight spike");
  23503. v_trans_x = v_prev_x;
  23504. v_trans_y = v_prev_y;
  23505. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  23506. }
  23507. }
  23508. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  23509. }
  23510. const contourMovements = [];
  23511. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23512. if ( j === il ) j = 0;
  23513. if ( k === il ) k = 0;
  23514. // (j)---(i)---(k)
  23515. // console.log('i,j,k', i, j , k)
  23516. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  23517. }
  23518. const holesMovements = [];
  23519. let oneHoleMovements, verticesMovements = contourMovements.concat();
  23520. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23521. const ahole = holes[ h ];
  23522. oneHoleMovements = [];
  23523. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23524. if ( j === il ) j = 0;
  23525. if ( k === il ) k = 0;
  23526. // (j)---(i)---(k)
  23527. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  23528. }
  23529. holesMovements.push( oneHoleMovements );
  23530. verticesMovements = verticesMovements.concat( oneHoleMovements );
  23531. }
  23532. // Loop bevelSegments, 1 for the front, 1 for the back
  23533. for ( let b = 0; b < bevelSegments; b ++ ) {
  23534. //for ( b = bevelSegments; b > 0; b -- ) {
  23535. const t = b / bevelSegments;
  23536. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23537. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23538. // contract shape
  23539. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23540. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23541. v( vert.x, vert.y, - z );
  23542. }
  23543. // expand holes
  23544. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23545. const ahole = holes[ h ];
  23546. oneHoleMovements = holesMovements[ h ];
  23547. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23548. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23549. v( vert.x, vert.y, - z );
  23550. }
  23551. }
  23552. }
  23553. const bs = bevelSize + bevelOffset;
  23554. // Back facing vertices
  23555. for ( let i = 0; i < vlen; i ++ ) {
  23556. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23557. if ( ! extrudeByPath ) {
  23558. v( vert.x, vert.y, 0 );
  23559. } else {
  23560. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  23561. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  23562. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  23563. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  23564. v( position2.x, position2.y, position2.z );
  23565. }
  23566. }
  23567. // Add stepped vertices...
  23568. // Including front facing vertices
  23569. for ( let s = 1; s <= steps; s ++ ) {
  23570. for ( let i = 0; i < vlen; i ++ ) {
  23571. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23572. if ( ! extrudeByPath ) {
  23573. v( vert.x, vert.y, depth / steps * s );
  23574. } else {
  23575. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  23576. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  23577. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  23578. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  23579. v( position2.x, position2.y, position2.z );
  23580. }
  23581. }
  23582. }
  23583. // Add bevel segments planes
  23584. //for ( b = 1; b <= bevelSegments; b ++ ) {
  23585. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  23586. const t = b / bevelSegments;
  23587. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23588. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23589. // contract shape
  23590. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23591. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23592. v( vert.x, vert.y, depth + z );
  23593. }
  23594. // expand holes
  23595. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23596. const ahole = holes[ h ];
  23597. oneHoleMovements = holesMovements[ h ];
  23598. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23599. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23600. if ( ! extrudeByPath ) {
  23601. v( vert.x, vert.y, depth + z );
  23602. } else {
  23603. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  23604. }
  23605. }
  23606. }
  23607. }
  23608. /* Faces */
  23609. // Top and bottom faces
  23610. buildLidFaces();
  23611. // Sides faces
  23612. buildSideFaces();
  23613. ///// Internal functions
  23614. function buildLidFaces() {
  23615. const start = verticesArray.length / 3;
  23616. if ( bevelEnabled ) {
  23617. let layer = 0; // steps + 1
  23618. let offset = vlen * layer;
  23619. // Bottom faces
  23620. for ( let i = 0; i < flen; i ++ ) {
  23621. const face = faces[ i ];
  23622. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  23623. }
  23624. layer = steps + bevelSegments * 2;
  23625. offset = vlen * layer;
  23626. // Top faces
  23627. for ( let i = 0; i < flen; i ++ ) {
  23628. const face = faces[ i ];
  23629. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  23630. }
  23631. } else {
  23632. // Bottom faces
  23633. for ( let i = 0; i < flen; i ++ ) {
  23634. const face = faces[ i ];
  23635. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  23636. }
  23637. // Top faces
  23638. for ( let i = 0; i < flen; i ++ ) {
  23639. const face = faces[ i ];
  23640. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  23641. }
  23642. }
  23643. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  23644. }
  23645. // Create faces for the z-sides of the shape
  23646. function buildSideFaces() {
  23647. const start = verticesArray.length / 3;
  23648. let layeroffset = 0;
  23649. sidewalls( contour, layeroffset );
  23650. layeroffset += contour.length;
  23651. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23652. const ahole = holes[ h ];
  23653. sidewalls( ahole, layeroffset );
  23654. //, true
  23655. layeroffset += ahole.length;
  23656. }
  23657. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  23658. }
  23659. function sidewalls( contour, layeroffset ) {
  23660. let i = contour.length;
  23661. while ( -- i >= 0 ) {
  23662. const j = i;
  23663. let k = i - 1;
  23664. if ( k < 0 ) k = contour.length - 1;
  23665. //console.log('b', i,j, i-1, k,vertices.length);
  23666. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  23667. const slen1 = vlen * s;
  23668. const slen2 = vlen * ( s + 1 );
  23669. const a = layeroffset + j + slen1,
  23670. b = layeroffset + k + slen1,
  23671. c = layeroffset + k + slen2,
  23672. d = layeroffset + j + slen2;
  23673. f4( a, b, c, d );
  23674. }
  23675. }
  23676. }
  23677. function v( x, y, z ) {
  23678. placeholder.push( x );
  23679. placeholder.push( y );
  23680. placeholder.push( z );
  23681. }
  23682. function f3( a, b, c ) {
  23683. addVertex( a );
  23684. addVertex( b );
  23685. addVertex( c );
  23686. const nextIndex = verticesArray.length / 3;
  23687. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23688. addUV( uvs[ 0 ] );
  23689. addUV( uvs[ 1 ] );
  23690. addUV( uvs[ 2 ] );
  23691. }
  23692. function f4( a, b, c, d ) {
  23693. addVertex( a );
  23694. addVertex( b );
  23695. addVertex( d );
  23696. addVertex( b );
  23697. addVertex( c );
  23698. addVertex( d );
  23699. const nextIndex = verticesArray.length / 3;
  23700. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23701. addUV( uvs[ 0 ] );
  23702. addUV( uvs[ 1 ] );
  23703. addUV( uvs[ 3 ] );
  23704. addUV( uvs[ 1 ] );
  23705. addUV( uvs[ 2 ] );
  23706. addUV( uvs[ 3 ] );
  23707. }
  23708. function addVertex( index ) {
  23709. verticesArray.push( placeholder[ index * 3 + 0 ] );
  23710. verticesArray.push( placeholder[ index * 3 + 1 ] );
  23711. verticesArray.push( placeholder[ index * 3 + 2 ] );
  23712. }
  23713. function addUV( vector2 ) {
  23714. uvArray.push( vector2.x );
  23715. uvArray.push( vector2.y );
  23716. }
  23717. }
  23718. }
  23719. copy( source ) {
  23720. super.copy( source );
  23721. this.parameters = Object.assign( {}, source.parameters );
  23722. return this;
  23723. }
  23724. toJSON() {
  23725. const data = super.toJSON();
  23726. const shapes = this.parameters.shapes;
  23727. const options = this.parameters.options;
  23728. return toJSON$1( shapes, options, data );
  23729. }
  23730. static fromJSON( data, shapes ) {
  23731. const geometryShapes = [];
  23732. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23733. const shape = shapes[ data.shapes[ j ] ];
  23734. geometryShapes.push( shape );
  23735. }
  23736. const extrudePath = data.options.extrudePath;
  23737. if ( extrudePath !== undefined ) {
  23738. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  23739. }
  23740. return new ExtrudeGeometry( geometryShapes, data.options );
  23741. }
  23742. }
  23743. const WorldUVGenerator = {
  23744. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  23745. const a_x = vertices[ indexA * 3 ];
  23746. const a_y = vertices[ indexA * 3 + 1 ];
  23747. const b_x = vertices[ indexB * 3 ];
  23748. const b_y = vertices[ indexB * 3 + 1 ];
  23749. const c_x = vertices[ indexC * 3 ];
  23750. const c_y = vertices[ indexC * 3 + 1 ];
  23751. return [
  23752. new Vector2( a_x, a_y ),
  23753. new Vector2( b_x, b_y ),
  23754. new Vector2( c_x, c_y )
  23755. ];
  23756. },
  23757. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  23758. const a_x = vertices[ indexA * 3 ];
  23759. const a_y = vertices[ indexA * 3 + 1 ];
  23760. const a_z = vertices[ indexA * 3 + 2 ];
  23761. const b_x = vertices[ indexB * 3 ];
  23762. const b_y = vertices[ indexB * 3 + 1 ];
  23763. const b_z = vertices[ indexB * 3 + 2 ];
  23764. const c_x = vertices[ indexC * 3 ];
  23765. const c_y = vertices[ indexC * 3 + 1 ];
  23766. const c_z = vertices[ indexC * 3 + 2 ];
  23767. const d_x = vertices[ indexD * 3 ];
  23768. const d_y = vertices[ indexD * 3 + 1 ];
  23769. const d_z = vertices[ indexD * 3 + 2 ];
  23770. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  23771. return [
  23772. new Vector2( a_x, 1 - a_z ),
  23773. new Vector2( b_x, 1 - b_z ),
  23774. new Vector2( c_x, 1 - c_z ),
  23775. new Vector2( d_x, 1 - d_z )
  23776. ];
  23777. } else {
  23778. return [
  23779. new Vector2( a_y, 1 - a_z ),
  23780. new Vector2( b_y, 1 - b_z ),
  23781. new Vector2( c_y, 1 - c_z ),
  23782. new Vector2( d_y, 1 - d_z )
  23783. ];
  23784. }
  23785. }
  23786. };
  23787. function toJSON$1( shapes, options, data ) {
  23788. data.shapes = [];
  23789. if ( Array.isArray( shapes ) ) {
  23790. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23791. const shape = shapes[ i ];
  23792. data.shapes.push( shape.uuid );
  23793. }
  23794. } else {
  23795. data.shapes.push( shapes.uuid );
  23796. }
  23797. data.options = Object.assign( {}, options );
  23798. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  23799. return data;
  23800. }
  23801. class IcosahedronGeometry extends PolyhedronGeometry {
  23802. constructor( radius = 1, detail = 0 ) {
  23803. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23804. const vertices = [
  23805. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23806. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23807. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23808. ];
  23809. const indices = [
  23810. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23811. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23812. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23813. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23814. ];
  23815. super( vertices, indices, radius, detail );
  23816. this.type = 'IcosahedronGeometry';
  23817. this.parameters = {
  23818. radius: radius,
  23819. detail: detail
  23820. };
  23821. }
  23822. static fromJSON( data ) {
  23823. return new IcosahedronGeometry( data.radius, data.detail );
  23824. }
  23825. }
  23826. class OctahedronGeometry extends PolyhedronGeometry {
  23827. constructor( radius = 1, detail = 0 ) {
  23828. const vertices = [
  23829. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  23830. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23831. ];
  23832. const indices = [
  23833. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  23834. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  23835. 1, 3, 4, 1, 4, 2
  23836. ];
  23837. super( vertices, indices, radius, detail );
  23838. this.type = 'OctahedronGeometry';
  23839. this.parameters = {
  23840. radius: radius,
  23841. detail: detail
  23842. };
  23843. }
  23844. static fromJSON( data ) {
  23845. return new OctahedronGeometry( data.radius, data.detail );
  23846. }
  23847. }
  23848. class RingGeometry extends BufferGeometry {
  23849. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23850. super();
  23851. this.type = 'RingGeometry';
  23852. this.parameters = {
  23853. innerRadius: innerRadius,
  23854. outerRadius: outerRadius,
  23855. thetaSegments: thetaSegments,
  23856. phiSegments: phiSegments,
  23857. thetaStart: thetaStart,
  23858. thetaLength: thetaLength
  23859. };
  23860. thetaSegments = Math.max( 3, thetaSegments );
  23861. phiSegments = Math.max( 1, phiSegments );
  23862. // buffers
  23863. const indices = [];
  23864. const vertices = [];
  23865. const normals = [];
  23866. const uvs = [];
  23867. // some helper variables
  23868. let radius = innerRadius;
  23869. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23870. const vertex = new Vector3();
  23871. const uv = new Vector2();
  23872. // generate vertices, normals and uvs
  23873. for ( let j = 0; j <= phiSegments; j ++ ) {
  23874. for ( let i = 0; i <= thetaSegments; i ++ ) {
  23875. // values are generate from the inside of the ring to the outside
  23876. const segment = thetaStart + i / thetaSegments * thetaLength;
  23877. // vertex
  23878. vertex.x = radius * Math.cos( segment );
  23879. vertex.y = radius * Math.sin( segment );
  23880. vertices.push( vertex.x, vertex.y, vertex.z );
  23881. // normal
  23882. normals.push( 0, 0, 1 );
  23883. // uv
  23884. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23885. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23886. uvs.push( uv.x, uv.y );
  23887. }
  23888. // increase the radius for next row of vertices
  23889. radius += radiusStep;
  23890. }
  23891. // indices
  23892. for ( let j = 0; j < phiSegments; j ++ ) {
  23893. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  23894. for ( let i = 0; i < thetaSegments; i ++ ) {
  23895. const segment = i + thetaSegmentLevel;
  23896. const a = segment;
  23897. const b = segment + thetaSegments + 1;
  23898. const c = segment + thetaSegments + 2;
  23899. const d = segment + 1;
  23900. // faces
  23901. indices.push( a, b, d );
  23902. indices.push( b, c, d );
  23903. }
  23904. }
  23905. // build geometry
  23906. this.setIndex( indices );
  23907. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23908. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23909. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23910. }
  23911. copy( source ) {
  23912. super.copy( source );
  23913. this.parameters = Object.assign( {}, source.parameters );
  23914. return this;
  23915. }
  23916. static fromJSON( data ) {
  23917. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  23918. }
  23919. }
  23920. class ShapeGeometry extends BufferGeometry {
  23921. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  23922. super();
  23923. this.type = 'ShapeGeometry';
  23924. this.parameters = {
  23925. shapes: shapes,
  23926. curveSegments: curveSegments
  23927. };
  23928. // buffers
  23929. const indices = [];
  23930. const vertices = [];
  23931. const normals = [];
  23932. const uvs = [];
  23933. // helper variables
  23934. let groupStart = 0;
  23935. let groupCount = 0;
  23936. // allow single and array values for "shapes" parameter
  23937. if ( Array.isArray( shapes ) === false ) {
  23938. addShape( shapes );
  23939. } else {
  23940. for ( let i = 0; i < shapes.length; i ++ ) {
  23941. addShape( shapes[ i ] );
  23942. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  23943. groupStart += groupCount;
  23944. groupCount = 0;
  23945. }
  23946. }
  23947. // build geometry
  23948. this.setIndex( indices );
  23949. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23950. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23951. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23952. // helper functions
  23953. function addShape( shape ) {
  23954. const indexOffset = vertices.length / 3;
  23955. const points = shape.extractPoints( curveSegments );
  23956. let shapeVertices = points.shape;
  23957. const shapeHoles = points.holes;
  23958. // check direction of vertices
  23959. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  23960. shapeVertices = shapeVertices.reverse();
  23961. }
  23962. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23963. const shapeHole = shapeHoles[ i ];
  23964. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  23965. shapeHoles[ i ] = shapeHole.reverse();
  23966. }
  23967. }
  23968. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  23969. // join vertices of inner and outer paths to a single array
  23970. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23971. const shapeHole = shapeHoles[ i ];
  23972. shapeVertices = shapeVertices.concat( shapeHole );
  23973. }
  23974. // vertices, normals, uvs
  23975. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  23976. const vertex = shapeVertices[ i ];
  23977. vertices.push( vertex.x, vertex.y, 0 );
  23978. normals.push( 0, 0, 1 );
  23979. uvs.push( vertex.x, vertex.y ); // world uvs
  23980. }
  23981. // indices
  23982. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  23983. const face = faces[ i ];
  23984. const a = face[ 0 ] + indexOffset;
  23985. const b = face[ 1 ] + indexOffset;
  23986. const c = face[ 2 ] + indexOffset;
  23987. indices.push( a, b, c );
  23988. groupCount += 3;
  23989. }
  23990. }
  23991. }
  23992. copy( source ) {
  23993. super.copy( source );
  23994. this.parameters = Object.assign( {}, source.parameters );
  23995. return this;
  23996. }
  23997. toJSON() {
  23998. const data = super.toJSON();
  23999. const shapes = this.parameters.shapes;
  24000. return toJSON( shapes, data );
  24001. }
  24002. static fromJSON( data, shapes ) {
  24003. const geometryShapes = [];
  24004. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  24005. const shape = shapes[ data.shapes[ j ] ];
  24006. geometryShapes.push( shape );
  24007. }
  24008. return new ShapeGeometry( geometryShapes, data.curveSegments );
  24009. }
  24010. }
  24011. function toJSON( shapes, data ) {
  24012. data.shapes = [];
  24013. if ( Array.isArray( shapes ) ) {
  24014. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  24015. const shape = shapes[ i ];
  24016. data.shapes.push( shape.uuid );
  24017. }
  24018. } else {
  24019. data.shapes.push( shapes.uuid );
  24020. }
  24021. return data;
  24022. }
  24023. class SphereGeometry extends BufferGeometry {
  24024. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  24025. super();
  24026. this.type = 'SphereGeometry';
  24027. this.parameters = {
  24028. radius: radius,
  24029. widthSegments: widthSegments,
  24030. heightSegments: heightSegments,
  24031. phiStart: phiStart,
  24032. phiLength: phiLength,
  24033. thetaStart: thetaStart,
  24034. thetaLength: thetaLength
  24035. };
  24036. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  24037. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  24038. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  24039. let index = 0;
  24040. const grid = [];
  24041. const vertex = new Vector3();
  24042. const normal = new Vector3();
  24043. // buffers
  24044. const indices = [];
  24045. const vertices = [];
  24046. const normals = [];
  24047. const uvs = [];
  24048. // generate vertices, normals and uvs
  24049. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  24050. const verticesRow = [];
  24051. const v = iy / heightSegments;
  24052. // special case for the poles
  24053. let uOffset = 0;
  24054. if ( iy === 0 && thetaStart === 0 ) {
  24055. uOffset = 0.5 / widthSegments;
  24056. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  24057. uOffset = - 0.5 / widthSegments;
  24058. }
  24059. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  24060. const u = ix / widthSegments;
  24061. // vertex
  24062. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  24063. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  24064. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  24065. vertices.push( vertex.x, vertex.y, vertex.z );
  24066. // normal
  24067. normal.copy( vertex ).normalize();
  24068. normals.push( normal.x, normal.y, normal.z );
  24069. // uv
  24070. uvs.push( u + uOffset, 1 - v );
  24071. verticesRow.push( index ++ );
  24072. }
  24073. grid.push( verticesRow );
  24074. }
  24075. // indices
  24076. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  24077. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  24078. const a = grid[ iy ][ ix + 1 ];
  24079. const b = grid[ iy ][ ix ];
  24080. const c = grid[ iy + 1 ][ ix ];
  24081. const d = grid[ iy + 1 ][ ix + 1 ];
  24082. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  24083. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  24084. }
  24085. }
  24086. // build geometry
  24087. this.setIndex( indices );
  24088. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24089. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24090. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24091. }
  24092. copy( source ) {
  24093. super.copy( source );
  24094. this.parameters = Object.assign( {}, source.parameters );
  24095. return this;
  24096. }
  24097. static fromJSON( data ) {
  24098. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  24099. }
  24100. }
  24101. class TetrahedronGeometry extends PolyhedronGeometry {
  24102. constructor( radius = 1, detail = 0 ) {
  24103. const vertices = [
  24104. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  24105. ];
  24106. const indices = [
  24107. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  24108. ];
  24109. super( vertices, indices, radius, detail );
  24110. this.type = 'TetrahedronGeometry';
  24111. this.parameters = {
  24112. radius: radius,
  24113. detail: detail
  24114. };
  24115. }
  24116. static fromJSON( data ) {
  24117. return new TetrahedronGeometry( data.radius, data.detail );
  24118. }
  24119. }
  24120. class TorusGeometry extends BufferGeometry {
  24121. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  24122. super();
  24123. this.type = 'TorusGeometry';
  24124. this.parameters = {
  24125. radius: radius,
  24126. tube: tube,
  24127. radialSegments: radialSegments,
  24128. tubularSegments: tubularSegments,
  24129. arc: arc
  24130. };
  24131. radialSegments = Math.floor( radialSegments );
  24132. tubularSegments = Math.floor( tubularSegments );
  24133. // buffers
  24134. const indices = [];
  24135. const vertices = [];
  24136. const normals = [];
  24137. const uvs = [];
  24138. // helper variables
  24139. const center = new Vector3();
  24140. const vertex = new Vector3();
  24141. const normal = new Vector3();
  24142. // generate vertices, normals and uvs
  24143. for ( let j = 0; j <= radialSegments; j ++ ) {
  24144. for ( let i = 0; i <= tubularSegments; i ++ ) {
  24145. const u = i / tubularSegments * arc;
  24146. const v = j / radialSegments * Math.PI * 2;
  24147. // vertex
  24148. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  24149. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  24150. vertex.z = tube * Math.sin( v );
  24151. vertices.push( vertex.x, vertex.y, vertex.z );
  24152. // normal
  24153. center.x = radius * Math.cos( u );
  24154. center.y = radius * Math.sin( u );
  24155. normal.subVectors( vertex, center ).normalize();
  24156. normals.push( normal.x, normal.y, normal.z );
  24157. // uv
  24158. uvs.push( i / tubularSegments );
  24159. uvs.push( j / radialSegments );
  24160. }
  24161. }
  24162. // generate indices
  24163. for ( let j = 1; j <= radialSegments; j ++ ) {
  24164. for ( let i = 1; i <= tubularSegments; i ++ ) {
  24165. // indices
  24166. const a = ( tubularSegments + 1 ) * j + i - 1;
  24167. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  24168. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  24169. const d = ( tubularSegments + 1 ) * j + i;
  24170. // faces
  24171. indices.push( a, b, d );
  24172. indices.push( b, c, d );
  24173. }
  24174. }
  24175. // build geometry
  24176. this.setIndex( indices );
  24177. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24178. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24179. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24180. }
  24181. copy( source ) {
  24182. super.copy( source );
  24183. this.parameters = Object.assign( {}, source.parameters );
  24184. return this;
  24185. }
  24186. static fromJSON( data ) {
  24187. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  24188. }
  24189. }
  24190. class TorusKnotGeometry extends BufferGeometry {
  24191. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  24192. super();
  24193. this.type = 'TorusKnotGeometry';
  24194. this.parameters = {
  24195. radius: radius,
  24196. tube: tube,
  24197. tubularSegments: tubularSegments,
  24198. radialSegments: radialSegments,
  24199. p: p,
  24200. q: q
  24201. };
  24202. tubularSegments = Math.floor( tubularSegments );
  24203. radialSegments = Math.floor( radialSegments );
  24204. // buffers
  24205. const indices = [];
  24206. const vertices = [];
  24207. const normals = [];
  24208. const uvs = [];
  24209. // helper variables
  24210. const vertex = new Vector3();
  24211. const normal = new Vector3();
  24212. const P1 = new Vector3();
  24213. const P2 = new Vector3();
  24214. const B = new Vector3();
  24215. const T = new Vector3();
  24216. const N = new Vector3();
  24217. // generate vertices, normals and uvs
  24218. for ( let i = 0; i <= tubularSegments; ++ i ) {
  24219. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  24220. const u = i / tubularSegments * p * Math.PI * 2;
  24221. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  24222. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  24223. calculatePositionOnCurve( u, p, q, radius, P1 );
  24224. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  24225. // calculate orthonormal basis
  24226. T.subVectors( P2, P1 );
  24227. N.addVectors( P2, P1 );
  24228. B.crossVectors( T, N );
  24229. N.crossVectors( B, T );
  24230. // normalize B, N. T can be ignored, we don't use it
  24231. B.normalize();
  24232. N.normalize();
  24233. for ( let j = 0; j <= radialSegments; ++ j ) {
  24234. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  24235. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  24236. const v = j / radialSegments * Math.PI * 2;
  24237. const cx = - tube * Math.cos( v );
  24238. const cy = tube * Math.sin( v );
  24239. // now calculate the final vertex position.
  24240. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  24241. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  24242. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  24243. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  24244. vertices.push( vertex.x, vertex.y, vertex.z );
  24245. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  24246. normal.subVectors( vertex, P1 ).normalize();
  24247. normals.push( normal.x, normal.y, normal.z );
  24248. // uv
  24249. uvs.push( i / tubularSegments );
  24250. uvs.push( j / radialSegments );
  24251. }
  24252. }
  24253. // generate indices
  24254. for ( let j = 1; j <= tubularSegments; j ++ ) {
  24255. for ( let i = 1; i <= radialSegments; i ++ ) {
  24256. // indices
  24257. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  24258. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  24259. const c = ( radialSegments + 1 ) * j + i;
  24260. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  24261. // faces
  24262. indices.push( a, b, d );
  24263. indices.push( b, c, d );
  24264. }
  24265. }
  24266. // build geometry
  24267. this.setIndex( indices );
  24268. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24269. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24270. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24271. // this function calculates the current position on the torus curve
  24272. function calculatePositionOnCurve( u, p, q, radius, position ) {
  24273. const cu = Math.cos( u );
  24274. const su = Math.sin( u );
  24275. const quOverP = q / p * u;
  24276. const cs = Math.cos( quOverP );
  24277. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  24278. position.y = radius * ( 2 + cs ) * su * 0.5;
  24279. position.z = radius * Math.sin( quOverP ) * 0.5;
  24280. }
  24281. }
  24282. copy( source ) {
  24283. super.copy( source );
  24284. this.parameters = Object.assign( {}, source.parameters );
  24285. return this;
  24286. }
  24287. static fromJSON( data ) {
  24288. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  24289. }
  24290. }
  24291. class TubeGeometry extends BufferGeometry {
  24292. 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 ) {
  24293. super();
  24294. this.type = 'TubeGeometry';
  24295. this.parameters = {
  24296. path: path,
  24297. tubularSegments: tubularSegments,
  24298. radius: radius,
  24299. radialSegments: radialSegments,
  24300. closed: closed
  24301. };
  24302. const frames = path.computeFrenetFrames( tubularSegments, closed );
  24303. // expose internals
  24304. this.tangents = frames.tangents;
  24305. this.normals = frames.normals;
  24306. this.binormals = frames.binormals;
  24307. // helper variables
  24308. const vertex = new Vector3();
  24309. const normal = new Vector3();
  24310. const uv = new Vector2();
  24311. let P = new Vector3();
  24312. // buffer
  24313. const vertices = [];
  24314. const normals = [];
  24315. const uvs = [];
  24316. const indices = [];
  24317. // create buffer data
  24318. generateBufferData();
  24319. // build geometry
  24320. this.setIndex( indices );
  24321. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24322. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24323. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24324. // functions
  24325. function generateBufferData() {
  24326. for ( let i = 0; i < tubularSegments; i ++ ) {
  24327. generateSegment( i );
  24328. }
  24329. // if the geometry is not closed, generate the last row of vertices and normals
  24330. // at the regular position on the given path
  24331. //
  24332. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  24333. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  24334. // uvs are generated in a separate function.
  24335. // this makes it easy compute correct values for closed geometries
  24336. generateUVs();
  24337. // finally create faces
  24338. generateIndices();
  24339. }
  24340. function generateSegment( i ) {
  24341. // we use getPointAt to sample evenly distributed points from the given path
  24342. P = path.getPointAt( i / tubularSegments, P );
  24343. // retrieve corresponding normal and binormal
  24344. const N = frames.normals[ i ];
  24345. const B = frames.binormals[ i ];
  24346. // generate normals and vertices for the current segment
  24347. for ( let j = 0; j <= radialSegments; j ++ ) {
  24348. const v = j / radialSegments * Math.PI * 2;
  24349. const sin = Math.sin( v );
  24350. const cos = - Math.cos( v );
  24351. // normal
  24352. normal.x = ( cos * N.x + sin * B.x );
  24353. normal.y = ( cos * N.y + sin * B.y );
  24354. normal.z = ( cos * N.z + sin * B.z );
  24355. normal.normalize();
  24356. normals.push( normal.x, normal.y, normal.z );
  24357. // vertex
  24358. vertex.x = P.x + radius * normal.x;
  24359. vertex.y = P.y + radius * normal.y;
  24360. vertex.z = P.z + radius * normal.z;
  24361. vertices.push( vertex.x, vertex.y, vertex.z );
  24362. }
  24363. }
  24364. function generateIndices() {
  24365. for ( let j = 1; j <= tubularSegments; j ++ ) {
  24366. for ( let i = 1; i <= radialSegments; i ++ ) {
  24367. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  24368. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  24369. const c = ( radialSegments + 1 ) * j + i;
  24370. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  24371. // faces
  24372. indices.push( a, b, d );
  24373. indices.push( b, c, d );
  24374. }
  24375. }
  24376. }
  24377. function generateUVs() {
  24378. for ( let i = 0; i <= tubularSegments; i ++ ) {
  24379. for ( let j = 0; j <= radialSegments; j ++ ) {
  24380. uv.x = i / tubularSegments;
  24381. uv.y = j / radialSegments;
  24382. uvs.push( uv.x, uv.y );
  24383. }
  24384. }
  24385. }
  24386. }
  24387. copy( source ) {
  24388. super.copy( source );
  24389. this.parameters = Object.assign( {}, source.parameters );
  24390. return this;
  24391. }
  24392. toJSON() {
  24393. const data = super.toJSON();
  24394. data.path = this.parameters.path.toJSON();
  24395. return data;
  24396. }
  24397. static fromJSON( data ) {
  24398. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24399. // User defined curves or instances of CurvePath will not be deserialized.
  24400. return new TubeGeometry(
  24401. new Curves[ data.path.type ]().fromJSON( data.path ),
  24402. data.tubularSegments,
  24403. data.radius,
  24404. data.radialSegments,
  24405. data.closed
  24406. );
  24407. }
  24408. }
  24409. class WireframeGeometry extends BufferGeometry {
  24410. constructor( geometry = null ) {
  24411. super();
  24412. this.type = 'WireframeGeometry';
  24413. this.parameters = {
  24414. geometry: geometry
  24415. };
  24416. if ( geometry !== null ) {
  24417. // buffer
  24418. const vertices = [];
  24419. const edges = new Set();
  24420. // helper variables
  24421. const start = new Vector3();
  24422. const end = new Vector3();
  24423. if ( geometry.index !== null ) {
  24424. // indexed BufferGeometry
  24425. const position = geometry.attributes.position;
  24426. const indices = geometry.index;
  24427. let groups = geometry.groups;
  24428. if ( groups.length === 0 ) {
  24429. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  24430. }
  24431. // create a data structure that contains all edges without duplicates
  24432. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  24433. const group = groups[ o ];
  24434. const groupStart = group.start;
  24435. const groupCount = group.count;
  24436. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  24437. for ( let j = 0; j < 3; j ++ ) {
  24438. const index1 = indices.getX( i + j );
  24439. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  24440. start.fromBufferAttribute( position, index1 );
  24441. end.fromBufferAttribute( position, index2 );
  24442. if ( isUniqueEdge( start, end, edges ) === true ) {
  24443. vertices.push( start.x, start.y, start.z );
  24444. vertices.push( end.x, end.y, end.z );
  24445. }
  24446. }
  24447. }
  24448. }
  24449. } else {
  24450. // non-indexed BufferGeometry
  24451. const position = geometry.attributes.position;
  24452. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  24453. for ( let j = 0; j < 3; j ++ ) {
  24454. // three edges per triangle, an edge is represented as (index1, index2)
  24455. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  24456. const index1 = 3 * i + j;
  24457. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  24458. start.fromBufferAttribute( position, index1 );
  24459. end.fromBufferAttribute( position, index2 );
  24460. if ( isUniqueEdge( start, end, edges ) === true ) {
  24461. vertices.push( start.x, start.y, start.z );
  24462. vertices.push( end.x, end.y, end.z );
  24463. }
  24464. }
  24465. }
  24466. }
  24467. // build geometry
  24468. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24469. }
  24470. }
  24471. copy( source ) {
  24472. super.copy( source );
  24473. this.parameters = Object.assign( {}, source.parameters );
  24474. return this;
  24475. }
  24476. }
  24477. function isUniqueEdge( start, end, edges ) {
  24478. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  24479. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  24480. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  24481. return false;
  24482. } else {
  24483. edges.add( hash1 );
  24484. edges.add( hash2 );
  24485. return true;
  24486. }
  24487. }
  24488. var Geometries = /*#__PURE__*/Object.freeze({
  24489. __proto__: null,
  24490. BoxGeometry: BoxGeometry,
  24491. CapsuleGeometry: CapsuleGeometry,
  24492. CircleGeometry: CircleGeometry,
  24493. ConeGeometry: ConeGeometry,
  24494. CylinderGeometry: CylinderGeometry,
  24495. DodecahedronGeometry: DodecahedronGeometry,
  24496. EdgesGeometry: EdgesGeometry,
  24497. ExtrudeGeometry: ExtrudeGeometry,
  24498. IcosahedronGeometry: IcosahedronGeometry,
  24499. LatheGeometry: LatheGeometry,
  24500. OctahedronGeometry: OctahedronGeometry,
  24501. PlaneGeometry: PlaneGeometry,
  24502. PolyhedronGeometry: PolyhedronGeometry,
  24503. RingGeometry: RingGeometry,
  24504. ShapeGeometry: ShapeGeometry,
  24505. SphereGeometry: SphereGeometry,
  24506. TetrahedronGeometry: TetrahedronGeometry,
  24507. TorusGeometry: TorusGeometry,
  24508. TorusKnotGeometry: TorusKnotGeometry,
  24509. TubeGeometry: TubeGeometry,
  24510. WireframeGeometry: WireframeGeometry
  24511. });
  24512. class ShadowMaterial extends Material {
  24513. constructor( parameters ) {
  24514. super();
  24515. this.isShadowMaterial = true;
  24516. this.type = 'ShadowMaterial';
  24517. this.color = new Color( 0x000000 );
  24518. this.transparent = true;
  24519. this.fog = true;
  24520. this.setValues( parameters );
  24521. }
  24522. copy( source ) {
  24523. super.copy( source );
  24524. this.color.copy( source.color );
  24525. this.fog = source.fog;
  24526. return this;
  24527. }
  24528. }
  24529. class RawShaderMaterial extends ShaderMaterial {
  24530. constructor( parameters ) {
  24531. super( parameters );
  24532. this.isRawShaderMaterial = true;
  24533. this.type = 'RawShaderMaterial';
  24534. }
  24535. }
  24536. class MeshStandardMaterial extends Material {
  24537. constructor( parameters ) {
  24538. super();
  24539. this.isMeshStandardMaterial = true;
  24540. this.defines = { 'STANDARD': '' };
  24541. this.type = 'MeshStandardMaterial';
  24542. this.color = new Color( 0xffffff ); // diffuse
  24543. this.roughness = 1.0;
  24544. this.metalness = 0.0;
  24545. this.map = null;
  24546. this.lightMap = null;
  24547. this.lightMapIntensity = 1.0;
  24548. this.aoMap = null;
  24549. this.aoMapIntensity = 1.0;
  24550. this.emissive = new Color( 0x000000 );
  24551. this.emissiveIntensity = 1.0;
  24552. this.emissiveMap = null;
  24553. this.bumpMap = null;
  24554. this.bumpScale = 1;
  24555. this.normalMap = null;
  24556. this.normalMapType = TangentSpaceNormalMap;
  24557. this.normalScale = new Vector2( 1, 1 );
  24558. this.displacementMap = null;
  24559. this.displacementScale = 1;
  24560. this.displacementBias = 0;
  24561. this.roughnessMap = null;
  24562. this.metalnessMap = null;
  24563. this.alphaMap = null;
  24564. this.envMap = null;
  24565. this.envMapRotation = new Euler();
  24566. this.envMapIntensity = 1.0;
  24567. this.wireframe = false;
  24568. this.wireframeLinewidth = 1;
  24569. this.wireframeLinecap = 'round';
  24570. this.wireframeLinejoin = 'round';
  24571. this.flatShading = false;
  24572. this.fog = true;
  24573. this.setValues( parameters );
  24574. }
  24575. copy( source ) {
  24576. super.copy( source );
  24577. this.defines = { 'STANDARD': '' };
  24578. this.color.copy( source.color );
  24579. this.roughness = source.roughness;
  24580. this.metalness = source.metalness;
  24581. this.map = source.map;
  24582. this.lightMap = source.lightMap;
  24583. this.lightMapIntensity = source.lightMapIntensity;
  24584. this.aoMap = source.aoMap;
  24585. this.aoMapIntensity = source.aoMapIntensity;
  24586. this.emissive.copy( source.emissive );
  24587. this.emissiveMap = source.emissiveMap;
  24588. this.emissiveIntensity = source.emissiveIntensity;
  24589. this.bumpMap = source.bumpMap;
  24590. this.bumpScale = source.bumpScale;
  24591. this.normalMap = source.normalMap;
  24592. this.normalMapType = source.normalMapType;
  24593. this.normalScale.copy( source.normalScale );
  24594. this.displacementMap = source.displacementMap;
  24595. this.displacementScale = source.displacementScale;
  24596. this.displacementBias = source.displacementBias;
  24597. this.roughnessMap = source.roughnessMap;
  24598. this.metalnessMap = source.metalnessMap;
  24599. this.alphaMap = source.alphaMap;
  24600. this.envMap = source.envMap;
  24601. this.envMapRotation.copy( source.envMapRotation );
  24602. this.envMapIntensity = source.envMapIntensity;
  24603. this.wireframe = source.wireframe;
  24604. this.wireframeLinewidth = source.wireframeLinewidth;
  24605. this.wireframeLinecap = source.wireframeLinecap;
  24606. this.wireframeLinejoin = source.wireframeLinejoin;
  24607. this.flatShading = source.flatShading;
  24608. this.fog = source.fog;
  24609. return this;
  24610. }
  24611. }
  24612. class MeshPhysicalMaterial extends MeshStandardMaterial {
  24613. constructor( parameters ) {
  24614. super();
  24615. this.isMeshPhysicalMaterial = true;
  24616. this.defines = {
  24617. 'STANDARD': '',
  24618. 'PHYSICAL': ''
  24619. };
  24620. this.type = 'MeshPhysicalMaterial';
  24621. this.anisotropyRotation = 0;
  24622. this.anisotropyMap = null;
  24623. this.clearcoatMap = null;
  24624. this.clearcoatRoughness = 0.0;
  24625. this.clearcoatRoughnessMap = null;
  24626. this.clearcoatNormalScale = new Vector2( 1, 1 );
  24627. this.clearcoatNormalMap = null;
  24628. this.ior = 1.5;
  24629. Object.defineProperty( this, 'reflectivity', {
  24630. get: function () {
  24631. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  24632. },
  24633. set: function ( reflectivity ) {
  24634. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  24635. }
  24636. } );
  24637. this.iridescenceMap = null;
  24638. this.iridescenceIOR = 1.3;
  24639. this.iridescenceThicknessRange = [ 100, 400 ];
  24640. this.iridescenceThicknessMap = null;
  24641. this.sheenColor = new Color( 0x000000 );
  24642. this.sheenColorMap = null;
  24643. this.sheenRoughness = 1.0;
  24644. this.sheenRoughnessMap = null;
  24645. this.transmissionMap = null;
  24646. this.thickness = 0;
  24647. this.thicknessMap = null;
  24648. this.attenuationDistance = Infinity;
  24649. this.attenuationColor = new Color( 1, 1, 1 );
  24650. this.specularIntensity = 1.0;
  24651. this.specularIntensityMap = null;
  24652. this.specularColor = new Color( 1, 1, 1 );
  24653. this.specularColorMap = null;
  24654. this._anisotropy = 0;
  24655. this._clearcoat = 0;
  24656. this._dispersion = 0;
  24657. this._iridescence = 0;
  24658. this._sheen = 0.0;
  24659. this._transmission = 0;
  24660. this.setValues( parameters );
  24661. }
  24662. get anisotropy() {
  24663. return this._anisotropy;
  24664. }
  24665. set anisotropy( value ) {
  24666. if ( this._anisotropy > 0 !== value > 0 ) {
  24667. this.version ++;
  24668. }
  24669. this._anisotropy = value;
  24670. }
  24671. get clearcoat() {
  24672. return this._clearcoat;
  24673. }
  24674. set clearcoat( value ) {
  24675. if ( this._clearcoat > 0 !== value > 0 ) {
  24676. this.version ++;
  24677. }
  24678. this._clearcoat = value;
  24679. }
  24680. get iridescence() {
  24681. return this._iridescence;
  24682. }
  24683. set iridescence( value ) {
  24684. if ( this._iridescence > 0 !== value > 0 ) {
  24685. this.version ++;
  24686. }
  24687. this._iridescence = value;
  24688. }
  24689. get dispersion() {
  24690. return this._dispersion;
  24691. }
  24692. set dispersion( value ) {
  24693. if ( this._dispersion > 0 !== value > 0 ) {
  24694. this.version ++;
  24695. }
  24696. this._dispersion = value;
  24697. }
  24698. get sheen() {
  24699. return this._sheen;
  24700. }
  24701. set sheen( value ) {
  24702. if ( this._sheen > 0 !== value > 0 ) {
  24703. this.version ++;
  24704. }
  24705. this._sheen = value;
  24706. }
  24707. get transmission() {
  24708. return this._transmission;
  24709. }
  24710. set transmission( value ) {
  24711. if ( this._transmission > 0 !== value > 0 ) {
  24712. this.version ++;
  24713. }
  24714. this._transmission = value;
  24715. }
  24716. copy( source ) {
  24717. super.copy( source );
  24718. this.defines = {
  24719. 'STANDARD': '',
  24720. 'PHYSICAL': ''
  24721. };
  24722. this.anisotropy = source.anisotropy;
  24723. this.anisotropyRotation = source.anisotropyRotation;
  24724. this.anisotropyMap = source.anisotropyMap;
  24725. this.clearcoat = source.clearcoat;
  24726. this.clearcoatMap = source.clearcoatMap;
  24727. this.clearcoatRoughness = source.clearcoatRoughness;
  24728. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  24729. this.clearcoatNormalMap = source.clearcoatNormalMap;
  24730. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  24731. this.dispersion = source.dispersion;
  24732. this.ior = source.ior;
  24733. this.iridescence = source.iridescence;
  24734. this.iridescenceMap = source.iridescenceMap;
  24735. this.iridescenceIOR = source.iridescenceIOR;
  24736. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  24737. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  24738. this.sheen = source.sheen;
  24739. this.sheenColor.copy( source.sheenColor );
  24740. this.sheenColorMap = source.sheenColorMap;
  24741. this.sheenRoughness = source.sheenRoughness;
  24742. this.sheenRoughnessMap = source.sheenRoughnessMap;
  24743. this.transmission = source.transmission;
  24744. this.transmissionMap = source.transmissionMap;
  24745. this.thickness = source.thickness;
  24746. this.thicknessMap = source.thicknessMap;
  24747. this.attenuationDistance = source.attenuationDistance;
  24748. this.attenuationColor.copy( source.attenuationColor );
  24749. this.specularIntensity = source.specularIntensity;
  24750. this.specularIntensityMap = source.specularIntensityMap;
  24751. this.specularColor.copy( source.specularColor );
  24752. this.specularColorMap = source.specularColorMap;
  24753. return this;
  24754. }
  24755. }
  24756. class MeshPhongMaterial extends Material {
  24757. constructor( parameters ) {
  24758. super();
  24759. this.isMeshPhongMaterial = true;
  24760. this.type = 'MeshPhongMaterial';
  24761. this.color = new Color( 0xffffff ); // diffuse
  24762. this.specular = new Color( 0x111111 );
  24763. this.shininess = 30;
  24764. this.map = null;
  24765. this.lightMap = null;
  24766. this.lightMapIntensity = 1.0;
  24767. this.aoMap = null;
  24768. this.aoMapIntensity = 1.0;
  24769. this.emissive = new Color( 0x000000 );
  24770. this.emissiveIntensity = 1.0;
  24771. this.emissiveMap = null;
  24772. this.bumpMap = null;
  24773. this.bumpScale = 1;
  24774. this.normalMap = null;
  24775. this.normalMapType = TangentSpaceNormalMap;
  24776. this.normalScale = new Vector2( 1, 1 );
  24777. this.displacementMap = null;
  24778. this.displacementScale = 1;
  24779. this.displacementBias = 0;
  24780. this.specularMap = null;
  24781. this.alphaMap = null;
  24782. this.envMap = null;
  24783. this.envMapRotation = new Euler();
  24784. this.combine = MultiplyOperation;
  24785. this.reflectivity = 1;
  24786. this.refractionRatio = 0.98;
  24787. this.wireframe = false;
  24788. this.wireframeLinewidth = 1;
  24789. this.wireframeLinecap = 'round';
  24790. this.wireframeLinejoin = 'round';
  24791. this.flatShading = false;
  24792. this.fog = true;
  24793. this.setValues( parameters );
  24794. }
  24795. copy( source ) {
  24796. super.copy( source );
  24797. this.color.copy( source.color );
  24798. this.specular.copy( source.specular );
  24799. this.shininess = source.shininess;
  24800. this.map = source.map;
  24801. this.lightMap = source.lightMap;
  24802. this.lightMapIntensity = source.lightMapIntensity;
  24803. this.aoMap = source.aoMap;
  24804. this.aoMapIntensity = source.aoMapIntensity;
  24805. this.emissive.copy( source.emissive );
  24806. this.emissiveMap = source.emissiveMap;
  24807. this.emissiveIntensity = source.emissiveIntensity;
  24808. this.bumpMap = source.bumpMap;
  24809. this.bumpScale = source.bumpScale;
  24810. this.normalMap = source.normalMap;
  24811. this.normalMapType = source.normalMapType;
  24812. this.normalScale.copy( source.normalScale );
  24813. this.displacementMap = source.displacementMap;
  24814. this.displacementScale = source.displacementScale;
  24815. this.displacementBias = source.displacementBias;
  24816. this.specularMap = source.specularMap;
  24817. this.alphaMap = source.alphaMap;
  24818. this.envMap = source.envMap;
  24819. this.envMapRotation.copy( source.envMapRotation );
  24820. this.combine = source.combine;
  24821. this.reflectivity = source.reflectivity;
  24822. this.refractionRatio = source.refractionRatio;
  24823. this.wireframe = source.wireframe;
  24824. this.wireframeLinewidth = source.wireframeLinewidth;
  24825. this.wireframeLinecap = source.wireframeLinecap;
  24826. this.wireframeLinejoin = source.wireframeLinejoin;
  24827. this.flatShading = source.flatShading;
  24828. this.fog = source.fog;
  24829. return this;
  24830. }
  24831. }
  24832. class MeshToonMaterial extends Material {
  24833. constructor( parameters ) {
  24834. super();
  24835. this.isMeshToonMaterial = true;
  24836. this.defines = { 'TOON': '' };
  24837. this.type = 'MeshToonMaterial';
  24838. this.color = new Color( 0xffffff );
  24839. this.map = null;
  24840. this.gradientMap = null;
  24841. this.lightMap = null;
  24842. this.lightMapIntensity = 1.0;
  24843. this.aoMap = null;
  24844. this.aoMapIntensity = 1.0;
  24845. this.emissive = new Color( 0x000000 );
  24846. this.emissiveIntensity = 1.0;
  24847. this.emissiveMap = null;
  24848. this.bumpMap = null;
  24849. this.bumpScale = 1;
  24850. this.normalMap = null;
  24851. this.normalMapType = TangentSpaceNormalMap;
  24852. this.normalScale = new Vector2( 1, 1 );
  24853. this.displacementMap = null;
  24854. this.displacementScale = 1;
  24855. this.displacementBias = 0;
  24856. this.alphaMap = null;
  24857. this.wireframe = false;
  24858. this.wireframeLinewidth = 1;
  24859. this.wireframeLinecap = 'round';
  24860. this.wireframeLinejoin = 'round';
  24861. this.fog = true;
  24862. this.setValues( parameters );
  24863. }
  24864. copy( source ) {
  24865. super.copy( source );
  24866. this.color.copy( source.color );
  24867. this.map = source.map;
  24868. this.gradientMap = source.gradientMap;
  24869. this.lightMap = source.lightMap;
  24870. this.lightMapIntensity = source.lightMapIntensity;
  24871. this.aoMap = source.aoMap;
  24872. this.aoMapIntensity = source.aoMapIntensity;
  24873. this.emissive.copy( source.emissive );
  24874. this.emissiveMap = source.emissiveMap;
  24875. this.emissiveIntensity = source.emissiveIntensity;
  24876. this.bumpMap = source.bumpMap;
  24877. this.bumpScale = source.bumpScale;
  24878. this.normalMap = source.normalMap;
  24879. this.normalMapType = source.normalMapType;
  24880. this.normalScale.copy( source.normalScale );
  24881. this.displacementMap = source.displacementMap;
  24882. this.displacementScale = source.displacementScale;
  24883. this.displacementBias = source.displacementBias;
  24884. this.alphaMap = source.alphaMap;
  24885. this.wireframe = source.wireframe;
  24886. this.wireframeLinewidth = source.wireframeLinewidth;
  24887. this.wireframeLinecap = source.wireframeLinecap;
  24888. this.wireframeLinejoin = source.wireframeLinejoin;
  24889. this.fog = source.fog;
  24890. return this;
  24891. }
  24892. }
  24893. class MeshNormalMaterial extends Material {
  24894. constructor( parameters ) {
  24895. super();
  24896. this.isMeshNormalMaterial = true;
  24897. this.type = 'MeshNormalMaterial';
  24898. this.bumpMap = null;
  24899. this.bumpScale = 1;
  24900. this.normalMap = null;
  24901. this.normalMapType = TangentSpaceNormalMap;
  24902. this.normalScale = new Vector2( 1, 1 );
  24903. this.displacementMap = null;
  24904. this.displacementScale = 1;
  24905. this.displacementBias = 0;
  24906. this.wireframe = false;
  24907. this.wireframeLinewidth = 1;
  24908. this.flatShading = false;
  24909. this.setValues( parameters );
  24910. }
  24911. copy( source ) {
  24912. super.copy( source );
  24913. this.bumpMap = source.bumpMap;
  24914. this.bumpScale = source.bumpScale;
  24915. this.normalMap = source.normalMap;
  24916. this.normalMapType = source.normalMapType;
  24917. this.normalScale.copy( source.normalScale );
  24918. this.displacementMap = source.displacementMap;
  24919. this.displacementScale = source.displacementScale;
  24920. this.displacementBias = source.displacementBias;
  24921. this.wireframe = source.wireframe;
  24922. this.wireframeLinewidth = source.wireframeLinewidth;
  24923. this.flatShading = source.flatShading;
  24924. return this;
  24925. }
  24926. }
  24927. class MeshLambertMaterial extends Material {
  24928. constructor( parameters ) {
  24929. super();
  24930. this.isMeshLambertMaterial = true;
  24931. this.type = 'MeshLambertMaterial';
  24932. this.color = new Color( 0xffffff ); // diffuse
  24933. this.map = null;
  24934. this.lightMap = null;
  24935. this.lightMapIntensity = 1.0;
  24936. this.aoMap = null;
  24937. this.aoMapIntensity = 1.0;
  24938. this.emissive = new Color( 0x000000 );
  24939. this.emissiveIntensity = 1.0;
  24940. this.emissiveMap = null;
  24941. this.bumpMap = null;
  24942. this.bumpScale = 1;
  24943. this.normalMap = null;
  24944. this.normalMapType = TangentSpaceNormalMap;
  24945. this.normalScale = new Vector2( 1, 1 );
  24946. this.displacementMap = null;
  24947. this.displacementScale = 1;
  24948. this.displacementBias = 0;
  24949. this.specularMap = null;
  24950. this.alphaMap = null;
  24951. this.envMap = null;
  24952. this.envMapRotation = new Euler();
  24953. this.combine = MultiplyOperation;
  24954. this.reflectivity = 1;
  24955. this.refractionRatio = 0.98;
  24956. this.wireframe = false;
  24957. this.wireframeLinewidth = 1;
  24958. this.wireframeLinecap = 'round';
  24959. this.wireframeLinejoin = 'round';
  24960. this.flatShading = false;
  24961. this.fog = true;
  24962. this.setValues( parameters );
  24963. }
  24964. copy( source ) {
  24965. super.copy( source );
  24966. this.color.copy( source.color );
  24967. this.map = source.map;
  24968. this.lightMap = source.lightMap;
  24969. this.lightMapIntensity = source.lightMapIntensity;
  24970. this.aoMap = source.aoMap;
  24971. this.aoMapIntensity = source.aoMapIntensity;
  24972. this.emissive.copy( source.emissive );
  24973. this.emissiveMap = source.emissiveMap;
  24974. this.emissiveIntensity = source.emissiveIntensity;
  24975. this.bumpMap = source.bumpMap;
  24976. this.bumpScale = source.bumpScale;
  24977. this.normalMap = source.normalMap;
  24978. this.normalMapType = source.normalMapType;
  24979. this.normalScale.copy( source.normalScale );
  24980. this.displacementMap = source.displacementMap;
  24981. this.displacementScale = source.displacementScale;
  24982. this.displacementBias = source.displacementBias;
  24983. this.specularMap = source.specularMap;
  24984. this.alphaMap = source.alphaMap;
  24985. this.envMap = source.envMap;
  24986. this.envMapRotation.copy( source.envMapRotation );
  24987. this.combine = source.combine;
  24988. this.reflectivity = source.reflectivity;
  24989. this.refractionRatio = source.refractionRatio;
  24990. this.wireframe = source.wireframe;
  24991. this.wireframeLinewidth = source.wireframeLinewidth;
  24992. this.wireframeLinecap = source.wireframeLinecap;
  24993. this.wireframeLinejoin = source.wireframeLinejoin;
  24994. this.flatShading = source.flatShading;
  24995. this.fog = source.fog;
  24996. return this;
  24997. }
  24998. }
  24999. class MeshMatcapMaterial extends Material {
  25000. constructor( parameters ) {
  25001. super();
  25002. this.isMeshMatcapMaterial = true;
  25003. this.defines = { 'MATCAP': '' };
  25004. this.type = 'MeshMatcapMaterial';
  25005. this.color = new Color( 0xffffff ); // diffuse
  25006. this.matcap = null;
  25007. this.map = null;
  25008. this.bumpMap = null;
  25009. this.bumpScale = 1;
  25010. this.normalMap = null;
  25011. this.normalMapType = TangentSpaceNormalMap;
  25012. this.normalScale = new Vector2( 1, 1 );
  25013. this.displacementMap = null;
  25014. this.displacementScale = 1;
  25015. this.displacementBias = 0;
  25016. this.alphaMap = null;
  25017. this.flatShading = false;
  25018. this.fog = true;
  25019. this.setValues( parameters );
  25020. }
  25021. copy( source ) {
  25022. super.copy( source );
  25023. this.defines = { 'MATCAP': '' };
  25024. this.color.copy( source.color );
  25025. this.matcap = source.matcap;
  25026. this.map = source.map;
  25027. this.bumpMap = source.bumpMap;
  25028. this.bumpScale = source.bumpScale;
  25029. this.normalMap = source.normalMap;
  25030. this.normalMapType = source.normalMapType;
  25031. this.normalScale.copy( source.normalScale );
  25032. this.displacementMap = source.displacementMap;
  25033. this.displacementScale = source.displacementScale;
  25034. this.displacementBias = source.displacementBias;
  25035. this.alphaMap = source.alphaMap;
  25036. this.flatShading = source.flatShading;
  25037. this.fog = source.fog;
  25038. return this;
  25039. }
  25040. }
  25041. class LineDashedMaterial extends LineBasicMaterial {
  25042. constructor( parameters ) {
  25043. super();
  25044. this.isLineDashedMaterial = true;
  25045. this.type = 'LineDashedMaterial';
  25046. this.scale = 1;
  25047. this.dashSize = 3;
  25048. this.gapSize = 1;
  25049. this.setValues( parameters );
  25050. }
  25051. copy( source ) {
  25052. super.copy( source );
  25053. this.scale = source.scale;
  25054. this.dashSize = source.dashSize;
  25055. this.gapSize = source.gapSize;
  25056. return this;
  25057. }
  25058. }
  25059. // converts an array to a specific type
  25060. function convertArray( array, type, forceClone ) {
  25061. if ( ! array || // let 'undefined' and 'null' pass
  25062. ! forceClone && array.constructor === type ) return array;
  25063. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  25064. return new type( array ); // create typed array
  25065. }
  25066. return Array.prototype.slice.call( array ); // create Array
  25067. }
  25068. function isTypedArray( object ) {
  25069. return ArrayBuffer.isView( object ) &&
  25070. ! ( object instanceof DataView );
  25071. }
  25072. // returns an array by which times and values can be sorted
  25073. function getKeyframeOrder( times ) {
  25074. function compareTime( i, j ) {
  25075. return times[ i ] - times[ j ];
  25076. }
  25077. const n = times.length;
  25078. const result = new Array( n );
  25079. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  25080. result.sort( compareTime );
  25081. return result;
  25082. }
  25083. // uses the array previously returned by 'getKeyframeOrder' to sort data
  25084. function sortedArray( values, stride, order ) {
  25085. const nValues = values.length;
  25086. const result = new values.constructor( nValues );
  25087. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  25088. const srcOffset = order[ i ] * stride;
  25089. for ( let j = 0; j !== stride; ++ j ) {
  25090. result[ dstOffset ++ ] = values[ srcOffset + j ];
  25091. }
  25092. }
  25093. return result;
  25094. }
  25095. // function for parsing AOS keyframe formats
  25096. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  25097. let i = 1, key = jsonKeys[ 0 ];
  25098. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  25099. key = jsonKeys[ i ++ ];
  25100. }
  25101. if ( key === undefined ) return; // no data
  25102. let value = key[ valuePropertyName ];
  25103. if ( value === undefined ) return; // no data
  25104. if ( Array.isArray( value ) ) {
  25105. do {
  25106. value = key[ valuePropertyName ];
  25107. if ( value !== undefined ) {
  25108. times.push( key.time );
  25109. values.push.apply( values, value ); // push all elements
  25110. }
  25111. key = jsonKeys[ i ++ ];
  25112. } while ( key !== undefined );
  25113. } else if ( value.toArray !== undefined ) {
  25114. // ...assume THREE.Math-ish
  25115. do {
  25116. value = key[ valuePropertyName ];
  25117. if ( value !== undefined ) {
  25118. times.push( key.time );
  25119. value.toArray( values, values.length );
  25120. }
  25121. key = jsonKeys[ i ++ ];
  25122. } while ( key !== undefined );
  25123. } else {
  25124. // otherwise push as-is
  25125. do {
  25126. value = key[ valuePropertyName ];
  25127. if ( value !== undefined ) {
  25128. times.push( key.time );
  25129. values.push( value );
  25130. }
  25131. key = jsonKeys[ i ++ ];
  25132. } while ( key !== undefined );
  25133. }
  25134. }
  25135. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  25136. const clip = sourceClip.clone();
  25137. clip.name = name;
  25138. const tracks = [];
  25139. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  25140. const track = clip.tracks[ i ];
  25141. const valueSize = track.getValueSize();
  25142. const times = [];
  25143. const values = [];
  25144. for ( let j = 0; j < track.times.length; ++ j ) {
  25145. const frame = track.times[ j ] * fps;
  25146. if ( frame < startFrame || frame >= endFrame ) continue;
  25147. times.push( track.times[ j ] );
  25148. for ( let k = 0; k < valueSize; ++ k ) {
  25149. values.push( track.values[ j * valueSize + k ] );
  25150. }
  25151. }
  25152. if ( times.length === 0 ) continue;
  25153. track.times = convertArray( times, track.times.constructor );
  25154. track.values = convertArray( values, track.values.constructor );
  25155. tracks.push( track );
  25156. }
  25157. clip.tracks = tracks;
  25158. // find minimum .times value across all tracks in the trimmed clip
  25159. let minStartTime = Infinity;
  25160. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  25161. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  25162. minStartTime = clip.tracks[ i ].times[ 0 ];
  25163. }
  25164. }
  25165. // shift all tracks such that clip begins at t=0
  25166. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  25167. clip.tracks[ i ].shift( - 1 * minStartTime );
  25168. }
  25169. clip.resetDuration();
  25170. return clip;
  25171. }
  25172. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  25173. if ( fps <= 0 ) fps = 30;
  25174. const numTracks = referenceClip.tracks.length;
  25175. const referenceTime = referenceFrame / fps;
  25176. // Make each track's values relative to the values at the reference frame
  25177. for ( let i = 0; i < numTracks; ++ i ) {
  25178. const referenceTrack = referenceClip.tracks[ i ];
  25179. const referenceTrackType = referenceTrack.ValueTypeName;
  25180. // Skip this track if it's non-numeric
  25181. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  25182. // Find the track in the target clip whose name and type matches the reference track
  25183. const targetTrack = targetClip.tracks.find( function ( track ) {
  25184. return track.name === referenceTrack.name
  25185. && track.ValueTypeName === referenceTrackType;
  25186. } );
  25187. if ( targetTrack === undefined ) continue;
  25188. let referenceOffset = 0;
  25189. const referenceValueSize = referenceTrack.getValueSize();
  25190. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  25191. referenceOffset = referenceValueSize / 3;
  25192. }
  25193. let targetOffset = 0;
  25194. const targetValueSize = targetTrack.getValueSize();
  25195. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  25196. targetOffset = targetValueSize / 3;
  25197. }
  25198. const lastIndex = referenceTrack.times.length - 1;
  25199. let referenceValue;
  25200. // Find the value to subtract out of the track
  25201. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  25202. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  25203. const startIndex = referenceOffset;
  25204. const endIndex = referenceValueSize - referenceOffset;
  25205. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  25206. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  25207. // Reference frame is after the last keyframe, so just use the last keyframe
  25208. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  25209. const endIndex = startIndex + referenceValueSize - referenceOffset;
  25210. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  25211. } else {
  25212. // Interpolate to the reference value
  25213. const interpolant = referenceTrack.createInterpolant();
  25214. const startIndex = referenceOffset;
  25215. const endIndex = referenceValueSize - referenceOffset;
  25216. interpolant.evaluate( referenceTime );
  25217. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  25218. }
  25219. // Conjugate the quaternion
  25220. if ( referenceTrackType === 'quaternion' ) {
  25221. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  25222. referenceQuat.toArray( referenceValue );
  25223. }
  25224. // Subtract the reference value from all of the track values
  25225. const numTimes = targetTrack.times.length;
  25226. for ( let j = 0; j < numTimes; ++ j ) {
  25227. const valueStart = j * targetValueSize + targetOffset;
  25228. if ( referenceTrackType === 'quaternion' ) {
  25229. // Multiply the conjugate for quaternion track types
  25230. Quaternion.multiplyQuaternionsFlat(
  25231. targetTrack.values,
  25232. valueStart,
  25233. referenceValue,
  25234. 0,
  25235. targetTrack.values,
  25236. valueStart
  25237. );
  25238. } else {
  25239. const valueEnd = targetValueSize - targetOffset * 2;
  25240. // Subtract each value for all other numeric track types
  25241. for ( let k = 0; k < valueEnd; ++ k ) {
  25242. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  25243. }
  25244. }
  25245. }
  25246. }
  25247. targetClip.blendMode = AdditiveAnimationBlendMode;
  25248. return targetClip;
  25249. }
  25250. const AnimationUtils = {
  25251. convertArray: convertArray,
  25252. isTypedArray: isTypedArray,
  25253. getKeyframeOrder: getKeyframeOrder,
  25254. sortedArray: sortedArray,
  25255. flattenJSON: flattenJSON,
  25256. subclip: subclip,
  25257. makeClipAdditive: makeClipAdditive
  25258. };
  25259. /**
  25260. * Abstract base class of interpolants over parametric samples.
  25261. *
  25262. * The parameter domain is one dimensional, typically the time or a path
  25263. * along a curve defined by the data.
  25264. *
  25265. * The sample values can have any dimensionality and derived classes may
  25266. * apply special interpretations to the data.
  25267. *
  25268. * This class provides the interval seek in a Template Method, deferring
  25269. * the actual interpolation to derived classes.
  25270. *
  25271. * Time complexity is O(1) for linear access crossing at most two points
  25272. * and O(log N) for random access, where N is the number of positions.
  25273. *
  25274. * References:
  25275. *
  25276. * http://www.oodesign.com/template-method-pattern.html
  25277. *
  25278. */
  25279. class Interpolant {
  25280. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25281. this.parameterPositions = parameterPositions;
  25282. this._cachedIndex = 0;
  25283. this.resultBuffer = resultBuffer !== undefined ?
  25284. resultBuffer : new sampleValues.constructor( sampleSize );
  25285. this.sampleValues = sampleValues;
  25286. this.valueSize = sampleSize;
  25287. this.settings = null;
  25288. this.DefaultSettings_ = {};
  25289. }
  25290. evaluate( t ) {
  25291. const pp = this.parameterPositions;
  25292. let i1 = this._cachedIndex,
  25293. t1 = pp[ i1 ],
  25294. t0 = pp[ i1 - 1 ];
  25295. validate_interval: {
  25296. seek: {
  25297. let right;
  25298. linear_scan: {
  25299. //- See http://jsperf.com/comparison-to-undefined/3
  25300. //- slower code:
  25301. //-
  25302. //- if ( t >= t1 || t1 === undefined ) {
  25303. forward_scan: if ( ! ( t < t1 ) ) {
  25304. for ( let giveUpAt = i1 + 2; ; ) {
  25305. if ( t1 === undefined ) {
  25306. if ( t < t0 ) break forward_scan;
  25307. // after end
  25308. i1 = pp.length;
  25309. this._cachedIndex = i1;
  25310. return this.copySampleValue_( i1 - 1 );
  25311. }
  25312. if ( i1 === giveUpAt ) break; // this loop
  25313. t0 = t1;
  25314. t1 = pp[ ++ i1 ];
  25315. if ( t < t1 ) {
  25316. // we have arrived at the sought interval
  25317. break seek;
  25318. }
  25319. }
  25320. // prepare binary search on the right side of the index
  25321. right = pp.length;
  25322. break linear_scan;
  25323. }
  25324. //- slower code:
  25325. //- if ( t < t0 || t0 === undefined ) {
  25326. if ( ! ( t >= t0 ) ) {
  25327. // looping?
  25328. const t1global = pp[ 1 ];
  25329. if ( t < t1global ) {
  25330. i1 = 2; // + 1, using the scan for the details
  25331. t0 = t1global;
  25332. }
  25333. // linear reverse scan
  25334. for ( let giveUpAt = i1 - 2; ; ) {
  25335. if ( t0 === undefined ) {
  25336. // before start
  25337. this._cachedIndex = 0;
  25338. return this.copySampleValue_( 0 );
  25339. }
  25340. if ( i1 === giveUpAt ) break; // this loop
  25341. t1 = t0;
  25342. t0 = pp[ -- i1 - 1 ];
  25343. if ( t >= t0 ) {
  25344. // we have arrived at the sought interval
  25345. break seek;
  25346. }
  25347. }
  25348. // prepare binary search on the left side of the index
  25349. right = i1;
  25350. i1 = 0;
  25351. break linear_scan;
  25352. }
  25353. // the interval is valid
  25354. break validate_interval;
  25355. } // linear scan
  25356. // binary search
  25357. while ( i1 < right ) {
  25358. const mid = ( i1 + right ) >>> 1;
  25359. if ( t < pp[ mid ] ) {
  25360. right = mid;
  25361. } else {
  25362. i1 = mid + 1;
  25363. }
  25364. }
  25365. t1 = pp[ i1 ];
  25366. t0 = pp[ i1 - 1 ];
  25367. // check boundary cases, again
  25368. if ( t0 === undefined ) {
  25369. this._cachedIndex = 0;
  25370. return this.copySampleValue_( 0 );
  25371. }
  25372. if ( t1 === undefined ) {
  25373. i1 = pp.length;
  25374. this._cachedIndex = i1;
  25375. return this.copySampleValue_( i1 - 1 );
  25376. }
  25377. } // seek
  25378. this._cachedIndex = i1;
  25379. this.intervalChanged_( i1, t0, t1 );
  25380. } // validate_interval
  25381. return this.interpolate_( i1, t0, t, t1 );
  25382. }
  25383. getSettings_() {
  25384. return this.settings || this.DefaultSettings_;
  25385. }
  25386. copySampleValue_( index ) {
  25387. // copies a sample value to the result buffer
  25388. const result = this.resultBuffer,
  25389. values = this.sampleValues,
  25390. stride = this.valueSize,
  25391. offset = index * stride;
  25392. for ( let i = 0; i !== stride; ++ i ) {
  25393. result[ i ] = values[ offset + i ];
  25394. }
  25395. return result;
  25396. }
  25397. // Template methods for derived classes:
  25398. interpolate_( /* i1, t0, t, t1 */ ) {
  25399. throw new Error( 'call to abstract method' );
  25400. // implementations shall return this.resultBuffer
  25401. }
  25402. intervalChanged_( /* i1, t0, t1 */ ) {
  25403. // empty
  25404. }
  25405. }
  25406. /**
  25407. * Fast and simple cubic spline interpolant.
  25408. *
  25409. * It was derived from a Hermitian construction setting the first derivative
  25410. * at each sample position to the linear slope between neighboring positions
  25411. * over their parameter interval.
  25412. */
  25413. class CubicInterpolant extends Interpolant {
  25414. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25415. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25416. this._weightPrev = - 0;
  25417. this._offsetPrev = - 0;
  25418. this._weightNext = - 0;
  25419. this._offsetNext = - 0;
  25420. this.DefaultSettings_ = {
  25421. endingStart: ZeroCurvatureEnding,
  25422. endingEnd: ZeroCurvatureEnding
  25423. };
  25424. }
  25425. intervalChanged_( i1, t0, t1 ) {
  25426. const pp = this.parameterPositions;
  25427. let iPrev = i1 - 2,
  25428. iNext = i1 + 1,
  25429. tPrev = pp[ iPrev ],
  25430. tNext = pp[ iNext ];
  25431. if ( tPrev === undefined ) {
  25432. switch ( this.getSettings_().endingStart ) {
  25433. case ZeroSlopeEnding:
  25434. // f'(t0) = 0
  25435. iPrev = i1;
  25436. tPrev = 2 * t0 - t1;
  25437. break;
  25438. case WrapAroundEnding:
  25439. // use the other end of the curve
  25440. iPrev = pp.length - 2;
  25441. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  25442. break;
  25443. default: // ZeroCurvatureEnding
  25444. // f''(t0) = 0 a.k.a. Natural Spline
  25445. iPrev = i1;
  25446. tPrev = t1;
  25447. }
  25448. }
  25449. if ( tNext === undefined ) {
  25450. switch ( this.getSettings_().endingEnd ) {
  25451. case ZeroSlopeEnding:
  25452. // f'(tN) = 0
  25453. iNext = i1;
  25454. tNext = 2 * t1 - t0;
  25455. break;
  25456. case WrapAroundEnding:
  25457. // use the other end of the curve
  25458. iNext = 1;
  25459. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  25460. break;
  25461. default: // ZeroCurvatureEnding
  25462. // f''(tN) = 0, a.k.a. Natural Spline
  25463. iNext = i1 - 1;
  25464. tNext = t0;
  25465. }
  25466. }
  25467. const halfDt = ( t1 - t0 ) * 0.5,
  25468. stride = this.valueSize;
  25469. this._weightPrev = halfDt / ( t0 - tPrev );
  25470. this._weightNext = halfDt / ( tNext - t1 );
  25471. this._offsetPrev = iPrev * stride;
  25472. this._offsetNext = iNext * stride;
  25473. }
  25474. interpolate_( i1, t0, t, t1 ) {
  25475. const result = this.resultBuffer,
  25476. values = this.sampleValues,
  25477. stride = this.valueSize,
  25478. o1 = i1 * stride, o0 = o1 - stride,
  25479. oP = this._offsetPrev, oN = this._offsetNext,
  25480. wP = this._weightPrev, wN = this._weightNext,
  25481. p = ( t - t0 ) / ( t1 - t0 ),
  25482. pp = p * p,
  25483. ppp = pp * p;
  25484. // evaluate polynomials
  25485. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  25486. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  25487. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  25488. const sN = wN * ppp - wN * pp;
  25489. // combine data linearly
  25490. for ( let i = 0; i !== stride; ++ i ) {
  25491. result[ i ] =
  25492. sP * values[ oP + i ] +
  25493. s0 * values[ o0 + i ] +
  25494. s1 * values[ o1 + i ] +
  25495. sN * values[ oN + i ];
  25496. }
  25497. return result;
  25498. }
  25499. }
  25500. class LinearInterpolant extends Interpolant {
  25501. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25502. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25503. }
  25504. interpolate_( i1, t0, t, t1 ) {
  25505. const result = this.resultBuffer,
  25506. values = this.sampleValues,
  25507. stride = this.valueSize,
  25508. offset1 = i1 * stride,
  25509. offset0 = offset1 - stride,
  25510. weight1 = ( t - t0 ) / ( t1 - t0 ),
  25511. weight0 = 1 - weight1;
  25512. for ( let i = 0; i !== stride; ++ i ) {
  25513. result[ i ] =
  25514. values[ offset0 + i ] * weight0 +
  25515. values[ offset1 + i ] * weight1;
  25516. }
  25517. return result;
  25518. }
  25519. }
  25520. /**
  25521. *
  25522. * Interpolant that evaluates to the sample value at the position preceding
  25523. * the parameter.
  25524. */
  25525. class DiscreteInterpolant extends Interpolant {
  25526. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25527. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25528. }
  25529. interpolate_( i1 /*, t0, t, t1 */ ) {
  25530. return this.copySampleValue_( i1 - 1 );
  25531. }
  25532. }
  25533. class KeyframeTrack {
  25534. constructor( name, times, values, interpolation ) {
  25535. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  25536. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  25537. this.name = name;
  25538. this.times = convertArray( times, this.TimeBufferType );
  25539. this.values = convertArray( values, this.ValueBufferType );
  25540. this.setInterpolation( interpolation || this.DefaultInterpolation );
  25541. }
  25542. // Serialization (in static context, because of constructor invocation
  25543. // and automatic invocation of .toJSON):
  25544. static toJSON( track ) {
  25545. const trackType = track.constructor;
  25546. let json;
  25547. // derived classes can define a static toJSON method
  25548. if ( trackType.toJSON !== this.toJSON ) {
  25549. json = trackType.toJSON( track );
  25550. } else {
  25551. // by default, we assume the data can be serialized as-is
  25552. json = {
  25553. 'name': track.name,
  25554. 'times': convertArray( track.times, Array ),
  25555. 'values': convertArray( track.values, Array )
  25556. };
  25557. const interpolation = track.getInterpolation();
  25558. if ( interpolation !== track.DefaultInterpolation ) {
  25559. json.interpolation = interpolation;
  25560. }
  25561. }
  25562. json.type = track.ValueTypeName; // mandatory
  25563. return json;
  25564. }
  25565. InterpolantFactoryMethodDiscrete( result ) {
  25566. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  25567. }
  25568. InterpolantFactoryMethodLinear( result ) {
  25569. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25570. }
  25571. InterpolantFactoryMethodSmooth( result ) {
  25572. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  25573. }
  25574. setInterpolation( interpolation ) {
  25575. let factoryMethod;
  25576. switch ( interpolation ) {
  25577. case InterpolateDiscrete:
  25578. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  25579. break;
  25580. case InterpolateLinear:
  25581. factoryMethod = this.InterpolantFactoryMethodLinear;
  25582. break;
  25583. case InterpolateSmooth:
  25584. factoryMethod = this.InterpolantFactoryMethodSmooth;
  25585. break;
  25586. }
  25587. if ( factoryMethod === undefined ) {
  25588. const message = 'unsupported interpolation for ' +
  25589. this.ValueTypeName + ' keyframe track named ' + this.name;
  25590. if ( this.createInterpolant === undefined ) {
  25591. // fall back to default, unless the default itself is messed up
  25592. if ( interpolation !== this.DefaultInterpolation ) {
  25593. this.setInterpolation( this.DefaultInterpolation );
  25594. } else {
  25595. throw new Error( message ); // fatal, in this case
  25596. }
  25597. }
  25598. console.warn( 'THREE.KeyframeTrack:', message );
  25599. return this;
  25600. }
  25601. this.createInterpolant = factoryMethod;
  25602. return this;
  25603. }
  25604. getInterpolation() {
  25605. switch ( this.createInterpolant ) {
  25606. case this.InterpolantFactoryMethodDiscrete:
  25607. return InterpolateDiscrete;
  25608. case this.InterpolantFactoryMethodLinear:
  25609. return InterpolateLinear;
  25610. case this.InterpolantFactoryMethodSmooth:
  25611. return InterpolateSmooth;
  25612. }
  25613. }
  25614. getValueSize() {
  25615. return this.values.length / this.times.length;
  25616. }
  25617. // move all keyframes either forwards or backwards in time
  25618. shift( timeOffset ) {
  25619. if ( timeOffset !== 0.0 ) {
  25620. const times = this.times;
  25621. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25622. times[ i ] += timeOffset;
  25623. }
  25624. }
  25625. return this;
  25626. }
  25627. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25628. scale( timeScale ) {
  25629. if ( timeScale !== 1.0 ) {
  25630. const times = this.times;
  25631. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25632. times[ i ] *= timeScale;
  25633. }
  25634. }
  25635. return this;
  25636. }
  25637. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25638. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25639. trim( startTime, endTime ) {
  25640. const times = this.times,
  25641. nKeys = times.length;
  25642. let from = 0,
  25643. to = nKeys - 1;
  25644. while ( from !== nKeys && times[ from ] < startTime ) {
  25645. ++ from;
  25646. }
  25647. while ( to !== - 1 && times[ to ] > endTime ) {
  25648. -- to;
  25649. }
  25650. ++ to; // inclusive -> exclusive bound
  25651. if ( from !== 0 || to !== nKeys ) {
  25652. // empty tracks are forbidden, so keep at least one keyframe
  25653. if ( from >= to ) {
  25654. to = Math.max( to, 1 );
  25655. from = to - 1;
  25656. }
  25657. const stride = this.getValueSize();
  25658. this.times = times.slice( from, to );
  25659. this.values = this.values.slice( from * stride, to * stride );
  25660. }
  25661. return this;
  25662. }
  25663. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25664. validate() {
  25665. let valid = true;
  25666. const valueSize = this.getValueSize();
  25667. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25668. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25669. valid = false;
  25670. }
  25671. const times = this.times,
  25672. values = this.values,
  25673. nKeys = times.length;
  25674. if ( nKeys === 0 ) {
  25675. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25676. valid = false;
  25677. }
  25678. let prevTime = null;
  25679. for ( let i = 0; i !== nKeys; i ++ ) {
  25680. const currTime = times[ i ];
  25681. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25682. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25683. valid = false;
  25684. break;
  25685. }
  25686. if ( prevTime !== null && prevTime > currTime ) {
  25687. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25688. valid = false;
  25689. break;
  25690. }
  25691. prevTime = currTime;
  25692. }
  25693. if ( values !== undefined ) {
  25694. if ( isTypedArray( values ) ) {
  25695. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  25696. const value = values[ i ];
  25697. if ( isNaN( value ) ) {
  25698. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25699. valid = false;
  25700. break;
  25701. }
  25702. }
  25703. }
  25704. }
  25705. return valid;
  25706. }
  25707. // removes equivalent sequential keys as common in morph target sequences
  25708. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25709. optimize() {
  25710. // times or values may be shared with other tracks, so overwriting is unsafe
  25711. const times = this.times.slice(),
  25712. values = this.values.slice(),
  25713. stride = this.getValueSize(),
  25714. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25715. lastIndex = times.length - 1;
  25716. let writeIndex = 1;
  25717. for ( let i = 1; i < lastIndex; ++ i ) {
  25718. let keep = false;
  25719. const time = times[ i ];
  25720. const timeNext = times[ i + 1 ];
  25721. // remove adjacent keyframes scheduled at the same time
  25722. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  25723. if ( ! smoothInterpolation ) {
  25724. // remove unnecessary keyframes same as their neighbors
  25725. const offset = i * stride,
  25726. offsetP = offset - stride,
  25727. offsetN = offset + stride;
  25728. for ( let j = 0; j !== stride; ++ j ) {
  25729. const value = values[ offset + j ];
  25730. if ( value !== values[ offsetP + j ] ||
  25731. value !== values[ offsetN + j ] ) {
  25732. keep = true;
  25733. break;
  25734. }
  25735. }
  25736. } else {
  25737. keep = true;
  25738. }
  25739. }
  25740. // in-place compaction
  25741. if ( keep ) {
  25742. if ( i !== writeIndex ) {
  25743. times[ writeIndex ] = times[ i ];
  25744. const readOffset = i * stride,
  25745. writeOffset = writeIndex * stride;
  25746. for ( let j = 0; j !== stride; ++ j ) {
  25747. values[ writeOffset + j ] = values[ readOffset + j ];
  25748. }
  25749. }
  25750. ++ writeIndex;
  25751. }
  25752. }
  25753. // flush last keyframe (compaction looks ahead)
  25754. if ( lastIndex > 0 ) {
  25755. times[ writeIndex ] = times[ lastIndex ];
  25756. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25757. values[ writeOffset + j ] = values[ readOffset + j ];
  25758. }
  25759. ++ writeIndex;
  25760. }
  25761. if ( writeIndex !== times.length ) {
  25762. this.times = times.slice( 0, writeIndex );
  25763. this.values = values.slice( 0, writeIndex * stride );
  25764. } else {
  25765. this.times = times;
  25766. this.values = values;
  25767. }
  25768. return this;
  25769. }
  25770. clone() {
  25771. const times = this.times.slice();
  25772. const values = this.values.slice();
  25773. const TypedKeyframeTrack = this.constructor;
  25774. const track = new TypedKeyframeTrack( this.name, times, values );
  25775. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  25776. track.createInterpolant = this.createInterpolant;
  25777. return track;
  25778. }
  25779. }
  25780. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  25781. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  25782. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25783. /**
  25784. * A Track of Boolean keyframe values.
  25785. */
  25786. class BooleanKeyframeTrack extends KeyframeTrack {
  25787. // No interpolation parameter because only InterpolateDiscrete is valid.
  25788. constructor( name, times, values ) {
  25789. super( name, times, values );
  25790. }
  25791. }
  25792. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  25793. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  25794. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25795. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25796. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25797. /**
  25798. * A Track of keyframe values that represent color.
  25799. */
  25800. class ColorKeyframeTrack extends KeyframeTrack {}
  25801. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  25802. /**
  25803. * A Track of numeric keyframe values.
  25804. */
  25805. class NumberKeyframeTrack extends KeyframeTrack {}
  25806. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  25807. /**
  25808. * Spherical linear unit quaternion interpolant.
  25809. */
  25810. class QuaternionLinearInterpolant extends Interpolant {
  25811. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25812. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25813. }
  25814. interpolate_( i1, t0, t, t1 ) {
  25815. const result = this.resultBuffer,
  25816. values = this.sampleValues,
  25817. stride = this.valueSize,
  25818. alpha = ( t - t0 ) / ( t1 - t0 );
  25819. let offset = i1 * stride;
  25820. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  25821. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  25822. }
  25823. return result;
  25824. }
  25825. }
  25826. /**
  25827. * A Track of quaternion keyframe values.
  25828. */
  25829. class QuaternionKeyframeTrack extends KeyframeTrack {
  25830. InterpolantFactoryMethodLinear( result ) {
  25831. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25832. }
  25833. }
  25834. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  25835. // ValueBufferType is inherited
  25836. // DefaultInterpolation is inherited;
  25837. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25838. /**
  25839. * A Track that interpolates Strings
  25840. */
  25841. class StringKeyframeTrack extends KeyframeTrack {
  25842. // No interpolation parameter because only InterpolateDiscrete is valid.
  25843. constructor( name, times, values ) {
  25844. super( name, times, values );
  25845. }
  25846. }
  25847. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  25848. StringKeyframeTrack.prototype.ValueBufferType = Array;
  25849. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25850. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25851. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25852. /**
  25853. * A Track of vectored keyframe values.
  25854. */
  25855. class VectorKeyframeTrack extends KeyframeTrack {}
  25856. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  25857. class AnimationClip {
  25858. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  25859. this.name = name;
  25860. this.tracks = tracks;
  25861. this.duration = duration;
  25862. this.blendMode = blendMode;
  25863. this.uuid = generateUUID();
  25864. // this means it should figure out its duration by scanning the tracks
  25865. if ( this.duration < 0 ) {
  25866. this.resetDuration();
  25867. }
  25868. }
  25869. static parse( json ) {
  25870. const tracks = [],
  25871. jsonTracks = json.tracks,
  25872. frameTime = 1.0 / ( json.fps || 1.0 );
  25873. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25874. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25875. }
  25876. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  25877. clip.uuid = json.uuid;
  25878. return clip;
  25879. }
  25880. static toJSON( clip ) {
  25881. const tracks = [],
  25882. clipTracks = clip.tracks;
  25883. const json = {
  25884. 'name': clip.name,
  25885. 'duration': clip.duration,
  25886. 'tracks': tracks,
  25887. 'uuid': clip.uuid,
  25888. 'blendMode': clip.blendMode
  25889. };
  25890. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25891. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25892. }
  25893. return json;
  25894. }
  25895. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  25896. const numMorphTargets = morphTargetSequence.length;
  25897. const tracks = [];
  25898. for ( let i = 0; i < numMorphTargets; i ++ ) {
  25899. let times = [];
  25900. let values = [];
  25901. times.push(
  25902. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25903. i,
  25904. ( i + 1 ) % numMorphTargets );
  25905. values.push( 0, 1, 0 );
  25906. const order = getKeyframeOrder( times );
  25907. times = sortedArray( times, 1, order );
  25908. values = sortedArray( values, 1, order );
  25909. // if there is a key at the first frame, duplicate it as the
  25910. // last frame as well for perfect loop.
  25911. if ( ! noLoop && times[ 0 ] === 0 ) {
  25912. times.push( numMorphTargets );
  25913. values.push( values[ 0 ] );
  25914. }
  25915. tracks.push(
  25916. new NumberKeyframeTrack(
  25917. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25918. times, values
  25919. ).scale( 1.0 / fps ) );
  25920. }
  25921. return new this( name, - 1, tracks );
  25922. }
  25923. static findByName( objectOrClipArray, name ) {
  25924. let clipArray = objectOrClipArray;
  25925. if ( ! Array.isArray( objectOrClipArray ) ) {
  25926. const o = objectOrClipArray;
  25927. clipArray = o.geometry && o.geometry.animations || o.animations;
  25928. }
  25929. for ( let i = 0; i < clipArray.length; i ++ ) {
  25930. if ( clipArray[ i ].name === name ) {
  25931. return clipArray[ i ];
  25932. }
  25933. }
  25934. return null;
  25935. }
  25936. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  25937. const animationToMorphTargets = {};
  25938. // tested with https://regex101.com/ on trick sequences
  25939. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25940. const pattern = /^([\w-]*?)([\d]+)$/;
  25941. // sort morph target names into animation groups based
  25942. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25943. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  25944. const morphTarget = morphTargets[ i ];
  25945. const parts = morphTarget.name.match( pattern );
  25946. if ( parts && parts.length > 1 ) {
  25947. const name = parts[ 1 ];
  25948. let animationMorphTargets = animationToMorphTargets[ name ];
  25949. if ( ! animationMorphTargets ) {
  25950. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25951. }
  25952. animationMorphTargets.push( morphTarget );
  25953. }
  25954. }
  25955. const clips = [];
  25956. for ( const name in animationToMorphTargets ) {
  25957. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25958. }
  25959. return clips;
  25960. }
  25961. // parse the animation.hierarchy format
  25962. static parseAnimation( animation, bones ) {
  25963. if ( ! animation ) {
  25964. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25965. return null;
  25966. }
  25967. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25968. // only return track if there are actually keys.
  25969. if ( animationKeys.length !== 0 ) {
  25970. const times = [];
  25971. const values = [];
  25972. flattenJSON( animationKeys, times, values, propertyName );
  25973. // empty keys are filtered out, so check again
  25974. if ( times.length !== 0 ) {
  25975. destTracks.push( new trackType( trackName, times, values ) );
  25976. }
  25977. }
  25978. };
  25979. const tracks = [];
  25980. const clipName = animation.name || 'default';
  25981. const fps = animation.fps || 30;
  25982. const blendMode = animation.blendMode;
  25983. // automatic length determination in AnimationClip.
  25984. let duration = animation.length || - 1;
  25985. const hierarchyTracks = animation.hierarchy || [];
  25986. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  25987. const animationKeys = hierarchyTracks[ h ].keys;
  25988. // skip empty tracks
  25989. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25990. // process morph targets
  25991. if ( animationKeys[ 0 ].morphTargets ) {
  25992. // figure out all morph targets used in this track
  25993. const morphTargetNames = {};
  25994. let k;
  25995. for ( k = 0; k < animationKeys.length; k ++ ) {
  25996. if ( animationKeys[ k ].morphTargets ) {
  25997. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25998. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25999. }
  26000. }
  26001. }
  26002. // create a track for each morph target with all zero
  26003. // morphTargetInfluences except for the keys in which
  26004. // the morphTarget is named.
  26005. for ( const morphTargetName in morphTargetNames ) {
  26006. const times = [];
  26007. const values = [];
  26008. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  26009. const animationKey = animationKeys[ k ];
  26010. times.push( animationKey.time );
  26011. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  26012. }
  26013. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  26014. }
  26015. duration = morphTargetNames.length * fps;
  26016. } else {
  26017. // ...assume skeletal animation
  26018. const boneName = '.bones[' + bones[ h ].name + ']';
  26019. addNonemptyTrack(
  26020. VectorKeyframeTrack, boneName + '.position',
  26021. animationKeys, 'pos', tracks );
  26022. addNonemptyTrack(
  26023. QuaternionKeyframeTrack, boneName + '.quaternion',
  26024. animationKeys, 'rot', tracks );
  26025. addNonemptyTrack(
  26026. VectorKeyframeTrack, boneName + '.scale',
  26027. animationKeys, 'scl', tracks );
  26028. }
  26029. }
  26030. if ( tracks.length === 0 ) {
  26031. return null;
  26032. }
  26033. const clip = new this( clipName, duration, tracks, blendMode );
  26034. return clip;
  26035. }
  26036. resetDuration() {
  26037. const tracks = this.tracks;
  26038. let duration = 0;
  26039. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  26040. const track = this.tracks[ i ];
  26041. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  26042. }
  26043. this.duration = duration;
  26044. return this;
  26045. }
  26046. trim() {
  26047. for ( let i = 0; i < this.tracks.length; i ++ ) {
  26048. this.tracks[ i ].trim( 0, this.duration );
  26049. }
  26050. return this;
  26051. }
  26052. validate() {
  26053. let valid = true;
  26054. for ( let i = 0; i < this.tracks.length; i ++ ) {
  26055. valid = valid && this.tracks[ i ].validate();
  26056. }
  26057. return valid;
  26058. }
  26059. optimize() {
  26060. for ( let i = 0; i < this.tracks.length; i ++ ) {
  26061. this.tracks[ i ].optimize();
  26062. }
  26063. return this;
  26064. }
  26065. clone() {
  26066. const tracks = [];
  26067. for ( let i = 0; i < this.tracks.length; i ++ ) {
  26068. tracks.push( this.tracks[ i ].clone() );
  26069. }
  26070. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  26071. }
  26072. toJSON() {
  26073. return this.constructor.toJSON( this );
  26074. }
  26075. }
  26076. function getTrackTypeForValueTypeName( typeName ) {
  26077. switch ( typeName.toLowerCase() ) {
  26078. case 'scalar':
  26079. case 'double':
  26080. case 'float':
  26081. case 'number':
  26082. case 'integer':
  26083. return NumberKeyframeTrack;
  26084. case 'vector':
  26085. case 'vector2':
  26086. case 'vector3':
  26087. case 'vector4':
  26088. return VectorKeyframeTrack;
  26089. case 'color':
  26090. return ColorKeyframeTrack;
  26091. case 'quaternion':
  26092. return QuaternionKeyframeTrack;
  26093. case 'bool':
  26094. case 'boolean':
  26095. return BooleanKeyframeTrack;
  26096. case 'string':
  26097. return StringKeyframeTrack;
  26098. }
  26099. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  26100. }
  26101. function parseKeyframeTrack( json ) {
  26102. if ( json.type === undefined ) {
  26103. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  26104. }
  26105. const trackType = getTrackTypeForValueTypeName( json.type );
  26106. if ( json.times === undefined ) {
  26107. const times = [], values = [];
  26108. flattenJSON( json.keys, times, values, 'value' );
  26109. json.times = times;
  26110. json.values = values;
  26111. }
  26112. // derived classes can define a static parse method
  26113. if ( trackType.parse !== undefined ) {
  26114. return trackType.parse( json );
  26115. } else {
  26116. // by default, we assume a constructor compatible with the base
  26117. return new trackType( json.name, json.times, json.values, json.interpolation );
  26118. }
  26119. }
  26120. const Cache = {
  26121. enabled: false,
  26122. files: {},
  26123. add: function ( key, file ) {
  26124. if ( this.enabled === false ) return;
  26125. // console.log( 'THREE.Cache', 'Adding key:', key );
  26126. this.files[ key ] = file;
  26127. },
  26128. get: function ( key ) {
  26129. if ( this.enabled === false ) return;
  26130. // console.log( 'THREE.Cache', 'Checking key:', key );
  26131. return this.files[ key ];
  26132. },
  26133. remove: function ( key ) {
  26134. delete this.files[ key ];
  26135. },
  26136. clear: function () {
  26137. this.files = {};
  26138. }
  26139. };
  26140. class LoadingManager {
  26141. constructor( onLoad, onProgress, onError ) {
  26142. const scope = this;
  26143. let isLoading = false;
  26144. let itemsLoaded = 0;
  26145. let itemsTotal = 0;
  26146. let urlModifier = undefined;
  26147. const handlers = [];
  26148. // Refer to #5689 for the reason why we don't set .onStart
  26149. // in the constructor
  26150. this.onStart = undefined;
  26151. this.onLoad = onLoad;
  26152. this.onProgress = onProgress;
  26153. this.onError = onError;
  26154. this.itemStart = function ( url ) {
  26155. itemsTotal ++;
  26156. if ( isLoading === false ) {
  26157. if ( scope.onStart !== undefined ) {
  26158. scope.onStart( url, itemsLoaded, itemsTotal );
  26159. }
  26160. }
  26161. isLoading = true;
  26162. };
  26163. this.itemEnd = function ( url ) {
  26164. itemsLoaded ++;
  26165. if ( scope.onProgress !== undefined ) {
  26166. scope.onProgress( url, itemsLoaded, itemsTotal );
  26167. }
  26168. if ( itemsLoaded === itemsTotal ) {
  26169. isLoading = false;
  26170. if ( scope.onLoad !== undefined ) {
  26171. scope.onLoad();
  26172. }
  26173. }
  26174. };
  26175. this.itemError = function ( url ) {
  26176. if ( scope.onError !== undefined ) {
  26177. scope.onError( url );
  26178. }
  26179. };
  26180. this.resolveURL = function ( url ) {
  26181. if ( urlModifier ) {
  26182. return urlModifier( url );
  26183. }
  26184. return url;
  26185. };
  26186. this.setURLModifier = function ( transform ) {
  26187. urlModifier = transform;
  26188. return this;
  26189. };
  26190. this.addHandler = function ( regex, loader ) {
  26191. handlers.push( regex, loader );
  26192. return this;
  26193. };
  26194. this.removeHandler = function ( regex ) {
  26195. const index = handlers.indexOf( regex );
  26196. if ( index !== - 1 ) {
  26197. handlers.splice( index, 2 );
  26198. }
  26199. return this;
  26200. };
  26201. this.getHandler = function ( file ) {
  26202. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  26203. const regex = handlers[ i ];
  26204. const loader = handlers[ i + 1 ];
  26205. if ( regex.global ) regex.lastIndex = 0; // see #17920
  26206. if ( regex.test( file ) ) {
  26207. return loader;
  26208. }
  26209. }
  26210. return null;
  26211. };
  26212. }
  26213. }
  26214. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  26215. class Loader {
  26216. constructor( manager ) {
  26217. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26218. this.crossOrigin = 'anonymous';
  26219. this.withCredentials = false;
  26220. this.path = '';
  26221. this.resourcePath = '';
  26222. this.requestHeader = {};
  26223. }
  26224. load( /* url, onLoad, onProgress, onError */ ) {}
  26225. loadAsync( url, onProgress ) {
  26226. const scope = this;
  26227. return new Promise( function ( resolve, reject ) {
  26228. scope.load( url, resolve, onProgress, reject );
  26229. } );
  26230. }
  26231. parse( /* data */ ) {}
  26232. setCrossOrigin( crossOrigin ) {
  26233. this.crossOrigin = crossOrigin;
  26234. return this;
  26235. }
  26236. setWithCredentials( value ) {
  26237. this.withCredentials = value;
  26238. return this;
  26239. }
  26240. setPath( path ) {
  26241. this.path = path;
  26242. return this;
  26243. }
  26244. setResourcePath( resourcePath ) {
  26245. this.resourcePath = resourcePath;
  26246. return this;
  26247. }
  26248. setRequestHeader( requestHeader ) {
  26249. this.requestHeader = requestHeader;
  26250. return this;
  26251. }
  26252. }
  26253. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  26254. const loading = {};
  26255. class HttpError extends Error {
  26256. constructor( message, response ) {
  26257. super( message );
  26258. this.response = response;
  26259. }
  26260. }
  26261. class FileLoader extends Loader {
  26262. constructor( manager ) {
  26263. super( manager );
  26264. }
  26265. load( url, onLoad, onProgress, onError ) {
  26266. if ( url === undefined ) url = '';
  26267. if ( this.path !== undefined ) url = this.path + url;
  26268. url = this.manager.resolveURL( url );
  26269. const cached = Cache.get( url );
  26270. if ( cached !== undefined ) {
  26271. this.manager.itemStart( url );
  26272. setTimeout( () => {
  26273. if ( onLoad ) onLoad( cached );
  26274. this.manager.itemEnd( url );
  26275. }, 0 );
  26276. return cached;
  26277. }
  26278. // Check if request is duplicate
  26279. if ( loading[ url ] !== undefined ) {
  26280. loading[ url ].push( {
  26281. onLoad: onLoad,
  26282. onProgress: onProgress,
  26283. onError: onError
  26284. } );
  26285. return;
  26286. }
  26287. // Initialise array for duplicate requests
  26288. loading[ url ] = [];
  26289. loading[ url ].push( {
  26290. onLoad: onLoad,
  26291. onProgress: onProgress,
  26292. onError: onError,
  26293. } );
  26294. // create request
  26295. const req = new Request( url, {
  26296. headers: new Headers( this.requestHeader ),
  26297. credentials: this.withCredentials ? 'include' : 'same-origin',
  26298. // An abort controller could be added within a future PR
  26299. } );
  26300. // record states ( avoid data race )
  26301. const mimeType = this.mimeType;
  26302. const responseType = this.responseType;
  26303. // start the fetch
  26304. fetch( req )
  26305. .then( response => {
  26306. if ( response.status === 200 || response.status === 0 ) {
  26307. // Some browsers return HTTP Status 0 when using non-http protocol
  26308. // e.g. 'file://' or 'data://'. Handle as success.
  26309. if ( response.status === 0 ) {
  26310. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  26311. }
  26312. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  26313. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  26314. return response;
  26315. }
  26316. const callbacks = loading[ url ];
  26317. const reader = response.body.getReader();
  26318. // Nginx needs X-File-Size check
  26319. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  26320. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  26321. const total = contentLength ? parseInt( contentLength ) : 0;
  26322. const lengthComputable = total !== 0;
  26323. let loaded = 0;
  26324. // periodically read data into the new stream tracking while download progress
  26325. const stream = new ReadableStream( {
  26326. start( controller ) {
  26327. readData();
  26328. function readData() {
  26329. reader.read().then( ( { done, value } ) => {
  26330. if ( done ) {
  26331. controller.close();
  26332. } else {
  26333. loaded += value.byteLength;
  26334. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  26335. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26336. const callback = callbacks[ i ];
  26337. if ( callback.onProgress ) callback.onProgress( event );
  26338. }
  26339. controller.enqueue( value );
  26340. readData();
  26341. }
  26342. }, ( e ) => {
  26343. controller.error( e );
  26344. } );
  26345. }
  26346. }
  26347. } );
  26348. return new Response( stream );
  26349. } else {
  26350. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  26351. }
  26352. } )
  26353. .then( response => {
  26354. switch ( responseType ) {
  26355. case 'arraybuffer':
  26356. return response.arrayBuffer();
  26357. case 'blob':
  26358. return response.blob();
  26359. case 'document':
  26360. return response.text()
  26361. .then( text => {
  26362. const parser = new DOMParser();
  26363. return parser.parseFromString( text, mimeType );
  26364. } );
  26365. case 'json':
  26366. return response.json();
  26367. default:
  26368. if ( mimeType === undefined ) {
  26369. return response.text();
  26370. } else {
  26371. // sniff encoding
  26372. const re = /charset="?([^;"\s]*)"?/i;
  26373. const exec = re.exec( mimeType );
  26374. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  26375. const decoder = new TextDecoder( label );
  26376. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  26377. }
  26378. }
  26379. } )
  26380. .then( data => {
  26381. // Add to cache only on HTTP success, so that we do not cache
  26382. // error response bodies as proper responses to requests.
  26383. Cache.add( url, data );
  26384. const callbacks = loading[ url ];
  26385. delete loading[ url ];
  26386. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26387. const callback = callbacks[ i ];
  26388. if ( callback.onLoad ) callback.onLoad( data );
  26389. }
  26390. } )
  26391. .catch( err => {
  26392. // Abort errors and other errors are handled the same
  26393. const callbacks = loading[ url ];
  26394. if ( callbacks === undefined ) {
  26395. // When onLoad was called and url was deleted in `loading`
  26396. this.manager.itemError( url );
  26397. throw err;
  26398. }
  26399. delete loading[ url ];
  26400. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26401. const callback = callbacks[ i ];
  26402. if ( callback.onError ) callback.onError( err );
  26403. }
  26404. this.manager.itemError( url );
  26405. } )
  26406. .finally( () => {
  26407. this.manager.itemEnd( url );
  26408. } );
  26409. this.manager.itemStart( url );
  26410. }
  26411. setResponseType( value ) {
  26412. this.responseType = value;
  26413. return this;
  26414. }
  26415. setMimeType( value ) {
  26416. this.mimeType = value;
  26417. return this;
  26418. }
  26419. }
  26420. class AnimationLoader extends Loader {
  26421. constructor( manager ) {
  26422. super( manager );
  26423. }
  26424. load( url, onLoad, onProgress, onError ) {
  26425. const scope = this;
  26426. const loader = new FileLoader( this.manager );
  26427. loader.setPath( this.path );
  26428. loader.setRequestHeader( this.requestHeader );
  26429. loader.setWithCredentials( this.withCredentials );
  26430. loader.load( url, function ( text ) {
  26431. try {
  26432. onLoad( scope.parse( JSON.parse( text ) ) );
  26433. } catch ( e ) {
  26434. if ( onError ) {
  26435. onError( e );
  26436. } else {
  26437. console.error( e );
  26438. }
  26439. scope.manager.itemError( url );
  26440. }
  26441. }, onProgress, onError );
  26442. }
  26443. parse( json ) {
  26444. const animations = [];
  26445. for ( let i = 0; i < json.length; i ++ ) {
  26446. const clip = AnimationClip.parse( json[ i ] );
  26447. animations.push( clip );
  26448. }
  26449. return animations;
  26450. }
  26451. }
  26452. /**
  26453. * Abstract Base class to block based textures loader (dds, pvr, ...)
  26454. *
  26455. * Sub classes have to implement the parse() method which will be used in load().
  26456. */
  26457. class CompressedTextureLoader extends Loader {
  26458. constructor( manager ) {
  26459. super( manager );
  26460. }
  26461. load( url, onLoad, onProgress, onError ) {
  26462. const scope = this;
  26463. const images = [];
  26464. const texture = new CompressedTexture();
  26465. const loader = new FileLoader( this.manager );
  26466. loader.setPath( this.path );
  26467. loader.setResponseType( 'arraybuffer' );
  26468. loader.setRequestHeader( this.requestHeader );
  26469. loader.setWithCredentials( scope.withCredentials );
  26470. let loaded = 0;
  26471. function loadTexture( i ) {
  26472. loader.load( url[ i ], function ( buffer ) {
  26473. const texDatas = scope.parse( buffer, true );
  26474. images[ i ] = {
  26475. width: texDatas.width,
  26476. height: texDatas.height,
  26477. format: texDatas.format,
  26478. mipmaps: texDatas.mipmaps
  26479. };
  26480. loaded += 1;
  26481. if ( loaded === 6 ) {
  26482. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  26483. texture.image = images;
  26484. texture.format = texDatas.format;
  26485. texture.needsUpdate = true;
  26486. if ( onLoad ) onLoad( texture );
  26487. }
  26488. }, onProgress, onError );
  26489. }
  26490. if ( Array.isArray( url ) ) {
  26491. for ( let i = 0, il = url.length; i < il; ++ i ) {
  26492. loadTexture( i );
  26493. }
  26494. } else {
  26495. // compressed cubemap texture stored in a single DDS file
  26496. loader.load( url, function ( buffer ) {
  26497. const texDatas = scope.parse( buffer, true );
  26498. if ( texDatas.isCubemap ) {
  26499. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  26500. for ( let f = 0; f < faces; f ++ ) {
  26501. images[ f ] = { mipmaps: [] };
  26502. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  26503. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  26504. images[ f ].format = texDatas.format;
  26505. images[ f ].width = texDatas.width;
  26506. images[ f ].height = texDatas.height;
  26507. }
  26508. }
  26509. texture.image = images;
  26510. } else {
  26511. texture.image.width = texDatas.width;
  26512. texture.image.height = texDatas.height;
  26513. texture.mipmaps = texDatas.mipmaps;
  26514. }
  26515. if ( texDatas.mipmapCount === 1 ) {
  26516. texture.minFilter = LinearFilter;
  26517. }
  26518. texture.format = texDatas.format;
  26519. texture.needsUpdate = true;
  26520. if ( onLoad ) onLoad( texture );
  26521. }, onProgress, onError );
  26522. }
  26523. return texture;
  26524. }
  26525. }
  26526. class ImageLoader extends Loader {
  26527. constructor( manager ) {
  26528. super( manager );
  26529. }
  26530. load( url, onLoad, onProgress, onError ) {
  26531. if ( this.path !== undefined ) url = this.path + url;
  26532. url = this.manager.resolveURL( url );
  26533. const scope = this;
  26534. const cached = Cache.get( url );
  26535. if ( cached !== undefined ) {
  26536. scope.manager.itemStart( url );
  26537. setTimeout( function () {
  26538. if ( onLoad ) onLoad( cached );
  26539. scope.manager.itemEnd( url );
  26540. }, 0 );
  26541. return cached;
  26542. }
  26543. const image = createElementNS( 'img' );
  26544. function onImageLoad() {
  26545. removeEventListeners();
  26546. Cache.add( url, this );
  26547. if ( onLoad ) onLoad( this );
  26548. scope.manager.itemEnd( url );
  26549. }
  26550. function onImageError( event ) {
  26551. removeEventListeners();
  26552. if ( onError ) onError( event );
  26553. scope.manager.itemError( url );
  26554. scope.manager.itemEnd( url );
  26555. }
  26556. function removeEventListeners() {
  26557. image.removeEventListener( 'load', onImageLoad, false );
  26558. image.removeEventListener( 'error', onImageError, false );
  26559. }
  26560. image.addEventListener( 'load', onImageLoad, false );
  26561. image.addEventListener( 'error', onImageError, false );
  26562. if ( url.slice( 0, 5 ) !== 'data:' ) {
  26563. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  26564. }
  26565. scope.manager.itemStart( url );
  26566. image.src = url;
  26567. return image;
  26568. }
  26569. }
  26570. class CubeTextureLoader extends Loader {
  26571. constructor( manager ) {
  26572. super( manager );
  26573. }
  26574. load( urls, onLoad, onProgress, onError ) {
  26575. const texture = new CubeTexture();
  26576. texture.colorSpace = SRGBColorSpace;
  26577. const loader = new ImageLoader( this.manager );
  26578. loader.setCrossOrigin( this.crossOrigin );
  26579. loader.setPath( this.path );
  26580. let loaded = 0;
  26581. function loadTexture( i ) {
  26582. loader.load( urls[ i ], function ( image ) {
  26583. texture.images[ i ] = image;
  26584. loaded ++;
  26585. if ( loaded === 6 ) {
  26586. texture.needsUpdate = true;
  26587. if ( onLoad ) onLoad( texture );
  26588. }
  26589. }, undefined, onError );
  26590. }
  26591. for ( let i = 0; i < urls.length; ++ i ) {
  26592. loadTexture( i );
  26593. }
  26594. return texture;
  26595. }
  26596. }
  26597. /**
  26598. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  26599. *
  26600. * Sub classes have to implement the parse() method which will be used in load().
  26601. */
  26602. class DataTextureLoader extends Loader {
  26603. constructor( manager ) {
  26604. super( manager );
  26605. }
  26606. load( url, onLoad, onProgress, onError ) {
  26607. const scope = this;
  26608. const texture = new DataTexture();
  26609. const loader = new FileLoader( this.manager );
  26610. loader.setResponseType( 'arraybuffer' );
  26611. loader.setRequestHeader( this.requestHeader );
  26612. loader.setPath( this.path );
  26613. loader.setWithCredentials( scope.withCredentials );
  26614. loader.load( url, function ( buffer ) {
  26615. let texData;
  26616. try {
  26617. texData = scope.parse( buffer );
  26618. } catch ( error ) {
  26619. if ( onError !== undefined ) {
  26620. onError( error );
  26621. } else {
  26622. console.error( error );
  26623. return;
  26624. }
  26625. }
  26626. if ( texData.image !== undefined ) {
  26627. texture.image = texData.image;
  26628. } else if ( texData.data !== undefined ) {
  26629. texture.image.width = texData.width;
  26630. texture.image.height = texData.height;
  26631. texture.image.data = texData.data;
  26632. }
  26633. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  26634. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  26635. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  26636. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  26637. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  26638. if ( texData.colorSpace !== undefined ) {
  26639. texture.colorSpace = texData.colorSpace;
  26640. }
  26641. if ( texData.flipY !== undefined ) {
  26642. texture.flipY = texData.flipY;
  26643. }
  26644. if ( texData.format !== undefined ) {
  26645. texture.format = texData.format;
  26646. }
  26647. if ( texData.type !== undefined ) {
  26648. texture.type = texData.type;
  26649. }
  26650. if ( texData.mipmaps !== undefined ) {
  26651. texture.mipmaps = texData.mipmaps;
  26652. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  26653. }
  26654. if ( texData.mipmapCount === 1 ) {
  26655. texture.minFilter = LinearFilter;
  26656. }
  26657. if ( texData.generateMipmaps !== undefined ) {
  26658. texture.generateMipmaps = texData.generateMipmaps;
  26659. }
  26660. texture.needsUpdate = true;
  26661. if ( onLoad ) onLoad( texture, texData );
  26662. }, onProgress, onError );
  26663. return texture;
  26664. }
  26665. }
  26666. class TextureLoader extends Loader {
  26667. constructor( manager ) {
  26668. super( manager );
  26669. }
  26670. load( url, onLoad, onProgress, onError ) {
  26671. const texture = new Texture();
  26672. const loader = new ImageLoader( this.manager );
  26673. loader.setCrossOrigin( this.crossOrigin );
  26674. loader.setPath( this.path );
  26675. loader.load( url, function ( image ) {
  26676. texture.image = image;
  26677. texture.needsUpdate = true;
  26678. if ( onLoad !== undefined ) {
  26679. onLoad( texture );
  26680. }
  26681. }, onProgress, onError );
  26682. return texture;
  26683. }
  26684. }
  26685. class Light extends Object3D {
  26686. constructor( color, intensity = 1 ) {
  26687. super();
  26688. this.isLight = true;
  26689. this.type = 'Light';
  26690. this.color = new Color( color );
  26691. this.intensity = intensity;
  26692. }
  26693. dispose() {
  26694. // Empty here in base class; some subclasses override.
  26695. }
  26696. copy( source, recursive ) {
  26697. super.copy( source, recursive );
  26698. this.color.copy( source.color );
  26699. this.intensity = source.intensity;
  26700. return this;
  26701. }
  26702. toJSON( meta ) {
  26703. const data = super.toJSON( meta );
  26704. data.object.color = this.color.getHex();
  26705. data.object.intensity = this.intensity;
  26706. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  26707. if ( this.distance !== undefined ) data.object.distance = this.distance;
  26708. if ( this.angle !== undefined ) data.object.angle = this.angle;
  26709. if ( this.decay !== undefined ) data.object.decay = this.decay;
  26710. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  26711. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  26712. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  26713. return data;
  26714. }
  26715. }
  26716. class HemisphereLight extends Light {
  26717. constructor( skyColor, groundColor, intensity ) {
  26718. super( skyColor, intensity );
  26719. this.isHemisphereLight = true;
  26720. this.type = 'HemisphereLight';
  26721. this.position.copy( Object3D.DEFAULT_UP );
  26722. this.updateMatrix();
  26723. this.groundColor = new Color( groundColor );
  26724. }
  26725. copy( source, recursive ) {
  26726. super.copy( source, recursive );
  26727. this.groundColor.copy( source.groundColor );
  26728. return this;
  26729. }
  26730. }
  26731. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  26732. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  26733. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  26734. class LightShadow {
  26735. constructor( camera ) {
  26736. this.camera = camera;
  26737. this.intensity = 1;
  26738. this.bias = 0;
  26739. this.normalBias = 0;
  26740. this.radius = 1;
  26741. this.blurSamples = 8;
  26742. this.mapSize = new Vector2( 512, 512 );
  26743. this.map = null;
  26744. this.mapPass = null;
  26745. this.matrix = new Matrix4();
  26746. this.autoUpdate = true;
  26747. this.needsUpdate = false;
  26748. this._frustum = new Frustum();
  26749. this._frameExtents = new Vector2( 1, 1 );
  26750. this._viewportCount = 1;
  26751. this._viewports = [
  26752. new Vector4( 0, 0, 1, 1 )
  26753. ];
  26754. }
  26755. getViewportCount() {
  26756. return this._viewportCount;
  26757. }
  26758. getFrustum() {
  26759. return this._frustum;
  26760. }
  26761. updateMatrices( light ) {
  26762. const shadowCamera = this.camera;
  26763. const shadowMatrix = this.matrix;
  26764. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  26765. shadowCamera.position.copy( _lightPositionWorld$1 );
  26766. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  26767. shadowCamera.lookAt( _lookTarget$1 );
  26768. shadowCamera.updateMatrixWorld();
  26769. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  26770. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  26771. shadowMatrix.set(
  26772. 0.5, 0.0, 0.0, 0.5,
  26773. 0.0, 0.5, 0.0, 0.5,
  26774. 0.0, 0.0, 0.5, 0.5,
  26775. 0.0, 0.0, 0.0, 1.0
  26776. );
  26777. shadowMatrix.multiply( _projScreenMatrix$1 );
  26778. }
  26779. getViewport( viewportIndex ) {
  26780. return this._viewports[ viewportIndex ];
  26781. }
  26782. getFrameExtents() {
  26783. return this._frameExtents;
  26784. }
  26785. dispose() {
  26786. if ( this.map ) {
  26787. this.map.dispose();
  26788. }
  26789. if ( this.mapPass ) {
  26790. this.mapPass.dispose();
  26791. }
  26792. }
  26793. copy( source ) {
  26794. this.camera = source.camera.clone();
  26795. this.intensity = source.intensity;
  26796. this.bias = source.bias;
  26797. this.radius = source.radius;
  26798. this.mapSize.copy( source.mapSize );
  26799. return this;
  26800. }
  26801. clone() {
  26802. return new this.constructor().copy( this );
  26803. }
  26804. toJSON() {
  26805. const object = {};
  26806. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  26807. if ( this.bias !== 0 ) object.bias = this.bias;
  26808. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  26809. if ( this.radius !== 1 ) object.radius = this.radius;
  26810. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  26811. object.camera = this.camera.toJSON( false ).object;
  26812. delete object.camera.matrix;
  26813. return object;
  26814. }
  26815. }
  26816. class SpotLightShadow extends LightShadow {
  26817. constructor() {
  26818. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  26819. this.isSpotLightShadow = true;
  26820. this.focus = 1;
  26821. }
  26822. updateMatrices( light ) {
  26823. const camera = this.camera;
  26824. const fov = RAD2DEG * 2 * light.angle * this.focus;
  26825. const aspect = this.mapSize.width / this.mapSize.height;
  26826. const far = light.distance || camera.far;
  26827. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  26828. camera.fov = fov;
  26829. camera.aspect = aspect;
  26830. camera.far = far;
  26831. camera.updateProjectionMatrix();
  26832. }
  26833. super.updateMatrices( light );
  26834. }
  26835. copy( source ) {
  26836. super.copy( source );
  26837. this.focus = source.focus;
  26838. return this;
  26839. }
  26840. }
  26841. class SpotLight extends Light {
  26842. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  26843. super( color, intensity );
  26844. this.isSpotLight = true;
  26845. this.type = 'SpotLight';
  26846. this.position.copy( Object3D.DEFAULT_UP );
  26847. this.updateMatrix();
  26848. this.target = new Object3D();
  26849. this.distance = distance;
  26850. this.angle = angle;
  26851. this.penumbra = penumbra;
  26852. this.decay = decay;
  26853. this.map = null;
  26854. this.shadow = new SpotLightShadow();
  26855. }
  26856. get power() {
  26857. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26858. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  26859. return this.intensity * Math.PI;
  26860. }
  26861. set power( power ) {
  26862. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26863. this.intensity = power / Math.PI;
  26864. }
  26865. dispose() {
  26866. this.shadow.dispose();
  26867. }
  26868. copy( source, recursive ) {
  26869. super.copy( source, recursive );
  26870. this.distance = source.distance;
  26871. this.angle = source.angle;
  26872. this.penumbra = source.penumbra;
  26873. this.decay = source.decay;
  26874. this.target = source.target.clone();
  26875. this.shadow = source.shadow.clone();
  26876. return this;
  26877. }
  26878. }
  26879. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  26880. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  26881. const _lookTarget = /*@__PURE__*/ new Vector3();
  26882. class PointLightShadow extends LightShadow {
  26883. constructor() {
  26884. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  26885. this.isPointLightShadow = true;
  26886. this._frameExtents = new Vector2( 4, 2 );
  26887. this._viewportCount = 6;
  26888. this._viewports = [
  26889. // These viewports map a cube-map onto a 2D texture with the
  26890. // following orientation:
  26891. //
  26892. // xzXZ
  26893. // y Y
  26894. //
  26895. // X - Positive x direction
  26896. // x - Negative x direction
  26897. // Y - Positive y direction
  26898. // y - Negative y direction
  26899. // Z - Positive z direction
  26900. // z - Negative z direction
  26901. // positive X
  26902. new Vector4( 2, 1, 1, 1 ),
  26903. // negative X
  26904. new Vector4( 0, 1, 1, 1 ),
  26905. // positive Z
  26906. new Vector4( 3, 1, 1, 1 ),
  26907. // negative Z
  26908. new Vector4( 1, 1, 1, 1 ),
  26909. // positive Y
  26910. new Vector4( 3, 0, 1, 1 ),
  26911. // negative Y
  26912. new Vector4( 1, 0, 1, 1 )
  26913. ];
  26914. this._cubeDirections = [
  26915. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  26916. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  26917. ];
  26918. this._cubeUps = [
  26919. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  26920. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  26921. ];
  26922. }
  26923. updateMatrices( light, viewportIndex = 0 ) {
  26924. const camera = this.camera;
  26925. const shadowMatrix = this.matrix;
  26926. const far = light.distance || camera.far;
  26927. if ( far !== camera.far ) {
  26928. camera.far = far;
  26929. camera.updateProjectionMatrix();
  26930. }
  26931. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  26932. camera.position.copy( _lightPositionWorld );
  26933. _lookTarget.copy( camera.position );
  26934. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  26935. camera.up.copy( this._cubeUps[ viewportIndex ] );
  26936. camera.lookAt( _lookTarget );
  26937. camera.updateMatrixWorld();
  26938. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  26939. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  26940. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  26941. }
  26942. }
  26943. class PointLight extends Light {
  26944. constructor( color, intensity, distance = 0, decay = 2 ) {
  26945. super( color, intensity );
  26946. this.isPointLight = true;
  26947. this.type = 'PointLight';
  26948. this.distance = distance;
  26949. this.decay = decay;
  26950. this.shadow = new PointLightShadow();
  26951. }
  26952. get power() {
  26953. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26954. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  26955. return this.intensity * 4 * Math.PI;
  26956. }
  26957. set power( power ) {
  26958. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26959. this.intensity = power / ( 4 * Math.PI );
  26960. }
  26961. dispose() {
  26962. this.shadow.dispose();
  26963. }
  26964. copy( source, recursive ) {
  26965. super.copy( source, recursive );
  26966. this.distance = source.distance;
  26967. this.decay = source.decay;
  26968. this.shadow = source.shadow.clone();
  26969. return this;
  26970. }
  26971. }
  26972. class DirectionalLightShadow extends LightShadow {
  26973. constructor() {
  26974. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  26975. this.isDirectionalLightShadow = true;
  26976. }
  26977. }
  26978. class DirectionalLight extends Light {
  26979. constructor( color, intensity ) {
  26980. super( color, intensity );
  26981. this.isDirectionalLight = true;
  26982. this.type = 'DirectionalLight';
  26983. this.position.copy( Object3D.DEFAULT_UP );
  26984. this.updateMatrix();
  26985. this.target = new Object3D();
  26986. this.shadow = new DirectionalLightShadow();
  26987. }
  26988. dispose() {
  26989. this.shadow.dispose();
  26990. }
  26991. copy( source ) {
  26992. super.copy( source );
  26993. this.target = source.target.clone();
  26994. this.shadow = source.shadow.clone();
  26995. return this;
  26996. }
  26997. }
  26998. class AmbientLight extends Light {
  26999. constructor( color, intensity ) {
  27000. super( color, intensity );
  27001. this.isAmbientLight = true;
  27002. this.type = 'AmbientLight';
  27003. }
  27004. }
  27005. class RectAreaLight extends Light {
  27006. constructor( color, intensity, width = 10, height = 10 ) {
  27007. super( color, intensity );
  27008. this.isRectAreaLight = true;
  27009. this.type = 'RectAreaLight';
  27010. this.width = width;
  27011. this.height = height;
  27012. }
  27013. get power() {
  27014. // compute the light's luminous power (in lumens) from its intensity (in nits)
  27015. return this.intensity * this.width * this.height * Math.PI;
  27016. }
  27017. set power( power ) {
  27018. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  27019. this.intensity = power / ( this.width * this.height * Math.PI );
  27020. }
  27021. copy( source ) {
  27022. super.copy( source );
  27023. this.width = source.width;
  27024. this.height = source.height;
  27025. return this;
  27026. }
  27027. toJSON( meta ) {
  27028. const data = super.toJSON( meta );
  27029. data.object.width = this.width;
  27030. data.object.height = this.height;
  27031. return data;
  27032. }
  27033. }
  27034. /**
  27035. * Primary reference:
  27036. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  27037. *
  27038. * Secondary reference:
  27039. * https://www.ppsloan.org/publications/StupidSH36.pdf
  27040. */
  27041. // 3-band SH defined by 9 coefficients
  27042. class SphericalHarmonics3 {
  27043. constructor() {
  27044. this.isSphericalHarmonics3 = true;
  27045. this.coefficients = [];
  27046. for ( let i = 0; i < 9; i ++ ) {
  27047. this.coefficients.push( new Vector3() );
  27048. }
  27049. }
  27050. set( coefficients ) {
  27051. for ( let i = 0; i < 9; i ++ ) {
  27052. this.coefficients[ i ].copy( coefficients[ i ] );
  27053. }
  27054. return this;
  27055. }
  27056. zero() {
  27057. for ( let i = 0; i < 9; i ++ ) {
  27058. this.coefficients[ i ].set( 0, 0, 0 );
  27059. }
  27060. return this;
  27061. }
  27062. // get the radiance in the direction of the normal
  27063. // target is a Vector3
  27064. getAt( normal, target ) {
  27065. // normal is assumed to be unit length
  27066. const x = normal.x, y = normal.y, z = normal.z;
  27067. const coeff = this.coefficients;
  27068. // band 0
  27069. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  27070. // band 1
  27071. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  27072. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  27073. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  27074. // band 2
  27075. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  27076. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  27077. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  27078. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  27079. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  27080. return target;
  27081. }
  27082. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  27083. // target is a Vector3
  27084. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  27085. getIrradianceAt( normal, target ) {
  27086. // normal is assumed to be unit length
  27087. const x = normal.x, y = normal.y, z = normal.z;
  27088. const coeff = this.coefficients;
  27089. // band 0
  27090. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  27091. // band 1
  27092. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  27093. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  27094. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  27095. // band 2
  27096. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  27097. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  27098. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  27099. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  27100. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  27101. return target;
  27102. }
  27103. add( sh ) {
  27104. for ( let i = 0; i < 9; i ++ ) {
  27105. this.coefficients[ i ].add( sh.coefficients[ i ] );
  27106. }
  27107. return this;
  27108. }
  27109. addScaledSH( sh, s ) {
  27110. for ( let i = 0; i < 9; i ++ ) {
  27111. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  27112. }
  27113. return this;
  27114. }
  27115. scale( s ) {
  27116. for ( let i = 0; i < 9; i ++ ) {
  27117. this.coefficients[ i ].multiplyScalar( s );
  27118. }
  27119. return this;
  27120. }
  27121. lerp( sh, alpha ) {
  27122. for ( let i = 0; i < 9; i ++ ) {
  27123. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  27124. }
  27125. return this;
  27126. }
  27127. equals( sh ) {
  27128. for ( let i = 0; i < 9; i ++ ) {
  27129. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  27130. return false;
  27131. }
  27132. }
  27133. return true;
  27134. }
  27135. copy( sh ) {
  27136. return this.set( sh.coefficients );
  27137. }
  27138. clone() {
  27139. return new this.constructor().copy( this );
  27140. }
  27141. fromArray( array, offset = 0 ) {
  27142. const coefficients = this.coefficients;
  27143. for ( let i = 0; i < 9; i ++ ) {
  27144. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  27145. }
  27146. return this;
  27147. }
  27148. toArray( array = [], offset = 0 ) {
  27149. const coefficients = this.coefficients;
  27150. for ( let i = 0; i < 9; i ++ ) {
  27151. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  27152. }
  27153. return array;
  27154. }
  27155. // evaluate the basis functions
  27156. // shBasis is an Array[ 9 ]
  27157. static getBasisAt( normal, shBasis ) {
  27158. // normal is assumed to be unit length
  27159. const x = normal.x, y = normal.y, z = normal.z;
  27160. // band 0
  27161. shBasis[ 0 ] = 0.282095;
  27162. // band 1
  27163. shBasis[ 1 ] = 0.488603 * y;
  27164. shBasis[ 2 ] = 0.488603 * z;
  27165. shBasis[ 3 ] = 0.488603 * x;
  27166. // band 2
  27167. shBasis[ 4 ] = 1.092548 * x * y;
  27168. shBasis[ 5 ] = 1.092548 * y * z;
  27169. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  27170. shBasis[ 7 ] = 1.092548 * x * z;
  27171. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  27172. }
  27173. }
  27174. class LightProbe extends Light {
  27175. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  27176. super( undefined, intensity );
  27177. this.isLightProbe = true;
  27178. this.sh = sh;
  27179. }
  27180. copy( source ) {
  27181. super.copy( source );
  27182. this.sh.copy( source.sh );
  27183. return this;
  27184. }
  27185. fromJSON( json ) {
  27186. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  27187. this.sh.fromArray( json.sh );
  27188. return this;
  27189. }
  27190. toJSON( meta ) {
  27191. const data = super.toJSON( meta );
  27192. data.object.sh = this.sh.toArray();
  27193. return data;
  27194. }
  27195. }
  27196. class MaterialLoader extends Loader {
  27197. constructor( manager ) {
  27198. super( manager );
  27199. this.textures = {};
  27200. }
  27201. load( url, onLoad, onProgress, onError ) {
  27202. const scope = this;
  27203. const loader = new FileLoader( scope.manager );
  27204. loader.setPath( scope.path );
  27205. loader.setRequestHeader( scope.requestHeader );
  27206. loader.setWithCredentials( scope.withCredentials );
  27207. loader.load( url, function ( text ) {
  27208. try {
  27209. onLoad( scope.parse( JSON.parse( text ) ) );
  27210. } catch ( e ) {
  27211. if ( onError ) {
  27212. onError( e );
  27213. } else {
  27214. console.error( e );
  27215. }
  27216. scope.manager.itemError( url );
  27217. }
  27218. }, onProgress, onError );
  27219. }
  27220. parse( json ) {
  27221. const textures = this.textures;
  27222. function getTexture( name ) {
  27223. if ( textures[ name ] === undefined ) {
  27224. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  27225. }
  27226. return textures[ name ];
  27227. }
  27228. const material = this.createMaterialFromType( json.type );
  27229. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  27230. if ( json.name !== undefined ) material.name = json.name;
  27231. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  27232. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  27233. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  27234. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  27235. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  27236. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  27237. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  27238. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  27239. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  27240. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  27241. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  27242. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  27243. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  27244. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  27245. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  27246. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  27247. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  27248. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  27249. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  27250. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  27251. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  27252. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  27253. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  27254. if ( json.fog !== undefined ) material.fog = json.fog;
  27255. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  27256. if ( json.blending !== undefined ) material.blending = json.blending;
  27257. if ( json.combine !== undefined ) material.combine = json.combine;
  27258. if ( json.side !== undefined ) material.side = json.side;
  27259. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  27260. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  27261. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  27262. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  27263. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  27264. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  27265. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  27266. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  27267. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  27268. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  27269. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  27270. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  27271. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  27272. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  27273. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  27274. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  27275. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  27276. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  27277. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  27278. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  27279. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  27280. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  27281. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  27282. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  27283. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  27284. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  27285. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  27286. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  27287. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  27288. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  27289. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  27290. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  27291. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  27292. if ( json.scale !== undefined ) material.scale = json.scale;
  27293. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  27294. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  27295. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  27296. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  27297. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  27298. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  27299. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  27300. if ( json.visible !== undefined ) material.visible = json.visible;
  27301. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  27302. if ( json.userData !== undefined ) material.userData = json.userData;
  27303. if ( json.vertexColors !== undefined ) {
  27304. if ( typeof json.vertexColors === 'number' ) {
  27305. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  27306. } else {
  27307. material.vertexColors = json.vertexColors;
  27308. }
  27309. }
  27310. // Shader Material
  27311. if ( json.uniforms !== undefined ) {
  27312. for ( const name in json.uniforms ) {
  27313. const uniform = json.uniforms[ name ];
  27314. material.uniforms[ name ] = {};
  27315. switch ( uniform.type ) {
  27316. case 't':
  27317. material.uniforms[ name ].value = getTexture( uniform.value );
  27318. break;
  27319. case 'c':
  27320. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  27321. break;
  27322. case 'v2':
  27323. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  27324. break;
  27325. case 'v3':
  27326. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  27327. break;
  27328. case 'v4':
  27329. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  27330. break;
  27331. case 'm3':
  27332. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  27333. break;
  27334. case 'm4':
  27335. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  27336. break;
  27337. default:
  27338. material.uniforms[ name ].value = uniform.value;
  27339. }
  27340. }
  27341. }
  27342. if ( json.defines !== undefined ) material.defines = json.defines;
  27343. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  27344. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  27345. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  27346. if ( json.extensions !== undefined ) {
  27347. for ( const key in json.extensions ) {
  27348. material.extensions[ key ] = json.extensions[ key ];
  27349. }
  27350. }
  27351. if ( json.lights !== undefined ) material.lights = json.lights;
  27352. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  27353. // for PointsMaterial
  27354. if ( json.size !== undefined ) material.size = json.size;
  27355. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  27356. // maps
  27357. if ( json.map !== undefined ) material.map = getTexture( json.map );
  27358. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  27359. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  27360. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  27361. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  27362. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  27363. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  27364. if ( json.normalScale !== undefined ) {
  27365. let normalScale = json.normalScale;
  27366. if ( Array.isArray( normalScale ) === false ) {
  27367. // Blender exporter used to export a scalar. See #7459
  27368. normalScale = [ normalScale, normalScale ];
  27369. }
  27370. material.normalScale = new Vector2().fromArray( normalScale );
  27371. }
  27372. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  27373. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  27374. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  27375. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  27376. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  27377. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  27378. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  27379. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  27380. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  27381. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  27382. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  27383. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  27384. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  27385. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  27386. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  27387. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  27388. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  27389. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  27390. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  27391. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  27392. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  27393. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  27394. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  27395. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  27396. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  27397. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  27398. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  27399. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  27400. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  27401. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  27402. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  27403. return material;
  27404. }
  27405. setTextures( value ) {
  27406. this.textures = value;
  27407. return this;
  27408. }
  27409. createMaterialFromType( type ) {
  27410. return MaterialLoader.createMaterialFromType( type );
  27411. }
  27412. static createMaterialFromType( type ) {
  27413. const materialLib = {
  27414. ShadowMaterial,
  27415. SpriteMaterial,
  27416. RawShaderMaterial,
  27417. ShaderMaterial,
  27418. PointsMaterial,
  27419. MeshPhysicalMaterial,
  27420. MeshStandardMaterial,
  27421. MeshPhongMaterial,
  27422. MeshToonMaterial,
  27423. MeshNormalMaterial,
  27424. MeshLambertMaterial,
  27425. MeshDepthMaterial,
  27426. MeshDistanceMaterial,
  27427. MeshBasicMaterial,
  27428. MeshMatcapMaterial,
  27429. LineDashedMaterial,
  27430. LineBasicMaterial,
  27431. Material
  27432. };
  27433. return new materialLib[ type ]();
  27434. }
  27435. }
  27436. class LoaderUtils {
  27437. static decodeText( array ) { // @deprecated, r165
  27438. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  27439. if ( typeof TextDecoder !== 'undefined' ) {
  27440. return new TextDecoder().decode( array );
  27441. }
  27442. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  27443. // throws a "maximum call stack size exceeded" error for large arrays.
  27444. let s = '';
  27445. for ( let i = 0, il = array.length; i < il; i ++ ) {
  27446. // Implicitly assumes little-endian.
  27447. s += String.fromCharCode( array[ i ] );
  27448. }
  27449. try {
  27450. // merges multi-byte utf-8 characters.
  27451. return decodeURIComponent( escape( s ) );
  27452. } catch ( e ) { // see #16358
  27453. return s;
  27454. }
  27455. }
  27456. static extractUrlBase( url ) {
  27457. const index = url.lastIndexOf( '/' );
  27458. if ( index === - 1 ) return './';
  27459. return url.slice( 0, index + 1 );
  27460. }
  27461. static resolveURL( url, path ) {
  27462. // Invalid URL
  27463. if ( typeof url !== 'string' || url === '' ) return '';
  27464. // Host Relative URL
  27465. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  27466. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  27467. }
  27468. // Absolute URL http://,https://,//
  27469. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  27470. // Data URI
  27471. if ( /^data:.*,.*$/i.test( url ) ) return url;
  27472. // Blob URL
  27473. if ( /^blob:.*$/i.test( url ) ) return url;
  27474. // Relative URL
  27475. return path + url;
  27476. }
  27477. }
  27478. class InstancedBufferGeometry extends BufferGeometry {
  27479. constructor() {
  27480. super();
  27481. this.isInstancedBufferGeometry = true;
  27482. this.type = 'InstancedBufferGeometry';
  27483. this.instanceCount = Infinity;
  27484. }
  27485. copy( source ) {
  27486. super.copy( source );
  27487. this.instanceCount = source.instanceCount;
  27488. return this;
  27489. }
  27490. toJSON() {
  27491. const data = super.toJSON();
  27492. data.instanceCount = this.instanceCount;
  27493. data.isInstancedBufferGeometry = true;
  27494. return data;
  27495. }
  27496. }
  27497. class BufferGeometryLoader extends Loader {
  27498. constructor( manager ) {
  27499. super( manager );
  27500. }
  27501. load( url, onLoad, onProgress, onError ) {
  27502. const scope = this;
  27503. const loader = new FileLoader( scope.manager );
  27504. loader.setPath( scope.path );
  27505. loader.setRequestHeader( scope.requestHeader );
  27506. loader.setWithCredentials( scope.withCredentials );
  27507. loader.load( url, function ( text ) {
  27508. try {
  27509. onLoad( scope.parse( JSON.parse( text ) ) );
  27510. } catch ( e ) {
  27511. if ( onError ) {
  27512. onError( e );
  27513. } else {
  27514. console.error( e );
  27515. }
  27516. scope.manager.itemError( url );
  27517. }
  27518. }, onProgress, onError );
  27519. }
  27520. parse( json ) {
  27521. const interleavedBufferMap = {};
  27522. const arrayBufferMap = {};
  27523. function getInterleavedBuffer( json, uuid ) {
  27524. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  27525. const interleavedBuffers = json.interleavedBuffers;
  27526. const interleavedBuffer = interleavedBuffers[ uuid ];
  27527. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  27528. const array = getTypedArray( interleavedBuffer.type, buffer );
  27529. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  27530. ib.uuid = interleavedBuffer.uuid;
  27531. interleavedBufferMap[ uuid ] = ib;
  27532. return ib;
  27533. }
  27534. function getArrayBuffer( json, uuid ) {
  27535. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  27536. const arrayBuffers = json.arrayBuffers;
  27537. const arrayBuffer = arrayBuffers[ uuid ];
  27538. const ab = new Uint32Array( arrayBuffer ).buffer;
  27539. arrayBufferMap[ uuid ] = ab;
  27540. return ab;
  27541. }
  27542. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  27543. const index = json.data.index;
  27544. if ( index !== undefined ) {
  27545. const typedArray = getTypedArray( index.type, index.array );
  27546. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  27547. }
  27548. const attributes = json.data.attributes;
  27549. for ( const key in attributes ) {
  27550. const attribute = attributes[ key ];
  27551. let bufferAttribute;
  27552. if ( attribute.isInterleavedBufferAttribute ) {
  27553. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27554. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27555. } else {
  27556. const typedArray = getTypedArray( attribute.type, attribute.array );
  27557. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  27558. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  27559. }
  27560. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27561. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  27562. geometry.setAttribute( key, bufferAttribute );
  27563. }
  27564. const morphAttributes = json.data.morphAttributes;
  27565. if ( morphAttributes ) {
  27566. for ( const key in morphAttributes ) {
  27567. const attributeArray = morphAttributes[ key ];
  27568. const array = [];
  27569. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  27570. const attribute = attributeArray[ i ];
  27571. let bufferAttribute;
  27572. if ( attribute.isInterleavedBufferAttribute ) {
  27573. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27574. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27575. } else {
  27576. const typedArray = getTypedArray( attribute.type, attribute.array );
  27577. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  27578. }
  27579. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27580. array.push( bufferAttribute );
  27581. }
  27582. geometry.morphAttributes[ key ] = array;
  27583. }
  27584. }
  27585. const morphTargetsRelative = json.data.morphTargetsRelative;
  27586. if ( morphTargetsRelative ) {
  27587. geometry.morphTargetsRelative = true;
  27588. }
  27589. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  27590. if ( groups !== undefined ) {
  27591. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  27592. const group = groups[ i ];
  27593. geometry.addGroup( group.start, group.count, group.materialIndex );
  27594. }
  27595. }
  27596. const boundingSphere = json.data.boundingSphere;
  27597. if ( boundingSphere !== undefined ) {
  27598. const center = new Vector3();
  27599. if ( boundingSphere.center !== undefined ) {
  27600. center.fromArray( boundingSphere.center );
  27601. }
  27602. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  27603. }
  27604. if ( json.name ) geometry.name = json.name;
  27605. if ( json.userData ) geometry.userData = json.userData;
  27606. return geometry;
  27607. }
  27608. }
  27609. class ObjectLoader extends Loader {
  27610. constructor( manager ) {
  27611. super( manager );
  27612. }
  27613. load( url, onLoad, onProgress, onError ) {
  27614. const scope = this;
  27615. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27616. this.resourcePath = this.resourcePath || path;
  27617. const loader = new FileLoader( this.manager );
  27618. loader.setPath( this.path );
  27619. loader.setRequestHeader( this.requestHeader );
  27620. loader.setWithCredentials( this.withCredentials );
  27621. loader.load( url, function ( text ) {
  27622. let json = null;
  27623. try {
  27624. json = JSON.parse( text );
  27625. } catch ( error ) {
  27626. if ( onError !== undefined ) onError( error );
  27627. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  27628. return;
  27629. }
  27630. const metadata = json.metadata;
  27631. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27632. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  27633. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27634. return;
  27635. }
  27636. scope.parse( json, onLoad );
  27637. }, onProgress, onError );
  27638. }
  27639. async loadAsync( url, onProgress ) {
  27640. const scope = this;
  27641. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27642. this.resourcePath = this.resourcePath || path;
  27643. const loader = new FileLoader( this.manager );
  27644. loader.setPath( this.path );
  27645. loader.setRequestHeader( this.requestHeader );
  27646. loader.setWithCredentials( this.withCredentials );
  27647. const text = await loader.loadAsync( url, onProgress );
  27648. const json = JSON.parse( text );
  27649. const metadata = json.metadata;
  27650. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27651. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27652. }
  27653. return await scope.parseAsync( json );
  27654. }
  27655. parse( json, onLoad ) {
  27656. const animations = this.parseAnimations( json.animations );
  27657. const shapes = this.parseShapes( json.shapes );
  27658. const geometries = this.parseGeometries( json.geometries, shapes );
  27659. const images = this.parseImages( json.images, function () {
  27660. if ( onLoad !== undefined ) onLoad( object );
  27661. } );
  27662. const textures = this.parseTextures( json.textures, images );
  27663. const materials = this.parseMaterials( json.materials, textures );
  27664. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27665. const skeletons = this.parseSkeletons( json.skeletons, object );
  27666. this.bindSkeletons( object, skeletons );
  27667. this.bindLightTargets( object );
  27668. //
  27669. if ( onLoad !== undefined ) {
  27670. let hasImages = false;
  27671. for ( const uuid in images ) {
  27672. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  27673. hasImages = true;
  27674. break;
  27675. }
  27676. }
  27677. if ( hasImages === false ) onLoad( object );
  27678. }
  27679. return object;
  27680. }
  27681. async parseAsync( json ) {
  27682. const animations = this.parseAnimations( json.animations );
  27683. const shapes = this.parseShapes( json.shapes );
  27684. const geometries = this.parseGeometries( json.geometries, shapes );
  27685. const images = await this.parseImagesAsync( json.images );
  27686. const textures = this.parseTextures( json.textures, images );
  27687. const materials = this.parseMaterials( json.materials, textures );
  27688. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27689. const skeletons = this.parseSkeletons( json.skeletons, object );
  27690. this.bindSkeletons( object, skeletons );
  27691. this.bindLightTargets( object );
  27692. return object;
  27693. }
  27694. parseShapes( json ) {
  27695. const shapes = {};
  27696. if ( json !== undefined ) {
  27697. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27698. const shape = new Shape().fromJSON( json[ i ] );
  27699. shapes[ shape.uuid ] = shape;
  27700. }
  27701. }
  27702. return shapes;
  27703. }
  27704. parseSkeletons( json, object ) {
  27705. const skeletons = {};
  27706. const bones = {};
  27707. // generate bone lookup table
  27708. object.traverse( function ( child ) {
  27709. if ( child.isBone ) bones[ child.uuid ] = child;
  27710. } );
  27711. // create skeletons
  27712. if ( json !== undefined ) {
  27713. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27714. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  27715. skeletons[ skeleton.uuid ] = skeleton;
  27716. }
  27717. }
  27718. return skeletons;
  27719. }
  27720. parseGeometries( json, shapes ) {
  27721. const geometries = {};
  27722. if ( json !== undefined ) {
  27723. const bufferGeometryLoader = new BufferGeometryLoader();
  27724. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27725. let geometry;
  27726. const data = json[ i ];
  27727. switch ( data.type ) {
  27728. case 'BufferGeometry':
  27729. case 'InstancedBufferGeometry':
  27730. geometry = bufferGeometryLoader.parse( data );
  27731. break;
  27732. default:
  27733. if ( data.type in Geometries ) {
  27734. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  27735. } else {
  27736. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  27737. }
  27738. }
  27739. geometry.uuid = data.uuid;
  27740. if ( data.name !== undefined ) geometry.name = data.name;
  27741. if ( data.userData !== undefined ) geometry.userData = data.userData;
  27742. geometries[ data.uuid ] = geometry;
  27743. }
  27744. }
  27745. return geometries;
  27746. }
  27747. parseMaterials( json, textures ) {
  27748. const cache = {}; // MultiMaterial
  27749. const materials = {};
  27750. if ( json !== undefined ) {
  27751. const loader = new MaterialLoader();
  27752. loader.setTextures( textures );
  27753. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27754. const data = json[ i ];
  27755. if ( cache[ data.uuid ] === undefined ) {
  27756. cache[ data.uuid ] = loader.parse( data );
  27757. }
  27758. materials[ data.uuid ] = cache[ data.uuid ];
  27759. }
  27760. }
  27761. return materials;
  27762. }
  27763. parseAnimations( json ) {
  27764. const animations = {};
  27765. if ( json !== undefined ) {
  27766. for ( let i = 0; i < json.length; i ++ ) {
  27767. const data = json[ i ];
  27768. const clip = AnimationClip.parse( data );
  27769. animations[ clip.uuid ] = clip;
  27770. }
  27771. }
  27772. return animations;
  27773. }
  27774. parseImages( json, onLoad ) {
  27775. const scope = this;
  27776. const images = {};
  27777. let loader;
  27778. function loadImage( url ) {
  27779. scope.manager.itemStart( url );
  27780. return loader.load( url, function () {
  27781. scope.manager.itemEnd( url );
  27782. }, undefined, function () {
  27783. scope.manager.itemError( url );
  27784. scope.manager.itemEnd( url );
  27785. } );
  27786. }
  27787. function deserializeImage( image ) {
  27788. if ( typeof image === 'string' ) {
  27789. const url = image;
  27790. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27791. return loadImage( path );
  27792. } else {
  27793. if ( image.data ) {
  27794. return {
  27795. data: getTypedArray( image.type, image.data ),
  27796. width: image.width,
  27797. height: image.height
  27798. };
  27799. } else {
  27800. return null;
  27801. }
  27802. }
  27803. }
  27804. if ( json !== undefined && json.length > 0 ) {
  27805. const manager = new LoadingManager( onLoad );
  27806. loader = new ImageLoader( manager );
  27807. loader.setCrossOrigin( this.crossOrigin );
  27808. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27809. const image = json[ i ];
  27810. const url = image.url;
  27811. if ( Array.isArray( url ) ) {
  27812. // load array of images e.g CubeTexture
  27813. const imageArray = [];
  27814. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27815. const currentUrl = url[ j ];
  27816. const deserializedImage = deserializeImage( currentUrl );
  27817. if ( deserializedImage !== null ) {
  27818. if ( deserializedImage instanceof HTMLImageElement ) {
  27819. imageArray.push( deserializedImage );
  27820. } else {
  27821. // special case: handle array of data textures for cube textures
  27822. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27823. }
  27824. }
  27825. }
  27826. images[ image.uuid ] = new Source( imageArray );
  27827. } else {
  27828. // load single image
  27829. const deserializedImage = deserializeImage( image.url );
  27830. images[ image.uuid ] = new Source( deserializedImage );
  27831. }
  27832. }
  27833. }
  27834. return images;
  27835. }
  27836. async parseImagesAsync( json ) {
  27837. const scope = this;
  27838. const images = {};
  27839. let loader;
  27840. async function deserializeImage( image ) {
  27841. if ( typeof image === 'string' ) {
  27842. const url = image;
  27843. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27844. return await loader.loadAsync( path );
  27845. } else {
  27846. if ( image.data ) {
  27847. return {
  27848. data: getTypedArray( image.type, image.data ),
  27849. width: image.width,
  27850. height: image.height
  27851. };
  27852. } else {
  27853. return null;
  27854. }
  27855. }
  27856. }
  27857. if ( json !== undefined && json.length > 0 ) {
  27858. loader = new ImageLoader( this.manager );
  27859. loader.setCrossOrigin( this.crossOrigin );
  27860. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27861. const image = json[ i ];
  27862. const url = image.url;
  27863. if ( Array.isArray( url ) ) {
  27864. // load array of images e.g CubeTexture
  27865. const imageArray = [];
  27866. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27867. const currentUrl = url[ j ];
  27868. const deserializedImage = await deserializeImage( currentUrl );
  27869. if ( deserializedImage !== null ) {
  27870. if ( deserializedImage instanceof HTMLImageElement ) {
  27871. imageArray.push( deserializedImage );
  27872. } else {
  27873. // special case: handle array of data textures for cube textures
  27874. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27875. }
  27876. }
  27877. }
  27878. images[ image.uuid ] = new Source( imageArray );
  27879. } else {
  27880. // load single image
  27881. const deserializedImage = await deserializeImage( image.url );
  27882. images[ image.uuid ] = new Source( deserializedImage );
  27883. }
  27884. }
  27885. }
  27886. return images;
  27887. }
  27888. parseTextures( json, images ) {
  27889. function parseConstant( value, type ) {
  27890. if ( typeof value === 'number' ) return value;
  27891. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27892. return type[ value ];
  27893. }
  27894. const textures = {};
  27895. if ( json !== undefined ) {
  27896. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27897. const data = json[ i ];
  27898. if ( data.image === undefined ) {
  27899. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27900. }
  27901. if ( images[ data.image ] === undefined ) {
  27902. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27903. }
  27904. const source = images[ data.image ];
  27905. const image = source.data;
  27906. let texture;
  27907. if ( Array.isArray( image ) ) {
  27908. texture = new CubeTexture();
  27909. if ( image.length === 6 ) texture.needsUpdate = true;
  27910. } else {
  27911. if ( image && image.data ) {
  27912. texture = new DataTexture();
  27913. } else {
  27914. texture = new Texture();
  27915. }
  27916. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  27917. }
  27918. texture.source = source;
  27919. texture.uuid = data.uuid;
  27920. if ( data.name !== undefined ) texture.name = data.name;
  27921. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27922. if ( data.channel !== undefined ) texture.channel = data.channel;
  27923. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27924. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27925. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27926. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27927. if ( data.wrap !== undefined ) {
  27928. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27929. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27930. }
  27931. if ( data.format !== undefined ) texture.format = data.format;
  27932. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  27933. if ( data.type !== undefined ) texture.type = data.type;
  27934. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  27935. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27936. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27937. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27938. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27939. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  27940. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27941. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27942. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  27943. if ( data.userData !== undefined ) texture.userData = data.userData;
  27944. textures[ data.uuid ] = texture;
  27945. }
  27946. }
  27947. return textures;
  27948. }
  27949. parseObject( data, geometries, materials, textures, animations ) {
  27950. let object;
  27951. function getGeometry( name ) {
  27952. if ( geometries[ name ] === undefined ) {
  27953. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27954. }
  27955. return geometries[ name ];
  27956. }
  27957. function getMaterial( name ) {
  27958. if ( name === undefined ) return undefined;
  27959. if ( Array.isArray( name ) ) {
  27960. const array = [];
  27961. for ( let i = 0, l = name.length; i < l; i ++ ) {
  27962. const uuid = name[ i ];
  27963. if ( materials[ uuid ] === undefined ) {
  27964. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27965. }
  27966. array.push( materials[ uuid ] );
  27967. }
  27968. return array;
  27969. }
  27970. if ( materials[ name ] === undefined ) {
  27971. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27972. }
  27973. return materials[ name ];
  27974. }
  27975. function getTexture( uuid ) {
  27976. if ( textures[ uuid ] === undefined ) {
  27977. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  27978. }
  27979. return textures[ uuid ];
  27980. }
  27981. let geometry, material;
  27982. switch ( data.type ) {
  27983. case 'Scene':
  27984. object = new Scene();
  27985. if ( data.background !== undefined ) {
  27986. if ( Number.isInteger( data.background ) ) {
  27987. object.background = new Color( data.background );
  27988. } else {
  27989. object.background = getTexture( data.background );
  27990. }
  27991. }
  27992. if ( data.environment !== undefined ) {
  27993. object.environment = getTexture( data.environment );
  27994. }
  27995. if ( data.fog !== undefined ) {
  27996. if ( data.fog.type === 'Fog' ) {
  27997. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27998. } else if ( data.fog.type === 'FogExp2' ) {
  27999. object.fog = new FogExp2( data.fog.color, data.fog.density );
  28000. }
  28001. if ( data.fog.name !== '' ) {
  28002. object.fog.name = data.fog.name;
  28003. }
  28004. }
  28005. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  28006. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  28007. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  28008. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  28009. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  28010. break;
  28011. case 'PerspectiveCamera':
  28012. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  28013. if ( data.focus !== undefined ) object.focus = data.focus;
  28014. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  28015. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  28016. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  28017. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  28018. break;
  28019. case 'OrthographicCamera':
  28020. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  28021. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  28022. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  28023. break;
  28024. case 'AmbientLight':
  28025. object = new AmbientLight( data.color, data.intensity );
  28026. break;
  28027. case 'DirectionalLight':
  28028. object = new DirectionalLight( data.color, data.intensity );
  28029. object.target = data.target || '';
  28030. break;
  28031. case 'PointLight':
  28032. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  28033. break;
  28034. case 'RectAreaLight':
  28035. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  28036. break;
  28037. case 'SpotLight':
  28038. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  28039. object.target = data.target || '';
  28040. break;
  28041. case 'HemisphereLight':
  28042. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  28043. break;
  28044. case 'LightProbe':
  28045. object = new LightProbe().fromJSON( data );
  28046. break;
  28047. case 'SkinnedMesh':
  28048. geometry = getGeometry( data.geometry );
  28049. material = getMaterial( data.material );
  28050. object = new SkinnedMesh( geometry, material );
  28051. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  28052. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  28053. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  28054. break;
  28055. case 'Mesh':
  28056. geometry = getGeometry( data.geometry );
  28057. material = getMaterial( data.material );
  28058. object = new Mesh( geometry, material );
  28059. break;
  28060. case 'InstancedMesh':
  28061. geometry = getGeometry( data.geometry );
  28062. material = getMaterial( data.material );
  28063. const count = data.count;
  28064. const instanceMatrix = data.instanceMatrix;
  28065. const instanceColor = data.instanceColor;
  28066. object = new InstancedMesh( geometry, material, count );
  28067. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  28068. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  28069. break;
  28070. case 'BatchedMesh':
  28071. geometry = getGeometry( data.geometry );
  28072. material = getMaterial( data.material );
  28073. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  28074. object.geometry = geometry;
  28075. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  28076. object.sortObjects = data.sortObjects;
  28077. object._drawRanges = data.drawRanges;
  28078. object._reservedRanges = data.reservedRanges;
  28079. object._visibility = data.visibility;
  28080. object._active = data.active;
  28081. object._bounds = data.bounds.map( bound => {
  28082. const box = new Box3();
  28083. box.min.fromArray( bound.boxMin );
  28084. box.max.fromArray( bound.boxMax );
  28085. const sphere = new Sphere();
  28086. sphere.radius = bound.sphereRadius;
  28087. sphere.center.fromArray( bound.sphereCenter );
  28088. return {
  28089. boxInitialized: bound.boxInitialized,
  28090. box: box,
  28091. sphereInitialized: bound.sphereInitialized,
  28092. sphere: sphere
  28093. };
  28094. } );
  28095. object._maxInstanceCount = data.maxInstanceCount;
  28096. object._maxVertexCount = data.maxVertexCount;
  28097. object._maxIndexCount = data.maxIndexCount;
  28098. object._geometryInitialized = data.geometryInitialized;
  28099. object._geometryCount = data.geometryCount;
  28100. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  28101. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  28102. break;
  28103. case 'LOD':
  28104. object = new LOD();
  28105. break;
  28106. case 'Line':
  28107. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  28108. break;
  28109. case 'LineLoop':
  28110. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  28111. break;
  28112. case 'LineSegments':
  28113. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  28114. break;
  28115. case 'PointCloud':
  28116. case 'Points':
  28117. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  28118. break;
  28119. case 'Sprite':
  28120. object = new Sprite( getMaterial( data.material ) );
  28121. break;
  28122. case 'Group':
  28123. object = new Group();
  28124. break;
  28125. case 'Bone':
  28126. object = new Bone();
  28127. break;
  28128. default:
  28129. object = new Object3D();
  28130. }
  28131. object.uuid = data.uuid;
  28132. if ( data.name !== undefined ) object.name = data.name;
  28133. if ( data.matrix !== undefined ) {
  28134. object.matrix.fromArray( data.matrix );
  28135. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  28136. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  28137. } else {
  28138. if ( data.position !== undefined ) object.position.fromArray( data.position );
  28139. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  28140. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  28141. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  28142. }
  28143. if ( data.up !== undefined ) object.up.fromArray( data.up );
  28144. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  28145. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  28146. if ( data.shadow ) {
  28147. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  28148. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  28149. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  28150. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  28151. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  28152. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  28153. }
  28154. if ( data.visible !== undefined ) object.visible = data.visible;
  28155. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  28156. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  28157. if ( data.userData !== undefined ) object.userData = data.userData;
  28158. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  28159. if ( data.children !== undefined ) {
  28160. const children = data.children;
  28161. for ( let i = 0; i < children.length; i ++ ) {
  28162. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  28163. }
  28164. }
  28165. if ( data.animations !== undefined ) {
  28166. const objectAnimations = data.animations;
  28167. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  28168. const uuid = objectAnimations[ i ];
  28169. object.animations.push( animations[ uuid ] );
  28170. }
  28171. }
  28172. if ( data.type === 'LOD' ) {
  28173. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  28174. const levels = data.levels;
  28175. for ( let l = 0; l < levels.length; l ++ ) {
  28176. const level = levels[ l ];
  28177. const child = object.getObjectByProperty( 'uuid', level.object );
  28178. if ( child !== undefined ) {
  28179. object.addLevel( child, level.distance, level.hysteresis );
  28180. }
  28181. }
  28182. }
  28183. return object;
  28184. }
  28185. bindSkeletons( object, skeletons ) {
  28186. if ( Object.keys( skeletons ).length === 0 ) return;
  28187. object.traverse( function ( child ) {
  28188. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  28189. const skeleton = skeletons[ child.skeleton ];
  28190. if ( skeleton === undefined ) {
  28191. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  28192. } else {
  28193. child.bind( skeleton, child.bindMatrix );
  28194. }
  28195. }
  28196. } );
  28197. }
  28198. bindLightTargets( object ) {
  28199. object.traverse( function ( child ) {
  28200. if ( child.isDirectionalLight || child.isSpotLight ) {
  28201. const uuid = child.target;
  28202. const target = object.getObjectByProperty( 'uuid', uuid );
  28203. if ( target !== undefined ) {
  28204. child.target = target;
  28205. } else {
  28206. child.target = new Object3D();
  28207. }
  28208. }
  28209. } );
  28210. }
  28211. }
  28212. const TEXTURE_MAPPING = {
  28213. UVMapping: UVMapping,
  28214. CubeReflectionMapping: CubeReflectionMapping,
  28215. CubeRefractionMapping: CubeRefractionMapping,
  28216. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  28217. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  28218. CubeUVReflectionMapping: CubeUVReflectionMapping
  28219. };
  28220. const TEXTURE_WRAPPING = {
  28221. RepeatWrapping: RepeatWrapping,
  28222. ClampToEdgeWrapping: ClampToEdgeWrapping,
  28223. MirroredRepeatWrapping: MirroredRepeatWrapping
  28224. };
  28225. const TEXTURE_FILTER = {
  28226. NearestFilter: NearestFilter,
  28227. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  28228. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  28229. LinearFilter: LinearFilter,
  28230. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  28231. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  28232. };
  28233. class ImageBitmapLoader extends Loader {
  28234. constructor( manager ) {
  28235. super( manager );
  28236. this.isImageBitmapLoader = true;
  28237. if ( typeof createImageBitmap === 'undefined' ) {
  28238. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  28239. }
  28240. if ( typeof fetch === 'undefined' ) {
  28241. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  28242. }
  28243. this.options = { premultiplyAlpha: 'none' };
  28244. }
  28245. setOptions( options ) {
  28246. this.options = options;
  28247. return this;
  28248. }
  28249. load( url, onLoad, onProgress, onError ) {
  28250. if ( url === undefined ) url = '';
  28251. if ( this.path !== undefined ) url = this.path + url;
  28252. url = this.manager.resolveURL( url );
  28253. const scope = this;
  28254. const cached = Cache.get( url );
  28255. if ( cached !== undefined ) {
  28256. scope.manager.itemStart( url );
  28257. // If cached is a promise, wait for it to resolve
  28258. if ( cached.then ) {
  28259. cached.then( imageBitmap => {
  28260. if ( onLoad ) onLoad( imageBitmap );
  28261. scope.manager.itemEnd( url );
  28262. } ).catch( e => {
  28263. if ( onError ) onError( e );
  28264. } );
  28265. return;
  28266. }
  28267. // If cached is not a promise (i.e., it's already an imageBitmap)
  28268. setTimeout( function () {
  28269. if ( onLoad ) onLoad( cached );
  28270. scope.manager.itemEnd( url );
  28271. }, 0 );
  28272. return cached;
  28273. }
  28274. const fetchOptions = {};
  28275. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  28276. fetchOptions.headers = this.requestHeader;
  28277. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  28278. return res.blob();
  28279. } ).then( function ( blob ) {
  28280. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  28281. } ).then( function ( imageBitmap ) {
  28282. Cache.add( url, imageBitmap );
  28283. if ( onLoad ) onLoad( imageBitmap );
  28284. scope.manager.itemEnd( url );
  28285. return imageBitmap;
  28286. } ).catch( function ( e ) {
  28287. if ( onError ) onError( e );
  28288. Cache.remove( url );
  28289. scope.manager.itemError( url );
  28290. scope.manager.itemEnd( url );
  28291. } );
  28292. Cache.add( url, promise );
  28293. scope.manager.itemStart( url );
  28294. }
  28295. }
  28296. let _context;
  28297. class AudioContext {
  28298. static getContext() {
  28299. if ( _context === undefined ) {
  28300. _context = new ( window.AudioContext || window.webkitAudioContext )();
  28301. }
  28302. return _context;
  28303. }
  28304. static setContext( value ) {
  28305. _context = value;
  28306. }
  28307. }
  28308. class AudioLoader extends Loader {
  28309. constructor( manager ) {
  28310. super( manager );
  28311. }
  28312. load( url, onLoad, onProgress, onError ) {
  28313. const scope = this;
  28314. const loader = new FileLoader( this.manager );
  28315. loader.setResponseType( 'arraybuffer' );
  28316. loader.setPath( this.path );
  28317. loader.setRequestHeader( this.requestHeader );
  28318. loader.setWithCredentials( this.withCredentials );
  28319. loader.load( url, function ( buffer ) {
  28320. try {
  28321. // Create a copy of the buffer. The `decodeAudioData` method
  28322. // detaches the buffer when complete, preventing reuse.
  28323. const bufferCopy = buffer.slice( 0 );
  28324. const context = AudioContext.getContext();
  28325. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  28326. onLoad( audioBuffer );
  28327. } ).catch( handleError );
  28328. } catch ( e ) {
  28329. handleError( e );
  28330. }
  28331. }, onProgress, onError );
  28332. function handleError( e ) {
  28333. if ( onError ) {
  28334. onError( e );
  28335. } else {
  28336. console.error( e );
  28337. }
  28338. scope.manager.itemError( url );
  28339. }
  28340. }
  28341. }
  28342. const _eyeRight = /*@__PURE__*/ new Matrix4();
  28343. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  28344. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  28345. class StereoCamera {
  28346. constructor() {
  28347. this.type = 'StereoCamera';
  28348. this.aspect = 1;
  28349. this.eyeSep = 0.064;
  28350. this.cameraL = new PerspectiveCamera();
  28351. this.cameraL.layers.enable( 1 );
  28352. this.cameraL.matrixAutoUpdate = false;
  28353. this.cameraR = new PerspectiveCamera();
  28354. this.cameraR.layers.enable( 2 );
  28355. this.cameraR.matrixAutoUpdate = false;
  28356. this._cache = {
  28357. focus: null,
  28358. fov: null,
  28359. aspect: null,
  28360. near: null,
  28361. far: null,
  28362. zoom: null,
  28363. eyeSep: null
  28364. };
  28365. }
  28366. update( camera ) {
  28367. const cache = this._cache;
  28368. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  28369. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  28370. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  28371. if ( needsUpdate ) {
  28372. cache.focus = camera.focus;
  28373. cache.fov = camera.fov;
  28374. cache.aspect = camera.aspect * this.aspect;
  28375. cache.near = camera.near;
  28376. cache.far = camera.far;
  28377. cache.zoom = camera.zoom;
  28378. cache.eyeSep = this.eyeSep;
  28379. // Off-axis stereoscopic effect based on
  28380. // http://paulbourke.net/stereographics/stereorender/
  28381. _projectionMatrix.copy( camera.projectionMatrix );
  28382. const eyeSepHalf = cache.eyeSep / 2;
  28383. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  28384. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  28385. let xmin, xmax;
  28386. // translate xOffset
  28387. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  28388. _eyeRight.elements[ 12 ] = eyeSepHalf;
  28389. // for left eye
  28390. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  28391. xmax = ymax * cache.aspect + eyeSepOnProjection;
  28392. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  28393. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28394. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  28395. // for right eye
  28396. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  28397. xmax = ymax * cache.aspect - eyeSepOnProjection;
  28398. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  28399. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28400. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  28401. }
  28402. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  28403. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  28404. }
  28405. }
  28406. class Clock {
  28407. constructor( autoStart = true ) {
  28408. this.autoStart = autoStart;
  28409. this.startTime = 0;
  28410. this.oldTime = 0;
  28411. this.elapsedTime = 0;
  28412. this.running = false;
  28413. }
  28414. start() {
  28415. this.startTime = now();
  28416. this.oldTime = this.startTime;
  28417. this.elapsedTime = 0;
  28418. this.running = true;
  28419. }
  28420. stop() {
  28421. this.getElapsedTime();
  28422. this.running = false;
  28423. this.autoStart = false;
  28424. }
  28425. getElapsedTime() {
  28426. this.getDelta();
  28427. return this.elapsedTime;
  28428. }
  28429. getDelta() {
  28430. let diff = 0;
  28431. if ( this.autoStart && ! this.running ) {
  28432. this.start();
  28433. return 0;
  28434. }
  28435. if ( this.running ) {
  28436. const newTime = now();
  28437. diff = ( newTime - this.oldTime ) / 1000;
  28438. this.oldTime = newTime;
  28439. this.elapsedTime += diff;
  28440. }
  28441. return diff;
  28442. }
  28443. }
  28444. function now() {
  28445. return performance.now();
  28446. }
  28447. const _position$1 = /*@__PURE__*/ new Vector3();
  28448. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  28449. const _scale$1 = /*@__PURE__*/ new Vector3();
  28450. const _orientation$1 = /*@__PURE__*/ new Vector3();
  28451. class AudioListener extends Object3D {
  28452. constructor() {
  28453. super();
  28454. this.type = 'AudioListener';
  28455. this.context = AudioContext.getContext();
  28456. this.gain = this.context.createGain();
  28457. this.gain.connect( this.context.destination );
  28458. this.filter = null;
  28459. this.timeDelta = 0;
  28460. // private
  28461. this._clock = new Clock();
  28462. }
  28463. getInput() {
  28464. return this.gain;
  28465. }
  28466. removeFilter() {
  28467. if ( this.filter !== null ) {
  28468. this.gain.disconnect( this.filter );
  28469. this.filter.disconnect( this.context.destination );
  28470. this.gain.connect( this.context.destination );
  28471. this.filter = null;
  28472. }
  28473. return this;
  28474. }
  28475. getFilter() {
  28476. return this.filter;
  28477. }
  28478. setFilter( value ) {
  28479. if ( this.filter !== null ) {
  28480. this.gain.disconnect( this.filter );
  28481. this.filter.disconnect( this.context.destination );
  28482. } else {
  28483. this.gain.disconnect( this.context.destination );
  28484. }
  28485. this.filter = value;
  28486. this.gain.connect( this.filter );
  28487. this.filter.connect( this.context.destination );
  28488. return this;
  28489. }
  28490. getMasterVolume() {
  28491. return this.gain.gain.value;
  28492. }
  28493. setMasterVolume( value ) {
  28494. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28495. return this;
  28496. }
  28497. updateMatrixWorld( force ) {
  28498. super.updateMatrixWorld( force );
  28499. const listener = this.context.listener;
  28500. const up = this.up;
  28501. this.timeDelta = this._clock.getDelta();
  28502. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  28503. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  28504. if ( listener.positionX ) {
  28505. // code path for Chrome (see #14393)
  28506. const endTime = this.context.currentTime + this.timeDelta;
  28507. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  28508. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  28509. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  28510. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  28511. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  28512. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  28513. listener.upX.linearRampToValueAtTime( up.x, endTime );
  28514. listener.upY.linearRampToValueAtTime( up.y, endTime );
  28515. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  28516. } else {
  28517. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  28518. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  28519. }
  28520. }
  28521. }
  28522. class Audio extends Object3D {
  28523. constructor( listener ) {
  28524. super();
  28525. this.type = 'Audio';
  28526. this.listener = listener;
  28527. this.context = listener.context;
  28528. this.gain = this.context.createGain();
  28529. this.gain.connect( listener.getInput() );
  28530. this.autoplay = false;
  28531. this.buffer = null;
  28532. this.detune = 0;
  28533. this.loop = false;
  28534. this.loopStart = 0;
  28535. this.loopEnd = 0;
  28536. this.offset = 0;
  28537. this.duration = undefined;
  28538. this.playbackRate = 1;
  28539. this.isPlaying = false;
  28540. this.hasPlaybackControl = true;
  28541. this.source = null;
  28542. this.sourceType = 'empty';
  28543. this._startedAt = 0;
  28544. this._progress = 0;
  28545. this._connected = false;
  28546. this.filters = [];
  28547. }
  28548. getOutput() {
  28549. return this.gain;
  28550. }
  28551. setNodeSource( audioNode ) {
  28552. this.hasPlaybackControl = false;
  28553. this.sourceType = 'audioNode';
  28554. this.source = audioNode;
  28555. this.connect();
  28556. return this;
  28557. }
  28558. setMediaElementSource( mediaElement ) {
  28559. this.hasPlaybackControl = false;
  28560. this.sourceType = 'mediaNode';
  28561. this.source = this.context.createMediaElementSource( mediaElement );
  28562. this.connect();
  28563. return this;
  28564. }
  28565. setMediaStreamSource( mediaStream ) {
  28566. this.hasPlaybackControl = false;
  28567. this.sourceType = 'mediaStreamNode';
  28568. this.source = this.context.createMediaStreamSource( mediaStream );
  28569. this.connect();
  28570. return this;
  28571. }
  28572. setBuffer( audioBuffer ) {
  28573. this.buffer = audioBuffer;
  28574. this.sourceType = 'buffer';
  28575. if ( this.autoplay ) this.play();
  28576. return this;
  28577. }
  28578. play( delay = 0 ) {
  28579. if ( this.isPlaying === true ) {
  28580. console.warn( 'THREE.Audio: Audio is already playing.' );
  28581. return;
  28582. }
  28583. if ( this.hasPlaybackControl === false ) {
  28584. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28585. return;
  28586. }
  28587. this._startedAt = this.context.currentTime + delay;
  28588. const source = this.context.createBufferSource();
  28589. source.buffer = this.buffer;
  28590. source.loop = this.loop;
  28591. source.loopStart = this.loopStart;
  28592. source.loopEnd = this.loopEnd;
  28593. source.onended = this.onEnded.bind( this );
  28594. source.start( this._startedAt, this._progress + this.offset, this.duration );
  28595. this.isPlaying = true;
  28596. this.source = source;
  28597. this.setDetune( this.detune );
  28598. this.setPlaybackRate( this.playbackRate );
  28599. return this.connect();
  28600. }
  28601. pause() {
  28602. if ( this.hasPlaybackControl === false ) {
  28603. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28604. return;
  28605. }
  28606. if ( this.isPlaying === true ) {
  28607. // update current progress
  28608. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  28609. if ( this.loop === true ) {
  28610. // ensure _progress does not exceed duration with looped audios
  28611. this._progress = this._progress % ( this.duration || this.buffer.duration );
  28612. }
  28613. this.source.stop();
  28614. this.source.onended = null;
  28615. this.isPlaying = false;
  28616. }
  28617. return this;
  28618. }
  28619. stop() {
  28620. if ( this.hasPlaybackControl === false ) {
  28621. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28622. return;
  28623. }
  28624. this._progress = 0;
  28625. if ( this.source !== null ) {
  28626. this.source.stop();
  28627. this.source.onended = null;
  28628. }
  28629. this.isPlaying = false;
  28630. return this;
  28631. }
  28632. connect() {
  28633. if ( this.filters.length > 0 ) {
  28634. this.source.connect( this.filters[ 0 ] );
  28635. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28636. this.filters[ i - 1 ].connect( this.filters[ i ] );
  28637. }
  28638. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  28639. } else {
  28640. this.source.connect( this.getOutput() );
  28641. }
  28642. this._connected = true;
  28643. return this;
  28644. }
  28645. disconnect() {
  28646. if ( this._connected === false ) {
  28647. return;
  28648. }
  28649. if ( this.filters.length > 0 ) {
  28650. this.source.disconnect( this.filters[ 0 ] );
  28651. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28652. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  28653. }
  28654. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  28655. } else {
  28656. this.source.disconnect( this.getOutput() );
  28657. }
  28658. this._connected = false;
  28659. return this;
  28660. }
  28661. getFilters() {
  28662. return this.filters;
  28663. }
  28664. setFilters( value ) {
  28665. if ( ! value ) value = [];
  28666. if ( this._connected === true ) {
  28667. this.disconnect();
  28668. this.filters = value.slice();
  28669. this.connect();
  28670. } else {
  28671. this.filters = value.slice();
  28672. }
  28673. return this;
  28674. }
  28675. setDetune( value ) {
  28676. this.detune = value;
  28677. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  28678. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  28679. }
  28680. return this;
  28681. }
  28682. getDetune() {
  28683. return this.detune;
  28684. }
  28685. getFilter() {
  28686. return this.getFilters()[ 0 ];
  28687. }
  28688. setFilter( filter ) {
  28689. return this.setFilters( filter ? [ filter ] : [] );
  28690. }
  28691. setPlaybackRate( value ) {
  28692. if ( this.hasPlaybackControl === false ) {
  28693. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28694. return;
  28695. }
  28696. this.playbackRate = value;
  28697. if ( this.isPlaying === true ) {
  28698. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  28699. }
  28700. return this;
  28701. }
  28702. getPlaybackRate() {
  28703. return this.playbackRate;
  28704. }
  28705. onEnded() {
  28706. this.isPlaying = false;
  28707. }
  28708. getLoop() {
  28709. if ( this.hasPlaybackControl === false ) {
  28710. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28711. return false;
  28712. }
  28713. return this.loop;
  28714. }
  28715. setLoop( value ) {
  28716. if ( this.hasPlaybackControl === false ) {
  28717. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28718. return;
  28719. }
  28720. this.loop = value;
  28721. if ( this.isPlaying === true ) {
  28722. this.source.loop = this.loop;
  28723. }
  28724. return this;
  28725. }
  28726. setLoopStart( value ) {
  28727. this.loopStart = value;
  28728. return this;
  28729. }
  28730. setLoopEnd( value ) {
  28731. this.loopEnd = value;
  28732. return this;
  28733. }
  28734. getVolume() {
  28735. return this.gain.gain.value;
  28736. }
  28737. setVolume( value ) {
  28738. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28739. return this;
  28740. }
  28741. }
  28742. const _position = /*@__PURE__*/ new Vector3();
  28743. const _quaternion = /*@__PURE__*/ new Quaternion();
  28744. const _scale = /*@__PURE__*/ new Vector3();
  28745. const _orientation = /*@__PURE__*/ new Vector3();
  28746. class PositionalAudio extends Audio {
  28747. constructor( listener ) {
  28748. super( listener );
  28749. this.panner = this.context.createPanner();
  28750. this.panner.panningModel = 'HRTF';
  28751. this.panner.connect( this.gain );
  28752. }
  28753. connect() {
  28754. super.connect();
  28755. this.panner.connect( this.gain );
  28756. }
  28757. disconnect() {
  28758. super.disconnect();
  28759. this.panner.disconnect( this.gain );
  28760. }
  28761. getOutput() {
  28762. return this.panner;
  28763. }
  28764. getRefDistance() {
  28765. return this.panner.refDistance;
  28766. }
  28767. setRefDistance( value ) {
  28768. this.panner.refDistance = value;
  28769. return this;
  28770. }
  28771. getRolloffFactor() {
  28772. return this.panner.rolloffFactor;
  28773. }
  28774. setRolloffFactor( value ) {
  28775. this.panner.rolloffFactor = value;
  28776. return this;
  28777. }
  28778. getDistanceModel() {
  28779. return this.panner.distanceModel;
  28780. }
  28781. setDistanceModel( value ) {
  28782. this.panner.distanceModel = value;
  28783. return this;
  28784. }
  28785. getMaxDistance() {
  28786. return this.panner.maxDistance;
  28787. }
  28788. setMaxDistance( value ) {
  28789. this.panner.maxDistance = value;
  28790. return this;
  28791. }
  28792. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28793. this.panner.coneInnerAngle = coneInnerAngle;
  28794. this.panner.coneOuterAngle = coneOuterAngle;
  28795. this.panner.coneOuterGain = coneOuterGain;
  28796. return this;
  28797. }
  28798. updateMatrixWorld( force ) {
  28799. super.updateMatrixWorld( force );
  28800. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  28801. this.matrixWorld.decompose( _position, _quaternion, _scale );
  28802. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  28803. const panner = this.panner;
  28804. if ( panner.positionX ) {
  28805. // code path for Chrome and Firefox (see #14393)
  28806. const endTime = this.context.currentTime + this.listener.timeDelta;
  28807. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  28808. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  28809. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  28810. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  28811. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  28812. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  28813. } else {
  28814. panner.setPosition( _position.x, _position.y, _position.z );
  28815. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  28816. }
  28817. }
  28818. }
  28819. class AudioAnalyser {
  28820. constructor( audio, fftSize = 2048 ) {
  28821. this.analyser = audio.context.createAnalyser();
  28822. this.analyser.fftSize = fftSize;
  28823. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28824. audio.getOutput().connect( this.analyser );
  28825. }
  28826. getFrequencyData() {
  28827. this.analyser.getByteFrequencyData( this.data );
  28828. return this.data;
  28829. }
  28830. getAverageFrequency() {
  28831. let value = 0;
  28832. const data = this.getFrequencyData();
  28833. for ( let i = 0; i < data.length; i ++ ) {
  28834. value += data[ i ];
  28835. }
  28836. return value / data.length;
  28837. }
  28838. }
  28839. class PropertyMixer {
  28840. constructor( binding, typeName, valueSize ) {
  28841. this.binding = binding;
  28842. this.valueSize = valueSize;
  28843. let mixFunction,
  28844. mixFunctionAdditive,
  28845. setIdentity;
  28846. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  28847. //
  28848. // interpolators can use .buffer as their .result
  28849. // the data then goes to 'incoming'
  28850. //
  28851. // 'accu0' and 'accu1' are used frame-interleaved for
  28852. // the cumulative result and are compared to detect
  28853. // changes
  28854. //
  28855. // 'orig' stores the original state of the property
  28856. //
  28857. // 'add' is used for additive cumulative results
  28858. //
  28859. // 'work' is optional and is only present for quaternion types. It is used
  28860. // to store intermediate quaternion multiplication results
  28861. switch ( typeName ) {
  28862. case 'quaternion':
  28863. mixFunction = this._slerp;
  28864. mixFunctionAdditive = this._slerpAdditive;
  28865. setIdentity = this._setAdditiveIdentityQuaternion;
  28866. this.buffer = new Float64Array( valueSize * 6 );
  28867. this._workIndex = 5;
  28868. break;
  28869. case 'string':
  28870. case 'bool':
  28871. mixFunction = this._select;
  28872. // Use the regular mix function and for additive on these types,
  28873. // additive is not relevant for non-numeric types
  28874. mixFunctionAdditive = this._select;
  28875. setIdentity = this._setAdditiveIdentityOther;
  28876. this.buffer = new Array( valueSize * 5 );
  28877. break;
  28878. default:
  28879. mixFunction = this._lerp;
  28880. mixFunctionAdditive = this._lerpAdditive;
  28881. setIdentity = this._setAdditiveIdentityNumeric;
  28882. this.buffer = new Float64Array( valueSize * 5 );
  28883. }
  28884. this._mixBufferRegion = mixFunction;
  28885. this._mixBufferRegionAdditive = mixFunctionAdditive;
  28886. this._setIdentity = setIdentity;
  28887. this._origIndex = 3;
  28888. this._addIndex = 4;
  28889. this.cumulativeWeight = 0;
  28890. this.cumulativeWeightAdditive = 0;
  28891. this.useCount = 0;
  28892. this.referenceCount = 0;
  28893. }
  28894. // accumulate data in the 'incoming' region into 'accu<i>'
  28895. accumulate( accuIndex, weight ) {
  28896. // note: happily accumulating nothing when weight = 0, the caller knows
  28897. // the weight and shouldn't have made the call in the first place
  28898. const buffer = this.buffer,
  28899. stride = this.valueSize,
  28900. offset = accuIndex * stride + stride;
  28901. let currentWeight = this.cumulativeWeight;
  28902. if ( currentWeight === 0 ) {
  28903. // accuN := incoming * weight
  28904. for ( let i = 0; i !== stride; ++ i ) {
  28905. buffer[ offset + i ] = buffer[ i ];
  28906. }
  28907. currentWeight = weight;
  28908. } else {
  28909. // accuN := accuN + incoming * weight
  28910. currentWeight += weight;
  28911. const mix = weight / currentWeight;
  28912. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28913. }
  28914. this.cumulativeWeight = currentWeight;
  28915. }
  28916. // accumulate data in the 'incoming' region into 'add'
  28917. accumulateAdditive( weight ) {
  28918. const buffer = this.buffer,
  28919. stride = this.valueSize,
  28920. offset = stride * this._addIndex;
  28921. if ( this.cumulativeWeightAdditive === 0 ) {
  28922. // add = identity
  28923. this._setIdentity();
  28924. }
  28925. // add := add + incoming * weight
  28926. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  28927. this.cumulativeWeightAdditive += weight;
  28928. }
  28929. // apply the state of 'accu<i>' to the binding when accus differ
  28930. apply( accuIndex ) {
  28931. const stride = this.valueSize,
  28932. buffer = this.buffer,
  28933. offset = accuIndex * stride + stride,
  28934. weight = this.cumulativeWeight,
  28935. weightAdditive = this.cumulativeWeightAdditive,
  28936. binding = this.binding;
  28937. this.cumulativeWeight = 0;
  28938. this.cumulativeWeightAdditive = 0;
  28939. if ( weight < 1 ) {
  28940. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28941. const originalValueOffset = stride * this._origIndex;
  28942. this._mixBufferRegion(
  28943. buffer, offset, originalValueOffset, 1 - weight, stride );
  28944. }
  28945. if ( weightAdditive > 0 ) {
  28946. // accuN := accuN + additive accuN
  28947. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  28948. }
  28949. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  28950. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28951. // value has changed -> update scene graph
  28952. binding.setValue( buffer, offset );
  28953. break;
  28954. }
  28955. }
  28956. }
  28957. // remember the state of the bound property and copy it to both accus
  28958. saveOriginalState() {
  28959. const binding = this.binding;
  28960. const buffer = this.buffer,
  28961. stride = this.valueSize,
  28962. originalValueOffset = stride * this._origIndex;
  28963. binding.getValue( buffer, originalValueOffset );
  28964. // accu[0..1] := orig -- initially detect changes against the original
  28965. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  28966. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  28967. }
  28968. // Add to identity for additive
  28969. this._setIdentity();
  28970. this.cumulativeWeight = 0;
  28971. this.cumulativeWeightAdditive = 0;
  28972. }
  28973. // apply the state previously taken via 'saveOriginalState' to the binding
  28974. restoreOriginalState() {
  28975. const originalValueOffset = this.valueSize * 3;
  28976. this.binding.setValue( this.buffer, originalValueOffset );
  28977. }
  28978. _setAdditiveIdentityNumeric() {
  28979. const startIndex = this._addIndex * this.valueSize;
  28980. const endIndex = startIndex + this.valueSize;
  28981. for ( let i = startIndex; i < endIndex; i ++ ) {
  28982. this.buffer[ i ] = 0;
  28983. }
  28984. }
  28985. _setAdditiveIdentityQuaternion() {
  28986. this._setAdditiveIdentityNumeric();
  28987. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  28988. }
  28989. _setAdditiveIdentityOther() {
  28990. const startIndex = this._origIndex * this.valueSize;
  28991. const targetIndex = this._addIndex * this.valueSize;
  28992. for ( let i = 0; i < this.valueSize; i ++ ) {
  28993. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  28994. }
  28995. }
  28996. // mix functions
  28997. _select( buffer, dstOffset, srcOffset, t, stride ) {
  28998. if ( t >= 0.5 ) {
  28999. for ( let i = 0; i !== stride; ++ i ) {
  29000. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  29001. }
  29002. }
  29003. }
  29004. _slerp( buffer, dstOffset, srcOffset, t ) {
  29005. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  29006. }
  29007. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  29008. const workOffset = this._workIndex * stride;
  29009. // Store result in intermediate buffer offset
  29010. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  29011. // Slerp to the intermediate result
  29012. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  29013. }
  29014. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  29015. const s = 1 - t;
  29016. for ( let i = 0; i !== stride; ++ i ) {
  29017. const j = dstOffset + i;
  29018. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  29019. }
  29020. }
  29021. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  29022. for ( let i = 0; i !== stride; ++ i ) {
  29023. const j = dstOffset + i;
  29024. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  29025. }
  29026. }
  29027. }
  29028. // Characters [].:/ are reserved for track binding syntax.
  29029. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  29030. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  29031. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  29032. // only latin characters, and the unicode \p{L} is not yet supported. So
  29033. // instead, we exclude reserved characters and match everything else.
  29034. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  29035. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  29036. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  29037. // be matched to parse the rest of the track name.
  29038. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  29039. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  29040. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  29041. // Object on target node, and accessor. May not contain reserved
  29042. // characters. Accessor may contain any character except closing bracket.
  29043. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  29044. // Property and accessor. May not contain reserved characters. Accessor may
  29045. // contain any non-bracket characters.
  29046. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  29047. const _trackRe = new RegExp( ''
  29048. + '^'
  29049. + _directoryRe
  29050. + _nodeRe
  29051. + _objectRe
  29052. + _propertyRe
  29053. + '$'
  29054. );
  29055. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  29056. class Composite {
  29057. constructor( targetGroup, path, optionalParsedPath ) {
  29058. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  29059. this._targetGroup = targetGroup;
  29060. this._bindings = targetGroup.subscribe_( path, parsedPath );
  29061. }
  29062. getValue( array, offset ) {
  29063. this.bind(); // bind all binding
  29064. const firstValidIndex = this._targetGroup.nCachedObjects_,
  29065. binding = this._bindings[ firstValidIndex ];
  29066. // and only call .getValue on the first
  29067. if ( binding !== undefined ) binding.getValue( array, offset );
  29068. }
  29069. setValue( array, offset ) {
  29070. const bindings = this._bindings;
  29071. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29072. bindings[ i ].setValue( array, offset );
  29073. }
  29074. }
  29075. bind() {
  29076. const bindings = this._bindings;
  29077. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29078. bindings[ i ].bind();
  29079. }
  29080. }
  29081. unbind() {
  29082. const bindings = this._bindings;
  29083. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29084. bindings[ i ].unbind();
  29085. }
  29086. }
  29087. }
  29088. // Note: This class uses a State pattern on a per-method basis:
  29089. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  29090. // prototype version of these methods with one that represents
  29091. // the bound state. When the property is not found, the methods
  29092. // become no-ops.
  29093. class PropertyBinding {
  29094. constructor( rootNode, path, parsedPath ) {
  29095. this.path = path;
  29096. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  29097. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  29098. this.rootNode = rootNode;
  29099. // initial state of these methods that calls 'bind'
  29100. this.getValue = this._getValue_unbound;
  29101. this.setValue = this._setValue_unbound;
  29102. }
  29103. static create( root, path, parsedPath ) {
  29104. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  29105. return new PropertyBinding( root, path, parsedPath );
  29106. } else {
  29107. return new PropertyBinding.Composite( root, path, parsedPath );
  29108. }
  29109. }
  29110. /**
  29111. * Replaces spaces with underscores and removes unsupported characters from
  29112. * node names, to ensure compatibility with parseTrackName().
  29113. *
  29114. * @param {string} name Node name to be sanitized.
  29115. * @return {string}
  29116. */
  29117. static sanitizeNodeName( name ) {
  29118. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  29119. }
  29120. static parseTrackName( trackName ) {
  29121. const matches = _trackRe.exec( trackName );
  29122. if ( matches === null ) {
  29123. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  29124. }
  29125. const results = {
  29126. // directoryName: matches[ 1 ], // (tschw) currently unused
  29127. nodeName: matches[ 2 ],
  29128. objectName: matches[ 3 ],
  29129. objectIndex: matches[ 4 ],
  29130. propertyName: matches[ 5 ], // required
  29131. propertyIndex: matches[ 6 ]
  29132. };
  29133. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  29134. if ( lastDot !== undefined && lastDot !== - 1 ) {
  29135. const objectName = results.nodeName.substring( lastDot + 1 );
  29136. // Object names must be checked against an allowlist. Otherwise, there
  29137. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  29138. // 'bar' could be the objectName, or part of a nodeName (which can
  29139. // include '.' characters).
  29140. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  29141. results.nodeName = results.nodeName.substring( 0, lastDot );
  29142. results.objectName = objectName;
  29143. }
  29144. }
  29145. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  29146. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  29147. }
  29148. return results;
  29149. }
  29150. static findNode( root, nodeName ) {
  29151. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  29152. return root;
  29153. }
  29154. // search into skeleton bones.
  29155. if ( root.skeleton ) {
  29156. const bone = root.skeleton.getBoneByName( nodeName );
  29157. if ( bone !== undefined ) {
  29158. return bone;
  29159. }
  29160. }
  29161. // search into node subtree.
  29162. if ( root.children ) {
  29163. const searchNodeSubtree = function ( children ) {
  29164. for ( let i = 0; i < children.length; i ++ ) {
  29165. const childNode = children[ i ];
  29166. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  29167. return childNode;
  29168. }
  29169. const result = searchNodeSubtree( childNode.children );
  29170. if ( result ) return result;
  29171. }
  29172. return null;
  29173. };
  29174. const subTreeNode = searchNodeSubtree( root.children );
  29175. if ( subTreeNode ) {
  29176. return subTreeNode;
  29177. }
  29178. }
  29179. return null;
  29180. }
  29181. // these are used to "bind" a nonexistent property
  29182. _getValue_unavailable() {}
  29183. _setValue_unavailable() {}
  29184. // Getters
  29185. _getValue_direct( buffer, offset ) {
  29186. buffer[ offset ] = this.targetObject[ this.propertyName ];
  29187. }
  29188. _getValue_array( buffer, offset ) {
  29189. const source = this.resolvedProperty;
  29190. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  29191. buffer[ offset ++ ] = source[ i ];
  29192. }
  29193. }
  29194. _getValue_arrayElement( buffer, offset ) {
  29195. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  29196. }
  29197. _getValue_toArray( buffer, offset ) {
  29198. this.resolvedProperty.toArray( buffer, offset );
  29199. }
  29200. // Direct
  29201. _setValue_direct( buffer, offset ) {
  29202. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29203. }
  29204. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  29205. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29206. this.targetObject.needsUpdate = true;
  29207. }
  29208. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29209. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29210. this.targetObject.matrixWorldNeedsUpdate = true;
  29211. }
  29212. // EntireArray
  29213. _setValue_array( buffer, offset ) {
  29214. const dest = this.resolvedProperty;
  29215. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29216. dest[ i ] = buffer[ offset ++ ];
  29217. }
  29218. }
  29219. _setValue_array_setNeedsUpdate( buffer, offset ) {
  29220. const dest = this.resolvedProperty;
  29221. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29222. dest[ i ] = buffer[ offset ++ ];
  29223. }
  29224. this.targetObject.needsUpdate = true;
  29225. }
  29226. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29227. const dest = this.resolvedProperty;
  29228. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29229. dest[ i ] = buffer[ offset ++ ];
  29230. }
  29231. this.targetObject.matrixWorldNeedsUpdate = true;
  29232. }
  29233. // ArrayElement
  29234. _setValue_arrayElement( buffer, offset ) {
  29235. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29236. }
  29237. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  29238. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29239. this.targetObject.needsUpdate = true;
  29240. }
  29241. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29242. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29243. this.targetObject.matrixWorldNeedsUpdate = true;
  29244. }
  29245. // HasToFromArray
  29246. _setValue_fromArray( buffer, offset ) {
  29247. this.resolvedProperty.fromArray( buffer, offset );
  29248. }
  29249. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  29250. this.resolvedProperty.fromArray( buffer, offset );
  29251. this.targetObject.needsUpdate = true;
  29252. }
  29253. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29254. this.resolvedProperty.fromArray( buffer, offset );
  29255. this.targetObject.matrixWorldNeedsUpdate = true;
  29256. }
  29257. _getValue_unbound( targetArray, offset ) {
  29258. this.bind();
  29259. this.getValue( targetArray, offset );
  29260. }
  29261. _setValue_unbound( sourceArray, offset ) {
  29262. this.bind();
  29263. this.setValue( sourceArray, offset );
  29264. }
  29265. // create getter / setter pair for a property in the scene graph
  29266. bind() {
  29267. let targetObject = this.node;
  29268. const parsedPath = this.parsedPath;
  29269. const objectName = parsedPath.objectName;
  29270. const propertyName = parsedPath.propertyName;
  29271. let propertyIndex = parsedPath.propertyIndex;
  29272. if ( ! targetObject ) {
  29273. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  29274. this.node = targetObject;
  29275. }
  29276. // set fail state so we can just 'return' on error
  29277. this.getValue = this._getValue_unavailable;
  29278. this.setValue = this._setValue_unavailable;
  29279. // ensure there is a value node
  29280. if ( ! targetObject ) {
  29281. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  29282. return;
  29283. }
  29284. if ( objectName ) {
  29285. let objectIndex = parsedPath.objectIndex;
  29286. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  29287. switch ( objectName ) {
  29288. case 'materials':
  29289. if ( ! targetObject.material ) {
  29290. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29291. return;
  29292. }
  29293. if ( ! targetObject.material.materials ) {
  29294. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  29295. return;
  29296. }
  29297. targetObject = targetObject.material.materials;
  29298. break;
  29299. case 'bones':
  29300. if ( ! targetObject.skeleton ) {
  29301. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  29302. return;
  29303. }
  29304. // potential future optimization: skip this if propertyIndex is already an integer
  29305. // and convert the integer string to a true integer.
  29306. targetObject = targetObject.skeleton.bones;
  29307. // support resolving morphTarget names into indices.
  29308. for ( let i = 0; i < targetObject.length; i ++ ) {
  29309. if ( targetObject[ i ].name === objectIndex ) {
  29310. objectIndex = i;
  29311. break;
  29312. }
  29313. }
  29314. break;
  29315. case 'map':
  29316. if ( 'map' in targetObject ) {
  29317. targetObject = targetObject.map;
  29318. break;
  29319. }
  29320. if ( ! targetObject.material ) {
  29321. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29322. return;
  29323. }
  29324. if ( ! targetObject.material.map ) {
  29325. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  29326. return;
  29327. }
  29328. targetObject = targetObject.material.map;
  29329. break;
  29330. default:
  29331. if ( targetObject[ objectName ] === undefined ) {
  29332. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  29333. return;
  29334. }
  29335. targetObject = targetObject[ objectName ];
  29336. }
  29337. if ( objectIndex !== undefined ) {
  29338. if ( targetObject[ objectIndex ] === undefined ) {
  29339. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  29340. return;
  29341. }
  29342. targetObject = targetObject[ objectIndex ];
  29343. }
  29344. }
  29345. // resolve property
  29346. const nodeProperty = targetObject[ propertyName ];
  29347. if ( nodeProperty === undefined ) {
  29348. const nodeName = parsedPath.nodeName;
  29349. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  29350. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  29351. return;
  29352. }
  29353. // determine versioning scheme
  29354. let versioning = this.Versioning.None;
  29355. this.targetObject = targetObject;
  29356. if ( targetObject.needsUpdate !== undefined ) { // material
  29357. versioning = this.Versioning.NeedsUpdate;
  29358. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  29359. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  29360. }
  29361. // determine how the property gets bound
  29362. let bindingType = this.BindingType.Direct;
  29363. if ( propertyIndex !== undefined ) {
  29364. // access a sub element of the property array (only primitives are supported right now)
  29365. if ( propertyName === 'morphTargetInfluences' ) {
  29366. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  29367. // support resolving morphTarget names into indices.
  29368. if ( ! targetObject.geometry ) {
  29369. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  29370. return;
  29371. }
  29372. if ( ! targetObject.geometry.morphAttributes ) {
  29373. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  29374. return;
  29375. }
  29376. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  29377. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  29378. }
  29379. }
  29380. bindingType = this.BindingType.ArrayElement;
  29381. this.resolvedProperty = nodeProperty;
  29382. this.propertyIndex = propertyIndex;
  29383. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  29384. // must use copy for Object3D.Euler/Quaternion
  29385. bindingType = this.BindingType.HasFromToArray;
  29386. this.resolvedProperty = nodeProperty;
  29387. } else if ( Array.isArray( nodeProperty ) ) {
  29388. bindingType = this.BindingType.EntireArray;
  29389. this.resolvedProperty = nodeProperty;
  29390. } else {
  29391. this.propertyName = propertyName;
  29392. }
  29393. // select getter / setter
  29394. this.getValue = this.GetterByBindingType[ bindingType ];
  29395. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  29396. }
  29397. unbind() {
  29398. this.node = null;
  29399. // back to the prototype version of getValue / setValue
  29400. // note: avoiding to mutate the shape of 'this' via 'delete'
  29401. this.getValue = this._getValue_unbound;
  29402. this.setValue = this._setValue_unbound;
  29403. }
  29404. }
  29405. PropertyBinding.Composite = Composite;
  29406. PropertyBinding.prototype.BindingType = {
  29407. Direct: 0,
  29408. EntireArray: 1,
  29409. ArrayElement: 2,
  29410. HasFromToArray: 3
  29411. };
  29412. PropertyBinding.prototype.Versioning = {
  29413. None: 0,
  29414. NeedsUpdate: 1,
  29415. MatrixWorldNeedsUpdate: 2
  29416. };
  29417. PropertyBinding.prototype.GetterByBindingType = [
  29418. PropertyBinding.prototype._getValue_direct,
  29419. PropertyBinding.prototype._getValue_array,
  29420. PropertyBinding.prototype._getValue_arrayElement,
  29421. PropertyBinding.prototype._getValue_toArray,
  29422. ];
  29423. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  29424. [
  29425. // Direct
  29426. PropertyBinding.prototype._setValue_direct,
  29427. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  29428. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  29429. ], [
  29430. // EntireArray
  29431. PropertyBinding.prototype._setValue_array,
  29432. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  29433. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  29434. ], [
  29435. // ArrayElement
  29436. PropertyBinding.prototype._setValue_arrayElement,
  29437. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  29438. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  29439. ], [
  29440. // HasToFromArray
  29441. PropertyBinding.prototype._setValue_fromArray,
  29442. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  29443. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  29444. ]
  29445. ];
  29446. /**
  29447. *
  29448. * A group of objects that receives a shared animation state.
  29449. *
  29450. * Usage:
  29451. *
  29452. * - Add objects you would otherwise pass as 'root' to the
  29453. * constructor or the .clipAction method of AnimationMixer.
  29454. *
  29455. * - Instead pass this object as 'root'.
  29456. *
  29457. * - You can also add and remove objects later when the mixer
  29458. * is running.
  29459. *
  29460. * Note:
  29461. *
  29462. * Objects of this class appear as one object to the mixer,
  29463. * so cache control of the individual objects must be done
  29464. * on the group.
  29465. *
  29466. * Limitation:
  29467. *
  29468. * - The animated properties must be compatible among the
  29469. * all objects in the group.
  29470. *
  29471. * - A single property can either be controlled through a
  29472. * target group or directly, but not both.
  29473. */
  29474. class AnimationObjectGroup {
  29475. constructor() {
  29476. this.isAnimationObjectGroup = true;
  29477. this.uuid = generateUUID();
  29478. // cached objects followed by the active ones
  29479. this._objects = Array.prototype.slice.call( arguments );
  29480. this.nCachedObjects_ = 0; // threshold
  29481. // note: read by PropertyBinding.Composite
  29482. const indices = {};
  29483. this._indicesByUUID = indices; // for bookkeeping
  29484. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29485. indices[ arguments[ i ].uuid ] = i;
  29486. }
  29487. this._paths = []; // inside: string
  29488. this._parsedPaths = []; // inside: { we don't care, here }
  29489. this._bindings = []; // inside: Array< PropertyBinding >
  29490. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  29491. const scope = this;
  29492. this.stats = {
  29493. objects: {
  29494. get total() {
  29495. return scope._objects.length;
  29496. },
  29497. get inUse() {
  29498. return this.total - scope.nCachedObjects_;
  29499. }
  29500. },
  29501. get bindingsPerObject() {
  29502. return scope._bindings.length;
  29503. }
  29504. };
  29505. }
  29506. add() {
  29507. const objects = this._objects,
  29508. indicesByUUID = this._indicesByUUID,
  29509. paths = this._paths,
  29510. parsedPaths = this._parsedPaths,
  29511. bindings = this._bindings,
  29512. nBindings = bindings.length;
  29513. let knownObject = undefined,
  29514. nObjects = objects.length,
  29515. nCachedObjects = this.nCachedObjects_;
  29516. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29517. const object = arguments[ i ],
  29518. uuid = object.uuid;
  29519. let index = indicesByUUID[ uuid ];
  29520. if ( index === undefined ) {
  29521. // unknown object -> add it to the ACTIVE region
  29522. index = nObjects ++;
  29523. indicesByUUID[ uuid ] = index;
  29524. objects.push( object );
  29525. // accounting is done, now do the same for all bindings
  29526. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29527. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  29528. }
  29529. } else if ( index < nCachedObjects ) {
  29530. knownObject = objects[ index ];
  29531. // move existing object to the ACTIVE region
  29532. const firstActiveIndex = -- nCachedObjects,
  29533. lastCachedObject = objects[ firstActiveIndex ];
  29534. indicesByUUID[ lastCachedObject.uuid ] = index;
  29535. objects[ index ] = lastCachedObject;
  29536. indicesByUUID[ uuid ] = firstActiveIndex;
  29537. objects[ firstActiveIndex ] = object;
  29538. // accounting is done, now do the same for all bindings
  29539. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29540. const bindingsForPath = bindings[ j ],
  29541. lastCached = bindingsForPath[ firstActiveIndex ];
  29542. let binding = bindingsForPath[ index ];
  29543. bindingsForPath[ index ] = lastCached;
  29544. if ( binding === undefined ) {
  29545. // since we do not bother to create new bindings
  29546. // for objects that are cached, the binding may
  29547. // or may not exist
  29548. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  29549. }
  29550. bindingsForPath[ firstActiveIndex ] = binding;
  29551. }
  29552. } else if ( objects[ index ] !== knownObject ) {
  29553. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  29554. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  29555. } // else the object is already where we want it to be
  29556. } // for arguments
  29557. this.nCachedObjects_ = nCachedObjects;
  29558. }
  29559. remove() {
  29560. const objects = this._objects,
  29561. indicesByUUID = this._indicesByUUID,
  29562. bindings = this._bindings,
  29563. nBindings = bindings.length;
  29564. let nCachedObjects = this.nCachedObjects_;
  29565. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29566. const object = arguments[ i ],
  29567. uuid = object.uuid,
  29568. index = indicesByUUID[ uuid ];
  29569. if ( index !== undefined && index >= nCachedObjects ) {
  29570. // move existing object into the CACHED region
  29571. const lastCachedIndex = nCachedObjects ++,
  29572. firstActiveObject = objects[ lastCachedIndex ];
  29573. indicesByUUID[ firstActiveObject.uuid ] = index;
  29574. objects[ index ] = firstActiveObject;
  29575. indicesByUUID[ uuid ] = lastCachedIndex;
  29576. objects[ lastCachedIndex ] = object;
  29577. // accounting is done, now do the same for all bindings
  29578. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29579. const bindingsForPath = bindings[ j ],
  29580. firstActive = bindingsForPath[ lastCachedIndex ],
  29581. binding = bindingsForPath[ index ];
  29582. bindingsForPath[ index ] = firstActive;
  29583. bindingsForPath[ lastCachedIndex ] = binding;
  29584. }
  29585. }
  29586. } // for arguments
  29587. this.nCachedObjects_ = nCachedObjects;
  29588. }
  29589. // remove & forget
  29590. uncache() {
  29591. const objects = this._objects,
  29592. indicesByUUID = this._indicesByUUID,
  29593. bindings = this._bindings,
  29594. nBindings = bindings.length;
  29595. let nCachedObjects = this.nCachedObjects_,
  29596. nObjects = objects.length;
  29597. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29598. const object = arguments[ i ],
  29599. uuid = object.uuid,
  29600. index = indicesByUUID[ uuid ];
  29601. if ( index !== undefined ) {
  29602. delete indicesByUUID[ uuid ];
  29603. if ( index < nCachedObjects ) {
  29604. // object is cached, shrink the CACHED region
  29605. const firstActiveIndex = -- nCachedObjects,
  29606. lastCachedObject = objects[ firstActiveIndex ],
  29607. lastIndex = -- nObjects,
  29608. lastObject = objects[ lastIndex ];
  29609. // last cached object takes this object's place
  29610. indicesByUUID[ lastCachedObject.uuid ] = index;
  29611. objects[ index ] = lastCachedObject;
  29612. // last object goes to the activated slot and pop
  29613. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29614. objects[ firstActiveIndex ] = lastObject;
  29615. objects.pop();
  29616. // accounting is done, now do the same for all bindings
  29617. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29618. const bindingsForPath = bindings[ j ],
  29619. lastCached = bindingsForPath[ firstActiveIndex ],
  29620. last = bindingsForPath[ lastIndex ];
  29621. bindingsForPath[ index ] = lastCached;
  29622. bindingsForPath[ firstActiveIndex ] = last;
  29623. bindingsForPath.pop();
  29624. }
  29625. } else {
  29626. // object is active, just swap with the last and pop
  29627. const lastIndex = -- nObjects,
  29628. lastObject = objects[ lastIndex ];
  29629. if ( lastIndex > 0 ) {
  29630. indicesByUUID[ lastObject.uuid ] = index;
  29631. }
  29632. objects[ index ] = lastObject;
  29633. objects.pop();
  29634. // accounting is done, now do the same for all bindings
  29635. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29636. const bindingsForPath = bindings[ j ];
  29637. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29638. bindingsForPath.pop();
  29639. }
  29640. } // cached or active
  29641. } // if object is known
  29642. } // for arguments
  29643. this.nCachedObjects_ = nCachedObjects;
  29644. }
  29645. // Internal interface used by befriended PropertyBinding.Composite:
  29646. subscribe_( path, parsedPath ) {
  29647. // returns an array of bindings for the given path that is changed
  29648. // according to the contained objects in the group
  29649. const indicesByPath = this._bindingsIndicesByPath;
  29650. let index = indicesByPath[ path ];
  29651. const bindings = this._bindings;
  29652. if ( index !== undefined ) return bindings[ index ];
  29653. const paths = this._paths,
  29654. parsedPaths = this._parsedPaths,
  29655. objects = this._objects,
  29656. nObjects = objects.length,
  29657. nCachedObjects = this.nCachedObjects_,
  29658. bindingsForPath = new Array( nObjects );
  29659. index = bindings.length;
  29660. indicesByPath[ path ] = index;
  29661. paths.push( path );
  29662. parsedPaths.push( parsedPath );
  29663. bindings.push( bindingsForPath );
  29664. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29665. const object = objects[ i ];
  29666. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29667. }
  29668. return bindingsForPath;
  29669. }
  29670. unsubscribe_( path ) {
  29671. // tells the group to forget about a property path and no longer
  29672. // update the array previously obtained with 'subscribe_'
  29673. const indicesByPath = this._bindingsIndicesByPath,
  29674. index = indicesByPath[ path ];
  29675. if ( index !== undefined ) {
  29676. const paths = this._paths,
  29677. parsedPaths = this._parsedPaths,
  29678. bindings = this._bindings,
  29679. lastBindingsIndex = bindings.length - 1,
  29680. lastBindings = bindings[ lastBindingsIndex ],
  29681. lastBindingsPath = path[ lastBindingsIndex ];
  29682. indicesByPath[ lastBindingsPath ] = index;
  29683. bindings[ index ] = lastBindings;
  29684. bindings.pop();
  29685. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29686. parsedPaths.pop();
  29687. paths[ index ] = paths[ lastBindingsIndex ];
  29688. paths.pop();
  29689. }
  29690. }
  29691. }
  29692. class AnimationAction {
  29693. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  29694. this._mixer = mixer;
  29695. this._clip = clip;
  29696. this._localRoot = localRoot;
  29697. this.blendMode = blendMode;
  29698. const tracks = clip.tracks,
  29699. nTracks = tracks.length,
  29700. interpolants = new Array( nTracks );
  29701. const interpolantSettings = {
  29702. endingStart: ZeroCurvatureEnding,
  29703. endingEnd: ZeroCurvatureEnding
  29704. };
  29705. for ( let i = 0; i !== nTracks; ++ i ) {
  29706. const interpolant = tracks[ i ].createInterpolant( null );
  29707. interpolants[ i ] = interpolant;
  29708. interpolant.settings = interpolantSettings;
  29709. }
  29710. this._interpolantSettings = interpolantSettings;
  29711. this._interpolants = interpolants; // bound by the mixer
  29712. // inside: PropertyMixer (managed by the mixer)
  29713. this._propertyBindings = new Array( nTracks );
  29714. this._cacheIndex = null; // for the memory manager
  29715. this._byClipCacheIndex = null; // for the memory manager
  29716. this._timeScaleInterpolant = null;
  29717. this._weightInterpolant = null;
  29718. this.loop = LoopRepeat;
  29719. this._loopCount = - 1;
  29720. // global mixer time when the action is to be started
  29721. // it's set back to 'null' upon start of the action
  29722. this._startTime = null;
  29723. // scaled local time of the action
  29724. // gets clamped or wrapped to 0..clip.duration according to loop
  29725. this.time = 0;
  29726. this.timeScale = 1;
  29727. this._effectiveTimeScale = 1;
  29728. this.weight = 1;
  29729. this._effectiveWeight = 1;
  29730. this.repetitions = Infinity; // no. of repetitions when looping
  29731. this.paused = false; // true -> zero effective time scale
  29732. this.enabled = true; // false -> zero effective weight
  29733. this.clampWhenFinished = false;// keep feeding the last frame?
  29734. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29735. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29736. }
  29737. // State & Scheduling
  29738. play() {
  29739. this._mixer._activateAction( this );
  29740. return this;
  29741. }
  29742. stop() {
  29743. this._mixer._deactivateAction( this );
  29744. return this.reset();
  29745. }
  29746. reset() {
  29747. this.paused = false;
  29748. this.enabled = true;
  29749. this.time = 0; // restart clip
  29750. this._loopCount = - 1;// forget previous loops
  29751. this._startTime = null;// forget scheduling
  29752. return this.stopFading().stopWarping();
  29753. }
  29754. isRunning() {
  29755. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29756. this._startTime === null && this._mixer._isActiveAction( this );
  29757. }
  29758. // return true when play has been called
  29759. isScheduled() {
  29760. return this._mixer._isActiveAction( this );
  29761. }
  29762. startAt( time ) {
  29763. this._startTime = time;
  29764. return this;
  29765. }
  29766. setLoop( mode, repetitions ) {
  29767. this.loop = mode;
  29768. this.repetitions = repetitions;
  29769. return this;
  29770. }
  29771. // Weight
  29772. // set the weight stopping any scheduled fading
  29773. // although .enabled = false yields an effective weight of zero, this
  29774. // method does *not* change .enabled, because it would be confusing
  29775. setEffectiveWeight( weight ) {
  29776. this.weight = weight;
  29777. // note: same logic as when updated at runtime
  29778. this._effectiveWeight = this.enabled ? weight : 0;
  29779. return this.stopFading();
  29780. }
  29781. // return the weight considering fading and .enabled
  29782. getEffectiveWeight() {
  29783. return this._effectiveWeight;
  29784. }
  29785. fadeIn( duration ) {
  29786. return this._scheduleFading( duration, 0, 1 );
  29787. }
  29788. fadeOut( duration ) {
  29789. return this._scheduleFading( duration, 1, 0 );
  29790. }
  29791. crossFadeFrom( fadeOutAction, duration, warp ) {
  29792. fadeOutAction.fadeOut( duration );
  29793. this.fadeIn( duration );
  29794. if ( warp ) {
  29795. const fadeInDuration = this._clip.duration,
  29796. fadeOutDuration = fadeOutAction._clip.duration,
  29797. startEndRatio = fadeOutDuration / fadeInDuration,
  29798. endStartRatio = fadeInDuration / fadeOutDuration;
  29799. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29800. this.warp( endStartRatio, 1.0, duration );
  29801. }
  29802. return this;
  29803. }
  29804. crossFadeTo( fadeInAction, duration, warp ) {
  29805. return fadeInAction.crossFadeFrom( this, duration, warp );
  29806. }
  29807. stopFading() {
  29808. const weightInterpolant = this._weightInterpolant;
  29809. if ( weightInterpolant !== null ) {
  29810. this._weightInterpolant = null;
  29811. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29812. }
  29813. return this;
  29814. }
  29815. // Time Scale Control
  29816. // set the time scale stopping any scheduled warping
  29817. // although .paused = true yields an effective time scale of zero, this
  29818. // method does *not* change .paused, because it would be confusing
  29819. setEffectiveTimeScale( timeScale ) {
  29820. this.timeScale = timeScale;
  29821. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29822. return this.stopWarping();
  29823. }
  29824. // return the time scale considering warping and .paused
  29825. getEffectiveTimeScale() {
  29826. return this._effectiveTimeScale;
  29827. }
  29828. setDuration( duration ) {
  29829. this.timeScale = this._clip.duration / duration;
  29830. return this.stopWarping();
  29831. }
  29832. syncWith( action ) {
  29833. this.time = action.time;
  29834. this.timeScale = action.timeScale;
  29835. return this.stopWarping();
  29836. }
  29837. halt( duration ) {
  29838. return this.warp( this._effectiveTimeScale, 0, duration );
  29839. }
  29840. warp( startTimeScale, endTimeScale, duration ) {
  29841. const mixer = this._mixer,
  29842. now = mixer.time,
  29843. timeScale = this.timeScale;
  29844. let interpolant = this._timeScaleInterpolant;
  29845. if ( interpolant === null ) {
  29846. interpolant = mixer._lendControlInterpolant();
  29847. this._timeScaleInterpolant = interpolant;
  29848. }
  29849. const times = interpolant.parameterPositions,
  29850. values = interpolant.sampleValues;
  29851. times[ 0 ] = now;
  29852. times[ 1 ] = now + duration;
  29853. values[ 0 ] = startTimeScale / timeScale;
  29854. values[ 1 ] = endTimeScale / timeScale;
  29855. return this;
  29856. }
  29857. stopWarping() {
  29858. const timeScaleInterpolant = this._timeScaleInterpolant;
  29859. if ( timeScaleInterpolant !== null ) {
  29860. this._timeScaleInterpolant = null;
  29861. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29862. }
  29863. return this;
  29864. }
  29865. // Object Accessors
  29866. getMixer() {
  29867. return this._mixer;
  29868. }
  29869. getClip() {
  29870. return this._clip;
  29871. }
  29872. getRoot() {
  29873. return this._localRoot || this._mixer._root;
  29874. }
  29875. // Interna
  29876. _update( time, deltaTime, timeDirection, accuIndex ) {
  29877. // called by the mixer
  29878. if ( ! this.enabled ) {
  29879. // call ._updateWeight() to update ._effectiveWeight
  29880. this._updateWeight( time );
  29881. return;
  29882. }
  29883. const startTime = this._startTime;
  29884. if ( startTime !== null ) {
  29885. // check for scheduled start of action
  29886. const timeRunning = ( time - startTime ) * timeDirection;
  29887. if ( timeRunning < 0 || timeDirection === 0 ) {
  29888. deltaTime = 0;
  29889. } else {
  29890. this._startTime = null; // unschedule
  29891. deltaTime = timeDirection * timeRunning;
  29892. }
  29893. }
  29894. // apply time scale and advance time
  29895. deltaTime *= this._updateTimeScale( time );
  29896. const clipTime = this._updateTime( deltaTime );
  29897. // note: _updateTime may disable the action resulting in
  29898. // an effective weight of 0
  29899. const weight = this._updateWeight( time );
  29900. if ( weight > 0 ) {
  29901. const interpolants = this._interpolants;
  29902. const propertyMixers = this._propertyBindings;
  29903. switch ( this.blendMode ) {
  29904. case AdditiveAnimationBlendMode:
  29905. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29906. interpolants[ j ].evaluate( clipTime );
  29907. propertyMixers[ j ].accumulateAdditive( weight );
  29908. }
  29909. break;
  29910. case NormalAnimationBlendMode:
  29911. default:
  29912. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29913. interpolants[ j ].evaluate( clipTime );
  29914. propertyMixers[ j ].accumulate( accuIndex, weight );
  29915. }
  29916. }
  29917. }
  29918. }
  29919. _updateWeight( time ) {
  29920. let weight = 0;
  29921. if ( this.enabled ) {
  29922. weight = this.weight;
  29923. const interpolant = this._weightInterpolant;
  29924. if ( interpolant !== null ) {
  29925. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29926. weight *= interpolantValue;
  29927. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29928. this.stopFading();
  29929. if ( interpolantValue === 0 ) {
  29930. // faded out, disable
  29931. this.enabled = false;
  29932. }
  29933. }
  29934. }
  29935. }
  29936. this._effectiveWeight = weight;
  29937. return weight;
  29938. }
  29939. _updateTimeScale( time ) {
  29940. let timeScale = 0;
  29941. if ( ! this.paused ) {
  29942. timeScale = this.timeScale;
  29943. const interpolant = this._timeScaleInterpolant;
  29944. if ( interpolant !== null ) {
  29945. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29946. timeScale *= interpolantValue;
  29947. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29948. this.stopWarping();
  29949. if ( timeScale === 0 ) {
  29950. // motion has halted, pause
  29951. this.paused = true;
  29952. } else {
  29953. // warp done - apply final time scale
  29954. this.timeScale = timeScale;
  29955. }
  29956. }
  29957. }
  29958. }
  29959. this._effectiveTimeScale = timeScale;
  29960. return timeScale;
  29961. }
  29962. _updateTime( deltaTime ) {
  29963. const duration = this._clip.duration;
  29964. const loop = this.loop;
  29965. let time = this.time + deltaTime;
  29966. let loopCount = this._loopCount;
  29967. const pingPong = ( loop === LoopPingPong );
  29968. if ( deltaTime === 0 ) {
  29969. if ( loopCount === - 1 ) return time;
  29970. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  29971. }
  29972. if ( loop === LoopOnce ) {
  29973. if ( loopCount === - 1 ) {
  29974. // just started
  29975. this._loopCount = 0;
  29976. this._setEndings( true, true, false );
  29977. }
  29978. handle_stop: {
  29979. if ( time >= duration ) {
  29980. time = duration;
  29981. } else if ( time < 0 ) {
  29982. time = 0;
  29983. } else {
  29984. this.time = time;
  29985. break handle_stop;
  29986. }
  29987. if ( this.clampWhenFinished ) this.paused = true;
  29988. else this.enabled = false;
  29989. this.time = time;
  29990. this._mixer.dispatchEvent( {
  29991. type: 'finished', action: this,
  29992. direction: deltaTime < 0 ? - 1 : 1
  29993. } );
  29994. }
  29995. } else { // repetitive Repeat or PingPong
  29996. if ( loopCount === - 1 ) {
  29997. // just started
  29998. if ( deltaTime >= 0 ) {
  29999. loopCount = 0;
  30000. this._setEndings( true, this.repetitions === 0, pingPong );
  30001. } else {
  30002. // when looping in reverse direction, the initial
  30003. // transition through zero counts as a repetition,
  30004. // so leave loopCount at -1
  30005. this._setEndings( this.repetitions === 0, true, pingPong );
  30006. }
  30007. }
  30008. if ( time >= duration || time < 0 ) {
  30009. // wrap around
  30010. const loopDelta = Math.floor( time / duration ); // signed
  30011. time -= duration * loopDelta;
  30012. loopCount += Math.abs( loopDelta );
  30013. const pending = this.repetitions - loopCount;
  30014. if ( pending <= 0 ) {
  30015. // have to stop (switch state, clamp time, fire event)
  30016. if ( this.clampWhenFinished ) this.paused = true;
  30017. else this.enabled = false;
  30018. time = deltaTime > 0 ? duration : 0;
  30019. this.time = time;
  30020. this._mixer.dispatchEvent( {
  30021. type: 'finished', action: this,
  30022. direction: deltaTime > 0 ? 1 : - 1
  30023. } );
  30024. } else {
  30025. // keep running
  30026. if ( pending === 1 ) {
  30027. // entering the last round
  30028. const atStart = deltaTime < 0;
  30029. this._setEndings( atStart, ! atStart, pingPong );
  30030. } else {
  30031. this._setEndings( false, false, pingPong );
  30032. }
  30033. this._loopCount = loopCount;
  30034. this.time = time;
  30035. this._mixer.dispatchEvent( {
  30036. type: 'loop', action: this, loopDelta: loopDelta
  30037. } );
  30038. }
  30039. } else {
  30040. this.time = time;
  30041. }
  30042. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  30043. // invert time for the "pong round"
  30044. return duration - time;
  30045. }
  30046. }
  30047. return time;
  30048. }
  30049. _setEndings( atStart, atEnd, pingPong ) {
  30050. const settings = this._interpolantSettings;
  30051. if ( pingPong ) {
  30052. settings.endingStart = ZeroSlopeEnding;
  30053. settings.endingEnd = ZeroSlopeEnding;
  30054. } else {
  30055. // assuming for LoopOnce atStart == atEnd == true
  30056. if ( atStart ) {
  30057. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30058. } else {
  30059. settings.endingStart = WrapAroundEnding;
  30060. }
  30061. if ( atEnd ) {
  30062. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30063. } else {
  30064. settings.endingEnd = WrapAroundEnding;
  30065. }
  30066. }
  30067. }
  30068. _scheduleFading( duration, weightNow, weightThen ) {
  30069. const mixer = this._mixer, now = mixer.time;
  30070. let interpolant = this._weightInterpolant;
  30071. if ( interpolant === null ) {
  30072. interpolant = mixer._lendControlInterpolant();
  30073. this._weightInterpolant = interpolant;
  30074. }
  30075. const times = interpolant.parameterPositions,
  30076. values = interpolant.sampleValues;
  30077. times[ 0 ] = now;
  30078. values[ 0 ] = weightNow;
  30079. times[ 1 ] = now + duration;
  30080. values[ 1 ] = weightThen;
  30081. return this;
  30082. }
  30083. }
  30084. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  30085. class AnimationMixer extends EventDispatcher {
  30086. constructor( root ) {
  30087. super();
  30088. this._root = root;
  30089. this._initMemoryManager();
  30090. this._accuIndex = 0;
  30091. this.time = 0;
  30092. this.timeScale = 1.0;
  30093. }
  30094. _bindAction( action, prototypeAction ) {
  30095. const root = action._localRoot || this._root,
  30096. tracks = action._clip.tracks,
  30097. nTracks = tracks.length,
  30098. bindings = action._propertyBindings,
  30099. interpolants = action._interpolants,
  30100. rootUuid = root.uuid,
  30101. bindingsByRoot = this._bindingsByRootAndName;
  30102. let bindingsByName = bindingsByRoot[ rootUuid ];
  30103. if ( bindingsByName === undefined ) {
  30104. bindingsByName = {};
  30105. bindingsByRoot[ rootUuid ] = bindingsByName;
  30106. }
  30107. for ( let i = 0; i !== nTracks; ++ i ) {
  30108. const track = tracks[ i ],
  30109. trackName = track.name;
  30110. let binding = bindingsByName[ trackName ];
  30111. if ( binding !== undefined ) {
  30112. ++ binding.referenceCount;
  30113. bindings[ i ] = binding;
  30114. } else {
  30115. binding = bindings[ i ];
  30116. if ( binding !== undefined ) {
  30117. // existing binding, make sure the cache knows
  30118. if ( binding._cacheIndex === null ) {
  30119. ++ binding.referenceCount;
  30120. this._addInactiveBinding( binding, rootUuid, trackName );
  30121. }
  30122. continue;
  30123. }
  30124. const path = prototypeAction && prototypeAction.
  30125. _propertyBindings[ i ].binding.parsedPath;
  30126. binding = new PropertyMixer(
  30127. PropertyBinding.create( root, trackName, path ),
  30128. track.ValueTypeName, track.getValueSize() );
  30129. ++ binding.referenceCount;
  30130. this._addInactiveBinding( binding, rootUuid, trackName );
  30131. bindings[ i ] = binding;
  30132. }
  30133. interpolants[ i ].resultBuffer = binding.buffer;
  30134. }
  30135. }
  30136. _activateAction( action ) {
  30137. if ( ! this._isActiveAction( action ) ) {
  30138. if ( action._cacheIndex === null ) {
  30139. // this action has been forgotten by the cache, but the user
  30140. // appears to be still using it -> rebind
  30141. const rootUuid = ( action._localRoot || this._root ).uuid,
  30142. clipUuid = action._clip.uuid,
  30143. actionsForClip = this._actionsByClip[ clipUuid ];
  30144. this._bindAction( action,
  30145. actionsForClip && actionsForClip.knownActions[ 0 ] );
  30146. this._addInactiveAction( action, clipUuid, rootUuid );
  30147. }
  30148. const bindings = action._propertyBindings;
  30149. // increment reference counts / sort out state
  30150. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30151. const binding = bindings[ i ];
  30152. if ( binding.useCount ++ === 0 ) {
  30153. this._lendBinding( binding );
  30154. binding.saveOriginalState();
  30155. }
  30156. }
  30157. this._lendAction( action );
  30158. }
  30159. }
  30160. _deactivateAction( action ) {
  30161. if ( this._isActiveAction( action ) ) {
  30162. const bindings = action._propertyBindings;
  30163. // decrement reference counts / sort out state
  30164. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30165. const binding = bindings[ i ];
  30166. if ( -- binding.useCount === 0 ) {
  30167. binding.restoreOriginalState();
  30168. this._takeBackBinding( binding );
  30169. }
  30170. }
  30171. this._takeBackAction( action );
  30172. }
  30173. }
  30174. // Memory manager
  30175. _initMemoryManager() {
  30176. this._actions = []; // 'nActiveActions' followed by inactive ones
  30177. this._nActiveActions = 0;
  30178. this._actionsByClip = {};
  30179. // inside:
  30180. // {
  30181. // knownActions: Array< AnimationAction > - used as prototypes
  30182. // actionByRoot: AnimationAction - lookup
  30183. // }
  30184. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  30185. this._nActiveBindings = 0;
  30186. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  30187. this._controlInterpolants = []; // same game as above
  30188. this._nActiveControlInterpolants = 0;
  30189. const scope = this;
  30190. this.stats = {
  30191. actions: {
  30192. get total() {
  30193. return scope._actions.length;
  30194. },
  30195. get inUse() {
  30196. return scope._nActiveActions;
  30197. }
  30198. },
  30199. bindings: {
  30200. get total() {
  30201. return scope._bindings.length;
  30202. },
  30203. get inUse() {
  30204. return scope._nActiveBindings;
  30205. }
  30206. },
  30207. controlInterpolants: {
  30208. get total() {
  30209. return scope._controlInterpolants.length;
  30210. },
  30211. get inUse() {
  30212. return scope._nActiveControlInterpolants;
  30213. }
  30214. }
  30215. };
  30216. }
  30217. // Memory management for AnimationAction objects
  30218. _isActiveAction( action ) {
  30219. const index = action._cacheIndex;
  30220. return index !== null && index < this._nActiveActions;
  30221. }
  30222. _addInactiveAction( action, clipUuid, rootUuid ) {
  30223. const actions = this._actions,
  30224. actionsByClip = this._actionsByClip;
  30225. let actionsForClip = actionsByClip[ clipUuid ];
  30226. if ( actionsForClip === undefined ) {
  30227. actionsForClip = {
  30228. knownActions: [ action ],
  30229. actionByRoot: {}
  30230. };
  30231. action._byClipCacheIndex = 0;
  30232. actionsByClip[ clipUuid ] = actionsForClip;
  30233. } else {
  30234. const knownActions = actionsForClip.knownActions;
  30235. action._byClipCacheIndex = knownActions.length;
  30236. knownActions.push( action );
  30237. }
  30238. action._cacheIndex = actions.length;
  30239. actions.push( action );
  30240. actionsForClip.actionByRoot[ rootUuid ] = action;
  30241. }
  30242. _removeInactiveAction( action ) {
  30243. const actions = this._actions,
  30244. lastInactiveAction = actions[ actions.length - 1 ],
  30245. cacheIndex = action._cacheIndex;
  30246. lastInactiveAction._cacheIndex = cacheIndex;
  30247. actions[ cacheIndex ] = lastInactiveAction;
  30248. actions.pop();
  30249. action._cacheIndex = null;
  30250. const clipUuid = action._clip.uuid,
  30251. actionsByClip = this._actionsByClip,
  30252. actionsForClip = actionsByClip[ clipUuid ],
  30253. knownActionsForClip = actionsForClip.knownActions,
  30254. lastKnownAction =
  30255. knownActionsForClip[ knownActionsForClip.length - 1 ],
  30256. byClipCacheIndex = action._byClipCacheIndex;
  30257. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  30258. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  30259. knownActionsForClip.pop();
  30260. action._byClipCacheIndex = null;
  30261. const actionByRoot = actionsForClip.actionByRoot,
  30262. rootUuid = ( action._localRoot || this._root ).uuid;
  30263. delete actionByRoot[ rootUuid ];
  30264. if ( knownActionsForClip.length === 0 ) {
  30265. delete actionsByClip[ clipUuid ];
  30266. }
  30267. this._removeInactiveBindingsForAction( action );
  30268. }
  30269. _removeInactiveBindingsForAction( action ) {
  30270. const bindings = action._propertyBindings;
  30271. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30272. const binding = bindings[ i ];
  30273. if ( -- binding.referenceCount === 0 ) {
  30274. this._removeInactiveBinding( binding );
  30275. }
  30276. }
  30277. }
  30278. _lendAction( action ) {
  30279. // [ active actions | inactive actions ]
  30280. // [ active actions >| inactive actions ]
  30281. // s a
  30282. // <-swap->
  30283. // a s
  30284. const actions = this._actions,
  30285. prevIndex = action._cacheIndex,
  30286. lastActiveIndex = this._nActiveActions ++,
  30287. firstInactiveAction = actions[ lastActiveIndex ];
  30288. action._cacheIndex = lastActiveIndex;
  30289. actions[ lastActiveIndex ] = action;
  30290. firstInactiveAction._cacheIndex = prevIndex;
  30291. actions[ prevIndex ] = firstInactiveAction;
  30292. }
  30293. _takeBackAction( action ) {
  30294. // [ active actions | inactive actions ]
  30295. // [ active actions |< inactive actions ]
  30296. // a s
  30297. // <-swap->
  30298. // s a
  30299. const actions = this._actions,
  30300. prevIndex = action._cacheIndex,
  30301. firstInactiveIndex = -- this._nActiveActions,
  30302. lastActiveAction = actions[ firstInactiveIndex ];
  30303. action._cacheIndex = firstInactiveIndex;
  30304. actions[ firstInactiveIndex ] = action;
  30305. lastActiveAction._cacheIndex = prevIndex;
  30306. actions[ prevIndex ] = lastActiveAction;
  30307. }
  30308. // Memory management for PropertyMixer objects
  30309. _addInactiveBinding( binding, rootUuid, trackName ) {
  30310. const bindingsByRoot = this._bindingsByRootAndName,
  30311. bindings = this._bindings;
  30312. let bindingByName = bindingsByRoot[ rootUuid ];
  30313. if ( bindingByName === undefined ) {
  30314. bindingByName = {};
  30315. bindingsByRoot[ rootUuid ] = bindingByName;
  30316. }
  30317. bindingByName[ trackName ] = binding;
  30318. binding._cacheIndex = bindings.length;
  30319. bindings.push( binding );
  30320. }
  30321. _removeInactiveBinding( binding ) {
  30322. const bindings = this._bindings,
  30323. propBinding = binding.binding,
  30324. rootUuid = propBinding.rootNode.uuid,
  30325. trackName = propBinding.path,
  30326. bindingsByRoot = this._bindingsByRootAndName,
  30327. bindingByName = bindingsByRoot[ rootUuid ],
  30328. lastInactiveBinding = bindings[ bindings.length - 1 ],
  30329. cacheIndex = binding._cacheIndex;
  30330. lastInactiveBinding._cacheIndex = cacheIndex;
  30331. bindings[ cacheIndex ] = lastInactiveBinding;
  30332. bindings.pop();
  30333. delete bindingByName[ trackName ];
  30334. if ( Object.keys( bindingByName ).length === 0 ) {
  30335. delete bindingsByRoot[ rootUuid ];
  30336. }
  30337. }
  30338. _lendBinding( binding ) {
  30339. const bindings = this._bindings,
  30340. prevIndex = binding._cacheIndex,
  30341. lastActiveIndex = this._nActiveBindings ++,
  30342. firstInactiveBinding = bindings[ lastActiveIndex ];
  30343. binding._cacheIndex = lastActiveIndex;
  30344. bindings[ lastActiveIndex ] = binding;
  30345. firstInactiveBinding._cacheIndex = prevIndex;
  30346. bindings[ prevIndex ] = firstInactiveBinding;
  30347. }
  30348. _takeBackBinding( binding ) {
  30349. const bindings = this._bindings,
  30350. prevIndex = binding._cacheIndex,
  30351. firstInactiveIndex = -- this._nActiveBindings,
  30352. lastActiveBinding = bindings[ firstInactiveIndex ];
  30353. binding._cacheIndex = firstInactiveIndex;
  30354. bindings[ firstInactiveIndex ] = binding;
  30355. lastActiveBinding._cacheIndex = prevIndex;
  30356. bindings[ prevIndex ] = lastActiveBinding;
  30357. }
  30358. // Memory management of Interpolants for weight and time scale
  30359. _lendControlInterpolant() {
  30360. const interpolants = this._controlInterpolants,
  30361. lastActiveIndex = this._nActiveControlInterpolants ++;
  30362. let interpolant = interpolants[ lastActiveIndex ];
  30363. if ( interpolant === undefined ) {
  30364. interpolant = new LinearInterpolant(
  30365. new Float32Array( 2 ), new Float32Array( 2 ),
  30366. 1, _controlInterpolantsResultBuffer );
  30367. interpolant.__cacheIndex = lastActiveIndex;
  30368. interpolants[ lastActiveIndex ] = interpolant;
  30369. }
  30370. return interpolant;
  30371. }
  30372. _takeBackControlInterpolant( interpolant ) {
  30373. const interpolants = this._controlInterpolants,
  30374. prevIndex = interpolant.__cacheIndex,
  30375. firstInactiveIndex = -- this._nActiveControlInterpolants,
  30376. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  30377. interpolant.__cacheIndex = firstInactiveIndex;
  30378. interpolants[ firstInactiveIndex ] = interpolant;
  30379. lastActiveInterpolant.__cacheIndex = prevIndex;
  30380. interpolants[ prevIndex ] = lastActiveInterpolant;
  30381. }
  30382. // return an action for a clip optionally using a custom root target
  30383. // object (this method allocates a lot of dynamic memory in case a
  30384. // previously unknown clip/root combination is specified)
  30385. clipAction( clip, optionalRoot, blendMode ) {
  30386. const root = optionalRoot || this._root,
  30387. rootUuid = root.uuid;
  30388. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  30389. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  30390. const actionsForClip = this._actionsByClip[ clipUuid ];
  30391. let prototypeAction = null;
  30392. if ( blendMode === undefined ) {
  30393. if ( clipObject !== null ) {
  30394. blendMode = clipObject.blendMode;
  30395. } else {
  30396. blendMode = NormalAnimationBlendMode;
  30397. }
  30398. }
  30399. if ( actionsForClip !== undefined ) {
  30400. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  30401. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  30402. return existingAction;
  30403. }
  30404. // we know the clip, so we don't have to parse all
  30405. // the bindings again but can just copy
  30406. prototypeAction = actionsForClip.knownActions[ 0 ];
  30407. // also, take the clip from the prototype action
  30408. if ( clipObject === null )
  30409. clipObject = prototypeAction._clip;
  30410. }
  30411. // clip must be known when specified via string
  30412. if ( clipObject === null ) return null;
  30413. // allocate all resources required to run it
  30414. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  30415. this._bindAction( newAction, prototypeAction );
  30416. // and make the action known to the memory manager
  30417. this._addInactiveAction( newAction, clipUuid, rootUuid );
  30418. return newAction;
  30419. }
  30420. // get an existing action
  30421. existingAction( clip, optionalRoot ) {
  30422. const root = optionalRoot || this._root,
  30423. rootUuid = root.uuid,
  30424. clipObject = typeof clip === 'string' ?
  30425. AnimationClip.findByName( root, clip ) : clip,
  30426. clipUuid = clipObject ? clipObject.uuid : clip,
  30427. actionsForClip = this._actionsByClip[ clipUuid ];
  30428. if ( actionsForClip !== undefined ) {
  30429. return actionsForClip.actionByRoot[ rootUuid ] || null;
  30430. }
  30431. return null;
  30432. }
  30433. // deactivates all previously scheduled actions
  30434. stopAllAction() {
  30435. const actions = this._actions,
  30436. nActions = this._nActiveActions;
  30437. for ( let i = nActions - 1; i >= 0; -- i ) {
  30438. actions[ i ].stop();
  30439. }
  30440. return this;
  30441. }
  30442. // advance the time and update apply the animation
  30443. update( deltaTime ) {
  30444. deltaTime *= this.timeScale;
  30445. const actions = this._actions,
  30446. nActions = this._nActiveActions,
  30447. time = this.time += deltaTime,
  30448. timeDirection = Math.sign( deltaTime ),
  30449. accuIndex = this._accuIndex ^= 1;
  30450. // run active actions
  30451. for ( let i = 0; i !== nActions; ++ i ) {
  30452. const action = actions[ i ];
  30453. action._update( time, deltaTime, timeDirection, accuIndex );
  30454. }
  30455. // update scene graph
  30456. const bindings = this._bindings,
  30457. nBindings = this._nActiveBindings;
  30458. for ( let i = 0; i !== nBindings; ++ i ) {
  30459. bindings[ i ].apply( accuIndex );
  30460. }
  30461. return this;
  30462. }
  30463. // Allows you to seek to a specific time in an animation.
  30464. setTime( timeInSeconds ) {
  30465. this.time = 0; // Zero out time attribute for AnimationMixer object;
  30466. for ( let i = 0; i < this._actions.length; i ++ ) {
  30467. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  30468. }
  30469. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  30470. }
  30471. // return this mixer's root target object
  30472. getRoot() {
  30473. return this._root;
  30474. }
  30475. // free all resources specific to a particular clip
  30476. uncacheClip( clip ) {
  30477. const actions = this._actions,
  30478. clipUuid = clip.uuid,
  30479. actionsByClip = this._actionsByClip,
  30480. actionsForClip = actionsByClip[ clipUuid ];
  30481. if ( actionsForClip !== undefined ) {
  30482. // note: just calling _removeInactiveAction would mess up the
  30483. // iteration state and also require updating the state we can
  30484. // just throw away
  30485. const actionsToRemove = actionsForClip.knownActions;
  30486. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  30487. const action = actionsToRemove[ i ];
  30488. this._deactivateAction( action );
  30489. const cacheIndex = action._cacheIndex,
  30490. lastInactiveAction = actions[ actions.length - 1 ];
  30491. action._cacheIndex = null;
  30492. action._byClipCacheIndex = null;
  30493. lastInactiveAction._cacheIndex = cacheIndex;
  30494. actions[ cacheIndex ] = lastInactiveAction;
  30495. actions.pop();
  30496. this._removeInactiveBindingsForAction( action );
  30497. }
  30498. delete actionsByClip[ clipUuid ];
  30499. }
  30500. }
  30501. // free all resources specific to a particular root target object
  30502. uncacheRoot( root ) {
  30503. const rootUuid = root.uuid,
  30504. actionsByClip = this._actionsByClip;
  30505. for ( const clipUuid in actionsByClip ) {
  30506. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  30507. action = actionByRoot[ rootUuid ];
  30508. if ( action !== undefined ) {
  30509. this._deactivateAction( action );
  30510. this._removeInactiveAction( action );
  30511. }
  30512. }
  30513. const bindingsByRoot = this._bindingsByRootAndName,
  30514. bindingByName = bindingsByRoot[ rootUuid ];
  30515. if ( bindingByName !== undefined ) {
  30516. for ( const trackName in bindingByName ) {
  30517. const binding = bindingByName[ trackName ];
  30518. binding.restoreOriginalState();
  30519. this._removeInactiveBinding( binding );
  30520. }
  30521. }
  30522. }
  30523. // remove a targeted clip from the cache
  30524. uncacheAction( clip, optionalRoot ) {
  30525. const action = this.existingAction( clip, optionalRoot );
  30526. if ( action !== null ) {
  30527. this._deactivateAction( action );
  30528. this._removeInactiveAction( action );
  30529. }
  30530. }
  30531. }
  30532. class Uniform {
  30533. constructor( value ) {
  30534. this.value = value;
  30535. }
  30536. clone() {
  30537. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  30538. }
  30539. }
  30540. let _id = 0;
  30541. class UniformsGroup extends EventDispatcher {
  30542. constructor() {
  30543. super();
  30544. this.isUniformsGroup = true;
  30545. Object.defineProperty( this, 'id', { value: _id ++ } );
  30546. this.name = '';
  30547. this.usage = StaticDrawUsage;
  30548. this.uniforms = [];
  30549. }
  30550. add( uniform ) {
  30551. this.uniforms.push( uniform );
  30552. return this;
  30553. }
  30554. remove( uniform ) {
  30555. const index = this.uniforms.indexOf( uniform );
  30556. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  30557. return this;
  30558. }
  30559. setName( name ) {
  30560. this.name = name;
  30561. return this;
  30562. }
  30563. setUsage( value ) {
  30564. this.usage = value;
  30565. return this;
  30566. }
  30567. dispose() {
  30568. this.dispatchEvent( { type: 'dispose' } );
  30569. return this;
  30570. }
  30571. copy( source ) {
  30572. this.name = source.name;
  30573. this.usage = source.usage;
  30574. const uniformsSource = source.uniforms;
  30575. this.uniforms.length = 0;
  30576. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  30577. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  30578. for ( let j = 0; j < uniforms.length; j ++ ) {
  30579. this.uniforms.push( uniforms[ j ].clone() );
  30580. }
  30581. }
  30582. return this;
  30583. }
  30584. clone() {
  30585. return new this.constructor().copy( this );
  30586. }
  30587. }
  30588. class InstancedInterleavedBuffer extends InterleavedBuffer {
  30589. constructor( array, stride, meshPerAttribute = 1 ) {
  30590. super( array, stride );
  30591. this.isInstancedInterleavedBuffer = true;
  30592. this.meshPerAttribute = meshPerAttribute;
  30593. }
  30594. copy( source ) {
  30595. super.copy( source );
  30596. this.meshPerAttribute = source.meshPerAttribute;
  30597. return this;
  30598. }
  30599. clone( data ) {
  30600. const ib = super.clone( data );
  30601. ib.meshPerAttribute = this.meshPerAttribute;
  30602. return ib;
  30603. }
  30604. toJSON( data ) {
  30605. const json = super.toJSON( data );
  30606. json.isInstancedInterleavedBuffer = true;
  30607. json.meshPerAttribute = this.meshPerAttribute;
  30608. return json;
  30609. }
  30610. }
  30611. class GLBufferAttribute {
  30612. constructor( buffer, type, itemSize, elementSize, count ) {
  30613. this.isGLBufferAttribute = true;
  30614. this.name = '';
  30615. this.buffer = buffer;
  30616. this.type = type;
  30617. this.itemSize = itemSize;
  30618. this.elementSize = elementSize;
  30619. this.count = count;
  30620. this.version = 0;
  30621. }
  30622. set needsUpdate( value ) {
  30623. if ( value === true ) this.version ++;
  30624. }
  30625. setBuffer( buffer ) {
  30626. this.buffer = buffer;
  30627. return this;
  30628. }
  30629. setType( type, elementSize ) {
  30630. this.type = type;
  30631. this.elementSize = elementSize;
  30632. return this;
  30633. }
  30634. setItemSize( itemSize ) {
  30635. this.itemSize = itemSize;
  30636. return this;
  30637. }
  30638. setCount( count ) {
  30639. this.count = count;
  30640. return this;
  30641. }
  30642. }
  30643. const _matrix = /*@__PURE__*/ new Matrix4();
  30644. class Raycaster {
  30645. constructor( origin, direction, near = 0, far = Infinity ) {
  30646. this.ray = new Ray( origin, direction );
  30647. // direction is assumed to be normalized (for accurate distance calculations)
  30648. this.near = near;
  30649. this.far = far;
  30650. this.camera = null;
  30651. this.layers = new Layers();
  30652. this.params = {
  30653. Mesh: {},
  30654. Line: { threshold: 1 },
  30655. LOD: {},
  30656. Points: { threshold: 1 },
  30657. Sprite: {}
  30658. };
  30659. }
  30660. set( origin, direction ) {
  30661. // direction is assumed to be normalized (for accurate distance calculations)
  30662. this.ray.set( origin, direction );
  30663. }
  30664. setFromCamera( coords, camera ) {
  30665. if ( camera.isPerspectiveCamera ) {
  30666. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30667. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30668. this.camera = camera;
  30669. } else if ( camera.isOrthographicCamera ) {
  30670. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30671. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  30672. this.camera = camera;
  30673. } else {
  30674. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  30675. }
  30676. }
  30677. setFromXRController( controller ) {
  30678. _matrix.identity().extractRotation( controller.matrixWorld );
  30679. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  30680. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  30681. return this;
  30682. }
  30683. intersectObject( object, recursive = true, intersects = [] ) {
  30684. intersect( object, this, intersects, recursive );
  30685. intersects.sort( ascSort );
  30686. return intersects;
  30687. }
  30688. intersectObjects( objects, recursive = true, intersects = [] ) {
  30689. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  30690. intersect( objects[ i ], this, intersects, recursive );
  30691. }
  30692. intersects.sort( ascSort );
  30693. return intersects;
  30694. }
  30695. }
  30696. function ascSort( a, b ) {
  30697. return a.distance - b.distance;
  30698. }
  30699. function intersect( object, raycaster, intersects, recursive ) {
  30700. let propagate = true;
  30701. if ( object.layers.test( raycaster.layers ) ) {
  30702. const result = object.raycast( raycaster, intersects );
  30703. if ( result === false ) propagate = false;
  30704. }
  30705. if ( propagate === true && recursive === true ) {
  30706. const children = object.children;
  30707. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30708. intersect( children[ i ], raycaster, intersects, true );
  30709. }
  30710. }
  30711. }
  30712. /**
  30713. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  30714. *
  30715. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  30716. * theta (the azimuthal angle) is measured from the positive z-axis.
  30717. */
  30718. class Spherical {
  30719. constructor( radius = 1, phi = 0, theta = 0 ) {
  30720. this.radius = radius;
  30721. this.phi = phi; // polar angle
  30722. this.theta = theta; // azimuthal angle
  30723. return this;
  30724. }
  30725. set( radius, phi, theta ) {
  30726. this.radius = radius;
  30727. this.phi = phi;
  30728. this.theta = theta;
  30729. return this;
  30730. }
  30731. copy( other ) {
  30732. this.radius = other.radius;
  30733. this.phi = other.phi;
  30734. this.theta = other.theta;
  30735. return this;
  30736. }
  30737. // restrict phi to be between EPS and PI-EPS
  30738. makeSafe() {
  30739. const EPS = 0.000001;
  30740. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  30741. return this;
  30742. }
  30743. setFromVector3( v ) {
  30744. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30745. }
  30746. setFromCartesianCoords( x, y, z ) {
  30747. this.radius = Math.sqrt( x * x + y * y + z * z );
  30748. if ( this.radius === 0 ) {
  30749. this.theta = 0;
  30750. this.phi = 0;
  30751. } else {
  30752. this.theta = Math.atan2( x, z );
  30753. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  30754. }
  30755. return this;
  30756. }
  30757. clone() {
  30758. return new this.constructor().copy( this );
  30759. }
  30760. }
  30761. /**
  30762. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  30763. */
  30764. class Cylindrical {
  30765. constructor( radius = 1, theta = 0, y = 0 ) {
  30766. this.radius = radius; // distance from the origin to a point in the x-z plane
  30767. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  30768. this.y = y; // height above the x-z plane
  30769. return this;
  30770. }
  30771. set( radius, theta, y ) {
  30772. this.radius = radius;
  30773. this.theta = theta;
  30774. this.y = y;
  30775. return this;
  30776. }
  30777. copy( other ) {
  30778. this.radius = other.radius;
  30779. this.theta = other.theta;
  30780. this.y = other.y;
  30781. return this;
  30782. }
  30783. setFromVector3( v ) {
  30784. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30785. }
  30786. setFromCartesianCoords( x, y, z ) {
  30787. this.radius = Math.sqrt( x * x + z * z );
  30788. this.theta = Math.atan2( x, z );
  30789. this.y = y;
  30790. return this;
  30791. }
  30792. clone() {
  30793. return new this.constructor().copy( this );
  30794. }
  30795. }
  30796. class Matrix2 {
  30797. constructor( n11, n12, n21, n22 ) {
  30798. Matrix2.prototype.isMatrix2 = true;
  30799. this.elements = [
  30800. 1, 0,
  30801. 0, 1,
  30802. ];
  30803. if ( n11 !== undefined ) {
  30804. this.set( n11, n12, n21, n22 );
  30805. }
  30806. }
  30807. identity() {
  30808. this.set(
  30809. 1, 0,
  30810. 0, 1,
  30811. );
  30812. return this;
  30813. }
  30814. fromArray( array, offset = 0 ) {
  30815. for ( let i = 0; i < 4; i ++ ) {
  30816. this.elements[ i ] = array[ i + offset ];
  30817. }
  30818. return this;
  30819. }
  30820. set( n11, n12, n21, n22 ) {
  30821. const te = this.elements;
  30822. te[ 0 ] = n11; te[ 2 ] = n12;
  30823. te[ 1 ] = n21; te[ 3 ] = n22;
  30824. return this;
  30825. }
  30826. }
  30827. const _vector$4 = /*@__PURE__*/ new Vector2();
  30828. class Box2 {
  30829. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  30830. this.isBox2 = true;
  30831. this.min = min;
  30832. this.max = max;
  30833. }
  30834. set( min, max ) {
  30835. this.min.copy( min );
  30836. this.max.copy( max );
  30837. return this;
  30838. }
  30839. setFromPoints( points ) {
  30840. this.makeEmpty();
  30841. for ( let i = 0, il = points.length; i < il; i ++ ) {
  30842. this.expandByPoint( points[ i ] );
  30843. }
  30844. return this;
  30845. }
  30846. setFromCenterAndSize( center, size ) {
  30847. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  30848. this.min.copy( center ).sub( halfSize );
  30849. this.max.copy( center ).add( halfSize );
  30850. return this;
  30851. }
  30852. clone() {
  30853. return new this.constructor().copy( this );
  30854. }
  30855. copy( box ) {
  30856. this.min.copy( box.min );
  30857. this.max.copy( box.max );
  30858. return this;
  30859. }
  30860. makeEmpty() {
  30861. this.min.x = this.min.y = + Infinity;
  30862. this.max.x = this.max.y = - Infinity;
  30863. return this;
  30864. }
  30865. isEmpty() {
  30866. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  30867. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  30868. }
  30869. getCenter( target ) {
  30870. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  30871. }
  30872. getSize( target ) {
  30873. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  30874. }
  30875. expandByPoint( point ) {
  30876. this.min.min( point );
  30877. this.max.max( point );
  30878. return this;
  30879. }
  30880. expandByVector( vector ) {
  30881. this.min.sub( vector );
  30882. this.max.add( vector );
  30883. return this;
  30884. }
  30885. expandByScalar( scalar ) {
  30886. this.min.addScalar( - scalar );
  30887. this.max.addScalar( scalar );
  30888. return this;
  30889. }
  30890. containsPoint( point ) {
  30891. return point.x >= this.min.x && point.x <= this.max.x &&
  30892. point.y >= this.min.y && point.y <= this.max.y;
  30893. }
  30894. containsBox( box ) {
  30895. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  30896. this.min.y <= box.min.y && box.max.y <= this.max.y;
  30897. }
  30898. getParameter( point, target ) {
  30899. // This can potentially have a divide by zero if the box
  30900. // has a size dimension of 0.
  30901. return target.set(
  30902. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  30903. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  30904. );
  30905. }
  30906. intersectsBox( box ) {
  30907. // using 4 splitting planes to rule out intersections
  30908. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  30909. box.max.y >= this.min.y && box.min.y <= this.max.y;
  30910. }
  30911. clampPoint( point, target ) {
  30912. return target.copy( point ).clamp( this.min, this.max );
  30913. }
  30914. distanceToPoint( point ) {
  30915. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  30916. }
  30917. intersect( box ) {
  30918. this.min.max( box.min );
  30919. this.max.min( box.max );
  30920. if ( this.isEmpty() ) this.makeEmpty();
  30921. return this;
  30922. }
  30923. union( box ) {
  30924. this.min.min( box.min );
  30925. this.max.max( box.max );
  30926. return this;
  30927. }
  30928. translate( offset ) {
  30929. this.min.add( offset );
  30930. this.max.add( offset );
  30931. return this;
  30932. }
  30933. equals( box ) {
  30934. return box.min.equals( this.min ) && box.max.equals( this.max );
  30935. }
  30936. }
  30937. const _startP = /*@__PURE__*/ new Vector3();
  30938. const _startEnd = /*@__PURE__*/ new Vector3();
  30939. class Line3 {
  30940. constructor( start = new Vector3(), end = new Vector3() ) {
  30941. this.start = start;
  30942. this.end = end;
  30943. }
  30944. set( start, end ) {
  30945. this.start.copy( start );
  30946. this.end.copy( end );
  30947. return this;
  30948. }
  30949. copy( line ) {
  30950. this.start.copy( line.start );
  30951. this.end.copy( line.end );
  30952. return this;
  30953. }
  30954. getCenter( target ) {
  30955. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  30956. }
  30957. delta( target ) {
  30958. return target.subVectors( this.end, this.start );
  30959. }
  30960. distanceSq() {
  30961. return this.start.distanceToSquared( this.end );
  30962. }
  30963. distance() {
  30964. return this.start.distanceTo( this.end );
  30965. }
  30966. at( t, target ) {
  30967. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30968. }
  30969. closestPointToPointParameter( point, clampToLine ) {
  30970. _startP.subVectors( point, this.start );
  30971. _startEnd.subVectors( this.end, this.start );
  30972. const startEnd2 = _startEnd.dot( _startEnd );
  30973. const startEnd_startP = _startEnd.dot( _startP );
  30974. let t = startEnd_startP / startEnd2;
  30975. if ( clampToLine ) {
  30976. t = clamp( t, 0, 1 );
  30977. }
  30978. return t;
  30979. }
  30980. closestPointToPoint( point, clampToLine, target ) {
  30981. const t = this.closestPointToPointParameter( point, clampToLine );
  30982. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30983. }
  30984. applyMatrix4( matrix ) {
  30985. this.start.applyMatrix4( matrix );
  30986. this.end.applyMatrix4( matrix );
  30987. return this;
  30988. }
  30989. equals( line ) {
  30990. return line.start.equals( this.start ) && line.end.equals( this.end );
  30991. }
  30992. clone() {
  30993. return new this.constructor().copy( this );
  30994. }
  30995. }
  30996. const _vector$3 = /*@__PURE__*/ new Vector3();
  30997. class SpotLightHelper extends Object3D {
  30998. constructor( light, color ) {
  30999. super();
  31000. this.light = light;
  31001. this.matrixAutoUpdate = false;
  31002. this.color = color;
  31003. this.type = 'SpotLightHelper';
  31004. const geometry = new BufferGeometry();
  31005. const positions = [
  31006. 0, 0, 0, 0, 0, 1,
  31007. 0, 0, 0, 1, 0, 1,
  31008. 0, 0, 0, - 1, 0, 1,
  31009. 0, 0, 0, 0, 1, 1,
  31010. 0, 0, 0, 0, - 1, 1
  31011. ];
  31012. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  31013. const p1 = ( i / l ) * Math.PI * 2;
  31014. const p2 = ( j / l ) * Math.PI * 2;
  31015. positions.push(
  31016. Math.cos( p1 ), Math.sin( p1 ), 1,
  31017. Math.cos( p2 ), Math.sin( p2 ), 1
  31018. );
  31019. }
  31020. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31021. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  31022. this.cone = new LineSegments( geometry, material );
  31023. this.add( this.cone );
  31024. this.update();
  31025. }
  31026. dispose() {
  31027. this.cone.geometry.dispose();
  31028. this.cone.material.dispose();
  31029. }
  31030. update() {
  31031. this.light.updateWorldMatrix( true, false );
  31032. this.light.target.updateWorldMatrix( true, false );
  31033. // update the local matrix based on the parent and light target transforms
  31034. if ( this.parent ) {
  31035. this.parent.updateWorldMatrix( true );
  31036. this.matrix
  31037. .copy( this.parent.matrixWorld )
  31038. .invert()
  31039. .multiply( this.light.matrixWorld );
  31040. } else {
  31041. this.matrix.copy( this.light.matrixWorld );
  31042. }
  31043. this.matrixWorld.copy( this.light.matrixWorld );
  31044. const coneLength = this.light.distance ? this.light.distance : 1000;
  31045. const coneWidth = coneLength * Math.tan( this.light.angle );
  31046. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  31047. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  31048. this.cone.lookAt( _vector$3 );
  31049. if ( this.color !== undefined ) {
  31050. this.cone.material.color.set( this.color );
  31051. } else {
  31052. this.cone.material.color.copy( this.light.color );
  31053. }
  31054. }
  31055. }
  31056. const _vector$2 = /*@__PURE__*/ new Vector3();
  31057. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  31058. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  31059. class SkeletonHelper extends LineSegments {
  31060. constructor( object ) {
  31061. const bones = getBoneList( object );
  31062. const geometry = new BufferGeometry();
  31063. const vertices = [];
  31064. const colors = [];
  31065. const color1 = new Color( 0, 0, 1 );
  31066. const color2 = new Color( 0, 1, 0 );
  31067. for ( let i = 0; i < bones.length; i ++ ) {
  31068. const bone = bones[ i ];
  31069. if ( bone.parent && bone.parent.isBone ) {
  31070. vertices.push( 0, 0, 0 );
  31071. vertices.push( 0, 0, 0 );
  31072. colors.push( color1.r, color1.g, color1.b );
  31073. colors.push( color2.r, color2.g, color2.b );
  31074. }
  31075. }
  31076. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31077. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31078. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  31079. super( geometry, material );
  31080. this.isSkeletonHelper = true;
  31081. this.type = 'SkeletonHelper';
  31082. this.root = object;
  31083. this.bones = bones;
  31084. this.matrix = object.matrixWorld;
  31085. this.matrixAutoUpdate = false;
  31086. }
  31087. updateMatrixWorld( force ) {
  31088. const bones = this.bones;
  31089. const geometry = this.geometry;
  31090. const position = geometry.getAttribute( 'position' );
  31091. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  31092. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  31093. const bone = bones[ i ];
  31094. if ( bone.parent && bone.parent.isBone ) {
  31095. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  31096. _vector$2.setFromMatrixPosition( _boneMatrix );
  31097. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  31098. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  31099. _vector$2.setFromMatrixPosition( _boneMatrix );
  31100. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  31101. j += 2;
  31102. }
  31103. }
  31104. geometry.getAttribute( 'position' ).needsUpdate = true;
  31105. super.updateMatrixWorld( force );
  31106. }
  31107. dispose() {
  31108. this.geometry.dispose();
  31109. this.material.dispose();
  31110. }
  31111. }
  31112. function getBoneList( object ) {
  31113. const boneList = [];
  31114. if ( object.isBone === true ) {
  31115. boneList.push( object );
  31116. }
  31117. for ( let i = 0; i < object.children.length; i ++ ) {
  31118. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  31119. }
  31120. return boneList;
  31121. }
  31122. class PointLightHelper extends Mesh {
  31123. constructor( light, sphereSize, color ) {
  31124. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  31125. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  31126. super( geometry, material );
  31127. this.light = light;
  31128. this.color = color;
  31129. this.type = 'PointLightHelper';
  31130. this.matrix = this.light.matrixWorld;
  31131. this.matrixAutoUpdate = false;
  31132. this.update();
  31133. /*
  31134. // TODO: delete this comment?
  31135. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  31136. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  31137. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  31138. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  31139. const d = light.distance;
  31140. if ( d === 0.0 ) {
  31141. this.lightDistance.visible = false;
  31142. } else {
  31143. this.lightDistance.scale.set( d, d, d );
  31144. }
  31145. this.add( this.lightDistance );
  31146. */
  31147. }
  31148. dispose() {
  31149. this.geometry.dispose();
  31150. this.material.dispose();
  31151. }
  31152. update() {
  31153. this.light.updateWorldMatrix( true, false );
  31154. if ( this.color !== undefined ) {
  31155. this.material.color.set( this.color );
  31156. } else {
  31157. this.material.color.copy( this.light.color );
  31158. }
  31159. /*
  31160. const d = this.light.distance;
  31161. if ( d === 0.0 ) {
  31162. this.lightDistance.visible = false;
  31163. } else {
  31164. this.lightDistance.visible = true;
  31165. this.lightDistance.scale.set( d, d, d );
  31166. }
  31167. */
  31168. }
  31169. }
  31170. const _vector$1 = /*@__PURE__*/ new Vector3();
  31171. const _color1 = /*@__PURE__*/ new Color();
  31172. const _color2 = /*@__PURE__*/ new Color();
  31173. class HemisphereLightHelper extends Object3D {
  31174. constructor( light, size, color ) {
  31175. super();
  31176. this.light = light;
  31177. this.matrix = light.matrixWorld;
  31178. this.matrixAutoUpdate = false;
  31179. this.color = color;
  31180. this.type = 'HemisphereLightHelper';
  31181. const geometry = new OctahedronGeometry( size );
  31182. geometry.rotateY( Math.PI * 0.5 );
  31183. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  31184. if ( this.color === undefined ) this.material.vertexColors = true;
  31185. const position = geometry.getAttribute( 'position' );
  31186. const colors = new Float32Array( position.count * 3 );
  31187. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  31188. this.add( new Mesh( geometry, this.material ) );
  31189. this.update();
  31190. }
  31191. dispose() {
  31192. this.children[ 0 ].geometry.dispose();
  31193. this.children[ 0 ].material.dispose();
  31194. }
  31195. update() {
  31196. const mesh = this.children[ 0 ];
  31197. if ( this.color !== undefined ) {
  31198. this.material.color.set( this.color );
  31199. } else {
  31200. const colors = mesh.geometry.getAttribute( 'color' );
  31201. _color1.copy( this.light.color );
  31202. _color2.copy( this.light.groundColor );
  31203. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  31204. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  31205. colors.setXYZ( i, color.r, color.g, color.b );
  31206. }
  31207. colors.needsUpdate = true;
  31208. }
  31209. this.light.updateWorldMatrix( true, false );
  31210. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  31211. }
  31212. }
  31213. class GridHelper extends LineSegments {
  31214. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  31215. color1 = new Color( color1 );
  31216. color2 = new Color( color2 );
  31217. const center = divisions / 2;
  31218. const step = size / divisions;
  31219. const halfSize = size / 2;
  31220. const vertices = [], colors = [];
  31221. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  31222. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  31223. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  31224. const color = i === center ? color1 : color2;
  31225. color.toArray( colors, j ); j += 3;
  31226. color.toArray( colors, j ); j += 3;
  31227. color.toArray( colors, j ); j += 3;
  31228. color.toArray( colors, j ); j += 3;
  31229. }
  31230. const geometry = new BufferGeometry();
  31231. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31232. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31233. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31234. super( geometry, material );
  31235. this.type = 'GridHelper';
  31236. }
  31237. dispose() {
  31238. this.geometry.dispose();
  31239. this.material.dispose();
  31240. }
  31241. }
  31242. class PolarGridHelper extends LineSegments {
  31243. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  31244. color1 = new Color( color1 );
  31245. color2 = new Color( color2 );
  31246. const vertices = [];
  31247. const colors = [];
  31248. // create the sectors
  31249. if ( sectors > 1 ) {
  31250. for ( let i = 0; i < sectors; i ++ ) {
  31251. const v = ( i / sectors ) * ( Math.PI * 2 );
  31252. const x = Math.sin( v ) * radius;
  31253. const z = Math.cos( v ) * radius;
  31254. vertices.push( 0, 0, 0 );
  31255. vertices.push( x, 0, z );
  31256. const color = ( i & 1 ) ? color1 : color2;
  31257. colors.push( color.r, color.g, color.b );
  31258. colors.push( color.r, color.g, color.b );
  31259. }
  31260. }
  31261. // create the rings
  31262. for ( let i = 0; i < rings; i ++ ) {
  31263. const color = ( i & 1 ) ? color1 : color2;
  31264. const r = radius - ( radius / rings * i );
  31265. for ( let j = 0; j < divisions; j ++ ) {
  31266. // first vertex
  31267. let v = ( j / divisions ) * ( Math.PI * 2 );
  31268. let x = Math.sin( v ) * r;
  31269. let z = Math.cos( v ) * r;
  31270. vertices.push( x, 0, z );
  31271. colors.push( color.r, color.g, color.b );
  31272. // second vertex
  31273. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  31274. x = Math.sin( v ) * r;
  31275. z = Math.cos( v ) * r;
  31276. vertices.push( x, 0, z );
  31277. colors.push( color.r, color.g, color.b );
  31278. }
  31279. }
  31280. const geometry = new BufferGeometry();
  31281. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31282. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31283. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31284. super( geometry, material );
  31285. this.type = 'PolarGridHelper';
  31286. }
  31287. dispose() {
  31288. this.geometry.dispose();
  31289. this.material.dispose();
  31290. }
  31291. }
  31292. const _v1 = /*@__PURE__*/ new Vector3();
  31293. const _v2 = /*@__PURE__*/ new Vector3();
  31294. const _v3 = /*@__PURE__*/ new Vector3();
  31295. class DirectionalLightHelper extends Object3D {
  31296. constructor( light, size, color ) {
  31297. super();
  31298. this.light = light;
  31299. this.matrix = light.matrixWorld;
  31300. this.matrixAutoUpdate = false;
  31301. this.color = color;
  31302. this.type = 'DirectionalLightHelper';
  31303. if ( size === undefined ) size = 1;
  31304. let geometry = new BufferGeometry();
  31305. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  31306. - size, size, 0,
  31307. size, size, 0,
  31308. size, - size, 0,
  31309. - size, - size, 0,
  31310. - size, size, 0
  31311. ], 3 ) );
  31312. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  31313. this.lightPlane = new Line( geometry, material );
  31314. this.add( this.lightPlane );
  31315. geometry = new BufferGeometry();
  31316. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  31317. this.targetLine = new Line( geometry, material );
  31318. this.add( this.targetLine );
  31319. this.update();
  31320. }
  31321. dispose() {
  31322. this.lightPlane.geometry.dispose();
  31323. this.lightPlane.material.dispose();
  31324. this.targetLine.geometry.dispose();
  31325. this.targetLine.material.dispose();
  31326. }
  31327. update() {
  31328. this.light.updateWorldMatrix( true, false );
  31329. this.light.target.updateWorldMatrix( true, false );
  31330. _v1.setFromMatrixPosition( this.light.matrixWorld );
  31331. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  31332. _v3.subVectors( _v2, _v1 );
  31333. this.lightPlane.lookAt( _v2 );
  31334. if ( this.color !== undefined ) {
  31335. this.lightPlane.material.color.set( this.color );
  31336. this.targetLine.material.color.set( this.color );
  31337. } else {
  31338. this.lightPlane.material.color.copy( this.light.color );
  31339. this.targetLine.material.color.copy( this.light.color );
  31340. }
  31341. this.targetLine.lookAt( _v2 );
  31342. this.targetLine.scale.z = _v3.length();
  31343. }
  31344. }
  31345. const _vector = /*@__PURE__*/ new Vector3();
  31346. const _camera = /*@__PURE__*/ new Camera();
  31347. /**
  31348. * - shows frustum, line of sight and up of the camera
  31349. * - suitable for fast updates
  31350. * - based on frustum visualization in lightgl.js shadowmap example
  31351. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  31352. */
  31353. class CameraHelper extends LineSegments {
  31354. constructor( camera ) {
  31355. const geometry = new BufferGeometry();
  31356. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  31357. const vertices = [];
  31358. const colors = [];
  31359. const pointMap = {};
  31360. // near
  31361. addLine( 'n1', 'n2' );
  31362. addLine( 'n2', 'n4' );
  31363. addLine( 'n4', 'n3' );
  31364. addLine( 'n3', 'n1' );
  31365. // far
  31366. addLine( 'f1', 'f2' );
  31367. addLine( 'f2', 'f4' );
  31368. addLine( 'f4', 'f3' );
  31369. addLine( 'f3', 'f1' );
  31370. // sides
  31371. addLine( 'n1', 'f1' );
  31372. addLine( 'n2', 'f2' );
  31373. addLine( 'n3', 'f3' );
  31374. addLine( 'n4', 'f4' );
  31375. // cone
  31376. addLine( 'p', 'n1' );
  31377. addLine( 'p', 'n2' );
  31378. addLine( 'p', 'n3' );
  31379. addLine( 'p', 'n4' );
  31380. // up
  31381. addLine( 'u1', 'u2' );
  31382. addLine( 'u2', 'u3' );
  31383. addLine( 'u3', 'u1' );
  31384. // target
  31385. addLine( 'c', 't' );
  31386. addLine( 'p', 'c' );
  31387. // cross
  31388. addLine( 'cn1', 'cn2' );
  31389. addLine( 'cn3', 'cn4' );
  31390. addLine( 'cf1', 'cf2' );
  31391. addLine( 'cf3', 'cf4' );
  31392. function addLine( a, b ) {
  31393. addPoint( a );
  31394. addPoint( b );
  31395. }
  31396. function addPoint( id ) {
  31397. vertices.push( 0, 0, 0 );
  31398. colors.push( 0, 0, 0 );
  31399. if ( pointMap[ id ] === undefined ) {
  31400. pointMap[ id ] = [];
  31401. }
  31402. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  31403. }
  31404. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31405. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31406. super( geometry, material );
  31407. this.type = 'CameraHelper';
  31408. this.camera = camera;
  31409. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  31410. this.matrix = camera.matrixWorld;
  31411. this.matrixAutoUpdate = false;
  31412. this.pointMap = pointMap;
  31413. this.update();
  31414. // colors
  31415. const colorFrustum = new Color( 0xffaa00 );
  31416. const colorCone = new Color( 0xff0000 );
  31417. const colorUp = new Color( 0x00aaff );
  31418. const colorTarget = new Color( 0xffffff );
  31419. const colorCross = new Color( 0x333333 );
  31420. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  31421. }
  31422. setColors( frustum, cone, up, target, cross ) {
  31423. const geometry = this.geometry;
  31424. const colorAttribute = geometry.getAttribute( 'color' );
  31425. // near
  31426. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  31427. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  31428. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  31429. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  31430. // far
  31431. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  31432. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  31433. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  31434. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  31435. // sides
  31436. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  31437. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  31438. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  31439. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  31440. // cone
  31441. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  31442. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  31443. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  31444. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  31445. // up
  31446. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  31447. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  31448. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  31449. // target
  31450. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  31451. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  31452. // cross
  31453. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  31454. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  31455. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  31456. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  31457. colorAttribute.needsUpdate = true;
  31458. }
  31459. update() {
  31460. const geometry = this.geometry;
  31461. const pointMap = this.pointMap;
  31462. const w = 1, h = 1;
  31463. // we need just camera projection matrix inverse
  31464. // world matrix must be identity
  31465. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  31466. // center / target
  31467. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  31468. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  31469. // near
  31470. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  31471. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  31472. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  31473. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  31474. // far
  31475. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  31476. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  31477. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  31478. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  31479. // up
  31480. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  31481. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  31482. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  31483. // cross
  31484. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  31485. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  31486. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  31487. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  31488. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  31489. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  31490. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  31491. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  31492. geometry.getAttribute( 'position' ).needsUpdate = true;
  31493. }
  31494. dispose() {
  31495. this.geometry.dispose();
  31496. this.material.dispose();
  31497. }
  31498. }
  31499. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  31500. _vector.set( x, y, z ).unproject( camera );
  31501. const points = pointMap[ point ];
  31502. if ( points !== undefined ) {
  31503. const position = geometry.getAttribute( 'position' );
  31504. for ( let i = 0, l = points.length; i < l; i ++ ) {
  31505. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  31506. }
  31507. }
  31508. }
  31509. const _box = /*@__PURE__*/ new Box3();
  31510. class BoxHelper extends LineSegments {
  31511. constructor( object, color = 0xffff00 ) {
  31512. 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 ] );
  31513. const positions = new Float32Array( 8 * 3 );
  31514. const geometry = new BufferGeometry();
  31515. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31516. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  31517. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31518. this.object = object;
  31519. this.type = 'BoxHelper';
  31520. this.matrixAutoUpdate = false;
  31521. this.update();
  31522. }
  31523. update( object ) {
  31524. if ( object !== undefined ) {
  31525. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  31526. }
  31527. if ( this.object !== undefined ) {
  31528. _box.setFromObject( this.object );
  31529. }
  31530. if ( _box.isEmpty() ) return;
  31531. const min = _box.min;
  31532. const max = _box.max;
  31533. /*
  31534. 5____4
  31535. 1/___0/|
  31536. | 6__|_7
  31537. 2/___3/
  31538. 0: max.x, max.y, max.z
  31539. 1: min.x, max.y, max.z
  31540. 2: min.x, min.y, max.z
  31541. 3: max.x, min.y, max.z
  31542. 4: max.x, max.y, min.z
  31543. 5: min.x, max.y, min.z
  31544. 6: min.x, min.y, min.z
  31545. 7: max.x, min.y, min.z
  31546. */
  31547. const position = this.geometry.attributes.position;
  31548. const array = position.array;
  31549. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  31550. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  31551. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  31552. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  31553. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  31554. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  31555. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  31556. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  31557. position.needsUpdate = true;
  31558. this.geometry.computeBoundingSphere();
  31559. }
  31560. setFromObject( object ) {
  31561. this.object = object;
  31562. this.update();
  31563. return this;
  31564. }
  31565. copy( source, recursive ) {
  31566. super.copy( source, recursive );
  31567. this.object = source.object;
  31568. return this;
  31569. }
  31570. dispose() {
  31571. this.geometry.dispose();
  31572. this.material.dispose();
  31573. }
  31574. }
  31575. class Box3Helper extends LineSegments {
  31576. constructor( box, color = 0xffff00 ) {
  31577. 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 ] );
  31578. 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 ];
  31579. const geometry = new BufferGeometry();
  31580. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31581. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31582. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31583. this.box = box;
  31584. this.type = 'Box3Helper';
  31585. this.geometry.computeBoundingSphere();
  31586. }
  31587. updateMatrixWorld( force ) {
  31588. const box = this.box;
  31589. if ( box.isEmpty() ) return;
  31590. box.getCenter( this.position );
  31591. box.getSize( this.scale );
  31592. this.scale.multiplyScalar( 0.5 );
  31593. super.updateMatrixWorld( force );
  31594. }
  31595. dispose() {
  31596. this.geometry.dispose();
  31597. this.material.dispose();
  31598. }
  31599. }
  31600. class PlaneHelper extends Line {
  31601. constructor( plane, size = 1, hex = 0xffff00 ) {
  31602. const color = hex;
  31603. 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 ];
  31604. const geometry = new BufferGeometry();
  31605. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31606. geometry.computeBoundingSphere();
  31607. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31608. this.type = 'PlaneHelper';
  31609. this.plane = plane;
  31610. this.size = size;
  31611. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  31612. const geometry2 = new BufferGeometry();
  31613. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  31614. geometry2.computeBoundingSphere();
  31615. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  31616. }
  31617. updateMatrixWorld( force ) {
  31618. this.position.set( 0, 0, 0 );
  31619. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  31620. this.lookAt( this.plane.normal );
  31621. this.translateZ( - this.plane.constant );
  31622. super.updateMatrixWorld( force );
  31623. }
  31624. dispose() {
  31625. this.geometry.dispose();
  31626. this.material.dispose();
  31627. this.children[ 0 ].geometry.dispose();
  31628. this.children[ 0 ].material.dispose();
  31629. }
  31630. }
  31631. const _axis = /*@__PURE__*/ new Vector3();
  31632. let _lineGeometry, _coneGeometry;
  31633. class ArrowHelper extends Object3D {
  31634. // dir is assumed to be normalized
  31635. 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 ) {
  31636. super();
  31637. this.type = 'ArrowHelper';
  31638. if ( _lineGeometry === undefined ) {
  31639. _lineGeometry = new BufferGeometry();
  31640. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  31641. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  31642. _coneGeometry.translate( 0, - 0.5, 0 );
  31643. }
  31644. this.position.copy( origin );
  31645. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31646. this.line.matrixAutoUpdate = false;
  31647. this.add( this.line );
  31648. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  31649. this.cone.matrixAutoUpdate = false;
  31650. this.add( this.cone );
  31651. this.setDirection( dir );
  31652. this.setLength( length, headLength, headWidth );
  31653. }
  31654. setDirection( dir ) {
  31655. // dir is assumed to be normalized
  31656. if ( dir.y > 0.99999 ) {
  31657. this.quaternion.set( 0, 0, 0, 1 );
  31658. } else if ( dir.y < - 0.99999 ) {
  31659. this.quaternion.set( 1, 0, 0, 0 );
  31660. } else {
  31661. _axis.set( dir.z, 0, - dir.x ).normalize();
  31662. const radians = Math.acos( dir.y );
  31663. this.quaternion.setFromAxisAngle( _axis, radians );
  31664. }
  31665. }
  31666. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  31667. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  31668. this.line.updateMatrix();
  31669. this.cone.scale.set( headWidth, headLength, headWidth );
  31670. this.cone.position.y = length;
  31671. this.cone.updateMatrix();
  31672. }
  31673. setColor( color ) {
  31674. this.line.material.color.set( color );
  31675. this.cone.material.color.set( color );
  31676. }
  31677. copy( source ) {
  31678. super.copy( source, false );
  31679. this.line.copy( source.line );
  31680. this.cone.copy( source.cone );
  31681. return this;
  31682. }
  31683. dispose() {
  31684. this.line.geometry.dispose();
  31685. this.line.material.dispose();
  31686. this.cone.geometry.dispose();
  31687. this.cone.material.dispose();
  31688. }
  31689. }
  31690. class AxesHelper extends LineSegments {
  31691. constructor( size = 1 ) {
  31692. const vertices = [
  31693. 0, 0, 0, size, 0, 0,
  31694. 0, 0, 0, 0, size, 0,
  31695. 0, 0, 0, 0, 0, size
  31696. ];
  31697. const colors = [
  31698. 1, 0, 0, 1, 0.6, 0,
  31699. 0, 1, 0, 0.6, 1, 0,
  31700. 0, 0, 1, 0, 0.6, 1
  31701. ];
  31702. const geometry = new BufferGeometry();
  31703. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31704. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31705. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31706. super( geometry, material );
  31707. this.type = 'AxesHelper';
  31708. }
  31709. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  31710. const color = new Color();
  31711. const array = this.geometry.attributes.color.array;
  31712. color.set( xAxisColor );
  31713. color.toArray( array, 0 );
  31714. color.toArray( array, 3 );
  31715. color.set( yAxisColor );
  31716. color.toArray( array, 6 );
  31717. color.toArray( array, 9 );
  31718. color.set( zAxisColor );
  31719. color.toArray( array, 12 );
  31720. color.toArray( array, 15 );
  31721. this.geometry.attributes.color.needsUpdate = true;
  31722. return this;
  31723. }
  31724. dispose() {
  31725. this.geometry.dispose();
  31726. this.material.dispose();
  31727. }
  31728. }
  31729. class ShapePath {
  31730. constructor() {
  31731. this.type = 'ShapePath';
  31732. this.color = new Color();
  31733. this.subPaths = [];
  31734. this.currentPath = null;
  31735. }
  31736. moveTo( x, y ) {
  31737. this.currentPath = new Path();
  31738. this.subPaths.push( this.currentPath );
  31739. this.currentPath.moveTo( x, y );
  31740. return this;
  31741. }
  31742. lineTo( x, y ) {
  31743. this.currentPath.lineTo( x, y );
  31744. return this;
  31745. }
  31746. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  31747. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  31748. return this;
  31749. }
  31750. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  31751. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  31752. return this;
  31753. }
  31754. splineThru( pts ) {
  31755. this.currentPath.splineThru( pts );
  31756. return this;
  31757. }
  31758. toShapes( isCCW ) {
  31759. function toShapesNoHoles( inSubpaths ) {
  31760. const shapes = [];
  31761. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  31762. const tmpPath = inSubpaths[ i ];
  31763. const tmpShape = new Shape();
  31764. tmpShape.curves = tmpPath.curves;
  31765. shapes.push( tmpShape );
  31766. }
  31767. return shapes;
  31768. }
  31769. function isPointInsidePolygon( inPt, inPolygon ) {
  31770. const polyLen = inPolygon.length;
  31771. // inPt on polygon contour => immediate success or
  31772. // toggling of inside/outside at every single! intersection point of an edge
  31773. // with the horizontal line through inPt, left of inPt
  31774. // not counting lowerY endpoints of edges and whole edges on that line
  31775. let inside = false;
  31776. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  31777. let edgeLowPt = inPolygon[ p ];
  31778. let edgeHighPt = inPolygon[ q ];
  31779. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  31780. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  31781. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  31782. // not parallel
  31783. if ( edgeDy < 0 ) {
  31784. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  31785. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  31786. }
  31787. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  31788. if ( inPt.y === edgeLowPt.y ) {
  31789. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  31790. // continue; // no intersection or edgeLowPt => doesn't count !!!
  31791. } else {
  31792. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  31793. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  31794. if ( perpEdge < 0 ) continue;
  31795. inside = ! inside; // true intersection left of inPt
  31796. }
  31797. } else {
  31798. // parallel or collinear
  31799. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  31800. // edge lies on the same horizontal line as inPt
  31801. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  31802. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  31803. // continue;
  31804. }
  31805. }
  31806. return inside;
  31807. }
  31808. const isClockWise = ShapeUtils.isClockWise;
  31809. const subPaths = this.subPaths;
  31810. if ( subPaths.length === 0 ) return [];
  31811. let solid, tmpPath, tmpShape;
  31812. const shapes = [];
  31813. if ( subPaths.length === 1 ) {
  31814. tmpPath = subPaths[ 0 ];
  31815. tmpShape = new Shape();
  31816. tmpShape.curves = tmpPath.curves;
  31817. shapes.push( tmpShape );
  31818. return shapes;
  31819. }
  31820. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  31821. holesFirst = isCCW ? ! holesFirst : holesFirst;
  31822. // console.log("Holes first", holesFirst);
  31823. const betterShapeHoles = [];
  31824. const newShapes = [];
  31825. let newShapeHoles = [];
  31826. let mainIdx = 0;
  31827. let tmpPoints;
  31828. newShapes[ mainIdx ] = undefined;
  31829. newShapeHoles[ mainIdx ] = [];
  31830. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  31831. tmpPath = subPaths[ i ];
  31832. tmpPoints = tmpPath.getPoints();
  31833. solid = isClockWise( tmpPoints );
  31834. solid = isCCW ? ! solid : solid;
  31835. if ( solid ) {
  31836. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  31837. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  31838. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  31839. if ( holesFirst ) mainIdx ++;
  31840. newShapeHoles[ mainIdx ] = [];
  31841. //console.log('cw', i);
  31842. } else {
  31843. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  31844. //console.log('ccw', i);
  31845. }
  31846. }
  31847. // only Holes? -> probably all Shapes with wrong orientation
  31848. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  31849. if ( newShapes.length > 1 ) {
  31850. let ambiguous = false;
  31851. let toChange = 0;
  31852. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31853. betterShapeHoles[ sIdx ] = [];
  31854. }
  31855. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31856. const sho = newShapeHoles[ sIdx ];
  31857. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  31858. const ho = sho[ hIdx ];
  31859. let hole_unassigned = true;
  31860. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  31861. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  31862. if ( sIdx !== s2Idx ) toChange ++;
  31863. if ( hole_unassigned ) {
  31864. hole_unassigned = false;
  31865. betterShapeHoles[ s2Idx ].push( ho );
  31866. } else {
  31867. ambiguous = true;
  31868. }
  31869. }
  31870. }
  31871. if ( hole_unassigned ) {
  31872. betterShapeHoles[ sIdx ].push( ho );
  31873. }
  31874. }
  31875. }
  31876. if ( toChange > 0 && ambiguous === false ) {
  31877. newShapeHoles = betterShapeHoles;
  31878. }
  31879. }
  31880. let tmpHoles;
  31881. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  31882. tmpShape = newShapes[ i ].s;
  31883. shapes.push( tmpShape );
  31884. tmpHoles = newShapeHoles[ i ];
  31885. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  31886. tmpShape.holes.push( tmpHoles[ j ].h );
  31887. }
  31888. }
  31889. //console.log("shape", shapes);
  31890. return shapes;
  31891. }
  31892. }
  31893. class Controls extends EventDispatcher {
  31894. constructor( object, domElement ) {
  31895. super();
  31896. this.object = object;
  31897. this.domElement = domElement;
  31898. this.enabled = true;
  31899. this.state = - 1;
  31900. this.keys = {};
  31901. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  31902. this.touches = { ONE: null, TWO: null };
  31903. }
  31904. connect() {}
  31905. disconnect() {}
  31906. dispose() {}
  31907. update( /* delta */ ) {}
  31908. }
  31909. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  31910. constructor( width = 1, height = 1, count = 1, options = {} ) {
  31911. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  31912. super( width, height, { ...options, count } );
  31913. this.isWebGLMultipleRenderTargets = true;
  31914. }
  31915. get texture() {
  31916. return this.textures;
  31917. }
  31918. }
  31919. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31920. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31921. revision: REVISION,
  31922. } } ) );
  31923. }
  31924. if ( typeof window !== 'undefined' ) {
  31925. if ( window.__THREE__ ) {
  31926. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  31927. } else {
  31928. window.__THREE__ = REVISION;
  31929. }
  31930. }
  31931. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  31932. exports.AddEquation = AddEquation;
  31933. exports.AddOperation = AddOperation;
  31934. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  31935. exports.AdditiveBlending = AdditiveBlending;
  31936. exports.AgXToneMapping = AgXToneMapping;
  31937. exports.AlphaFormat = AlphaFormat;
  31938. exports.AlwaysCompare = AlwaysCompare;
  31939. exports.AlwaysDepth = AlwaysDepth;
  31940. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  31941. exports.AmbientLight = AmbientLight;
  31942. exports.AnimationAction = AnimationAction;
  31943. exports.AnimationClip = AnimationClip;
  31944. exports.AnimationLoader = AnimationLoader;
  31945. exports.AnimationMixer = AnimationMixer;
  31946. exports.AnimationObjectGroup = AnimationObjectGroup;
  31947. exports.AnimationUtils = AnimationUtils;
  31948. exports.ArcCurve = ArcCurve;
  31949. exports.ArrayCamera = ArrayCamera;
  31950. exports.ArrowHelper = ArrowHelper;
  31951. exports.AttachedBindMode = AttachedBindMode;
  31952. exports.Audio = Audio;
  31953. exports.AudioAnalyser = AudioAnalyser;
  31954. exports.AudioContext = AudioContext;
  31955. exports.AudioListener = AudioListener;
  31956. exports.AudioLoader = AudioLoader;
  31957. exports.AxesHelper = AxesHelper;
  31958. exports.BackSide = BackSide;
  31959. exports.BasicDepthPacking = BasicDepthPacking;
  31960. exports.BasicShadowMap = BasicShadowMap;
  31961. exports.BatchedMesh = BatchedMesh;
  31962. exports.Bone = Bone;
  31963. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  31964. exports.Box2 = Box2;
  31965. exports.Box3 = Box3;
  31966. exports.Box3Helper = Box3Helper;
  31967. exports.BoxGeometry = BoxGeometry;
  31968. exports.BoxHelper = BoxHelper;
  31969. exports.BufferAttribute = BufferAttribute;
  31970. exports.BufferGeometry = BufferGeometry;
  31971. exports.BufferGeometryLoader = BufferGeometryLoader;
  31972. exports.ByteType = ByteType;
  31973. exports.Cache = Cache;
  31974. exports.Camera = Camera;
  31975. exports.CameraHelper = CameraHelper;
  31976. exports.CanvasTexture = CanvasTexture;
  31977. exports.CapsuleGeometry = CapsuleGeometry;
  31978. exports.CatmullRomCurve3 = CatmullRomCurve3;
  31979. exports.CineonToneMapping = CineonToneMapping;
  31980. exports.CircleGeometry = CircleGeometry;
  31981. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  31982. exports.Clock = Clock;
  31983. exports.Color = Color;
  31984. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  31985. exports.ColorManagement = ColorManagement;
  31986. exports.CompressedArrayTexture = CompressedArrayTexture;
  31987. exports.CompressedCubeTexture = CompressedCubeTexture;
  31988. exports.CompressedTexture = CompressedTexture;
  31989. exports.CompressedTextureLoader = CompressedTextureLoader;
  31990. exports.ConeGeometry = ConeGeometry;
  31991. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  31992. exports.ConstantColorFactor = ConstantColorFactor;
  31993. exports.Controls = Controls;
  31994. exports.CubeCamera = CubeCamera;
  31995. exports.CubeReflectionMapping = CubeReflectionMapping;
  31996. exports.CubeRefractionMapping = CubeRefractionMapping;
  31997. exports.CubeTexture = CubeTexture;
  31998. exports.CubeTextureLoader = CubeTextureLoader;
  31999. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  32000. exports.CubicBezierCurve = CubicBezierCurve;
  32001. exports.CubicBezierCurve3 = CubicBezierCurve3;
  32002. exports.CubicInterpolant = CubicInterpolant;
  32003. exports.CullFaceBack = CullFaceBack;
  32004. exports.CullFaceFront = CullFaceFront;
  32005. exports.CullFaceFrontBack = CullFaceFrontBack;
  32006. exports.CullFaceNone = CullFaceNone;
  32007. exports.Curve = Curve;
  32008. exports.CurvePath = CurvePath;
  32009. exports.CustomBlending = CustomBlending;
  32010. exports.CustomToneMapping = CustomToneMapping;
  32011. exports.CylinderGeometry = CylinderGeometry;
  32012. exports.Cylindrical = Cylindrical;
  32013. exports.Data3DTexture = Data3DTexture;
  32014. exports.DataArrayTexture = DataArrayTexture;
  32015. exports.DataTexture = DataTexture;
  32016. exports.DataTextureLoader = DataTextureLoader;
  32017. exports.DataUtils = DataUtils;
  32018. exports.DecrementStencilOp = DecrementStencilOp;
  32019. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  32020. exports.DefaultLoadingManager = DefaultLoadingManager;
  32021. exports.DepthFormat = DepthFormat;
  32022. exports.DepthStencilFormat = DepthStencilFormat;
  32023. exports.DepthTexture = DepthTexture;
  32024. exports.DetachedBindMode = DetachedBindMode;
  32025. exports.DirectionalLight = DirectionalLight;
  32026. exports.DirectionalLightHelper = DirectionalLightHelper;
  32027. exports.DiscreteInterpolant = DiscreteInterpolant;
  32028. exports.DisplayP3ColorSpace = DisplayP3ColorSpace;
  32029. exports.DodecahedronGeometry = DodecahedronGeometry;
  32030. exports.DoubleSide = DoubleSide;
  32031. exports.DstAlphaFactor = DstAlphaFactor;
  32032. exports.DstColorFactor = DstColorFactor;
  32033. exports.DynamicCopyUsage = DynamicCopyUsage;
  32034. exports.DynamicDrawUsage = DynamicDrawUsage;
  32035. exports.DynamicReadUsage = DynamicReadUsage;
  32036. exports.EdgesGeometry = EdgesGeometry;
  32037. exports.EllipseCurve = EllipseCurve;
  32038. exports.EqualCompare = EqualCompare;
  32039. exports.EqualDepth = EqualDepth;
  32040. exports.EqualStencilFunc = EqualStencilFunc;
  32041. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  32042. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  32043. exports.Euler = Euler;
  32044. exports.EventDispatcher = EventDispatcher;
  32045. exports.ExtrudeGeometry = ExtrudeGeometry;
  32046. exports.FileLoader = FileLoader;
  32047. exports.Float16BufferAttribute = Float16BufferAttribute;
  32048. exports.Float32BufferAttribute = Float32BufferAttribute;
  32049. exports.FloatType = FloatType;
  32050. exports.Fog = Fog;
  32051. exports.FogExp2 = FogExp2;
  32052. exports.FramebufferTexture = FramebufferTexture;
  32053. exports.FrontSide = FrontSide;
  32054. exports.Frustum = Frustum;
  32055. exports.GLBufferAttribute = GLBufferAttribute;
  32056. exports.GLSL1 = GLSL1;
  32057. exports.GLSL3 = GLSL3;
  32058. exports.GreaterCompare = GreaterCompare;
  32059. exports.GreaterDepth = GreaterDepth;
  32060. exports.GreaterEqualCompare = GreaterEqualCompare;
  32061. exports.GreaterEqualDepth = GreaterEqualDepth;
  32062. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  32063. exports.GreaterStencilFunc = GreaterStencilFunc;
  32064. exports.GridHelper = GridHelper;
  32065. exports.Group = Group;
  32066. exports.HalfFloatType = HalfFloatType;
  32067. exports.HemisphereLight = HemisphereLight;
  32068. exports.HemisphereLightHelper = HemisphereLightHelper;
  32069. exports.IcosahedronGeometry = IcosahedronGeometry;
  32070. exports.ImageBitmapLoader = ImageBitmapLoader;
  32071. exports.ImageLoader = ImageLoader;
  32072. exports.ImageUtils = ImageUtils;
  32073. exports.IncrementStencilOp = IncrementStencilOp;
  32074. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  32075. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  32076. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  32077. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  32078. exports.InstancedMesh = InstancedMesh;
  32079. exports.Int16BufferAttribute = Int16BufferAttribute;
  32080. exports.Int32BufferAttribute = Int32BufferAttribute;
  32081. exports.Int8BufferAttribute = Int8BufferAttribute;
  32082. exports.IntType = IntType;
  32083. exports.InterleavedBuffer = InterleavedBuffer;
  32084. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  32085. exports.Interpolant = Interpolant;
  32086. exports.InterpolateDiscrete = InterpolateDiscrete;
  32087. exports.InterpolateLinear = InterpolateLinear;
  32088. exports.InterpolateSmooth = InterpolateSmooth;
  32089. exports.InvertStencilOp = InvertStencilOp;
  32090. exports.KeepStencilOp = KeepStencilOp;
  32091. exports.KeyframeTrack = KeyframeTrack;
  32092. exports.LOD = LOD;
  32093. exports.LatheGeometry = LatheGeometry;
  32094. exports.Layers = Layers;
  32095. exports.LessCompare = LessCompare;
  32096. exports.LessDepth = LessDepth;
  32097. exports.LessEqualCompare = LessEqualCompare;
  32098. exports.LessEqualDepth = LessEqualDepth;
  32099. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  32100. exports.LessStencilFunc = LessStencilFunc;
  32101. exports.Light = Light;
  32102. exports.LightProbe = LightProbe;
  32103. exports.Line = Line;
  32104. exports.Line3 = Line3;
  32105. exports.LineBasicMaterial = LineBasicMaterial;
  32106. exports.LineCurve = LineCurve;
  32107. exports.LineCurve3 = LineCurve3;
  32108. exports.LineDashedMaterial = LineDashedMaterial;
  32109. exports.LineLoop = LineLoop;
  32110. exports.LineSegments = LineSegments;
  32111. exports.LinearDisplayP3ColorSpace = LinearDisplayP3ColorSpace;
  32112. exports.LinearFilter = LinearFilter;
  32113. exports.LinearInterpolant = LinearInterpolant;
  32114. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  32115. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  32116. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  32117. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  32118. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  32119. exports.LinearToneMapping = LinearToneMapping;
  32120. exports.LinearTransfer = LinearTransfer;
  32121. exports.Loader = Loader;
  32122. exports.LoaderUtils = LoaderUtils;
  32123. exports.LoadingManager = LoadingManager;
  32124. exports.LoopOnce = LoopOnce;
  32125. exports.LoopPingPong = LoopPingPong;
  32126. exports.LoopRepeat = LoopRepeat;
  32127. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  32128. exports.LuminanceFormat = LuminanceFormat;
  32129. exports.MOUSE = MOUSE;
  32130. exports.Material = Material;
  32131. exports.MaterialLoader = MaterialLoader;
  32132. exports.MathUtils = MathUtils;
  32133. exports.Matrix2 = Matrix2;
  32134. exports.Matrix3 = Matrix3;
  32135. exports.Matrix4 = Matrix4;
  32136. exports.MaxEquation = MaxEquation;
  32137. exports.Mesh = Mesh;
  32138. exports.MeshBasicMaterial = MeshBasicMaterial;
  32139. exports.MeshDepthMaterial = MeshDepthMaterial;
  32140. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  32141. exports.MeshLambertMaterial = MeshLambertMaterial;
  32142. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  32143. exports.MeshNormalMaterial = MeshNormalMaterial;
  32144. exports.MeshPhongMaterial = MeshPhongMaterial;
  32145. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  32146. exports.MeshStandardMaterial = MeshStandardMaterial;
  32147. exports.MeshToonMaterial = MeshToonMaterial;
  32148. exports.MinEquation = MinEquation;
  32149. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  32150. exports.MixOperation = MixOperation;
  32151. exports.MultiplyBlending = MultiplyBlending;
  32152. exports.MultiplyOperation = MultiplyOperation;
  32153. exports.NearestFilter = NearestFilter;
  32154. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  32155. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  32156. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  32157. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  32158. exports.NeutralToneMapping = NeutralToneMapping;
  32159. exports.NeverCompare = NeverCompare;
  32160. exports.NeverDepth = NeverDepth;
  32161. exports.NeverStencilFunc = NeverStencilFunc;
  32162. exports.NoBlending = NoBlending;
  32163. exports.NoColorSpace = NoColorSpace;
  32164. exports.NoToneMapping = NoToneMapping;
  32165. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  32166. exports.NormalBlending = NormalBlending;
  32167. exports.NotEqualCompare = NotEqualCompare;
  32168. exports.NotEqualDepth = NotEqualDepth;
  32169. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  32170. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  32171. exports.Object3D = Object3D;
  32172. exports.ObjectLoader = ObjectLoader;
  32173. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  32174. exports.OctahedronGeometry = OctahedronGeometry;
  32175. exports.OneFactor = OneFactor;
  32176. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  32177. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  32178. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  32179. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  32180. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  32181. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  32182. exports.OrthographicCamera = OrthographicCamera;
  32183. exports.P3Primaries = P3Primaries;
  32184. exports.PCFShadowMap = PCFShadowMap;
  32185. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  32186. exports.PMREMGenerator = PMREMGenerator;
  32187. exports.Path = Path;
  32188. exports.PerspectiveCamera = PerspectiveCamera;
  32189. exports.Plane = Plane;
  32190. exports.PlaneGeometry = PlaneGeometry;
  32191. exports.PlaneHelper = PlaneHelper;
  32192. exports.PointLight = PointLight;
  32193. exports.PointLightHelper = PointLightHelper;
  32194. exports.Points = Points;
  32195. exports.PointsMaterial = PointsMaterial;
  32196. exports.PolarGridHelper = PolarGridHelper;
  32197. exports.PolyhedronGeometry = PolyhedronGeometry;
  32198. exports.PositionalAudio = PositionalAudio;
  32199. exports.PropertyBinding = PropertyBinding;
  32200. exports.PropertyMixer = PropertyMixer;
  32201. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  32202. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  32203. exports.Quaternion = Quaternion;
  32204. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  32205. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  32206. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  32207. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  32208. exports.REVISION = REVISION;
  32209. exports.RGBADepthPacking = RGBADepthPacking;
  32210. exports.RGBAFormat = RGBAFormat;
  32211. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  32212. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  32213. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  32214. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  32215. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  32216. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  32217. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  32218. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  32219. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  32220. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  32221. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  32222. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  32223. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  32224. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  32225. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  32226. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  32227. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  32228. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  32229. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  32230. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  32231. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  32232. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  32233. exports.RGBDepthPacking = RGBDepthPacking;
  32234. exports.RGBFormat = RGBFormat;
  32235. exports.RGBIntegerFormat = RGBIntegerFormat;
  32236. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  32237. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  32238. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  32239. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  32240. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  32241. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  32242. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  32243. exports.RGDepthPacking = RGDepthPacking;
  32244. exports.RGFormat = RGFormat;
  32245. exports.RGIntegerFormat = RGIntegerFormat;
  32246. exports.RawShaderMaterial = RawShaderMaterial;
  32247. exports.Ray = Ray;
  32248. exports.Raycaster = Raycaster;
  32249. exports.Rec709Primaries = Rec709Primaries;
  32250. exports.RectAreaLight = RectAreaLight;
  32251. exports.RedFormat = RedFormat;
  32252. exports.RedIntegerFormat = RedIntegerFormat;
  32253. exports.ReinhardToneMapping = ReinhardToneMapping;
  32254. exports.RenderTarget = RenderTarget;
  32255. exports.RepeatWrapping = RepeatWrapping;
  32256. exports.ReplaceStencilOp = ReplaceStencilOp;
  32257. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  32258. exports.RingGeometry = RingGeometry;
  32259. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  32260. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  32261. exports.SRGBColorSpace = SRGBColorSpace;
  32262. exports.SRGBTransfer = SRGBTransfer;
  32263. exports.Scene = Scene;
  32264. exports.ShaderChunk = ShaderChunk;
  32265. exports.ShaderLib = ShaderLib;
  32266. exports.ShaderMaterial = ShaderMaterial;
  32267. exports.ShadowMaterial = ShadowMaterial;
  32268. exports.Shape = Shape;
  32269. exports.ShapeGeometry = ShapeGeometry;
  32270. exports.ShapePath = ShapePath;
  32271. exports.ShapeUtils = ShapeUtils;
  32272. exports.ShortType = ShortType;
  32273. exports.Skeleton = Skeleton;
  32274. exports.SkeletonHelper = SkeletonHelper;
  32275. exports.SkinnedMesh = SkinnedMesh;
  32276. exports.Source = Source;
  32277. exports.Sphere = Sphere;
  32278. exports.SphereGeometry = SphereGeometry;
  32279. exports.Spherical = Spherical;
  32280. exports.SphericalHarmonics3 = SphericalHarmonics3;
  32281. exports.SplineCurve = SplineCurve;
  32282. exports.SpotLight = SpotLight;
  32283. exports.SpotLightHelper = SpotLightHelper;
  32284. exports.Sprite = Sprite;
  32285. exports.SpriteMaterial = SpriteMaterial;
  32286. exports.SrcAlphaFactor = SrcAlphaFactor;
  32287. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  32288. exports.SrcColorFactor = SrcColorFactor;
  32289. exports.StaticCopyUsage = StaticCopyUsage;
  32290. exports.StaticDrawUsage = StaticDrawUsage;
  32291. exports.StaticReadUsage = StaticReadUsage;
  32292. exports.StereoCamera = StereoCamera;
  32293. exports.StreamCopyUsage = StreamCopyUsage;
  32294. exports.StreamDrawUsage = StreamDrawUsage;
  32295. exports.StreamReadUsage = StreamReadUsage;
  32296. exports.StringKeyframeTrack = StringKeyframeTrack;
  32297. exports.SubtractEquation = SubtractEquation;
  32298. exports.SubtractiveBlending = SubtractiveBlending;
  32299. exports.TOUCH = TOUCH;
  32300. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  32301. exports.TetrahedronGeometry = TetrahedronGeometry;
  32302. exports.Texture = Texture;
  32303. exports.TextureLoader = TextureLoader;
  32304. exports.TextureUtils = TextureUtils;
  32305. exports.TorusGeometry = TorusGeometry;
  32306. exports.TorusKnotGeometry = TorusKnotGeometry;
  32307. exports.Triangle = Triangle;
  32308. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  32309. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  32310. exports.TrianglesDrawMode = TrianglesDrawMode;
  32311. exports.TubeGeometry = TubeGeometry;
  32312. exports.UVMapping = UVMapping;
  32313. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  32314. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  32315. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  32316. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  32317. exports.Uniform = Uniform;
  32318. exports.UniformsGroup = UniformsGroup;
  32319. exports.UniformsLib = UniformsLib;
  32320. exports.UniformsUtils = UniformsUtils;
  32321. exports.UnsignedByteType = UnsignedByteType;
  32322. exports.UnsignedInt248Type = UnsignedInt248Type;
  32323. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  32324. exports.UnsignedIntType = UnsignedIntType;
  32325. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  32326. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  32327. exports.UnsignedShortType = UnsignedShortType;
  32328. exports.VSMShadowMap = VSMShadowMap;
  32329. exports.Vector2 = Vector2;
  32330. exports.Vector3 = Vector3;
  32331. exports.Vector4 = Vector4;
  32332. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  32333. exports.VideoTexture = VideoTexture;
  32334. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  32335. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  32336. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  32337. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  32338. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  32339. exports.WebGLRenderTarget = WebGLRenderTarget;
  32340. exports.WebGLRenderer = WebGLRenderer;
  32341. exports.WebGLUtils = WebGLUtils;
  32342. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  32343. exports.WireframeGeometry = WireframeGeometry;
  32344. exports.WrapAroundEnding = WrapAroundEnding;
  32345. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  32346. exports.ZeroFactor = ZeroFactor;
  32347. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  32348. exports.ZeroStencilOp = ZeroStencilOp;
  32349. exports.createCanvasElement = createCanvasElement;