three.cjs 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '172dev';
  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 LinearTransfer = 'linear';
  169. const SRGBTransfer = 'srgb';
  170. const ZeroStencilOp = 0;
  171. const KeepStencilOp = 7680;
  172. const ReplaceStencilOp = 7681;
  173. const IncrementStencilOp = 7682;
  174. const DecrementStencilOp = 7683;
  175. const IncrementWrapStencilOp = 34055;
  176. const DecrementWrapStencilOp = 34056;
  177. const InvertStencilOp = 5386;
  178. const NeverStencilFunc = 512;
  179. const LessStencilFunc = 513;
  180. const EqualStencilFunc = 514;
  181. const LessEqualStencilFunc = 515;
  182. const GreaterStencilFunc = 516;
  183. const NotEqualStencilFunc = 517;
  184. const GreaterEqualStencilFunc = 518;
  185. const AlwaysStencilFunc = 519;
  186. const NeverCompare = 512;
  187. const LessCompare = 513;
  188. const EqualCompare = 514;
  189. const LessEqualCompare = 515;
  190. const GreaterCompare = 516;
  191. const NotEqualCompare = 517;
  192. const GreaterEqualCompare = 518;
  193. const AlwaysCompare = 519;
  194. const StaticDrawUsage = 35044;
  195. const DynamicDrawUsage = 35048;
  196. const StreamDrawUsage = 35040;
  197. const StaticReadUsage = 35045;
  198. const DynamicReadUsage = 35049;
  199. const StreamReadUsage = 35041;
  200. const StaticCopyUsage = 35046;
  201. const DynamicCopyUsage = 35050;
  202. const StreamCopyUsage = 35042;
  203. const GLSL1 = '100';
  204. const GLSL3 = '300 es';
  205. const WebGLCoordinateSystem = 2000;
  206. const WebGPUCoordinateSystem = 2001;
  207. /**
  208. * https://github.com/mrdoob/eventdispatcher.js/
  209. */
  210. class EventDispatcher {
  211. addEventListener( type, listener ) {
  212. if ( this._listeners === undefined ) this._listeners = {};
  213. const listeners = this._listeners;
  214. if ( listeners[ type ] === undefined ) {
  215. listeners[ type ] = [];
  216. }
  217. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  218. listeners[ type ].push( listener );
  219. }
  220. }
  221. hasEventListener( type, listener ) {
  222. if ( this._listeners === undefined ) return false;
  223. const listeners = this._listeners;
  224. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  225. }
  226. removeEventListener( type, listener ) {
  227. if ( this._listeners === undefined ) return;
  228. const listeners = this._listeners;
  229. const listenerArray = listeners[ type ];
  230. if ( listenerArray !== undefined ) {
  231. const index = listenerArray.indexOf( listener );
  232. if ( index !== - 1 ) {
  233. listenerArray.splice( index, 1 );
  234. }
  235. }
  236. }
  237. dispatchEvent( event ) {
  238. if ( this._listeners === undefined ) return;
  239. const listeners = this._listeners;
  240. const listenerArray = listeners[ event.type ];
  241. if ( listenerArray !== undefined ) {
  242. event.target = this;
  243. // Make a copy, in case listeners are removed while iterating.
  244. const array = listenerArray.slice( 0 );
  245. for ( let i = 0, l = array.length; i < l; i ++ ) {
  246. array[ i ].call( this, event );
  247. }
  248. event.target = null;
  249. }
  250. }
  251. }
  252. 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' ];
  253. let _seed = 1234567;
  254. const DEG2RAD = Math.PI / 180;
  255. const RAD2DEG = 180 / Math.PI;
  256. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  257. function generateUUID() {
  258. const d0 = Math.random() * 0xffffffff | 0;
  259. const d1 = Math.random() * 0xffffffff | 0;
  260. const d2 = Math.random() * 0xffffffff | 0;
  261. const d3 = Math.random() * 0xffffffff | 0;
  262. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  263. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  264. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  265. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  266. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  267. return uuid.toLowerCase();
  268. }
  269. function clamp( value, min, max ) {
  270. return Math.max( min, Math.min( max, value ) );
  271. }
  272. // compute euclidean modulo of m % n
  273. // https://en.wikipedia.org/wiki/Modulo_operation
  274. function euclideanModulo( n, m ) {
  275. return ( ( n % m ) + m ) % m;
  276. }
  277. // Linear mapping from range <a1, a2> to range <b1, b2>
  278. function mapLinear( x, a1, a2, b1, b2 ) {
  279. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  280. }
  281. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  282. function inverseLerp( x, y, value ) {
  283. if ( x !== y ) {
  284. return ( value - x ) / ( y - x );
  285. } else {
  286. return 0;
  287. }
  288. }
  289. // https://en.wikipedia.org/wiki/Linear_interpolation
  290. function lerp( x, y, t ) {
  291. return ( 1 - t ) * x + t * y;
  292. }
  293. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  294. function damp( x, y, lambda, dt ) {
  295. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  296. }
  297. // https://www.desmos.com/calculator/vcsjnyz7x4
  298. function pingpong( x, length = 1 ) {
  299. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  300. }
  301. // http://en.wikipedia.org/wiki/Smoothstep
  302. function smoothstep( x, min, max ) {
  303. if ( x <= min ) return 0;
  304. if ( x >= max ) return 1;
  305. x = ( x - min ) / ( max - min );
  306. return x * x * ( 3 - 2 * x );
  307. }
  308. function smootherstep( x, min, max ) {
  309. if ( x <= min ) return 0;
  310. if ( x >= max ) return 1;
  311. x = ( x - min ) / ( max - min );
  312. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  313. }
  314. // Random integer from <low, high> interval
  315. function randInt( low, high ) {
  316. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  317. }
  318. // Random float from <low, high> interval
  319. function randFloat( low, high ) {
  320. return low + Math.random() * ( high - low );
  321. }
  322. // Random float from <-range/2, range/2> interval
  323. function randFloatSpread( range ) {
  324. return range * ( 0.5 - Math.random() );
  325. }
  326. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  327. function seededRandom( s ) {
  328. if ( s !== undefined ) _seed = s;
  329. // Mulberry32 generator
  330. let t = _seed += 0x6D2B79F5;
  331. t = Math.imul( t ^ t >>> 15, t | 1 );
  332. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  333. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  334. }
  335. function degToRad( degrees ) {
  336. return degrees * DEG2RAD;
  337. }
  338. function radToDeg( radians ) {
  339. return radians * RAD2DEG;
  340. }
  341. function isPowerOfTwo( value ) {
  342. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  343. }
  344. function ceilPowerOfTwo( value ) {
  345. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  346. }
  347. function floorPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  351. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  352. // rotations are applied to the axes in the order specified by 'order'
  353. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  354. // angles are in radians
  355. const cos = Math.cos;
  356. const sin = Math.sin;
  357. const c2 = cos( b / 2 );
  358. const s2 = sin( b / 2 );
  359. const c13 = cos( ( a + c ) / 2 );
  360. const s13 = sin( ( a + c ) / 2 );
  361. const c1_3 = cos( ( a - c ) / 2 );
  362. const s1_3 = sin( ( a - c ) / 2 );
  363. const c3_1 = cos( ( c - a ) / 2 );
  364. const s3_1 = sin( ( c - a ) / 2 );
  365. switch ( order ) {
  366. case 'XYX':
  367. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  368. break;
  369. case 'YZY':
  370. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  371. break;
  372. case 'ZXZ':
  373. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  374. break;
  375. case 'XZX':
  376. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  377. break;
  378. case 'YXY':
  379. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  380. break;
  381. case 'ZYZ':
  382. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  383. break;
  384. default:
  385. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  386. }
  387. }
  388. function denormalize( value, array ) {
  389. switch ( array.constructor ) {
  390. case Float32Array:
  391. return value;
  392. case Uint32Array:
  393. return value / 4294967295.0;
  394. case Uint16Array:
  395. return value / 65535.0;
  396. case Uint8Array:
  397. return value / 255.0;
  398. case Int32Array:
  399. return Math.max( value / 2147483647.0, - 1.0 );
  400. case Int16Array:
  401. return Math.max( value / 32767.0, - 1.0 );
  402. case Int8Array:
  403. return Math.max( value / 127.0, - 1.0 );
  404. default:
  405. throw new Error( 'Invalid component type.' );
  406. }
  407. }
  408. function normalize( value, array ) {
  409. switch ( array.constructor ) {
  410. case Float32Array:
  411. return value;
  412. case Uint32Array:
  413. return Math.round( value * 4294967295.0 );
  414. case Uint16Array:
  415. return Math.round( value * 65535.0 );
  416. case Uint8Array:
  417. return Math.round( value * 255.0 );
  418. case Int32Array:
  419. return Math.round( value * 2147483647.0 );
  420. case Int16Array:
  421. return Math.round( value * 32767.0 );
  422. case Int8Array:
  423. return Math.round( value * 127.0 );
  424. default:
  425. throw new Error( 'Invalid component type.' );
  426. }
  427. }
  428. const MathUtils = {
  429. DEG2RAD: DEG2RAD,
  430. RAD2DEG: RAD2DEG,
  431. generateUUID: generateUUID,
  432. clamp: clamp,
  433. euclideanModulo: euclideanModulo,
  434. mapLinear: mapLinear,
  435. inverseLerp: inverseLerp,
  436. lerp: lerp,
  437. damp: damp,
  438. pingpong: pingpong,
  439. smoothstep: smoothstep,
  440. smootherstep: smootherstep,
  441. randInt: randInt,
  442. randFloat: randFloat,
  443. randFloatSpread: randFloatSpread,
  444. seededRandom: seededRandom,
  445. degToRad: degToRad,
  446. radToDeg: radToDeg,
  447. isPowerOfTwo: isPowerOfTwo,
  448. ceilPowerOfTwo: ceilPowerOfTwo,
  449. floorPowerOfTwo: floorPowerOfTwo,
  450. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  451. normalize: normalize,
  452. denormalize: denormalize
  453. };
  454. class Vector2 {
  455. constructor( x = 0, y = 0 ) {
  456. Vector2.prototype.isVector2 = true;
  457. this.x = x;
  458. this.y = y;
  459. }
  460. get width() {
  461. return this.x;
  462. }
  463. set width( value ) {
  464. this.x = value;
  465. }
  466. get height() {
  467. return this.y;
  468. }
  469. set height( value ) {
  470. this.y = value;
  471. }
  472. set( x, y ) {
  473. this.x = x;
  474. this.y = y;
  475. return this;
  476. }
  477. setScalar( scalar ) {
  478. this.x = scalar;
  479. this.y = scalar;
  480. return this;
  481. }
  482. setX( x ) {
  483. this.x = x;
  484. return this;
  485. }
  486. setY( y ) {
  487. this.y = y;
  488. return this;
  489. }
  490. setComponent( index, value ) {
  491. switch ( index ) {
  492. case 0: this.x = value; break;
  493. case 1: this.y = value; break;
  494. default: throw new Error( 'index is out of range: ' + index );
  495. }
  496. return this;
  497. }
  498. getComponent( index ) {
  499. switch ( index ) {
  500. case 0: return this.x;
  501. case 1: return this.y;
  502. default: throw new Error( 'index is out of range: ' + index );
  503. }
  504. }
  505. clone() {
  506. return new this.constructor( this.x, this.y );
  507. }
  508. copy( v ) {
  509. this.x = v.x;
  510. this.y = v.y;
  511. return this;
  512. }
  513. add( v ) {
  514. this.x += v.x;
  515. this.y += v.y;
  516. return this;
  517. }
  518. addScalar( s ) {
  519. this.x += s;
  520. this.y += s;
  521. return this;
  522. }
  523. addVectors( a, b ) {
  524. this.x = a.x + b.x;
  525. this.y = a.y + b.y;
  526. return this;
  527. }
  528. addScaledVector( v, s ) {
  529. this.x += v.x * s;
  530. this.y += v.y * s;
  531. return this;
  532. }
  533. sub( v ) {
  534. this.x -= v.x;
  535. this.y -= v.y;
  536. return this;
  537. }
  538. subScalar( s ) {
  539. this.x -= s;
  540. this.y -= s;
  541. return this;
  542. }
  543. subVectors( a, b ) {
  544. this.x = a.x - b.x;
  545. this.y = a.y - b.y;
  546. return this;
  547. }
  548. multiply( v ) {
  549. this.x *= v.x;
  550. this.y *= v.y;
  551. return this;
  552. }
  553. multiplyScalar( scalar ) {
  554. this.x *= scalar;
  555. this.y *= scalar;
  556. return this;
  557. }
  558. divide( v ) {
  559. this.x /= v.x;
  560. this.y /= v.y;
  561. return this;
  562. }
  563. divideScalar( scalar ) {
  564. return this.multiplyScalar( 1 / scalar );
  565. }
  566. applyMatrix3( m ) {
  567. const x = this.x, y = this.y;
  568. const e = m.elements;
  569. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  570. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  571. return this;
  572. }
  573. min( v ) {
  574. this.x = Math.min( this.x, v.x );
  575. this.y = Math.min( this.y, v.y );
  576. return this;
  577. }
  578. max( v ) {
  579. this.x = Math.max( this.x, v.x );
  580. this.y = Math.max( this.y, v.y );
  581. return this;
  582. }
  583. clamp( min, max ) {
  584. // assumes min < max, componentwise
  585. this.x = clamp( this.x, min.x, max.x );
  586. this.y = clamp( this.y, min.y, max.y );
  587. return this;
  588. }
  589. clampScalar( minVal, maxVal ) {
  590. this.x = clamp( this.x, minVal, maxVal );
  591. this.y = clamp( this.y, minVal, maxVal );
  592. return this;
  593. }
  594. clampLength( min, max ) {
  595. const length = this.length();
  596. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  597. }
  598. floor() {
  599. this.x = Math.floor( this.x );
  600. this.y = Math.floor( this.y );
  601. return this;
  602. }
  603. ceil() {
  604. this.x = Math.ceil( this.x );
  605. this.y = Math.ceil( this.y );
  606. return this;
  607. }
  608. round() {
  609. this.x = Math.round( this.x );
  610. this.y = Math.round( this.y );
  611. return this;
  612. }
  613. roundToZero() {
  614. this.x = Math.trunc( this.x );
  615. this.y = Math.trunc( this.y );
  616. return this;
  617. }
  618. negate() {
  619. this.x = - this.x;
  620. this.y = - this.y;
  621. return this;
  622. }
  623. dot( v ) {
  624. return this.x * v.x + this.y * v.y;
  625. }
  626. cross( v ) {
  627. return this.x * v.y - this.y * v.x;
  628. }
  629. lengthSq() {
  630. return this.x * this.x + this.y * this.y;
  631. }
  632. length() {
  633. return Math.sqrt( this.x * this.x + this.y * this.y );
  634. }
  635. manhattanLength() {
  636. return Math.abs( this.x ) + Math.abs( this.y );
  637. }
  638. normalize() {
  639. return this.divideScalar( this.length() || 1 );
  640. }
  641. angle() {
  642. // computes the angle in radians with respect to the positive x-axis
  643. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  644. return angle;
  645. }
  646. angleTo( v ) {
  647. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  648. if ( denominator === 0 ) return Math.PI / 2;
  649. const theta = this.dot( v ) / denominator;
  650. // clamp, to handle numerical problems
  651. return Math.acos( clamp( theta, - 1, 1 ) );
  652. }
  653. distanceTo( v ) {
  654. return Math.sqrt( this.distanceToSquared( v ) );
  655. }
  656. distanceToSquared( v ) {
  657. const dx = this.x - v.x, dy = this.y - v.y;
  658. return dx * dx + dy * dy;
  659. }
  660. manhattanDistanceTo( v ) {
  661. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  662. }
  663. setLength( length ) {
  664. return this.normalize().multiplyScalar( length );
  665. }
  666. lerp( v, alpha ) {
  667. this.x += ( v.x - this.x ) * alpha;
  668. this.y += ( v.y - this.y ) * alpha;
  669. return this;
  670. }
  671. lerpVectors( v1, v2, alpha ) {
  672. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  673. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  674. return this;
  675. }
  676. equals( v ) {
  677. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  678. }
  679. fromArray( array, offset = 0 ) {
  680. this.x = array[ offset ];
  681. this.y = array[ offset + 1 ];
  682. return this;
  683. }
  684. toArray( array = [], offset = 0 ) {
  685. array[ offset ] = this.x;
  686. array[ offset + 1 ] = this.y;
  687. return array;
  688. }
  689. fromBufferAttribute( attribute, index ) {
  690. this.x = attribute.getX( index );
  691. this.y = attribute.getY( index );
  692. return this;
  693. }
  694. rotateAround( center, angle ) {
  695. const c = Math.cos( angle ), s = Math.sin( angle );
  696. const x = this.x - center.x;
  697. const y = this.y - center.y;
  698. this.x = x * c - y * s + center.x;
  699. this.y = x * s + y * c + center.y;
  700. return this;
  701. }
  702. random() {
  703. this.x = Math.random();
  704. this.y = Math.random();
  705. return this;
  706. }
  707. *[ Symbol.iterator ]() {
  708. yield this.x;
  709. yield this.y;
  710. }
  711. }
  712. class Matrix3 {
  713. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  714. Matrix3.prototype.isMatrix3 = true;
  715. this.elements = [
  716. 1, 0, 0,
  717. 0, 1, 0,
  718. 0, 0, 1
  719. ];
  720. if ( n11 !== undefined ) {
  721. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  722. }
  723. }
  724. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  725. const te = this.elements;
  726. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  727. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  728. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  729. return this;
  730. }
  731. identity() {
  732. this.set(
  733. 1, 0, 0,
  734. 0, 1, 0,
  735. 0, 0, 1
  736. );
  737. return this;
  738. }
  739. copy( m ) {
  740. const te = this.elements;
  741. const me = m.elements;
  742. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  743. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  744. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  745. return this;
  746. }
  747. extractBasis( xAxis, yAxis, zAxis ) {
  748. xAxis.setFromMatrix3Column( this, 0 );
  749. yAxis.setFromMatrix3Column( this, 1 );
  750. zAxis.setFromMatrix3Column( this, 2 );
  751. return this;
  752. }
  753. setFromMatrix4( m ) {
  754. const me = m.elements;
  755. this.set(
  756. me[ 0 ], me[ 4 ], me[ 8 ],
  757. me[ 1 ], me[ 5 ], me[ 9 ],
  758. me[ 2 ], me[ 6 ], me[ 10 ]
  759. );
  760. return this;
  761. }
  762. multiply( m ) {
  763. return this.multiplyMatrices( this, m );
  764. }
  765. premultiply( m ) {
  766. return this.multiplyMatrices( m, this );
  767. }
  768. multiplyMatrices( a, b ) {
  769. const ae = a.elements;
  770. const be = b.elements;
  771. const te = this.elements;
  772. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  773. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  774. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  775. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  776. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  777. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  778. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  779. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  780. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  781. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  782. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  783. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  784. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  785. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  786. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  787. return this;
  788. }
  789. multiplyScalar( s ) {
  790. const te = this.elements;
  791. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  792. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  793. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  794. return this;
  795. }
  796. determinant() {
  797. const te = this.elements;
  798. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  799. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  800. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  801. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  802. }
  803. invert() {
  804. const te = this.elements,
  805. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  806. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  807. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  808. t11 = n33 * n22 - n32 * n23,
  809. t12 = n32 * n13 - n33 * n12,
  810. t13 = n23 * n12 - n22 * n13,
  811. det = n11 * t11 + n21 * t12 + n31 * t13;
  812. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  813. const detInv = 1 / det;
  814. te[ 0 ] = t11 * detInv;
  815. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  816. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  817. te[ 3 ] = t12 * detInv;
  818. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  819. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  820. te[ 6 ] = t13 * detInv;
  821. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  822. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  823. return this;
  824. }
  825. transpose() {
  826. let tmp;
  827. const m = this.elements;
  828. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  829. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  830. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  831. return this;
  832. }
  833. getNormalMatrix( matrix4 ) {
  834. return this.setFromMatrix4( matrix4 ).invert().transpose();
  835. }
  836. transposeIntoArray( r ) {
  837. const m = this.elements;
  838. r[ 0 ] = m[ 0 ];
  839. r[ 1 ] = m[ 3 ];
  840. r[ 2 ] = m[ 6 ];
  841. r[ 3 ] = m[ 1 ];
  842. r[ 4 ] = m[ 4 ];
  843. r[ 5 ] = m[ 7 ];
  844. r[ 6 ] = m[ 2 ];
  845. r[ 7 ] = m[ 5 ];
  846. r[ 8 ] = m[ 8 ];
  847. return this;
  848. }
  849. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  850. const c = Math.cos( rotation );
  851. const s = Math.sin( rotation );
  852. this.set(
  853. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  854. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  855. 0, 0, 1
  856. );
  857. return this;
  858. }
  859. //
  860. scale( sx, sy ) {
  861. this.premultiply( _m3.makeScale( sx, sy ) );
  862. return this;
  863. }
  864. rotate( theta ) {
  865. this.premultiply( _m3.makeRotation( - theta ) );
  866. return this;
  867. }
  868. translate( tx, ty ) {
  869. this.premultiply( _m3.makeTranslation( tx, ty ) );
  870. return this;
  871. }
  872. // for 2D Transforms
  873. makeTranslation( x, y ) {
  874. if ( x.isVector2 ) {
  875. this.set(
  876. 1, 0, x.x,
  877. 0, 1, x.y,
  878. 0, 0, 1
  879. );
  880. } else {
  881. this.set(
  882. 1, 0, x,
  883. 0, 1, y,
  884. 0, 0, 1
  885. );
  886. }
  887. return this;
  888. }
  889. makeRotation( theta ) {
  890. // counterclockwise
  891. const c = Math.cos( theta );
  892. const s = Math.sin( theta );
  893. this.set(
  894. c, - s, 0,
  895. s, c, 0,
  896. 0, 0, 1
  897. );
  898. return this;
  899. }
  900. makeScale( x, y ) {
  901. this.set(
  902. x, 0, 0,
  903. 0, y, 0,
  904. 0, 0, 1
  905. );
  906. return this;
  907. }
  908. //
  909. equals( matrix ) {
  910. const te = this.elements;
  911. const me = matrix.elements;
  912. for ( let i = 0; i < 9; i ++ ) {
  913. if ( te[ i ] !== me[ i ] ) return false;
  914. }
  915. return true;
  916. }
  917. fromArray( array, offset = 0 ) {
  918. for ( let i = 0; i < 9; i ++ ) {
  919. this.elements[ i ] = array[ i + offset ];
  920. }
  921. return this;
  922. }
  923. toArray( array = [], offset = 0 ) {
  924. const te = this.elements;
  925. array[ offset ] = te[ 0 ];
  926. array[ offset + 1 ] = te[ 1 ];
  927. array[ offset + 2 ] = te[ 2 ];
  928. array[ offset + 3 ] = te[ 3 ];
  929. array[ offset + 4 ] = te[ 4 ];
  930. array[ offset + 5 ] = te[ 5 ];
  931. array[ offset + 6 ] = te[ 6 ];
  932. array[ offset + 7 ] = te[ 7 ];
  933. array[ offset + 8 ] = te[ 8 ];
  934. return array;
  935. }
  936. clone() {
  937. return new this.constructor().fromArray( this.elements );
  938. }
  939. }
  940. const _m3 = /*@__PURE__*/ new Matrix3();
  941. function arrayNeedsUint32( array ) {
  942. // assumes larger values usually on last
  943. for ( let i = array.length - 1; i >= 0; -- i ) {
  944. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  945. }
  946. return false;
  947. }
  948. const TYPED_ARRAYS = {
  949. Int8Array: Int8Array,
  950. Uint8Array: Uint8Array,
  951. Uint8ClampedArray: Uint8ClampedArray,
  952. Int16Array: Int16Array,
  953. Uint16Array: Uint16Array,
  954. Int32Array: Int32Array,
  955. Uint32Array: Uint32Array,
  956. Float32Array: Float32Array,
  957. Float64Array: Float64Array
  958. };
  959. function getTypedArray( type, buffer ) {
  960. return new TYPED_ARRAYS[ type ]( buffer );
  961. }
  962. function createElementNS( name ) {
  963. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  964. }
  965. function createCanvasElement() {
  966. const canvas = createElementNS( 'canvas' );
  967. canvas.style.display = 'block';
  968. return canvas;
  969. }
  970. const _cache = {};
  971. function warnOnce( message ) {
  972. if ( message in _cache ) return;
  973. _cache[ message ] = true;
  974. console.warn( message );
  975. }
  976. function probeAsync( gl, sync, interval ) {
  977. return new Promise( function ( resolve, reject ) {
  978. function probe() {
  979. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  980. case gl.WAIT_FAILED:
  981. reject();
  982. break;
  983. case gl.TIMEOUT_EXPIRED:
  984. setTimeout( probe, interval );
  985. break;
  986. default:
  987. resolve();
  988. }
  989. }
  990. setTimeout( probe, interval );
  991. } );
  992. }
  993. function toNormalizedProjectionMatrix( projectionMatrix ) {
  994. const m = projectionMatrix.elements;
  995. // Convert [-1, 1] to [0, 1] projection matrix
  996. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  997. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  998. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  999. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  1000. }
  1001. function toReversedProjectionMatrix( projectionMatrix ) {
  1002. const m = projectionMatrix.elements;
  1003. const isPerspectiveMatrix = m[ 11 ] === - 1;
  1004. // Reverse [0, 1] projection matrix
  1005. if ( isPerspectiveMatrix ) {
  1006. m[ 10 ] = - m[ 10 ] - 1;
  1007. m[ 14 ] = - m[ 14 ];
  1008. } else {
  1009. m[ 10 ] = - m[ 10 ];
  1010. m[ 14 ] = - m[ 14 ] + 1;
  1011. }
  1012. }
  1013. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1014. 0.4123908, 0.3575843, 0.1804808,
  1015. 0.2126390, 0.7151687, 0.0721923,
  1016. 0.0193308, 0.1191948, 0.9505322
  1017. );
  1018. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1019. 3.2409699, - 1.5373832, - 0.4986108,
  1020. - 0.9692436, 1.8759675, 0.0415551,
  1021. 0.0556301, - 0.2039770, 1.0569715
  1022. );
  1023. function createColorManagement() {
  1024. const ColorManagement = {
  1025. enabled: true,
  1026. workingColorSpace: LinearSRGBColorSpace,
  1027. /**
  1028. * Implementations of supported color spaces.
  1029. *
  1030. * Required:
  1031. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  1032. * - whitePoint: reference white [ x y ]
  1033. * - transfer: transfer function (pre-defined)
  1034. * - toXYZ: Matrix3 RGB to XYZ transform
  1035. * - fromXYZ: Matrix3 XYZ to RGB transform
  1036. * - luminanceCoefficients: RGB luminance coefficients
  1037. *
  1038. * Optional:
  1039. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  1040. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  1041. *
  1042. * Reference:
  1043. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  1044. */
  1045. spaces: {},
  1046. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1047. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1048. return color;
  1049. }
  1050. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1051. color.r = SRGBToLinear( color.r );
  1052. color.g = SRGBToLinear( color.g );
  1053. color.b = SRGBToLinear( color.b );
  1054. }
  1055. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1056. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1057. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1058. }
  1059. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1060. color.r = LinearToSRGB( color.r );
  1061. color.g = LinearToSRGB( color.g );
  1062. color.b = LinearToSRGB( color.b );
  1063. }
  1064. return color;
  1065. },
  1066. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1067. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1068. },
  1069. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1070. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1071. },
  1072. getPrimaries: function ( colorSpace ) {
  1073. return this.spaces[ colorSpace ].primaries;
  1074. },
  1075. getTransfer: function ( colorSpace ) {
  1076. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1077. return this.spaces[ colorSpace ].transfer;
  1078. },
  1079. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1080. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1081. },
  1082. define: function ( colorSpaces ) {
  1083. Object.assign( this.spaces, colorSpaces );
  1084. },
  1085. // Internal APIs
  1086. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1087. return targetMatrix
  1088. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1089. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1090. },
  1091. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1092. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1093. },
  1094. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1095. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1096. }
  1097. };
  1098. /******************************************************************************
  1099. * sRGB definitions
  1100. */
  1101. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1102. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1103. const D65 = [ 0.3127, 0.3290 ];
  1104. ColorManagement.define( {
  1105. [ LinearSRGBColorSpace ]: {
  1106. primaries: REC709_PRIMARIES,
  1107. whitePoint: D65,
  1108. transfer: LinearTransfer,
  1109. toXYZ: LINEAR_REC709_TO_XYZ,
  1110. fromXYZ: XYZ_TO_LINEAR_REC709,
  1111. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1112. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1113. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1114. },
  1115. [ SRGBColorSpace ]: {
  1116. primaries: REC709_PRIMARIES,
  1117. whitePoint: D65,
  1118. transfer: SRGBTransfer,
  1119. toXYZ: LINEAR_REC709_TO_XYZ,
  1120. fromXYZ: XYZ_TO_LINEAR_REC709,
  1121. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1122. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1123. },
  1124. } );
  1125. return ColorManagement;
  1126. }
  1127. const ColorManagement = /*@__PURE__*/ createColorManagement();
  1128. function SRGBToLinear( c ) {
  1129. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1130. }
  1131. function LinearToSRGB( c ) {
  1132. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1133. }
  1134. let _canvas;
  1135. class ImageUtils {
  1136. static getDataURL( image ) {
  1137. if ( /^data:/i.test( image.src ) ) {
  1138. return image.src;
  1139. }
  1140. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1141. return image.src;
  1142. }
  1143. let canvas;
  1144. if ( image instanceof HTMLCanvasElement ) {
  1145. canvas = image;
  1146. } else {
  1147. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1148. _canvas.width = image.width;
  1149. _canvas.height = image.height;
  1150. const context = _canvas.getContext( '2d' );
  1151. if ( image instanceof ImageData ) {
  1152. context.putImageData( image, 0, 0 );
  1153. } else {
  1154. context.drawImage( image, 0, 0, image.width, image.height );
  1155. }
  1156. canvas = _canvas;
  1157. }
  1158. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1159. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1160. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1161. } else {
  1162. return canvas.toDataURL( 'image/png' );
  1163. }
  1164. }
  1165. static sRGBToLinear( image ) {
  1166. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1167. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1168. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1169. const canvas = createElementNS( 'canvas' );
  1170. canvas.width = image.width;
  1171. canvas.height = image.height;
  1172. const context = canvas.getContext( '2d' );
  1173. context.drawImage( image, 0, 0, image.width, image.height );
  1174. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1175. const data = imageData.data;
  1176. for ( let i = 0; i < data.length; i ++ ) {
  1177. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1178. }
  1179. context.putImageData( imageData, 0, 0 );
  1180. return canvas;
  1181. } else if ( image.data ) {
  1182. const data = image.data.slice( 0 );
  1183. for ( let i = 0; i < data.length; i ++ ) {
  1184. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1185. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1186. } else {
  1187. // assuming float
  1188. data[ i ] = SRGBToLinear( data[ i ] );
  1189. }
  1190. }
  1191. return {
  1192. data: data,
  1193. width: image.width,
  1194. height: image.height
  1195. };
  1196. } else {
  1197. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1198. return image;
  1199. }
  1200. }
  1201. }
  1202. let _sourceId = 0;
  1203. class Source {
  1204. constructor( data = null ) {
  1205. this.isSource = true;
  1206. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1207. this.uuid = generateUUID();
  1208. this.data = data;
  1209. this.dataReady = true;
  1210. this.version = 0;
  1211. }
  1212. set needsUpdate( value ) {
  1213. if ( value === true ) this.version ++;
  1214. }
  1215. toJSON( meta ) {
  1216. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1217. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1218. return meta.images[ this.uuid ];
  1219. }
  1220. const output = {
  1221. uuid: this.uuid,
  1222. url: ''
  1223. };
  1224. const data = this.data;
  1225. if ( data !== null ) {
  1226. let url;
  1227. if ( Array.isArray( data ) ) {
  1228. // cube texture
  1229. url = [];
  1230. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1231. if ( data[ i ].isDataTexture ) {
  1232. url.push( serializeImage( data[ i ].image ) );
  1233. } else {
  1234. url.push( serializeImage( data[ i ] ) );
  1235. }
  1236. }
  1237. } else {
  1238. // texture
  1239. url = serializeImage( data );
  1240. }
  1241. output.url = url;
  1242. }
  1243. if ( ! isRootObject ) {
  1244. meta.images[ this.uuid ] = output;
  1245. }
  1246. return output;
  1247. }
  1248. }
  1249. function serializeImage( image ) {
  1250. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1251. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1252. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1253. // default images
  1254. return ImageUtils.getDataURL( image );
  1255. } else {
  1256. if ( image.data ) {
  1257. // images of DataTexture
  1258. return {
  1259. data: Array.from( image.data ),
  1260. width: image.width,
  1261. height: image.height,
  1262. type: image.data.constructor.name
  1263. };
  1264. } else {
  1265. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1266. return {};
  1267. }
  1268. }
  1269. }
  1270. let _textureId = 0;
  1271. class Texture extends EventDispatcher {
  1272. 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 ) {
  1273. super();
  1274. this.isTexture = true;
  1275. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1276. this.uuid = generateUUID();
  1277. this.name = '';
  1278. this.source = new Source( image );
  1279. this.mipmaps = [];
  1280. this.mapping = mapping;
  1281. this.channel = 0;
  1282. this.wrapS = wrapS;
  1283. this.wrapT = wrapT;
  1284. this.magFilter = magFilter;
  1285. this.minFilter = minFilter;
  1286. this.anisotropy = anisotropy;
  1287. this.format = format;
  1288. this.internalFormat = null;
  1289. this.type = type;
  1290. this.offset = new Vector2( 0, 0 );
  1291. this.repeat = new Vector2( 1, 1 );
  1292. this.center = new Vector2( 0, 0 );
  1293. this.rotation = 0;
  1294. this.matrixAutoUpdate = true;
  1295. this.matrix = new Matrix3();
  1296. this.generateMipmaps = true;
  1297. this.premultiplyAlpha = false;
  1298. this.flipY = true;
  1299. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1300. this.colorSpace = colorSpace;
  1301. this.userData = {};
  1302. this.version = 0;
  1303. this.onUpdate = null;
  1304. this.renderTarget = null; // assign texture to a render target
  1305. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1306. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1307. }
  1308. get image() {
  1309. return this.source.data;
  1310. }
  1311. set image( value = null ) {
  1312. this.source.data = value;
  1313. }
  1314. updateMatrix() {
  1315. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1316. }
  1317. clone() {
  1318. return new this.constructor().copy( this );
  1319. }
  1320. copy( source ) {
  1321. this.name = source.name;
  1322. this.source = source.source;
  1323. this.mipmaps = source.mipmaps.slice( 0 );
  1324. this.mapping = source.mapping;
  1325. this.channel = source.channel;
  1326. this.wrapS = source.wrapS;
  1327. this.wrapT = source.wrapT;
  1328. this.magFilter = source.magFilter;
  1329. this.minFilter = source.minFilter;
  1330. this.anisotropy = source.anisotropy;
  1331. this.format = source.format;
  1332. this.internalFormat = source.internalFormat;
  1333. this.type = source.type;
  1334. this.offset.copy( source.offset );
  1335. this.repeat.copy( source.repeat );
  1336. this.center.copy( source.center );
  1337. this.rotation = source.rotation;
  1338. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1339. this.matrix.copy( source.matrix );
  1340. this.generateMipmaps = source.generateMipmaps;
  1341. this.premultiplyAlpha = source.premultiplyAlpha;
  1342. this.flipY = source.flipY;
  1343. this.unpackAlignment = source.unpackAlignment;
  1344. this.colorSpace = source.colorSpace;
  1345. this.renderTarget = source.renderTarget;
  1346. this.isRenderTargetTexture = source.isRenderTargetTexture;
  1347. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1348. this.needsUpdate = true;
  1349. return this;
  1350. }
  1351. toJSON( meta ) {
  1352. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1353. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1354. return meta.textures[ this.uuid ];
  1355. }
  1356. const output = {
  1357. metadata: {
  1358. version: 4.6,
  1359. type: 'Texture',
  1360. generator: 'Texture.toJSON'
  1361. },
  1362. uuid: this.uuid,
  1363. name: this.name,
  1364. image: this.source.toJSON( meta ).uuid,
  1365. mapping: this.mapping,
  1366. channel: this.channel,
  1367. repeat: [ this.repeat.x, this.repeat.y ],
  1368. offset: [ this.offset.x, this.offset.y ],
  1369. center: [ this.center.x, this.center.y ],
  1370. rotation: this.rotation,
  1371. wrap: [ this.wrapS, this.wrapT ],
  1372. format: this.format,
  1373. internalFormat: this.internalFormat,
  1374. type: this.type,
  1375. colorSpace: this.colorSpace,
  1376. minFilter: this.minFilter,
  1377. magFilter: this.magFilter,
  1378. anisotropy: this.anisotropy,
  1379. flipY: this.flipY,
  1380. generateMipmaps: this.generateMipmaps,
  1381. premultiplyAlpha: this.premultiplyAlpha,
  1382. unpackAlignment: this.unpackAlignment
  1383. };
  1384. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1385. if ( ! isRootObject ) {
  1386. meta.textures[ this.uuid ] = output;
  1387. }
  1388. return output;
  1389. }
  1390. dispose() {
  1391. this.dispatchEvent( { type: 'dispose' } );
  1392. }
  1393. transformUv( uv ) {
  1394. if ( this.mapping !== UVMapping ) return uv;
  1395. uv.applyMatrix3( this.matrix );
  1396. if ( uv.x < 0 || uv.x > 1 ) {
  1397. switch ( this.wrapS ) {
  1398. case RepeatWrapping:
  1399. uv.x = uv.x - Math.floor( uv.x );
  1400. break;
  1401. case ClampToEdgeWrapping:
  1402. uv.x = uv.x < 0 ? 0 : 1;
  1403. break;
  1404. case MirroredRepeatWrapping:
  1405. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1406. uv.x = Math.ceil( uv.x ) - uv.x;
  1407. } else {
  1408. uv.x = uv.x - Math.floor( uv.x );
  1409. }
  1410. break;
  1411. }
  1412. }
  1413. if ( uv.y < 0 || uv.y > 1 ) {
  1414. switch ( this.wrapT ) {
  1415. case RepeatWrapping:
  1416. uv.y = uv.y - Math.floor( uv.y );
  1417. break;
  1418. case ClampToEdgeWrapping:
  1419. uv.y = uv.y < 0 ? 0 : 1;
  1420. break;
  1421. case MirroredRepeatWrapping:
  1422. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1423. uv.y = Math.ceil( uv.y ) - uv.y;
  1424. } else {
  1425. uv.y = uv.y - Math.floor( uv.y );
  1426. }
  1427. break;
  1428. }
  1429. }
  1430. if ( this.flipY ) {
  1431. uv.y = 1 - uv.y;
  1432. }
  1433. return uv;
  1434. }
  1435. set needsUpdate( value ) {
  1436. if ( value === true ) {
  1437. this.version ++;
  1438. this.source.needsUpdate = true;
  1439. }
  1440. }
  1441. set needsPMREMUpdate( value ) {
  1442. if ( value === true ) {
  1443. this.pmremVersion ++;
  1444. }
  1445. }
  1446. }
  1447. Texture.DEFAULT_IMAGE = null;
  1448. Texture.DEFAULT_MAPPING = UVMapping;
  1449. Texture.DEFAULT_ANISOTROPY = 1;
  1450. class Vector4 {
  1451. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1452. Vector4.prototype.isVector4 = true;
  1453. this.x = x;
  1454. this.y = y;
  1455. this.z = z;
  1456. this.w = w;
  1457. }
  1458. get width() {
  1459. return this.z;
  1460. }
  1461. set width( value ) {
  1462. this.z = value;
  1463. }
  1464. get height() {
  1465. return this.w;
  1466. }
  1467. set height( value ) {
  1468. this.w = value;
  1469. }
  1470. set( x, y, z, w ) {
  1471. this.x = x;
  1472. this.y = y;
  1473. this.z = z;
  1474. this.w = w;
  1475. return this;
  1476. }
  1477. setScalar( scalar ) {
  1478. this.x = scalar;
  1479. this.y = scalar;
  1480. this.z = scalar;
  1481. this.w = scalar;
  1482. return this;
  1483. }
  1484. setX( x ) {
  1485. this.x = x;
  1486. return this;
  1487. }
  1488. setY( y ) {
  1489. this.y = y;
  1490. return this;
  1491. }
  1492. setZ( z ) {
  1493. this.z = z;
  1494. return this;
  1495. }
  1496. setW( w ) {
  1497. this.w = w;
  1498. return this;
  1499. }
  1500. setComponent( index, value ) {
  1501. switch ( index ) {
  1502. case 0: this.x = value; break;
  1503. case 1: this.y = value; break;
  1504. case 2: this.z = value; break;
  1505. case 3: this.w = value; break;
  1506. default: throw new Error( 'index is out of range: ' + index );
  1507. }
  1508. return this;
  1509. }
  1510. getComponent( index ) {
  1511. switch ( index ) {
  1512. case 0: return this.x;
  1513. case 1: return this.y;
  1514. case 2: return this.z;
  1515. case 3: return this.w;
  1516. default: throw new Error( 'index is out of range: ' + index );
  1517. }
  1518. }
  1519. clone() {
  1520. return new this.constructor( this.x, this.y, this.z, this.w );
  1521. }
  1522. copy( v ) {
  1523. this.x = v.x;
  1524. this.y = v.y;
  1525. this.z = v.z;
  1526. this.w = ( v.w !== undefined ) ? v.w : 1;
  1527. return this;
  1528. }
  1529. add( v ) {
  1530. this.x += v.x;
  1531. this.y += v.y;
  1532. this.z += v.z;
  1533. this.w += v.w;
  1534. return this;
  1535. }
  1536. addScalar( s ) {
  1537. this.x += s;
  1538. this.y += s;
  1539. this.z += s;
  1540. this.w += s;
  1541. return this;
  1542. }
  1543. addVectors( a, b ) {
  1544. this.x = a.x + b.x;
  1545. this.y = a.y + b.y;
  1546. this.z = a.z + b.z;
  1547. this.w = a.w + b.w;
  1548. return this;
  1549. }
  1550. addScaledVector( v, s ) {
  1551. this.x += v.x * s;
  1552. this.y += v.y * s;
  1553. this.z += v.z * s;
  1554. this.w += v.w * s;
  1555. return this;
  1556. }
  1557. sub( v ) {
  1558. this.x -= v.x;
  1559. this.y -= v.y;
  1560. this.z -= v.z;
  1561. this.w -= v.w;
  1562. return this;
  1563. }
  1564. subScalar( s ) {
  1565. this.x -= s;
  1566. this.y -= s;
  1567. this.z -= s;
  1568. this.w -= s;
  1569. return this;
  1570. }
  1571. subVectors( a, b ) {
  1572. this.x = a.x - b.x;
  1573. this.y = a.y - b.y;
  1574. this.z = a.z - b.z;
  1575. this.w = a.w - b.w;
  1576. return this;
  1577. }
  1578. multiply( v ) {
  1579. this.x *= v.x;
  1580. this.y *= v.y;
  1581. this.z *= v.z;
  1582. this.w *= v.w;
  1583. return this;
  1584. }
  1585. multiplyScalar( scalar ) {
  1586. this.x *= scalar;
  1587. this.y *= scalar;
  1588. this.z *= scalar;
  1589. this.w *= scalar;
  1590. return this;
  1591. }
  1592. applyMatrix4( m ) {
  1593. const x = this.x, y = this.y, z = this.z, w = this.w;
  1594. const e = m.elements;
  1595. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1596. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1597. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1598. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1599. return this;
  1600. }
  1601. divide( v ) {
  1602. this.x /= v.x;
  1603. this.y /= v.y;
  1604. this.z /= v.z;
  1605. this.w /= v.w;
  1606. return this;
  1607. }
  1608. divideScalar( scalar ) {
  1609. return this.multiplyScalar( 1 / scalar );
  1610. }
  1611. setAxisAngleFromQuaternion( q ) {
  1612. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1613. // q is assumed to be normalized
  1614. this.w = 2 * Math.acos( q.w );
  1615. const s = Math.sqrt( 1 - q.w * q.w );
  1616. if ( s < 0.0001 ) {
  1617. this.x = 1;
  1618. this.y = 0;
  1619. this.z = 0;
  1620. } else {
  1621. this.x = q.x / s;
  1622. this.y = q.y / s;
  1623. this.z = q.z / s;
  1624. }
  1625. return this;
  1626. }
  1627. setAxisAngleFromRotationMatrix( m ) {
  1628. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1629. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1630. let angle, x, y, z; // variables for result
  1631. const epsilon = 0.01, // margin to allow for rounding errors
  1632. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1633. te = m.elements,
  1634. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1635. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1636. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1637. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1638. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1639. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1640. // singularity found
  1641. // first check for identity matrix which must have +1 for all terms
  1642. // in leading diagonal and zero in other terms
  1643. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1644. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1645. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1646. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1647. // this singularity is identity matrix so angle = 0
  1648. this.set( 1, 0, 0, 0 );
  1649. return this; // zero angle, arbitrary axis
  1650. }
  1651. // otherwise this singularity is angle = 180
  1652. angle = Math.PI;
  1653. const xx = ( m11 + 1 ) / 2;
  1654. const yy = ( m22 + 1 ) / 2;
  1655. const zz = ( m33 + 1 ) / 2;
  1656. const xy = ( m12 + m21 ) / 4;
  1657. const xz = ( m13 + m31 ) / 4;
  1658. const yz = ( m23 + m32 ) / 4;
  1659. if ( ( xx > yy ) && ( xx > zz ) ) {
  1660. // m11 is the largest diagonal term
  1661. if ( xx < epsilon ) {
  1662. x = 0;
  1663. y = 0.707106781;
  1664. z = 0.707106781;
  1665. } else {
  1666. x = Math.sqrt( xx );
  1667. y = xy / x;
  1668. z = xz / x;
  1669. }
  1670. } else if ( yy > zz ) {
  1671. // m22 is the largest diagonal term
  1672. if ( yy < epsilon ) {
  1673. x = 0.707106781;
  1674. y = 0;
  1675. z = 0.707106781;
  1676. } else {
  1677. y = Math.sqrt( yy );
  1678. x = xy / y;
  1679. z = yz / y;
  1680. }
  1681. } else {
  1682. // m33 is the largest diagonal term so base result on this
  1683. if ( zz < epsilon ) {
  1684. x = 0.707106781;
  1685. y = 0.707106781;
  1686. z = 0;
  1687. } else {
  1688. z = Math.sqrt( zz );
  1689. x = xz / z;
  1690. y = yz / z;
  1691. }
  1692. }
  1693. this.set( x, y, z, angle );
  1694. return this; // return 180 deg rotation
  1695. }
  1696. // as we have reached here there are no singularities so we can handle normally
  1697. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1698. ( m13 - m31 ) * ( m13 - m31 ) +
  1699. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1700. if ( Math.abs( s ) < 0.001 ) s = 1;
  1701. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1702. // caught by singularity test above, but I've left it in just in case
  1703. this.x = ( m32 - m23 ) / s;
  1704. this.y = ( m13 - m31 ) / s;
  1705. this.z = ( m21 - m12 ) / s;
  1706. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1707. return this;
  1708. }
  1709. setFromMatrixPosition( m ) {
  1710. const e = m.elements;
  1711. this.x = e[ 12 ];
  1712. this.y = e[ 13 ];
  1713. this.z = e[ 14 ];
  1714. this.w = e[ 15 ];
  1715. return this;
  1716. }
  1717. min( v ) {
  1718. this.x = Math.min( this.x, v.x );
  1719. this.y = Math.min( this.y, v.y );
  1720. this.z = Math.min( this.z, v.z );
  1721. this.w = Math.min( this.w, v.w );
  1722. return this;
  1723. }
  1724. max( v ) {
  1725. this.x = Math.max( this.x, v.x );
  1726. this.y = Math.max( this.y, v.y );
  1727. this.z = Math.max( this.z, v.z );
  1728. this.w = Math.max( this.w, v.w );
  1729. return this;
  1730. }
  1731. clamp( min, max ) {
  1732. // assumes min < max, componentwise
  1733. this.x = clamp( this.x, min.x, max.x );
  1734. this.y = clamp( this.y, min.y, max.y );
  1735. this.z = clamp( this.z, min.z, max.z );
  1736. this.w = clamp( this.w, min.w, max.w );
  1737. return this;
  1738. }
  1739. clampScalar( minVal, maxVal ) {
  1740. this.x = clamp( this.x, minVal, maxVal );
  1741. this.y = clamp( this.y, minVal, maxVal );
  1742. this.z = clamp( this.z, minVal, maxVal );
  1743. this.w = clamp( this.w, minVal, maxVal );
  1744. return this;
  1745. }
  1746. clampLength( min, max ) {
  1747. const length = this.length();
  1748. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  1749. }
  1750. floor() {
  1751. this.x = Math.floor( this.x );
  1752. this.y = Math.floor( this.y );
  1753. this.z = Math.floor( this.z );
  1754. this.w = Math.floor( this.w );
  1755. return this;
  1756. }
  1757. ceil() {
  1758. this.x = Math.ceil( this.x );
  1759. this.y = Math.ceil( this.y );
  1760. this.z = Math.ceil( this.z );
  1761. this.w = Math.ceil( this.w );
  1762. return this;
  1763. }
  1764. round() {
  1765. this.x = Math.round( this.x );
  1766. this.y = Math.round( this.y );
  1767. this.z = Math.round( this.z );
  1768. this.w = Math.round( this.w );
  1769. return this;
  1770. }
  1771. roundToZero() {
  1772. this.x = Math.trunc( this.x );
  1773. this.y = Math.trunc( this.y );
  1774. this.z = Math.trunc( this.z );
  1775. this.w = Math.trunc( this.w );
  1776. return this;
  1777. }
  1778. negate() {
  1779. this.x = - this.x;
  1780. this.y = - this.y;
  1781. this.z = - this.z;
  1782. this.w = - this.w;
  1783. return this;
  1784. }
  1785. dot( v ) {
  1786. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1787. }
  1788. lengthSq() {
  1789. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1790. }
  1791. length() {
  1792. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1793. }
  1794. manhattanLength() {
  1795. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1796. }
  1797. normalize() {
  1798. return this.divideScalar( this.length() || 1 );
  1799. }
  1800. setLength( length ) {
  1801. return this.normalize().multiplyScalar( length );
  1802. }
  1803. lerp( v, alpha ) {
  1804. this.x += ( v.x - this.x ) * alpha;
  1805. this.y += ( v.y - this.y ) * alpha;
  1806. this.z += ( v.z - this.z ) * alpha;
  1807. this.w += ( v.w - this.w ) * alpha;
  1808. return this;
  1809. }
  1810. lerpVectors( v1, v2, alpha ) {
  1811. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1812. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1813. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1814. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1815. return this;
  1816. }
  1817. equals( v ) {
  1818. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1819. }
  1820. fromArray( array, offset = 0 ) {
  1821. this.x = array[ offset ];
  1822. this.y = array[ offset + 1 ];
  1823. this.z = array[ offset + 2 ];
  1824. this.w = array[ offset + 3 ];
  1825. return this;
  1826. }
  1827. toArray( array = [], offset = 0 ) {
  1828. array[ offset ] = this.x;
  1829. array[ offset + 1 ] = this.y;
  1830. array[ offset + 2 ] = this.z;
  1831. array[ offset + 3 ] = this.w;
  1832. return array;
  1833. }
  1834. fromBufferAttribute( attribute, index ) {
  1835. this.x = attribute.getX( index );
  1836. this.y = attribute.getY( index );
  1837. this.z = attribute.getZ( index );
  1838. this.w = attribute.getW( index );
  1839. return this;
  1840. }
  1841. random() {
  1842. this.x = Math.random();
  1843. this.y = Math.random();
  1844. this.z = Math.random();
  1845. this.w = Math.random();
  1846. return this;
  1847. }
  1848. *[ Symbol.iterator ]() {
  1849. yield this.x;
  1850. yield this.y;
  1851. yield this.z;
  1852. yield this.w;
  1853. }
  1854. }
  1855. /*
  1856. In options, we can specify:
  1857. * Texture parameters for an auto-generated target texture
  1858. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1859. */
  1860. class RenderTarget extends EventDispatcher {
  1861. constructor( width = 1, height = 1, options = {} ) {
  1862. super();
  1863. this.isRenderTarget = true;
  1864. this.width = width;
  1865. this.height = height;
  1866. this.depth = 1;
  1867. this.scissor = new Vector4( 0, 0, width, height );
  1868. this.scissorTest = false;
  1869. this.viewport = new Vector4( 0, 0, width, height );
  1870. const image = { width: width, height: height, depth: 1 };
  1871. options = Object.assign( {
  1872. generateMipmaps: false,
  1873. internalFormat: null,
  1874. minFilter: LinearFilter,
  1875. depthBuffer: true,
  1876. stencilBuffer: false,
  1877. resolveDepthBuffer: true,
  1878. resolveStencilBuffer: true,
  1879. depthTexture: null,
  1880. samples: 0,
  1881. count: 1
  1882. }, options );
  1883. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1884. texture.flipY = false;
  1885. texture.generateMipmaps = options.generateMipmaps;
  1886. texture.internalFormat = options.internalFormat;
  1887. this.textures = [];
  1888. const count = options.count;
  1889. for ( let i = 0; i < count; i ++ ) {
  1890. this.textures[ i ] = texture.clone();
  1891. this.textures[ i ].isRenderTargetTexture = true;
  1892. this.textures[ i ].renderTarget = this;
  1893. }
  1894. this.depthBuffer = options.depthBuffer;
  1895. this.stencilBuffer = options.stencilBuffer;
  1896. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1897. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1898. this._depthTexture = null;
  1899. this.depthTexture = options.depthTexture;
  1900. this.samples = options.samples;
  1901. }
  1902. get texture() {
  1903. return this.textures[ 0 ];
  1904. }
  1905. set texture( value ) {
  1906. this.textures[ 0 ] = value;
  1907. }
  1908. set depthTexture( current ) {
  1909. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  1910. if ( current !== null ) current.renderTarget = this;
  1911. this._depthTexture = current;
  1912. }
  1913. get depthTexture() {
  1914. return this._depthTexture;
  1915. }
  1916. setSize( width, height, depth = 1 ) {
  1917. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1918. this.width = width;
  1919. this.height = height;
  1920. this.depth = depth;
  1921. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1922. this.textures[ i ].image.width = width;
  1923. this.textures[ i ].image.height = height;
  1924. this.textures[ i ].image.depth = depth;
  1925. }
  1926. this.dispose();
  1927. }
  1928. this.viewport.set( 0, 0, width, height );
  1929. this.scissor.set( 0, 0, width, height );
  1930. }
  1931. clone() {
  1932. return new this.constructor().copy( this );
  1933. }
  1934. copy( source ) {
  1935. this.width = source.width;
  1936. this.height = source.height;
  1937. this.depth = source.depth;
  1938. this.scissor.copy( source.scissor );
  1939. this.scissorTest = source.scissorTest;
  1940. this.viewport.copy( source.viewport );
  1941. this.textures.length = 0;
  1942. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1943. this.textures[ i ] = source.textures[ i ].clone();
  1944. this.textures[ i ].isRenderTargetTexture = true;
  1945. this.textures[ i ].renderTarget = this;
  1946. }
  1947. // ensure image object is not shared, see #20328
  1948. const image = Object.assign( {}, source.texture.image );
  1949. this.texture.source = new Source( image );
  1950. this.depthBuffer = source.depthBuffer;
  1951. this.stencilBuffer = source.stencilBuffer;
  1952. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1953. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1954. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1955. this.samples = source.samples;
  1956. return this;
  1957. }
  1958. dispose() {
  1959. this.dispatchEvent( { type: 'dispose' } );
  1960. }
  1961. }
  1962. class WebGLRenderTarget extends RenderTarget {
  1963. constructor( width = 1, height = 1, options = {} ) {
  1964. super( width, height, options );
  1965. this.isWebGLRenderTarget = true;
  1966. }
  1967. }
  1968. class DataArrayTexture extends Texture {
  1969. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1970. super( null );
  1971. this.isDataArrayTexture = true;
  1972. this.image = { data, width, height, depth };
  1973. this.magFilter = NearestFilter;
  1974. this.minFilter = NearestFilter;
  1975. this.wrapR = ClampToEdgeWrapping;
  1976. this.generateMipmaps = false;
  1977. this.flipY = false;
  1978. this.unpackAlignment = 1;
  1979. this.layerUpdates = new Set();
  1980. }
  1981. addLayerUpdate( layerIndex ) {
  1982. this.layerUpdates.add( layerIndex );
  1983. }
  1984. clearLayerUpdates() {
  1985. this.layerUpdates.clear();
  1986. }
  1987. }
  1988. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1989. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1990. super( width, height, options );
  1991. this.isWebGLArrayRenderTarget = true;
  1992. this.depth = depth;
  1993. this.texture = new DataArrayTexture( null, width, height, depth );
  1994. this.texture.isRenderTargetTexture = true;
  1995. }
  1996. }
  1997. class Data3DTexture extends Texture {
  1998. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1999. // We're going to add .setXXX() methods for setting properties later.
  2000. // Users can still set in DataTexture3D directly.
  2001. //
  2002. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2003. // texture.anisotropy = 16;
  2004. //
  2005. // See #14839
  2006. super( null );
  2007. this.isData3DTexture = true;
  2008. this.image = { data, width, height, depth };
  2009. this.magFilter = NearestFilter;
  2010. this.minFilter = NearestFilter;
  2011. this.wrapR = ClampToEdgeWrapping;
  2012. this.generateMipmaps = false;
  2013. this.flipY = false;
  2014. this.unpackAlignment = 1;
  2015. }
  2016. }
  2017. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2018. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  2019. super( width, height, options );
  2020. this.isWebGL3DRenderTarget = true;
  2021. this.depth = depth;
  2022. this.texture = new Data3DTexture( null, width, height, depth );
  2023. this.texture.isRenderTargetTexture = true;
  2024. }
  2025. }
  2026. class Quaternion {
  2027. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2028. this.isQuaternion = true;
  2029. this._x = x;
  2030. this._y = y;
  2031. this._z = z;
  2032. this._w = w;
  2033. }
  2034. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2035. // fuzz-free, array-based Quaternion SLERP operation
  2036. let x0 = src0[ srcOffset0 + 0 ],
  2037. y0 = src0[ srcOffset0 + 1 ],
  2038. z0 = src0[ srcOffset0 + 2 ],
  2039. w0 = src0[ srcOffset0 + 3 ];
  2040. const x1 = src1[ srcOffset1 + 0 ],
  2041. y1 = src1[ srcOffset1 + 1 ],
  2042. z1 = src1[ srcOffset1 + 2 ],
  2043. w1 = src1[ srcOffset1 + 3 ];
  2044. if ( t === 0 ) {
  2045. dst[ dstOffset + 0 ] = x0;
  2046. dst[ dstOffset + 1 ] = y0;
  2047. dst[ dstOffset + 2 ] = z0;
  2048. dst[ dstOffset + 3 ] = w0;
  2049. return;
  2050. }
  2051. if ( t === 1 ) {
  2052. dst[ dstOffset + 0 ] = x1;
  2053. dst[ dstOffset + 1 ] = y1;
  2054. dst[ dstOffset + 2 ] = z1;
  2055. dst[ dstOffset + 3 ] = w1;
  2056. return;
  2057. }
  2058. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2059. let s = 1 - t;
  2060. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2061. dir = ( cos >= 0 ? 1 : - 1 ),
  2062. sqrSin = 1 - cos * cos;
  2063. // Skip the Slerp for tiny steps to avoid numeric problems:
  2064. if ( sqrSin > Number.EPSILON ) {
  2065. const sin = Math.sqrt( sqrSin ),
  2066. len = Math.atan2( sin, cos * dir );
  2067. s = Math.sin( s * len ) / sin;
  2068. t = Math.sin( t * len ) / sin;
  2069. }
  2070. const tDir = t * dir;
  2071. x0 = x0 * s + x1 * tDir;
  2072. y0 = y0 * s + y1 * tDir;
  2073. z0 = z0 * s + z1 * tDir;
  2074. w0 = w0 * s + w1 * tDir;
  2075. // Normalize in case we just did a lerp:
  2076. if ( s === 1 - t ) {
  2077. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2078. x0 *= f;
  2079. y0 *= f;
  2080. z0 *= f;
  2081. w0 *= f;
  2082. }
  2083. }
  2084. dst[ dstOffset ] = x0;
  2085. dst[ dstOffset + 1 ] = y0;
  2086. dst[ dstOffset + 2 ] = z0;
  2087. dst[ dstOffset + 3 ] = w0;
  2088. }
  2089. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2090. const x0 = src0[ srcOffset0 ];
  2091. const y0 = src0[ srcOffset0 + 1 ];
  2092. const z0 = src0[ srcOffset0 + 2 ];
  2093. const w0 = src0[ srcOffset0 + 3 ];
  2094. const x1 = src1[ srcOffset1 ];
  2095. const y1 = src1[ srcOffset1 + 1 ];
  2096. const z1 = src1[ srcOffset1 + 2 ];
  2097. const w1 = src1[ srcOffset1 + 3 ];
  2098. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2099. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2100. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2101. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2102. return dst;
  2103. }
  2104. get x() {
  2105. return this._x;
  2106. }
  2107. set x( value ) {
  2108. this._x = value;
  2109. this._onChangeCallback();
  2110. }
  2111. get y() {
  2112. return this._y;
  2113. }
  2114. set y( value ) {
  2115. this._y = value;
  2116. this._onChangeCallback();
  2117. }
  2118. get z() {
  2119. return this._z;
  2120. }
  2121. set z( value ) {
  2122. this._z = value;
  2123. this._onChangeCallback();
  2124. }
  2125. get w() {
  2126. return this._w;
  2127. }
  2128. set w( value ) {
  2129. this._w = value;
  2130. this._onChangeCallback();
  2131. }
  2132. set( x, y, z, w ) {
  2133. this._x = x;
  2134. this._y = y;
  2135. this._z = z;
  2136. this._w = w;
  2137. this._onChangeCallback();
  2138. return this;
  2139. }
  2140. clone() {
  2141. return new this.constructor( this._x, this._y, this._z, this._w );
  2142. }
  2143. copy( quaternion ) {
  2144. this._x = quaternion.x;
  2145. this._y = quaternion.y;
  2146. this._z = quaternion.z;
  2147. this._w = quaternion.w;
  2148. this._onChangeCallback();
  2149. return this;
  2150. }
  2151. setFromEuler( euler, update = true ) {
  2152. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2153. // http://www.mathworks.com/matlabcentral/fileexchange/
  2154. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2155. // content/SpinCalc.m
  2156. const cos = Math.cos;
  2157. const sin = Math.sin;
  2158. const c1 = cos( x / 2 );
  2159. const c2 = cos( y / 2 );
  2160. const c3 = cos( z / 2 );
  2161. const s1 = sin( x / 2 );
  2162. const s2 = sin( y / 2 );
  2163. const s3 = sin( z / 2 );
  2164. switch ( order ) {
  2165. case 'XYZ':
  2166. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2167. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2168. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2169. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2170. break;
  2171. case 'YXZ':
  2172. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2173. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2174. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2175. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2176. break;
  2177. case 'ZXY':
  2178. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2179. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2180. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2181. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2182. break;
  2183. case 'ZYX':
  2184. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2185. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2186. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2187. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2188. break;
  2189. case 'YZX':
  2190. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2191. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2192. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2193. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2194. break;
  2195. case 'XZY':
  2196. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2197. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2198. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2199. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2200. break;
  2201. default:
  2202. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2203. }
  2204. if ( update === true ) this._onChangeCallback();
  2205. return this;
  2206. }
  2207. setFromAxisAngle( axis, angle ) {
  2208. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2209. // assumes axis is normalized
  2210. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2211. this._x = axis.x * s;
  2212. this._y = axis.y * s;
  2213. this._z = axis.z * s;
  2214. this._w = Math.cos( halfAngle );
  2215. this._onChangeCallback();
  2216. return this;
  2217. }
  2218. setFromRotationMatrix( m ) {
  2219. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2220. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2221. const te = m.elements,
  2222. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2223. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2224. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2225. trace = m11 + m22 + m33;
  2226. if ( trace > 0 ) {
  2227. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2228. this._w = 0.25 / s;
  2229. this._x = ( m32 - m23 ) * s;
  2230. this._y = ( m13 - m31 ) * s;
  2231. this._z = ( m21 - m12 ) * s;
  2232. } else if ( m11 > m22 && m11 > m33 ) {
  2233. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2234. this._w = ( m32 - m23 ) / s;
  2235. this._x = 0.25 * s;
  2236. this._y = ( m12 + m21 ) / s;
  2237. this._z = ( m13 + m31 ) / s;
  2238. } else if ( m22 > m33 ) {
  2239. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2240. this._w = ( m13 - m31 ) / s;
  2241. this._x = ( m12 + m21 ) / s;
  2242. this._y = 0.25 * s;
  2243. this._z = ( m23 + m32 ) / s;
  2244. } else {
  2245. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2246. this._w = ( m21 - m12 ) / s;
  2247. this._x = ( m13 + m31 ) / s;
  2248. this._y = ( m23 + m32 ) / s;
  2249. this._z = 0.25 * s;
  2250. }
  2251. this._onChangeCallback();
  2252. return this;
  2253. }
  2254. setFromUnitVectors( vFrom, vTo ) {
  2255. // assumes direction vectors vFrom and vTo are normalized
  2256. let r = vFrom.dot( vTo ) + 1;
  2257. if ( r < Number.EPSILON ) {
  2258. // vFrom and vTo point in opposite directions
  2259. r = 0;
  2260. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2261. this._x = - vFrom.y;
  2262. this._y = vFrom.x;
  2263. this._z = 0;
  2264. this._w = r;
  2265. } else {
  2266. this._x = 0;
  2267. this._y = - vFrom.z;
  2268. this._z = vFrom.y;
  2269. this._w = r;
  2270. }
  2271. } else {
  2272. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2273. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2274. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2275. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2276. this._w = r;
  2277. }
  2278. return this.normalize();
  2279. }
  2280. angleTo( q ) {
  2281. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2282. }
  2283. rotateTowards( q, step ) {
  2284. const angle = this.angleTo( q );
  2285. if ( angle === 0 ) return this;
  2286. const t = Math.min( 1, step / angle );
  2287. this.slerp( q, t );
  2288. return this;
  2289. }
  2290. identity() {
  2291. return this.set( 0, 0, 0, 1 );
  2292. }
  2293. invert() {
  2294. // quaternion is assumed to have unit length
  2295. return this.conjugate();
  2296. }
  2297. conjugate() {
  2298. this._x *= - 1;
  2299. this._y *= - 1;
  2300. this._z *= - 1;
  2301. this._onChangeCallback();
  2302. return this;
  2303. }
  2304. dot( v ) {
  2305. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2306. }
  2307. lengthSq() {
  2308. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2309. }
  2310. length() {
  2311. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2312. }
  2313. normalize() {
  2314. let l = this.length();
  2315. if ( l === 0 ) {
  2316. this._x = 0;
  2317. this._y = 0;
  2318. this._z = 0;
  2319. this._w = 1;
  2320. } else {
  2321. l = 1 / l;
  2322. this._x = this._x * l;
  2323. this._y = this._y * l;
  2324. this._z = this._z * l;
  2325. this._w = this._w * l;
  2326. }
  2327. this._onChangeCallback();
  2328. return this;
  2329. }
  2330. multiply( q ) {
  2331. return this.multiplyQuaternions( this, q );
  2332. }
  2333. premultiply( q ) {
  2334. return this.multiplyQuaternions( q, this );
  2335. }
  2336. multiplyQuaternions( a, b ) {
  2337. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2338. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2339. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2340. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2341. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2342. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2343. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2344. this._onChangeCallback();
  2345. return this;
  2346. }
  2347. slerp( qb, t ) {
  2348. if ( t === 0 ) return this;
  2349. if ( t === 1 ) return this.copy( qb );
  2350. const x = this._x, y = this._y, z = this._z, w = this._w;
  2351. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2352. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2353. if ( cosHalfTheta < 0 ) {
  2354. this._w = - qb._w;
  2355. this._x = - qb._x;
  2356. this._y = - qb._y;
  2357. this._z = - qb._z;
  2358. cosHalfTheta = - cosHalfTheta;
  2359. } else {
  2360. this.copy( qb );
  2361. }
  2362. if ( cosHalfTheta >= 1.0 ) {
  2363. this._w = w;
  2364. this._x = x;
  2365. this._y = y;
  2366. this._z = z;
  2367. return this;
  2368. }
  2369. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2370. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2371. const s = 1 - t;
  2372. this._w = s * w + t * this._w;
  2373. this._x = s * x + t * this._x;
  2374. this._y = s * y + t * this._y;
  2375. this._z = s * z + t * this._z;
  2376. this.normalize(); // normalize calls _onChangeCallback()
  2377. return this;
  2378. }
  2379. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2380. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2381. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2382. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2383. this._w = ( w * ratioA + this._w * ratioB );
  2384. this._x = ( x * ratioA + this._x * ratioB );
  2385. this._y = ( y * ratioA + this._y * ratioB );
  2386. this._z = ( z * ratioA + this._z * ratioB );
  2387. this._onChangeCallback();
  2388. return this;
  2389. }
  2390. slerpQuaternions( qa, qb, t ) {
  2391. return this.copy( qa ).slerp( qb, t );
  2392. }
  2393. random() {
  2394. // sets this quaternion to a uniform random unit quaternnion
  2395. // Ken Shoemake
  2396. // Uniform random rotations
  2397. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2398. const theta1 = 2 * Math.PI * Math.random();
  2399. const theta2 = 2 * Math.PI * Math.random();
  2400. const x0 = Math.random();
  2401. const r1 = Math.sqrt( 1 - x0 );
  2402. const r2 = Math.sqrt( x0 );
  2403. return this.set(
  2404. r1 * Math.sin( theta1 ),
  2405. r1 * Math.cos( theta1 ),
  2406. r2 * Math.sin( theta2 ),
  2407. r2 * Math.cos( theta2 ),
  2408. );
  2409. }
  2410. equals( quaternion ) {
  2411. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2412. }
  2413. fromArray( array, offset = 0 ) {
  2414. this._x = array[ offset ];
  2415. this._y = array[ offset + 1 ];
  2416. this._z = array[ offset + 2 ];
  2417. this._w = array[ offset + 3 ];
  2418. this._onChangeCallback();
  2419. return this;
  2420. }
  2421. toArray( array = [], offset = 0 ) {
  2422. array[ offset ] = this._x;
  2423. array[ offset + 1 ] = this._y;
  2424. array[ offset + 2 ] = this._z;
  2425. array[ offset + 3 ] = this._w;
  2426. return array;
  2427. }
  2428. fromBufferAttribute( attribute, index ) {
  2429. this._x = attribute.getX( index );
  2430. this._y = attribute.getY( index );
  2431. this._z = attribute.getZ( index );
  2432. this._w = attribute.getW( index );
  2433. this._onChangeCallback();
  2434. return this;
  2435. }
  2436. toJSON() {
  2437. return this.toArray();
  2438. }
  2439. _onChange( callback ) {
  2440. this._onChangeCallback = callback;
  2441. return this;
  2442. }
  2443. _onChangeCallback() {}
  2444. *[ Symbol.iterator ]() {
  2445. yield this._x;
  2446. yield this._y;
  2447. yield this._z;
  2448. yield this._w;
  2449. }
  2450. }
  2451. class Vector3 {
  2452. constructor( x = 0, y = 0, z = 0 ) {
  2453. Vector3.prototype.isVector3 = true;
  2454. this.x = x;
  2455. this.y = y;
  2456. this.z = z;
  2457. }
  2458. set( x, y, z ) {
  2459. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2460. this.x = x;
  2461. this.y = y;
  2462. this.z = z;
  2463. return this;
  2464. }
  2465. setScalar( scalar ) {
  2466. this.x = scalar;
  2467. this.y = scalar;
  2468. this.z = scalar;
  2469. return this;
  2470. }
  2471. setX( x ) {
  2472. this.x = x;
  2473. return this;
  2474. }
  2475. setY( y ) {
  2476. this.y = y;
  2477. return this;
  2478. }
  2479. setZ( z ) {
  2480. this.z = z;
  2481. return this;
  2482. }
  2483. setComponent( index, value ) {
  2484. switch ( index ) {
  2485. case 0: this.x = value; break;
  2486. case 1: this.y = value; break;
  2487. case 2: this.z = value; break;
  2488. default: throw new Error( 'index is out of range: ' + index );
  2489. }
  2490. return this;
  2491. }
  2492. getComponent( index ) {
  2493. switch ( index ) {
  2494. case 0: return this.x;
  2495. case 1: return this.y;
  2496. case 2: return this.z;
  2497. default: throw new Error( 'index is out of range: ' + index );
  2498. }
  2499. }
  2500. clone() {
  2501. return new this.constructor( this.x, this.y, this.z );
  2502. }
  2503. copy( v ) {
  2504. this.x = v.x;
  2505. this.y = v.y;
  2506. this.z = v.z;
  2507. return this;
  2508. }
  2509. add( v ) {
  2510. this.x += v.x;
  2511. this.y += v.y;
  2512. this.z += v.z;
  2513. return this;
  2514. }
  2515. addScalar( s ) {
  2516. this.x += s;
  2517. this.y += s;
  2518. this.z += s;
  2519. return this;
  2520. }
  2521. addVectors( a, b ) {
  2522. this.x = a.x + b.x;
  2523. this.y = a.y + b.y;
  2524. this.z = a.z + b.z;
  2525. return this;
  2526. }
  2527. addScaledVector( v, s ) {
  2528. this.x += v.x * s;
  2529. this.y += v.y * s;
  2530. this.z += v.z * s;
  2531. return this;
  2532. }
  2533. sub( v ) {
  2534. this.x -= v.x;
  2535. this.y -= v.y;
  2536. this.z -= v.z;
  2537. return this;
  2538. }
  2539. subScalar( s ) {
  2540. this.x -= s;
  2541. this.y -= s;
  2542. this.z -= s;
  2543. return this;
  2544. }
  2545. subVectors( a, b ) {
  2546. this.x = a.x - b.x;
  2547. this.y = a.y - b.y;
  2548. this.z = a.z - b.z;
  2549. return this;
  2550. }
  2551. multiply( v ) {
  2552. this.x *= v.x;
  2553. this.y *= v.y;
  2554. this.z *= v.z;
  2555. return this;
  2556. }
  2557. multiplyScalar( scalar ) {
  2558. this.x *= scalar;
  2559. this.y *= scalar;
  2560. this.z *= scalar;
  2561. return this;
  2562. }
  2563. multiplyVectors( a, b ) {
  2564. this.x = a.x * b.x;
  2565. this.y = a.y * b.y;
  2566. this.z = a.z * b.z;
  2567. return this;
  2568. }
  2569. applyEuler( euler ) {
  2570. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2571. }
  2572. applyAxisAngle( axis, angle ) {
  2573. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2574. }
  2575. applyMatrix3( m ) {
  2576. const x = this.x, y = this.y, z = this.z;
  2577. const e = m.elements;
  2578. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2579. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2580. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2581. return this;
  2582. }
  2583. applyNormalMatrix( m ) {
  2584. return this.applyMatrix3( m ).normalize();
  2585. }
  2586. applyMatrix4( m ) {
  2587. const x = this.x, y = this.y, z = this.z;
  2588. const e = m.elements;
  2589. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2590. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2591. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2592. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2593. return this;
  2594. }
  2595. applyQuaternion( q ) {
  2596. // quaternion q is assumed to have unit length
  2597. const vx = this.x, vy = this.y, vz = this.z;
  2598. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2599. // t = 2 * cross( q.xyz, v );
  2600. const tx = 2 * ( qy * vz - qz * vy );
  2601. const ty = 2 * ( qz * vx - qx * vz );
  2602. const tz = 2 * ( qx * vy - qy * vx );
  2603. // v + q.w * t + cross( q.xyz, t );
  2604. this.x = vx + qw * tx + qy * tz - qz * ty;
  2605. this.y = vy + qw * ty + qz * tx - qx * tz;
  2606. this.z = vz + qw * tz + qx * ty - qy * tx;
  2607. return this;
  2608. }
  2609. project( camera ) {
  2610. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2611. }
  2612. unproject( camera ) {
  2613. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2614. }
  2615. transformDirection( m ) {
  2616. // input: THREE.Matrix4 affine matrix
  2617. // vector interpreted as a direction
  2618. const x = this.x, y = this.y, z = this.z;
  2619. const e = m.elements;
  2620. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2621. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2622. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2623. return this.normalize();
  2624. }
  2625. divide( v ) {
  2626. this.x /= v.x;
  2627. this.y /= v.y;
  2628. this.z /= v.z;
  2629. return this;
  2630. }
  2631. divideScalar( scalar ) {
  2632. return this.multiplyScalar( 1 / scalar );
  2633. }
  2634. min( v ) {
  2635. this.x = Math.min( this.x, v.x );
  2636. this.y = Math.min( this.y, v.y );
  2637. this.z = Math.min( this.z, v.z );
  2638. return this;
  2639. }
  2640. max( v ) {
  2641. this.x = Math.max( this.x, v.x );
  2642. this.y = Math.max( this.y, v.y );
  2643. this.z = Math.max( this.z, v.z );
  2644. return this;
  2645. }
  2646. clamp( min, max ) {
  2647. // assumes min < max, componentwise
  2648. this.x = clamp( this.x, min.x, max.x );
  2649. this.y = clamp( this.y, min.y, max.y );
  2650. this.z = clamp( this.z, min.z, max.z );
  2651. return this;
  2652. }
  2653. clampScalar( minVal, maxVal ) {
  2654. this.x = clamp( this.x, minVal, maxVal );
  2655. this.y = clamp( this.y, minVal, maxVal );
  2656. this.z = clamp( this.z, minVal, maxVal );
  2657. return this;
  2658. }
  2659. clampLength( min, max ) {
  2660. const length = this.length();
  2661. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2662. }
  2663. floor() {
  2664. this.x = Math.floor( this.x );
  2665. this.y = Math.floor( this.y );
  2666. this.z = Math.floor( this.z );
  2667. return this;
  2668. }
  2669. ceil() {
  2670. this.x = Math.ceil( this.x );
  2671. this.y = Math.ceil( this.y );
  2672. this.z = Math.ceil( this.z );
  2673. return this;
  2674. }
  2675. round() {
  2676. this.x = Math.round( this.x );
  2677. this.y = Math.round( this.y );
  2678. this.z = Math.round( this.z );
  2679. return this;
  2680. }
  2681. roundToZero() {
  2682. this.x = Math.trunc( this.x );
  2683. this.y = Math.trunc( this.y );
  2684. this.z = Math.trunc( this.z );
  2685. return this;
  2686. }
  2687. negate() {
  2688. this.x = - this.x;
  2689. this.y = - this.y;
  2690. this.z = - this.z;
  2691. return this;
  2692. }
  2693. dot( v ) {
  2694. return this.x * v.x + this.y * v.y + this.z * v.z;
  2695. }
  2696. // TODO lengthSquared?
  2697. lengthSq() {
  2698. return this.x * this.x + this.y * this.y + this.z * this.z;
  2699. }
  2700. length() {
  2701. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2702. }
  2703. manhattanLength() {
  2704. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2705. }
  2706. normalize() {
  2707. return this.divideScalar( this.length() || 1 );
  2708. }
  2709. setLength( length ) {
  2710. return this.normalize().multiplyScalar( length );
  2711. }
  2712. lerp( v, alpha ) {
  2713. this.x += ( v.x - this.x ) * alpha;
  2714. this.y += ( v.y - this.y ) * alpha;
  2715. this.z += ( v.z - this.z ) * alpha;
  2716. return this;
  2717. }
  2718. lerpVectors( v1, v2, alpha ) {
  2719. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2720. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2721. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2722. return this;
  2723. }
  2724. cross( v ) {
  2725. return this.crossVectors( this, v );
  2726. }
  2727. crossVectors( a, b ) {
  2728. const ax = a.x, ay = a.y, az = a.z;
  2729. const bx = b.x, by = b.y, bz = b.z;
  2730. this.x = ay * bz - az * by;
  2731. this.y = az * bx - ax * bz;
  2732. this.z = ax * by - ay * bx;
  2733. return this;
  2734. }
  2735. projectOnVector( v ) {
  2736. const denominator = v.lengthSq();
  2737. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2738. const scalar = v.dot( this ) / denominator;
  2739. return this.copy( v ).multiplyScalar( scalar );
  2740. }
  2741. projectOnPlane( planeNormal ) {
  2742. _vector$c.copy( this ).projectOnVector( planeNormal );
  2743. return this.sub( _vector$c );
  2744. }
  2745. reflect( normal ) {
  2746. // reflect incident vector off plane orthogonal to normal
  2747. // normal is assumed to have unit length
  2748. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2749. }
  2750. angleTo( v ) {
  2751. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2752. if ( denominator === 0 ) return Math.PI / 2;
  2753. const theta = this.dot( v ) / denominator;
  2754. // clamp, to handle numerical problems
  2755. return Math.acos( clamp( theta, - 1, 1 ) );
  2756. }
  2757. distanceTo( v ) {
  2758. return Math.sqrt( this.distanceToSquared( v ) );
  2759. }
  2760. distanceToSquared( v ) {
  2761. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2762. return dx * dx + dy * dy + dz * dz;
  2763. }
  2764. manhattanDistanceTo( v ) {
  2765. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2766. }
  2767. setFromSpherical( s ) {
  2768. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2769. }
  2770. setFromSphericalCoords( radius, phi, theta ) {
  2771. const sinPhiRadius = Math.sin( phi ) * radius;
  2772. this.x = sinPhiRadius * Math.sin( theta );
  2773. this.y = Math.cos( phi ) * radius;
  2774. this.z = sinPhiRadius * Math.cos( theta );
  2775. return this;
  2776. }
  2777. setFromCylindrical( c ) {
  2778. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2779. }
  2780. setFromCylindricalCoords( radius, theta, y ) {
  2781. this.x = radius * Math.sin( theta );
  2782. this.y = y;
  2783. this.z = radius * Math.cos( theta );
  2784. return this;
  2785. }
  2786. setFromMatrixPosition( m ) {
  2787. const e = m.elements;
  2788. this.x = e[ 12 ];
  2789. this.y = e[ 13 ];
  2790. this.z = e[ 14 ];
  2791. return this;
  2792. }
  2793. setFromMatrixScale( m ) {
  2794. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2795. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2796. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2797. this.x = sx;
  2798. this.y = sy;
  2799. this.z = sz;
  2800. return this;
  2801. }
  2802. setFromMatrixColumn( m, index ) {
  2803. return this.fromArray( m.elements, index * 4 );
  2804. }
  2805. setFromMatrix3Column( m, index ) {
  2806. return this.fromArray( m.elements, index * 3 );
  2807. }
  2808. setFromEuler( e ) {
  2809. this.x = e._x;
  2810. this.y = e._y;
  2811. this.z = e._z;
  2812. return this;
  2813. }
  2814. setFromColor( c ) {
  2815. this.x = c.r;
  2816. this.y = c.g;
  2817. this.z = c.b;
  2818. return this;
  2819. }
  2820. equals( v ) {
  2821. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2822. }
  2823. fromArray( array, offset = 0 ) {
  2824. this.x = array[ offset ];
  2825. this.y = array[ offset + 1 ];
  2826. this.z = array[ offset + 2 ];
  2827. return this;
  2828. }
  2829. toArray( array = [], offset = 0 ) {
  2830. array[ offset ] = this.x;
  2831. array[ offset + 1 ] = this.y;
  2832. array[ offset + 2 ] = this.z;
  2833. return array;
  2834. }
  2835. fromBufferAttribute( attribute, index ) {
  2836. this.x = attribute.getX( index );
  2837. this.y = attribute.getY( index );
  2838. this.z = attribute.getZ( index );
  2839. return this;
  2840. }
  2841. random() {
  2842. this.x = Math.random();
  2843. this.y = Math.random();
  2844. this.z = Math.random();
  2845. return this;
  2846. }
  2847. randomDirection() {
  2848. // https://mathworld.wolfram.com/SpherePointPicking.html
  2849. const theta = Math.random() * Math.PI * 2;
  2850. const u = Math.random() * 2 - 1;
  2851. const c = Math.sqrt( 1 - u * u );
  2852. this.x = c * Math.cos( theta );
  2853. this.y = u;
  2854. this.z = c * Math.sin( theta );
  2855. return this;
  2856. }
  2857. *[ Symbol.iterator ]() {
  2858. yield this.x;
  2859. yield this.y;
  2860. yield this.z;
  2861. }
  2862. }
  2863. const _vector$c = /*@__PURE__*/ new Vector3();
  2864. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2865. class Box3 {
  2866. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2867. this.isBox3 = true;
  2868. this.min = min;
  2869. this.max = max;
  2870. }
  2871. set( min, max ) {
  2872. this.min.copy( min );
  2873. this.max.copy( max );
  2874. return this;
  2875. }
  2876. setFromArray( array ) {
  2877. this.makeEmpty();
  2878. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2879. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2880. }
  2881. return this;
  2882. }
  2883. setFromBufferAttribute( attribute ) {
  2884. this.makeEmpty();
  2885. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2886. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2887. }
  2888. return this;
  2889. }
  2890. setFromPoints( points ) {
  2891. this.makeEmpty();
  2892. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2893. this.expandByPoint( points[ i ] );
  2894. }
  2895. return this;
  2896. }
  2897. setFromCenterAndSize( center, size ) {
  2898. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2899. this.min.copy( center ).sub( halfSize );
  2900. this.max.copy( center ).add( halfSize );
  2901. return this;
  2902. }
  2903. setFromObject( object, precise = false ) {
  2904. this.makeEmpty();
  2905. return this.expandByObject( object, precise );
  2906. }
  2907. clone() {
  2908. return new this.constructor().copy( this );
  2909. }
  2910. copy( box ) {
  2911. this.min.copy( box.min );
  2912. this.max.copy( box.max );
  2913. return this;
  2914. }
  2915. makeEmpty() {
  2916. this.min.x = this.min.y = this.min.z = + Infinity;
  2917. this.max.x = this.max.y = this.max.z = - Infinity;
  2918. return this;
  2919. }
  2920. isEmpty() {
  2921. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2922. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2923. }
  2924. getCenter( target ) {
  2925. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2926. }
  2927. getSize( target ) {
  2928. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2929. }
  2930. expandByPoint( point ) {
  2931. this.min.min( point );
  2932. this.max.max( point );
  2933. return this;
  2934. }
  2935. expandByVector( vector ) {
  2936. this.min.sub( vector );
  2937. this.max.add( vector );
  2938. return this;
  2939. }
  2940. expandByScalar( scalar ) {
  2941. this.min.addScalar( - scalar );
  2942. this.max.addScalar( scalar );
  2943. return this;
  2944. }
  2945. expandByObject( object, precise = false ) {
  2946. // Computes the world-axis-aligned bounding box of an object (including its children),
  2947. // accounting for both the object's, and children's, world transforms
  2948. object.updateWorldMatrix( false, false );
  2949. const geometry = object.geometry;
  2950. if ( geometry !== undefined ) {
  2951. const positionAttribute = geometry.getAttribute( 'position' );
  2952. // precise AABB computation based on vertex data requires at least a position attribute.
  2953. // instancing isn't supported so far and uses the normal (conservative) code path.
  2954. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2955. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2956. if ( object.isMesh === true ) {
  2957. object.getVertexPosition( i, _vector$b );
  2958. } else {
  2959. _vector$b.fromBufferAttribute( positionAttribute, i );
  2960. }
  2961. _vector$b.applyMatrix4( object.matrixWorld );
  2962. this.expandByPoint( _vector$b );
  2963. }
  2964. } else {
  2965. if ( object.boundingBox !== undefined ) {
  2966. // object-level bounding box
  2967. if ( object.boundingBox === null ) {
  2968. object.computeBoundingBox();
  2969. }
  2970. _box$4.copy( object.boundingBox );
  2971. } else {
  2972. // geometry-level bounding box
  2973. if ( geometry.boundingBox === null ) {
  2974. geometry.computeBoundingBox();
  2975. }
  2976. _box$4.copy( geometry.boundingBox );
  2977. }
  2978. _box$4.applyMatrix4( object.matrixWorld );
  2979. this.union( _box$4 );
  2980. }
  2981. }
  2982. const children = object.children;
  2983. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2984. this.expandByObject( children[ i ], precise );
  2985. }
  2986. return this;
  2987. }
  2988. containsPoint( point ) {
  2989. return point.x >= this.min.x && point.x <= this.max.x &&
  2990. point.y >= this.min.y && point.y <= this.max.y &&
  2991. point.z >= this.min.z && point.z <= this.max.z;
  2992. }
  2993. containsBox( box ) {
  2994. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2995. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2996. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2997. }
  2998. getParameter( point, target ) {
  2999. // This can potentially have a divide by zero if the box
  3000. // has a size dimension of 0.
  3001. return target.set(
  3002. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3003. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3004. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3005. );
  3006. }
  3007. intersectsBox( box ) {
  3008. // using 6 splitting planes to rule out intersections.
  3009. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  3010. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  3011. box.max.z >= this.min.z && box.min.z <= this.max.z;
  3012. }
  3013. intersectsSphere( sphere ) {
  3014. // Find the point on the AABB closest to the sphere center.
  3015. this.clampPoint( sphere.center, _vector$b );
  3016. // If that point is inside the sphere, the AABB and sphere intersect.
  3017. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3018. }
  3019. intersectsPlane( plane ) {
  3020. // We compute the minimum and maximum dot product values. If those values
  3021. // are on the same side (back or front) of the plane, then there is no intersection.
  3022. let min, max;
  3023. if ( plane.normal.x > 0 ) {
  3024. min = plane.normal.x * this.min.x;
  3025. max = plane.normal.x * this.max.x;
  3026. } else {
  3027. min = plane.normal.x * this.max.x;
  3028. max = plane.normal.x * this.min.x;
  3029. }
  3030. if ( plane.normal.y > 0 ) {
  3031. min += plane.normal.y * this.min.y;
  3032. max += plane.normal.y * this.max.y;
  3033. } else {
  3034. min += plane.normal.y * this.max.y;
  3035. max += plane.normal.y * this.min.y;
  3036. }
  3037. if ( plane.normal.z > 0 ) {
  3038. min += plane.normal.z * this.min.z;
  3039. max += plane.normal.z * this.max.z;
  3040. } else {
  3041. min += plane.normal.z * this.max.z;
  3042. max += plane.normal.z * this.min.z;
  3043. }
  3044. return ( min <= - plane.constant && max >= - plane.constant );
  3045. }
  3046. intersectsTriangle( triangle ) {
  3047. if ( this.isEmpty() ) {
  3048. return false;
  3049. }
  3050. // compute box center and extents
  3051. this.getCenter( _center );
  3052. _extents.subVectors( this.max, _center );
  3053. // translate triangle to aabb origin
  3054. _v0$3.subVectors( triangle.a, _center );
  3055. _v1$7.subVectors( triangle.b, _center );
  3056. _v2$4.subVectors( triangle.c, _center );
  3057. // compute edge vectors for triangle
  3058. _f0.subVectors( _v1$7, _v0$3 );
  3059. _f1.subVectors( _v2$4, _v1$7 );
  3060. _f2.subVectors( _v0$3, _v2$4 );
  3061. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3062. // 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
  3063. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3064. let axes = [
  3065. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3066. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3067. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3068. ];
  3069. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  3070. return false;
  3071. }
  3072. // test 3 face normals from the aabb
  3073. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3074. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  3075. return false;
  3076. }
  3077. // finally testing the face normal of the triangle
  3078. // use already existing triangle edge vectors here
  3079. _triangleNormal.crossVectors( _f0, _f1 );
  3080. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3081. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  3082. }
  3083. clampPoint( point, target ) {
  3084. return target.copy( point ).clamp( this.min, this.max );
  3085. }
  3086. distanceToPoint( point ) {
  3087. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3088. }
  3089. getBoundingSphere( target ) {
  3090. if ( this.isEmpty() ) {
  3091. target.makeEmpty();
  3092. } else {
  3093. this.getCenter( target.center );
  3094. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3095. }
  3096. return target;
  3097. }
  3098. intersect( box ) {
  3099. this.min.max( box.min );
  3100. this.max.min( box.max );
  3101. // 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.
  3102. if ( this.isEmpty() ) this.makeEmpty();
  3103. return this;
  3104. }
  3105. union( box ) {
  3106. this.min.min( box.min );
  3107. this.max.max( box.max );
  3108. return this;
  3109. }
  3110. applyMatrix4( matrix ) {
  3111. // transform of empty box is an empty box.
  3112. if ( this.isEmpty() ) return this;
  3113. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3114. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3115. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3116. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3117. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3118. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3119. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3120. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3121. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3122. this.setFromPoints( _points );
  3123. return this;
  3124. }
  3125. translate( offset ) {
  3126. this.min.add( offset );
  3127. this.max.add( offset );
  3128. return this;
  3129. }
  3130. equals( box ) {
  3131. return box.min.equals( this.min ) && box.max.equals( this.max );
  3132. }
  3133. }
  3134. const _points = [
  3135. /*@__PURE__*/ new Vector3(),
  3136. /*@__PURE__*/ new Vector3(),
  3137. /*@__PURE__*/ new Vector3(),
  3138. /*@__PURE__*/ new Vector3(),
  3139. /*@__PURE__*/ new Vector3(),
  3140. /*@__PURE__*/ new Vector3(),
  3141. /*@__PURE__*/ new Vector3(),
  3142. /*@__PURE__*/ new Vector3()
  3143. ];
  3144. const _vector$b = /*@__PURE__*/ new Vector3();
  3145. const _box$4 = /*@__PURE__*/ new Box3();
  3146. // triangle centered vertices
  3147. const _v0$3 = /*@__PURE__*/ new Vector3();
  3148. const _v1$7 = /*@__PURE__*/ new Vector3();
  3149. const _v2$4 = /*@__PURE__*/ new Vector3();
  3150. // triangle edge vectors
  3151. const _f0 = /*@__PURE__*/ new Vector3();
  3152. const _f1 = /*@__PURE__*/ new Vector3();
  3153. const _f2 = /*@__PURE__*/ new Vector3();
  3154. const _center = /*@__PURE__*/ new Vector3();
  3155. const _extents = /*@__PURE__*/ new Vector3();
  3156. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3157. const _testAxis = /*@__PURE__*/ new Vector3();
  3158. function satForAxes( axes, v0, v1, v2, extents ) {
  3159. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3160. _testAxis.fromArray( axes, i );
  3161. // project the aabb onto the separating axis
  3162. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3163. // project all 3 vertices of the triangle onto the separating axis
  3164. const p0 = v0.dot( _testAxis );
  3165. const p1 = v1.dot( _testAxis );
  3166. const p2 = v2.dot( _testAxis );
  3167. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3168. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3169. // points of the projected triangle are outside the projected half-length of the aabb
  3170. // the axis is separating and we can exit
  3171. return false;
  3172. }
  3173. }
  3174. return true;
  3175. }
  3176. const _box$3 = /*@__PURE__*/ new Box3();
  3177. const _v1$6 = /*@__PURE__*/ new Vector3();
  3178. const _v2$3 = /*@__PURE__*/ new Vector3();
  3179. class Sphere {
  3180. constructor( center = new Vector3(), radius = - 1 ) {
  3181. this.isSphere = true;
  3182. this.center = center;
  3183. this.radius = radius;
  3184. }
  3185. set( center, radius ) {
  3186. this.center.copy( center );
  3187. this.radius = radius;
  3188. return this;
  3189. }
  3190. setFromPoints( points, optionalCenter ) {
  3191. const center = this.center;
  3192. if ( optionalCenter !== undefined ) {
  3193. center.copy( optionalCenter );
  3194. } else {
  3195. _box$3.setFromPoints( points ).getCenter( center );
  3196. }
  3197. let maxRadiusSq = 0;
  3198. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3199. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3200. }
  3201. this.radius = Math.sqrt( maxRadiusSq );
  3202. return this;
  3203. }
  3204. copy( sphere ) {
  3205. this.center.copy( sphere.center );
  3206. this.radius = sphere.radius;
  3207. return this;
  3208. }
  3209. isEmpty() {
  3210. return ( this.radius < 0 );
  3211. }
  3212. makeEmpty() {
  3213. this.center.set( 0, 0, 0 );
  3214. this.radius = - 1;
  3215. return this;
  3216. }
  3217. containsPoint( point ) {
  3218. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3219. }
  3220. distanceToPoint( point ) {
  3221. return ( point.distanceTo( this.center ) - this.radius );
  3222. }
  3223. intersectsSphere( sphere ) {
  3224. const radiusSum = this.radius + sphere.radius;
  3225. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3226. }
  3227. intersectsBox( box ) {
  3228. return box.intersectsSphere( this );
  3229. }
  3230. intersectsPlane( plane ) {
  3231. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3232. }
  3233. clampPoint( point, target ) {
  3234. const deltaLengthSq = this.center.distanceToSquared( point );
  3235. target.copy( point );
  3236. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3237. target.sub( this.center ).normalize();
  3238. target.multiplyScalar( this.radius ).add( this.center );
  3239. }
  3240. return target;
  3241. }
  3242. getBoundingBox( target ) {
  3243. if ( this.isEmpty() ) {
  3244. // Empty sphere produces empty bounding box
  3245. target.makeEmpty();
  3246. return target;
  3247. }
  3248. target.set( this.center, this.center );
  3249. target.expandByScalar( this.radius );
  3250. return target;
  3251. }
  3252. applyMatrix4( matrix ) {
  3253. this.center.applyMatrix4( matrix );
  3254. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3255. return this;
  3256. }
  3257. translate( offset ) {
  3258. this.center.add( offset );
  3259. return this;
  3260. }
  3261. expandByPoint( point ) {
  3262. if ( this.isEmpty() ) {
  3263. this.center.copy( point );
  3264. this.radius = 0;
  3265. return this;
  3266. }
  3267. _v1$6.subVectors( point, this.center );
  3268. const lengthSq = _v1$6.lengthSq();
  3269. if ( lengthSq > ( this.radius * this.radius ) ) {
  3270. // calculate the minimal sphere
  3271. const length = Math.sqrt( lengthSq );
  3272. const delta = ( length - this.radius ) * 0.5;
  3273. this.center.addScaledVector( _v1$6, delta / length );
  3274. this.radius += delta;
  3275. }
  3276. return this;
  3277. }
  3278. union( sphere ) {
  3279. if ( sphere.isEmpty() ) {
  3280. return this;
  3281. }
  3282. if ( this.isEmpty() ) {
  3283. this.copy( sphere );
  3284. return this;
  3285. }
  3286. if ( this.center.equals( sphere.center ) === true ) {
  3287. this.radius = Math.max( this.radius, sphere.radius );
  3288. } else {
  3289. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3290. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3291. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3292. }
  3293. return this;
  3294. }
  3295. equals( sphere ) {
  3296. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3297. }
  3298. clone() {
  3299. return new this.constructor().copy( this );
  3300. }
  3301. }
  3302. const _vector$a = /*@__PURE__*/ new Vector3();
  3303. const _segCenter = /*@__PURE__*/ new Vector3();
  3304. const _segDir = /*@__PURE__*/ new Vector3();
  3305. const _diff = /*@__PURE__*/ new Vector3();
  3306. const _edge1 = /*@__PURE__*/ new Vector3();
  3307. const _edge2 = /*@__PURE__*/ new Vector3();
  3308. const _normal$1 = /*@__PURE__*/ new Vector3();
  3309. class Ray {
  3310. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3311. this.origin = origin;
  3312. this.direction = direction;
  3313. }
  3314. set( origin, direction ) {
  3315. this.origin.copy( origin );
  3316. this.direction.copy( direction );
  3317. return this;
  3318. }
  3319. copy( ray ) {
  3320. this.origin.copy( ray.origin );
  3321. this.direction.copy( ray.direction );
  3322. return this;
  3323. }
  3324. at( t, target ) {
  3325. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3326. }
  3327. lookAt( v ) {
  3328. this.direction.copy( v ).sub( this.origin ).normalize();
  3329. return this;
  3330. }
  3331. recast( t ) {
  3332. this.origin.copy( this.at( t, _vector$a ) );
  3333. return this;
  3334. }
  3335. closestPointToPoint( point, target ) {
  3336. target.subVectors( point, this.origin );
  3337. const directionDistance = target.dot( this.direction );
  3338. if ( directionDistance < 0 ) {
  3339. return target.copy( this.origin );
  3340. }
  3341. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3342. }
  3343. distanceToPoint( point ) {
  3344. return Math.sqrt( this.distanceSqToPoint( point ) );
  3345. }
  3346. distanceSqToPoint( point ) {
  3347. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3348. // point behind the ray
  3349. if ( directionDistance < 0 ) {
  3350. return this.origin.distanceToSquared( point );
  3351. }
  3352. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3353. return _vector$a.distanceToSquared( point );
  3354. }
  3355. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3356. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3357. // It returns the min distance between the ray and the segment
  3358. // defined by v0 and v1
  3359. // It can also set two optional targets :
  3360. // - The closest point on the ray
  3361. // - The closest point on the segment
  3362. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3363. _segDir.copy( v1 ).sub( v0 ).normalize();
  3364. _diff.copy( this.origin ).sub( _segCenter );
  3365. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3366. const a01 = - this.direction.dot( _segDir );
  3367. const b0 = _diff.dot( this.direction );
  3368. const b1 = - _diff.dot( _segDir );
  3369. const c = _diff.lengthSq();
  3370. const det = Math.abs( 1 - a01 * a01 );
  3371. let s0, s1, sqrDist, extDet;
  3372. if ( det > 0 ) {
  3373. // The ray and segment are not parallel.
  3374. s0 = a01 * b1 - b0;
  3375. s1 = a01 * b0 - b1;
  3376. extDet = segExtent * det;
  3377. if ( s0 >= 0 ) {
  3378. if ( s1 >= - extDet ) {
  3379. if ( s1 <= extDet ) {
  3380. // region 0
  3381. // Minimum at interior points of ray and segment.
  3382. const invDet = 1 / det;
  3383. s0 *= invDet;
  3384. s1 *= invDet;
  3385. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3386. } else {
  3387. // region 1
  3388. s1 = segExtent;
  3389. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3390. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3391. }
  3392. } else {
  3393. // region 5
  3394. s1 = - segExtent;
  3395. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3396. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3397. }
  3398. } else {
  3399. if ( s1 <= - extDet ) {
  3400. // region 4
  3401. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3402. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3403. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3404. } else if ( s1 <= extDet ) {
  3405. // region 3
  3406. s0 = 0;
  3407. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3408. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3409. } else {
  3410. // region 2
  3411. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3412. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3413. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3414. }
  3415. }
  3416. } else {
  3417. // Ray and segment are parallel.
  3418. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3419. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3420. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3421. }
  3422. if ( optionalPointOnRay ) {
  3423. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3424. }
  3425. if ( optionalPointOnSegment ) {
  3426. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3427. }
  3428. return sqrDist;
  3429. }
  3430. intersectSphere( sphere, target ) {
  3431. _vector$a.subVectors( sphere.center, this.origin );
  3432. const tca = _vector$a.dot( this.direction );
  3433. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3434. const radius2 = sphere.radius * sphere.radius;
  3435. if ( d2 > radius2 ) return null;
  3436. const thc = Math.sqrt( radius2 - d2 );
  3437. // t0 = first intersect point - entrance on front of sphere
  3438. const t0 = tca - thc;
  3439. // t1 = second intersect point - exit point on back of sphere
  3440. const t1 = tca + thc;
  3441. // test to see if t1 is behind the ray - if so, return null
  3442. if ( t1 < 0 ) return null;
  3443. // test to see if t0 is behind the ray:
  3444. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3445. // in order to always return an intersect point that is in front of the ray.
  3446. if ( t0 < 0 ) return this.at( t1, target );
  3447. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3448. return this.at( t0, target );
  3449. }
  3450. intersectsSphere( sphere ) {
  3451. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3452. }
  3453. distanceToPlane( plane ) {
  3454. const denominator = plane.normal.dot( this.direction );
  3455. if ( denominator === 0 ) {
  3456. // line is coplanar, return origin
  3457. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3458. return 0;
  3459. }
  3460. // Null is preferable to undefined since undefined means.... it is undefined
  3461. return null;
  3462. }
  3463. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3464. // Return if the ray never intersects the plane
  3465. return t >= 0 ? t : null;
  3466. }
  3467. intersectPlane( plane, target ) {
  3468. const t = this.distanceToPlane( plane );
  3469. if ( t === null ) {
  3470. return null;
  3471. }
  3472. return this.at( t, target );
  3473. }
  3474. intersectsPlane( plane ) {
  3475. // check if the ray lies on the plane first
  3476. const distToPoint = plane.distanceToPoint( this.origin );
  3477. if ( distToPoint === 0 ) {
  3478. return true;
  3479. }
  3480. const denominator = plane.normal.dot( this.direction );
  3481. if ( denominator * distToPoint < 0 ) {
  3482. return true;
  3483. }
  3484. // ray origin is behind the plane (and is pointing behind it)
  3485. return false;
  3486. }
  3487. intersectBox( box, target ) {
  3488. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3489. const invdirx = 1 / this.direction.x,
  3490. invdiry = 1 / this.direction.y,
  3491. invdirz = 1 / this.direction.z;
  3492. const origin = this.origin;
  3493. if ( invdirx >= 0 ) {
  3494. tmin = ( box.min.x - origin.x ) * invdirx;
  3495. tmax = ( box.max.x - origin.x ) * invdirx;
  3496. } else {
  3497. tmin = ( box.max.x - origin.x ) * invdirx;
  3498. tmax = ( box.min.x - origin.x ) * invdirx;
  3499. }
  3500. if ( invdiry >= 0 ) {
  3501. tymin = ( box.min.y - origin.y ) * invdiry;
  3502. tymax = ( box.max.y - origin.y ) * invdiry;
  3503. } else {
  3504. tymin = ( box.max.y - origin.y ) * invdiry;
  3505. tymax = ( box.min.y - origin.y ) * invdiry;
  3506. }
  3507. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3508. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3509. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3510. if ( invdirz >= 0 ) {
  3511. tzmin = ( box.min.z - origin.z ) * invdirz;
  3512. tzmax = ( box.max.z - origin.z ) * invdirz;
  3513. } else {
  3514. tzmin = ( box.max.z - origin.z ) * invdirz;
  3515. tzmax = ( box.min.z - origin.z ) * invdirz;
  3516. }
  3517. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3518. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3519. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3520. //return point closest to the ray (positive side)
  3521. if ( tmax < 0 ) return null;
  3522. return this.at( tmin >= 0 ? tmin : tmax, target );
  3523. }
  3524. intersectsBox( box ) {
  3525. return this.intersectBox( box, _vector$a ) !== null;
  3526. }
  3527. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3528. // Compute the offset origin, edges, and normal.
  3529. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3530. _edge1.subVectors( b, a );
  3531. _edge2.subVectors( c, a );
  3532. _normal$1.crossVectors( _edge1, _edge2 );
  3533. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3534. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3535. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3536. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3537. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3538. let DdN = this.direction.dot( _normal$1 );
  3539. let sign;
  3540. if ( DdN > 0 ) {
  3541. if ( backfaceCulling ) return null;
  3542. sign = 1;
  3543. } else if ( DdN < 0 ) {
  3544. sign = - 1;
  3545. DdN = - DdN;
  3546. } else {
  3547. return null;
  3548. }
  3549. _diff.subVectors( this.origin, a );
  3550. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3551. // b1 < 0, no intersection
  3552. if ( DdQxE2 < 0 ) {
  3553. return null;
  3554. }
  3555. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3556. // b2 < 0, no intersection
  3557. if ( DdE1xQ < 0 ) {
  3558. return null;
  3559. }
  3560. // b1+b2 > 1, no intersection
  3561. if ( DdQxE2 + DdE1xQ > DdN ) {
  3562. return null;
  3563. }
  3564. // Line intersects triangle, check if ray does.
  3565. const QdN = - sign * _diff.dot( _normal$1 );
  3566. // t < 0, no intersection
  3567. if ( QdN < 0 ) {
  3568. return null;
  3569. }
  3570. // Ray intersects triangle.
  3571. return this.at( QdN / DdN, target );
  3572. }
  3573. applyMatrix4( matrix4 ) {
  3574. this.origin.applyMatrix4( matrix4 );
  3575. this.direction.transformDirection( matrix4 );
  3576. return this;
  3577. }
  3578. equals( ray ) {
  3579. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3580. }
  3581. clone() {
  3582. return new this.constructor().copy( this );
  3583. }
  3584. }
  3585. class Matrix4 {
  3586. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3587. Matrix4.prototype.isMatrix4 = true;
  3588. this.elements = [
  3589. 1, 0, 0, 0,
  3590. 0, 1, 0, 0,
  3591. 0, 0, 1, 0,
  3592. 0, 0, 0, 1
  3593. ];
  3594. if ( n11 !== undefined ) {
  3595. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3596. }
  3597. }
  3598. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3599. const te = this.elements;
  3600. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3601. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3602. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3603. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3604. return this;
  3605. }
  3606. identity() {
  3607. this.set(
  3608. 1, 0, 0, 0,
  3609. 0, 1, 0, 0,
  3610. 0, 0, 1, 0,
  3611. 0, 0, 0, 1
  3612. );
  3613. return this;
  3614. }
  3615. clone() {
  3616. return new Matrix4().fromArray( this.elements );
  3617. }
  3618. copy( m ) {
  3619. const te = this.elements;
  3620. const me = m.elements;
  3621. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3622. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3623. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3624. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3625. return this;
  3626. }
  3627. copyPosition( m ) {
  3628. const te = this.elements, me = m.elements;
  3629. te[ 12 ] = me[ 12 ];
  3630. te[ 13 ] = me[ 13 ];
  3631. te[ 14 ] = me[ 14 ];
  3632. return this;
  3633. }
  3634. setFromMatrix3( m ) {
  3635. const me = m.elements;
  3636. this.set(
  3637. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3638. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3639. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3640. 0, 0, 0, 1
  3641. );
  3642. return this;
  3643. }
  3644. extractBasis( xAxis, yAxis, zAxis ) {
  3645. xAxis.setFromMatrixColumn( this, 0 );
  3646. yAxis.setFromMatrixColumn( this, 1 );
  3647. zAxis.setFromMatrixColumn( this, 2 );
  3648. return this;
  3649. }
  3650. makeBasis( xAxis, yAxis, zAxis ) {
  3651. this.set(
  3652. xAxis.x, yAxis.x, zAxis.x, 0,
  3653. xAxis.y, yAxis.y, zAxis.y, 0,
  3654. xAxis.z, yAxis.z, zAxis.z, 0,
  3655. 0, 0, 0, 1
  3656. );
  3657. return this;
  3658. }
  3659. extractRotation( m ) {
  3660. // this method does not support reflection matrices
  3661. const te = this.elements;
  3662. const me = m.elements;
  3663. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3664. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3665. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3666. te[ 0 ] = me[ 0 ] * scaleX;
  3667. te[ 1 ] = me[ 1 ] * scaleX;
  3668. te[ 2 ] = me[ 2 ] * scaleX;
  3669. te[ 3 ] = 0;
  3670. te[ 4 ] = me[ 4 ] * scaleY;
  3671. te[ 5 ] = me[ 5 ] * scaleY;
  3672. te[ 6 ] = me[ 6 ] * scaleY;
  3673. te[ 7 ] = 0;
  3674. te[ 8 ] = me[ 8 ] * scaleZ;
  3675. te[ 9 ] = me[ 9 ] * scaleZ;
  3676. te[ 10 ] = me[ 10 ] * scaleZ;
  3677. te[ 11 ] = 0;
  3678. te[ 12 ] = 0;
  3679. te[ 13 ] = 0;
  3680. te[ 14 ] = 0;
  3681. te[ 15 ] = 1;
  3682. return this;
  3683. }
  3684. makeRotationFromEuler( euler ) {
  3685. const te = this.elements;
  3686. const x = euler.x, y = euler.y, z = euler.z;
  3687. const a = Math.cos( x ), b = Math.sin( x );
  3688. const c = Math.cos( y ), d = Math.sin( y );
  3689. const e = Math.cos( z ), f = Math.sin( z );
  3690. if ( euler.order === 'XYZ' ) {
  3691. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3692. te[ 0 ] = c * e;
  3693. te[ 4 ] = - c * f;
  3694. te[ 8 ] = d;
  3695. te[ 1 ] = af + be * d;
  3696. te[ 5 ] = ae - bf * d;
  3697. te[ 9 ] = - b * c;
  3698. te[ 2 ] = bf - ae * d;
  3699. te[ 6 ] = be + af * d;
  3700. te[ 10 ] = a * c;
  3701. } else if ( euler.order === 'YXZ' ) {
  3702. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3703. te[ 0 ] = ce + df * b;
  3704. te[ 4 ] = de * b - cf;
  3705. te[ 8 ] = a * d;
  3706. te[ 1 ] = a * f;
  3707. te[ 5 ] = a * e;
  3708. te[ 9 ] = - b;
  3709. te[ 2 ] = cf * b - de;
  3710. te[ 6 ] = df + ce * b;
  3711. te[ 10 ] = a * c;
  3712. } else if ( euler.order === 'ZXY' ) {
  3713. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3714. te[ 0 ] = ce - df * b;
  3715. te[ 4 ] = - a * f;
  3716. te[ 8 ] = de + cf * b;
  3717. te[ 1 ] = cf + de * b;
  3718. te[ 5 ] = a * e;
  3719. te[ 9 ] = df - ce * b;
  3720. te[ 2 ] = - a * d;
  3721. te[ 6 ] = b;
  3722. te[ 10 ] = a * c;
  3723. } else if ( euler.order === 'ZYX' ) {
  3724. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3725. te[ 0 ] = c * e;
  3726. te[ 4 ] = be * d - af;
  3727. te[ 8 ] = ae * d + bf;
  3728. te[ 1 ] = c * f;
  3729. te[ 5 ] = bf * d + ae;
  3730. te[ 9 ] = af * d - be;
  3731. te[ 2 ] = - d;
  3732. te[ 6 ] = b * c;
  3733. te[ 10 ] = a * c;
  3734. } else if ( euler.order === 'YZX' ) {
  3735. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3736. te[ 0 ] = c * e;
  3737. te[ 4 ] = bd - ac * f;
  3738. te[ 8 ] = bc * f + ad;
  3739. te[ 1 ] = f;
  3740. te[ 5 ] = a * e;
  3741. te[ 9 ] = - b * e;
  3742. te[ 2 ] = - d * e;
  3743. te[ 6 ] = ad * f + bc;
  3744. te[ 10 ] = ac - bd * f;
  3745. } else if ( euler.order === 'XZY' ) {
  3746. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3747. te[ 0 ] = c * e;
  3748. te[ 4 ] = - f;
  3749. te[ 8 ] = d * e;
  3750. te[ 1 ] = ac * f + bd;
  3751. te[ 5 ] = a * e;
  3752. te[ 9 ] = ad * f - bc;
  3753. te[ 2 ] = bc * f - ad;
  3754. te[ 6 ] = b * e;
  3755. te[ 10 ] = bd * f + ac;
  3756. }
  3757. // bottom row
  3758. te[ 3 ] = 0;
  3759. te[ 7 ] = 0;
  3760. te[ 11 ] = 0;
  3761. // last column
  3762. te[ 12 ] = 0;
  3763. te[ 13 ] = 0;
  3764. te[ 14 ] = 0;
  3765. te[ 15 ] = 1;
  3766. return this;
  3767. }
  3768. makeRotationFromQuaternion( q ) {
  3769. return this.compose( _zero, q, _one );
  3770. }
  3771. lookAt( eye, target, up ) {
  3772. const te = this.elements;
  3773. _z.subVectors( eye, target );
  3774. if ( _z.lengthSq() === 0 ) {
  3775. // eye and target are in the same position
  3776. _z.z = 1;
  3777. }
  3778. _z.normalize();
  3779. _x.crossVectors( up, _z );
  3780. if ( _x.lengthSq() === 0 ) {
  3781. // up and z are parallel
  3782. if ( Math.abs( up.z ) === 1 ) {
  3783. _z.x += 0.0001;
  3784. } else {
  3785. _z.z += 0.0001;
  3786. }
  3787. _z.normalize();
  3788. _x.crossVectors( up, _z );
  3789. }
  3790. _x.normalize();
  3791. _y.crossVectors( _z, _x );
  3792. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3793. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3794. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3795. return this;
  3796. }
  3797. multiply( m ) {
  3798. return this.multiplyMatrices( this, m );
  3799. }
  3800. premultiply( m ) {
  3801. return this.multiplyMatrices( m, this );
  3802. }
  3803. multiplyMatrices( a, b ) {
  3804. const ae = a.elements;
  3805. const be = b.elements;
  3806. const te = this.elements;
  3807. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3808. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3809. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3810. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3811. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3812. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3813. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3814. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3815. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3816. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3817. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3818. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3819. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3820. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3821. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3822. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3823. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3824. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3825. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3826. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3827. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3828. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3829. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3830. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3831. return this;
  3832. }
  3833. multiplyScalar( s ) {
  3834. const te = this.elements;
  3835. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3836. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3837. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3838. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3839. return this;
  3840. }
  3841. determinant() {
  3842. const te = this.elements;
  3843. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3844. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3845. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3846. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3847. //TODO: make this more efficient
  3848. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3849. return (
  3850. n41 * (
  3851. + n14 * n23 * n32
  3852. - n13 * n24 * n32
  3853. - n14 * n22 * n33
  3854. + n12 * n24 * n33
  3855. + n13 * n22 * n34
  3856. - n12 * n23 * n34
  3857. ) +
  3858. n42 * (
  3859. + n11 * n23 * n34
  3860. - n11 * n24 * n33
  3861. + n14 * n21 * n33
  3862. - n13 * n21 * n34
  3863. + n13 * n24 * n31
  3864. - n14 * n23 * n31
  3865. ) +
  3866. n43 * (
  3867. + n11 * n24 * n32
  3868. - n11 * n22 * n34
  3869. - n14 * n21 * n32
  3870. + n12 * n21 * n34
  3871. + n14 * n22 * n31
  3872. - n12 * n24 * n31
  3873. ) +
  3874. n44 * (
  3875. - n13 * n22 * n31
  3876. - n11 * n23 * n32
  3877. + n11 * n22 * n33
  3878. + n13 * n21 * n32
  3879. - n12 * n21 * n33
  3880. + n12 * n23 * n31
  3881. )
  3882. );
  3883. }
  3884. transpose() {
  3885. const te = this.elements;
  3886. let tmp;
  3887. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3888. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3889. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3890. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3891. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3892. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3893. return this;
  3894. }
  3895. setPosition( x, y, z ) {
  3896. const te = this.elements;
  3897. if ( x.isVector3 ) {
  3898. te[ 12 ] = x.x;
  3899. te[ 13 ] = x.y;
  3900. te[ 14 ] = x.z;
  3901. } else {
  3902. te[ 12 ] = x;
  3903. te[ 13 ] = y;
  3904. te[ 14 ] = z;
  3905. }
  3906. return this;
  3907. }
  3908. invert() {
  3909. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3910. const te = this.elements,
  3911. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3912. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3913. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3914. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3915. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3916. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3917. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3918. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3919. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3920. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3921. const detInv = 1 / det;
  3922. te[ 0 ] = t11 * detInv;
  3923. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3924. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3925. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3926. te[ 4 ] = t12 * detInv;
  3927. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3928. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3929. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3930. te[ 8 ] = t13 * detInv;
  3931. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3932. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3933. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3934. te[ 12 ] = t14 * detInv;
  3935. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3936. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3937. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3938. return this;
  3939. }
  3940. scale( v ) {
  3941. const te = this.elements;
  3942. const x = v.x, y = v.y, z = v.z;
  3943. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3944. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3945. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3946. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3947. return this;
  3948. }
  3949. getMaxScaleOnAxis() {
  3950. const te = this.elements;
  3951. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3952. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3953. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3954. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3955. }
  3956. makeTranslation( x, y, z ) {
  3957. if ( x.isVector3 ) {
  3958. this.set(
  3959. 1, 0, 0, x.x,
  3960. 0, 1, 0, x.y,
  3961. 0, 0, 1, x.z,
  3962. 0, 0, 0, 1
  3963. );
  3964. } else {
  3965. this.set(
  3966. 1, 0, 0, x,
  3967. 0, 1, 0, y,
  3968. 0, 0, 1, z,
  3969. 0, 0, 0, 1
  3970. );
  3971. }
  3972. return this;
  3973. }
  3974. makeRotationX( theta ) {
  3975. const c = Math.cos( theta ), s = Math.sin( theta );
  3976. this.set(
  3977. 1, 0, 0, 0,
  3978. 0, c, - s, 0,
  3979. 0, s, c, 0,
  3980. 0, 0, 0, 1
  3981. );
  3982. return this;
  3983. }
  3984. makeRotationY( theta ) {
  3985. const c = Math.cos( theta ), s = Math.sin( theta );
  3986. this.set(
  3987. c, 0, s, 0,
  3988. 0, 1, 0, 0,
  3989. - s, 0, c, 0,
  3990. 0, 0, 0, 1
  3991. );
  3992. return this;
  3993. }
  3994. makeRotationZ( theta ) {
  3995. const c = Math.cos( theta ), s = Math.sin( theta );
  3996. this.set(
  3997. c, - s, 0, 0,
  3998. s, c, 0, 0,
  3999. 0, 0, 1, 0,
  4000. 0, 0, 0, 1
  4001. );
  4002. return this;
  4003. }
  4004. makeRotationAxis( axis, angle ) {
  4005. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4006. const c = Math.cos( angle );
  4007. const s = Math.sin( angle );
  4008. const t = 1 - c;
  4009. const x = axis.x, y = axis.y, z = axis.z;
  4010. const tx = t * x, ty = t * y;
  4011. this.set(
  4012. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4013. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4014. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4015. 0, 0, 0, 1
  4016. );
  4017. return this;
  4018. }
  4019. makeScale( x, y, z ) {
  4020. this.set(
  4021. x, 0, 0, 0,
  4022. 0, y, 0, 0,
  4023. 0, 0, z, 0,
  4024. 0, 0, 0, 1
  4025. );
  4026. return this;
  4027. }
  4028. makeShear( xy, xz, yx, yz, zx, zy ) {
  4029. this.set(
  4030. 1, yx, zx, 0,
  4031. xy, 1, zy, 0,
  4032. xz, yz, 1, 0,
  4033. 0, 0, 0, 1
  4034. );
  4035. return this;
  4036. }
  4037. compose( position, quaternion, scale ) {
  4038. const te = this.elements;
  4039. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4040. const x2 = x + x, y2 = y + y, z2 = z + z;
  4041. const xx = x * x2, xy = x * y2, xz = x * z2;
  4042. const yy = y * y2, yz = y * z2, zz = z * z2;
  4043. const wx = w * x2, wy = w * y2, wz = w * z2;
  4044. const sx = scale.x, sy = scale.y, sz = scale.z;
  4045. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4046. te[ 1 ] = ( xy + wz ) * sx;
  4047. te[ 2 ] = ( xz - wy ) * sx;
  4048. te[ 3 ] = 0;
  4049. te[ 4 ] = ( xy - wz ) * sy;
  4050. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4051. te[ 6 ] = ( yz + wx ) * sy;
  4052. te[ 7 ] = 0;
  4053. te[ 8 ] = ( xz + wy ) * sz;
  4054. te[ 9 ] = ( yz - wx ) * sz;
  4055. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4056. te[ 11 ] = 0;
  4057. te[ 12 ] = position.x;
  4058. te[ 13 ] = position.y;
  4059. te[ 14 ] = position.z;
  4060. te[ 15 ] = 1;
  4061. return this;
  4062. }
  4063. decompose( position, quaternion, scale ) {
  4064. const te = this.elements;
  4065. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4066. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4067. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4068. // if determine is negative, we need to invert one scale
  4069. const det = this.determinant();
  4070. if ( det < 0 ) sx = - sx;
  4071. position.x = te[ 12 ];
  4072. position.y = te[ 13 ];
  4073. position.z = te[ 14 ];
  4074. // scale the rotation part
  4075. _m1$4.copy( this );
  4076. const invSX = 1 / sx;
  4077. const invSY = 1 / sy;
  4078. const invSZ = 1 / sz;
  4079. _m1$4.elements[ 0 ] *= invSX;
  4080. _m1$4.elements[ 1 ] *= invSX;
  4081. _m1$4.elements[ 2 ] *= invSX;
  4082. _m1$4.elements[ 4 ] *= invSY;
  4083. _m1$4.elements[ 5 ] *= invSY;
  4084. _m1$4.elements[ 6 ] *= invSY;
  4085. _m1$4.elements[ 8 ] *= invSZ;
  4086. _m1$4.elements[ 9 ] *= invSZ;
  4087. _m1$4.elements[ 10 ] *= invSZ;
  4088. quaternion.setFromRotationMatrix( _m1$4 );
  4089. scale.x = sx;
  4090. scale.y = sy;
  4091. scale.z = sz;
  4092. return this;
  4093. }
  4094. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4095. const te = this.elements;
  4096. const x = 2 * near / ( right - left );
  4097. const y = 2 * near / ( top - bottom );
  4098. const a = ( right + left ) / ( right - left );
  4099. const b = ( top + bottom ) / ( top - bottom );
  4100. let c, d;
  4101. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4102. c = - ( far + near ) / ( far - near );
  4103. d = ( - 2 * far * near ) / ( far - near );
  4104. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4105. c = - far / ( far - near );
  4106. d = ( - far * near ) / ( far - near );
  4107. } else {
  4108. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4109. }
  4110. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4111. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4112. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4113. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4114. return this;
  4115. }
  4116. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4117. const te = this.elements;
  4118. const w = 1.0 / ( right - left );
  4119. const h = 1.0 / ( top - bottom );
  4120. const p = 1.0 / ( far - near );
  4121. const x = ( right + left ) * w;
  4122. const y = ( top + bottom ) * h;
  4123. let z, zInv;
  4124. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4125. z = ( far + near ) * p;
  4126. zInv = - 2 * p;
  4127. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4128. z = near * p;
  4129. zInv = - 1 * p;
  4130. } else {
  4131. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4132. }
  4133. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4134. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4135. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4136. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4137. return this;
  4138. }
  4139. equals( matrix ) {
  4140. const te = this.elements;
  4141. const me = matrix.elements;
  4142. for ( let i = 0; i < 16; i ++ ) {
  4143. if ( te[ i ] !== me[ i ] ) return false;
  4144. }
  4145. return true;
  4146. }
  4147. fromArray( array, offset = 0 ) {
  4148. for ( let i = 0; i < 16; i ++ ) {
  4149. this.elements[ i ] = array[ i + offset ];
  4150. }
  4151. return this;
  4152. }
  4153. toArray( array = [], offset = 0 ) {
  4154. const te = this.elements;
  4155. array[ offset ] = te[ 0 ];
  4156. array[ offset + 1 ] = te[ 1 ];
  4157. array[ offset + 2 ] = te[ 2 ];
  4158. array[ offset + 3 ] = te[ 3 ];
  4159. array[ offset + 4 ] = te[ 4 ];
  4160. array[ offset + 5 ] = te[ 5 ];
  4161. array[ offset + 6 ] = te[ 6 ];
  4162. array[ offset + 7 ] = te[ 7 ];
  4163. array[ offset + 8 ] = te[ 8 ];
  4164. array[ offset + 9 ] = te[ 9 ];
  4165. array[ offset + 10 ] = te[ 10 ];
  4166. array[ offset + 11 ] = te[ 11 ];
  4167. array[ offset + 12 ] = te[ 12 ];
  4168. array[ offset + 13 ] = te[ 13 ];
  4169. array[ offset + 14 ] = te[ 14 ];
  4170. array[ offset + 15 ] = te[ 15 ];
  4171. return array;
  4172. }
  4173. }
  4174. const _v1$5 = /*@__PURE__*/ new Vector3();
  4175. const _m1$4 = /*@__PURE__*/ new Matrix4();
  4176. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4177. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4178. const _x = /*@__PURE__*/ new Vector3();
  4179. const _y = /*@__PURE__*/ new Vector3();
  4180. const _z = /*@__PURE__*/ new Vector3();
  4181. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4182. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4183. class Euler {
  4184. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4185. this.isEuler = true;
  4186. this._x = x;
  4187. this._y = y;
  4188. this._z = z;
  4189. this._order = order;
  4190. }
  4191. get x() {
  4192. return this._x;
  4193. }
  4194. set x( value ) {
  4195. this._x = value;
  4196. this._onChangeCallback();
  4197. }
  4198. get y() {
  4199. return this._y;
  4200. }
  4201. set y( value ) {
  4202. this._y = value;
  4203. this._onChangeCallback();
  4204. }
  4205. get z() {
  4206. return this._z;
  4207. }
  4208. set z( value ) {
  4209. this._z = value;
  4210. this._onChangeCallback();
  4211. }
  4212. get order() {
  4213. return this._order;
  4214. }
  4215. set order( value ) {
  4216. this._order = value;
  4217. this._onChangeCallback();
  4218. }
  4219. set( x, y, z, order = this._order ) {
  4220. this._x = x;
  4221. this._y = y;
  4222. this._z = z;
  4223. this._order = order;
  4224. this._onChangeCallback();
  4225. return this;
  4226. }
  4227. clone() {
  4228. return new this.constructor( this._x, this._y, this._z, this._order );
  4229. }
  4230. copy( euler ) {
  4231. this._x = euler._x;
  4232. this._y = euler._y;
  4233. this._z = euler._z;
  4234. this._order = euler._order;
  4235. this._onChangeCallback();
  4236. return this;
  4237. }
  4238. setFromRotationMatrix( m, order = this._order, update = true ) {
  4239. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4240. const te = m.elements;
  4241. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4242. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4243. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4244. switch ( order ) {
  4245. case 'XYZ':
  4246. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4247. if ( Math.abs( m13 ) < 0.9999999 ) {
  4248. this._x = Math.atan2( - m23, m33 );
  4249. this._z = Math.atan2( - m12, m11 );
  4250. } else {
  4251. this._x = Math.atan2( m32, m22 );
  4252. this._z = 0;
  4253. }
  4254. break;
  4255. case 'YXZ':
  4256. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4257. if ( Math.abs( m23 ) < 0.9999999 ) {
  4258. this._y = Math.atan2( m13, m33 );
  4259. this._z = Math.atan2( m21, m22 );
  4260. } else {
  4261. this._y = Math.atan2( - m31, m11 );
  4262. this._z = 0;
  4263. }
  4264. break;
  4265. case 'ZXY':
  4266. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4267. if ( Math.abs( m32 ) < 0.9999999 ) {
  4268. this._y = Math.atan2( - m31, m33 );
  4269. this._z = Math.atan2( - m12, m22 );
  4270. } else {
  4271. this._y = 0;
  4272. this._z = Math.atan2( m21, m11 );
  4273. }
  4274. break;
  4275. case 'ZYX':
  4276. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4277. if ( Math.abs( m31 ) < 0.9999999 ) {
  4278. this._x = Math.atan2( m32, m33 );
  4279. this._z = Math.atan2( m21, m11 );
  4280. } else {
  4281. this._x = 0;
  4282. this._z = Math.atan2( - m12, m22 );
  4283. }
  4284. break;
  4285. case 'YZX':
  4286. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4287. if ( Math.abs( m21 ) < 0.9999999 ) {
  4288. this._x = Math.atan2( - m23, m22 );
  4289. this._y = Math.atan2( - m31, m11 );
  4290. } else {
  4291. this._x = 0;
  4292. this._y = Math.atan2( m13, m33 );
  4293. }
  4294. break;
  4295. case 'XZY':
  4296. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4297. if ( Math.abs( m12 ) < 0.9999999 ) {
  4298. this._x = Math.atan2( m32, m22 );
  4299. this._y = Math.atan2( m13, m11 );
  4300. } else {
  4301. this._x = Math.atan2( - m23, m33 );
  4302. this._y = 0;
  4303. }
  4304. break;
  4305. default:
  4306. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4307. }
  4308. this._order = order;
  4309. if ( update === true ) this._onChangeCallback();
  4310. return this;
  4311. }
  4312. setFromQuaternion( q, order, update ) {
  4313. _matrix$2.makeRotationFromQuaternion( q );
  4314. return this.setFromRotationMatrix( _matrix$2, order, update );
  4315. }
  4316. setFromVector3( v, order = this._order ) {
  4317. return this.set( v.x, v.y, v.z, order );
  4318. }
  4319. reorder( newOrder ) {
  4320. // WARNING: this discards revolution information -bhouston
  4321. _quaternion$3.setFromEuler( this );
  4322. return this.setFromQuaternion( _quaternion$3, newOrder );
  4323. }
  4324. equals( euler ) {
  4325. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4326. }
  4327. fromArray( array ) {
  4328. this._x = array[ 0 ];
  4329. this._y = array[ 1 ];
  4330. this._z = array[ 2 ];
  4331. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4332. this._onChangeCallback();
  4333. return this;
  4334. }
  4335. toArray( array = [], offset = 0 ) {
  4336. array[ offset ] = this._x;
  4337. array[ offset + 1 ] = this._y;
  4338. array[ offset + 2 ] = this._z;
  4339. array[ offset + 3 ] = this._order;
  4340. return array;
  4341. }
  4342. _onChange( callback ) {
  4343. this._onChangeCallback = callback;
  4344. return this;
  4345. }
  4346. _onChangeCallback() {}
  4347. *[ Symbol.iterator ]() {
  4348. yield this._x;
  4349. yield this._y;
  4350. yield this._z;
  4351. yield this._order;
  4352. }
  4353. }
  4354. Euler.DEFAULT_ORDER = 'XYZ';
  4355. class Layers {
  4356. constructor() {
  4357. this.mask = 1 | 0;
  4358. }
  4359. set( channel ) {
  4360. this.mask = ( 1 << channel | 0 ) >>> 0;
  4361. }
  4362. enable( channel ) {
  4363. this.mask |= 1 << channel | 0;
  4364. }
  4365. enableAll() {
  4366. this.mask = 0xffffffff | 0;
  4367. }
  4368. toggle( channel ) {
  4369. this.mask ^= 1 << channel | 0;
  4370. }
  4371. disable( channel ) {
  4372. this.mask &= ~ ( 1 << channel | 0 );
  4373. }
  4374. disableAll() {
  4375. this.mask = 0;
  4376. }
  4377. test( layers ) {
  4378. return ( this.mask & layers.mask ) !== 0;
  4379. }
  4380. isEnabled( channel ) {
  4381. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4382. }
  4383. }
  4384. let _object3DId = 0;
  4385. const _v1$4 = /*@__PURE__*/ new Vector3();
  4386. const _q1 = /*@__PURE__*/ new Quaternion();
  4387. const _m1$3 = /*@__PURE__*/ new Matrix4();
  4388. const _target = /*@__PURE__*/ new Vector3();
  4389. const _position$3 = /*@__PURE__*/ new Vector3();
  4390. const _scale$2 = /*@__PURE__*/ new Vector3();
  4391. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4392. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4393. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4394. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4395. const _addedEvent = { type: 'added' };
  4396. const _removedEvent = { type: 'removed' };
  4397. const _childaddedEvent = { type: 'childadded', child: null };
  4398. const _childremovedEvent = { type: 'childremoved', child: null };
  4399. class Object3D extends EventDispatcher {
  4400. constructor() {
  4401. super();
  4402. this.isObject3D = true;
  4403. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4404. this.uuid = generateUUID();
  4405. this.name = '';
  4406. this.type = 'Object3D';
  4407. this.parent = null;
  4408. this.children = [];
  4409. this.up = Object3D.DEFAULT_UP.clone();
  4410. const position = new Vector3();
  4411. const rotation = new Euler();
  4412. const quaternion = new Quaternion();
  4413. const scale = new Vector3( 1, 1, 1 );
  4414. function onRotationChange() {
  4415. quaternion.setFromEuler( rotation, false );
  4416. }
  4417. function onQuaternionChange() {
  4418. rotation.setFromQuaternion( quaternion, undefined, false );
  4419. }
  4420. rotation._onChange( onRotationChange );
  4421. quaternion._onChange( onQuaternionChange );
  4422. Object.defineProperties( this, {
  4423. position: {
  4424. configurable: true,
  4425. enumerable: true,
  4426. value: position
  4427. },
  4428. rotation: {
  4429. configurable: true,
  4430. enumerable: true,
  4431. value: rotation
  4432. },
  4433. quaternion: {
  4434. configurable: true,
  4435. enumerable: true,
  4436. value: quaternion
  4437. },
  4438. scale: {
  4439. configurable: true,
  4440. enumerable: true,
  4441. value: scale
  4442. },
  4443. modelViewMatrix: {
  4444. value: new Matrix4()
  4445. },
  4446. normalMatrix: {
  4447. value: new Matrix3()
  4448. }
  4449. } );
  4450. this.matrix = new Matrix4();
  4451. this.matrixWorld = new Matrix4();
  4452. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4453. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4454. this.matrixWorldNeedsUpdate = false;
  4455. this.layers = new Layers();
  4456. this.visible = true;
  4457. this.castShadow = false;
  4458. this.receiveShadow = false;
  4459. this.frustumCulled = true;
  4460. this.renderOrder = 0;
  4461. this.animations = [];
  4462. this.userData = {};
  4463. }
  4464. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4465. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4466. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4467. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4468. applyMatrix4( matrix ) {
  4469. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4470. this.matrix.premultiply( matrix );
  4471. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4472. }
  4473. applyQuaternion( q ) {
  4474. this.quaternion.premultiply( q );
  4475. return this;
  4476. }
  4477. setRotationFromAxisAngle( axis, angle ) {
  4478. // assumes axis is normalized
  4479. this.quaternion.setFromAxisAngle( axis, angle );
  4480. }
  4481. setRotationFromEuler( euler ) {
  4482. this.quaternion.setFromEuler( euler, true );
  4483. }
  4484. setRotationFromMatrix( m ) {
  4485. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4486. this.quaternion.setFromRotationMatrix( m );
  4487. }
  4488. setRotationFromQuaternion( q ) {
  4489. // assumes q is normalized
  4490. this.quaternion.copy( q );
  4491. }
  4492. rotateOnAxis( axis, angle ) {
  4493. // rotate object on axis in object space
  4494. // axis is assumed to be normalized
  4495. _q1.setFromAxisAngle( axis, angle );
  4496. this.quaternion.multiply( _q1 );
  4497. return this;
  4498. }
  4499. rotateOnWorldAxis( axis, angle ) {
  4500. // rotate object on axis in world space
  4501. // axis is assumed to be normalized
  4502. // method assumes no rotated parent
  4503. _q1.setFromAxisAngle( axis, angle );
  4504. this.quaternion.premultiply( _q1 );
  4505. return this;
  4506. }
  4507. rotateX( angle ) {
  4508. return this.rotateOnAxis( _xAxis, angle );
  4509. }
  4510. rotateY( angle ) {
  4511. return this.rotateOnAxis( _yAxis, angle );
  4512. }
  4513. rotateZ( angle ) {
  4514. return this.rotateOnAxis( _zAxis, angle );
  4515. }
  4516. translateOnAxis( axis, distance ) {
  4517. // translate object by distance along axis in object space
  4518. // axis is assumed to be normalized
  4519. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4520. this.position.add( _v1$4.multiplyScalar( distance ) );
  4521. return this;
  4522. }
  4523. translateX( distance ) {
  4524. return this.translateOnAxis( _xAxis, distance );
  4525. }
  4526. translateY( distance ) {
  4527. return this.translateOnAxis( _yAxis, distance );
  4528. }
  4529. translateZ( distance ) {
  4530. return this.translateOnAxis( _zAxis, distance );
  4531. }
  4532. localToWorld( vector ) {
  4533. this.updateWorldMatrix( true, false );
  4534. return vector.applyMatrix4( this.matrixWorld );
  4535. }
  4536. worldToLocal( vector ) {
  4537. this.updateWorldMatrix( true, false );
  4538. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  4539. }
  4540. lookAt( x, y, z ) {
  4541. // This method does not support objects having non-uniformly-scaled parent(s)
  4542. if ( x.isVector3 ) {
  4543. _target.copy( x );
  4544. } else {
  4545. _target.set( x, y, z );
  4546. }
  4547. const parent = this.parent;
  4548. this.updateWorldMatrix( true, false );
  4549. _position$3.setFromMatrixPosition( this.matrixWorld );
  4550. if ( this.isCamera || this.isLight ) {
  4551. _m1$3.lookAt( _position$3, _target, this.up );
  4552. } else {
  4553. _m1$3.lookAt( _target, _position$3, this.up );
  4554. }
  4555. this.quaternion.setFromRotationMatrix( _m1$3 );
  4556. if ( parent ) {
  4557. _m1$3.extractRotation( parent.matrixWorld );
  4558. _q1.setFromRotationMatrix( _m1$3 );
  4559. this.quaternion.premultiply( _q1.invert() );
  4560. }
  4561. }
  4562. add( object ) {
  4563. if ( arguments.length > 1 ) {
  4564. for ( let i = 0; i < arguments.length; i ++ ) {
  4565. this.add( arguments[ i ] );
  4566. }
  4567. return this;
  4568. }
  4569. if ( object === this ) {
  4570. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4571. return this;
  4572. }
  4573. if ( object && object.isObject3D ) {
  4574. object.removeFromParent();
  4575. object.parent = this;
  4576. this.children.push( object );
  4577. object.dispatchEvent( _addedEvent );
  4578. _childaddedEvent.child = object;
  4579. this.dispatchEvent( _childaddedEvent );
  4580. _childaddedEvent.child = null;
  4581. } else {
  4582. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4583. }
  4584. return this;
  4585. }
  4586. remove( object ) {
  4587. if ( arguments.length > 1 ) {
  4588. for ( let i = 0; i < arguments.length; i ++ ) {
  4589. this.remove( arguments[ i ] );
  4590. }
  4591. return this;
  4592. }
  4593. const index = this.children.indexOf( object );
  4594. if ( index !== - 1 ) {
  4595. object.parent = null;
  4596. this.children.splice( index, 1 );
  4597. object.dispatchEvent( _removedEvent );
  4598. _childremovedEvent.child = object;
  4599. this.dispatchEvent( _childremovedEvent );
  4600. _childremovedEvent.child = null;
  4601. }
  4602. return this;
  4603. }
  4604. removeFromParent() {
  4605. const parent = this.parent;
  4606. if ( parent !== null ) {
  4607. parent.remove( this );
  4608. }
  4609. return this;
  4610. }
  4611. clear() {
  4612. return this.remove( ... this.children );
  4613. }
  4614. attach( object ) {
  4615. // adds object as a child of this, while maintaining the object's world transform
  4616. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4617. this.updateWorldMatrix( true, false );
  4618. _m1$3.copy( this.matrixWorld ).invert();
  4619. if ( object.parent !== null ) {
  4620. object.parent.updateWorldMatrix( true, false );
  4621. _m1$3.multiply( object.parent.matrixWorld );
  4622. }
  4623. object.applyMatrix4( _m1$3 );
  4624. object.removeFromParent();
  4625. object.parent = this;
  4626. this.children.push( object );
  4627. object.updateWorldMatrix( false, true );
  4628. object.dispatchEvent( _addedEvent );
  4629. _childaddedEvent.child = object;
  4630. this.dispatchEvent( _childaddedEvent );
  4631. _childaddedEvent.child = null;
  4632. return this;
  4633. }
  4634. getObjectById( id ) {
  4635. return this.getObjectByProperty( 'id', id );
  4636. }
  4637. getObjectByName( name ) {
  4638. return this.getObjectByProperty( 'name', name );
  4639. }
  4640. getObjectByProperty( name, value ) {
  4641. if ( this[ name ] === value ) return this;
  4642. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4643. const child = this.children[ i ];
  4644. const object = child.getObjectByProperty( name, value );
  4645. if ( object !== undefined ) {
  4646. return object;
  4647. }
  4648. }
  4649. return undefined;
  4650. }
  4651. getObjectsByProperty( name, value, result = [] ) {
  4652. if ( this[ name ] === value ) result.push( this );
  4653. const children = this.children;
  4654. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4655. children[ i ].getObjectsByProperty( name, value, result );
  4656. }
  4657. return result;
  4658. }
  4659. getWorldPosition( target ) {
  4660. this.updateWorldMatrix( true, false );
  4661. return target.setFromMatrixPosition( this.matrixWorld );
  4662. }
  4663. getWorldQuaternion( target ) {
  4664. this.updateWorldMatrix( true, false );
  4665. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4666. return target;
  4667. }
  4668. getWorldScale( target ) {
  4669. this.updateWorldMatrix( true, false );
  4670. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4671. return target;
  4672. }
  4673. getWorldDirection( target ) {
  4674. this.updateWorldMatrix( true, false );
  4675. const e = this.matrixWorld.elements;
  4676. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4677. }
  4678. raycast( /* raycaster, intersects */ ) {}
  4679. traverse( callback ) {
  4680. callback( this );
  4681. const children = this.children;
  4682. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4683. children[ i ].traverse( callback );
  4684. }
  4685. }
  4686. traverseVisible( callback ) {
  4687. if ( this.visible === false ) return;
  4688. callback( this );
  4689. const children = this.children;
  4690. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4691. children[ i ].traverseVisible( callback );
  4692. }
  4693. }
  4694. traverseAncestors( callback ) {
  4695. const parent = this.parent;
  4696. if ( parent !== null ) {
  4697. callback( parent );
  4698. parent.traverseAncestors( callback );
  4699. }
  4700. }
  4701. updateMatrix() {
  4702. this.matrix.compose( this.position, this.quaternion, this.scale );
  4703. this.matrixWorldNeedsUpdate = true;
  4704. }
  4705. updateMatrixWorld( force ) {
  4706. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4707. if ( this.matrixWorldNeedsUpdate || force ) {
  4708. if ( this.matrixWorldAutoUpdate === true ) {
  4709. if ( this.parent === null ) {
  4710. this.matrixWorld.copy( this.matrix );
  4711. } else {
  4712. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4713. }
  4714. }
  4715. this.matrixWorldNeedsUpdate = false;
  4716. force = true;
  4717. }
  4718. // make sure descendants are updated if required
  4719. const children = this.children;
  4720. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4721. const child = children[ i ];
  4722. child.updateMatrixWorld( force );
  4723. }
  4724. }
  4725. updateWorldMatrix( updateParents, updateChildren ) {
  4726. const parent = this.parent;
  4727. if ( updateParents === true && parent !== null ) {
  4728. parent.updateWorldMatrix( true, false );
  4729. }
  4730. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4731. if ( this.matrixWorldAutoUpdate === true ) {
  4732. if ( this.parent === null ) {
  4733. this.matrixWorld.copy( this.matrix );
  4734. } else {
  4735. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4736. }
  4737. }
  4738. // make sure descendants are updated
  4739. if ( updateChildren === true ) {
  4740. const children = this.children;
  4741. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4742. const child = children[ i ];
  4743. child.updateWorldMatrix( false, true );
  4744. }
  4745. }
  4746. }
  4747. toJSON( meta ) {
  4748. // meta is a string when called from JSON.stringify
  4749. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4750. const output = {};
  4751. // meta is a hash used to collect geometries, materials.
  4752. // not providing it implies that this is the root object
  4753. // being serialized.
  4754. if ( isRootObject ) {
  4755. // initialize meta obj
  4756. meta = {
  4757. geometries: {},
  4758. materials: {},
  4759. textures: {},
  4760. images: {},
  4761. shapes: {},
  4762. skeletons: {},
  4763. animations: {},
  4764. nodes: {}
  4765. };
  4766. output.metadata = {
  4767. version: 4.6,
  4768. type: 'Object',
  4769. generator: 'Object3D.toJSON'
  4770. };
  4771. }
  4772. // standard Object3D serialization
  4773. const object = {};
  4774. object.uuid = this.uuid;
  4775. object.type = this.type;
  4776. if ( this.name !== '' ) object.name = this.name;
  4777. if ( this.castShadow === true ) object.castShadow = true;
  4778. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4779. if ( this.visible === false ) object.visible = false;
  4780. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4781. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4782. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4783. object.layers = this.layers.mask;
  4784. object.matrix = this.matrix.toArray();
  4785. object.up = this.up.toArray();
  4786. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4787. // object specific properties
  4788. if ( this.isInstancedMesh ) {
  4789. object.type = 'InstancedMesh';
  4790. object.count = this.count;
  4791. object.instanceMatrix = this.instanceMatrix.toJSON();
  4792. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4793. }
  4794. if ( this.isBatchedMesh ) {
  4795. object.type = 'BatchedMesh';
  4796. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4797. object.sortObjects = this.sortObjects;
  4798. object.drawRanges = this._drawRanges;
  4799. object.reservedRanges = this._reservedRanges;
  4800. object.visibility = this._visibility;
  4801. object.active = this._active;
  4802. object.bounds = this._bounds.map( bound => ( {
  4803. boxInitialized: bound.boxInitialized,
  4804. boxMin: bound.box.min.toArray(),
  4805. boxMax: bound.box.max.toArray(),
  4806. sphereInitialized: bound.sphereInitialized,
  4807. sphereRadius: bound.sphere.radius,
  4808. sphereCenter: bound.sphere.center.toArray()
  4809. } ) );
  4810. object.maxInstanceCount = this._maxInstanceCount;
  4811. object.maxVertexCount = this._maxVertexCount;
  4812. object.maxIndexCount = this._maxIndexCount;
  4813. object.geometryInitialized = this._geometryInitialized;
  4814. object.geometryCount = this._geometryCount;
  4815. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4816. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4817. if ( this.boundingSphere !== null ) {
  4818. object.boundingSphere = {
  4819. center: object.boundingSphere.center.toArray(),
  4820. radius: object.boundingSphere.radius
  4821. };
  4822. }
  4823. if ( this.boundingBox !== null ) {
  4824. object.boundingBox = {
  4825. min: object.boundingBox.min.toArray(),
  4826. max: object.boundingBox.max.toArray()
  4827. };
  4828. }
  4829. }
  4830. //
  4831. function serialize( library, element ) {
  4832. if ( library[ element.uuid ] === undefined ) {
  4833. library[ element.uuid ] = element.toJSON( meta );
  4834. }
  4835. return element.uuid;
  4836. }
  4837. if ( this.isScene ) {
  4838. if ( this.background ) {
  4839. if ( this.background.isColor ) {
  4840. object.background = this.background.toJSON();
  4841. } else if ( this.background.isTexture ) {
  4842. object.background = this.background.toJSON( meta ).uuid;
  4843. }
  4844. }
  4845. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4846. object.environment = this.environment.toJSON( meta ).uuid;
  4847. }
  4848. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4849. object.geometry = serialize( meta.geometries, this.geometry );
  4850. const parameters = this.geometry.parameters;
  4851. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4852. const shapes = parameters.shapes;
  4853. if ( Array.isArray( shapes ) ) {
  4854. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4855. const shape = shapes[ i ];
  4856. serialize( meta.shapes, shape );
  4857. }
  4858. } else {
  4859. serialize( meta.shapes, shapes );
  4860. }
  4861. }
  4862. }
  4863. if ( this.isSkinnedMesh ) {
  4864. object.bindMode = this.bindMode;
  4865. object.bindMatrix = this.bindMatrix.toArray();
  4866. if ( this.skeleton !== undefined ) {
  4867. serialize( meta.skeletons, this.skeleton );
  4868. object.skeleton = this.skeleton.uuid;
  4869. }
  4870. }
  4871. if ( this.material !== undefined ) {
  4872. if ( Array.isArray( this.material ) ) {
  4873. const uuids = [];
  4874. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4875. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4876. }
  4877. object.material = uuids;
  4878. } else {
  4879. object.material = serialize( meta.materials, this.material );
  4880. }
  4881. }
  4882. //
  4883. if ( this.children.length > 0 ) {
  4884. object.children = [];
  4885. for ( let i = 0; i < this.children.length; i ++ ) {
  4886. object.children.push( this.children[ i ].toJSON( meta ).object );
  4887. }
  4888. }
  4889. //
  4890. if ( this.animations.length > 0 ) {
  4891. object.animations = [];
  4892. for ( let i = 0; i < this.animations.length; i ++ ) {
  4893. const animation = this.animations[ i ];
  4894. object.animations.push( serialize( meta.animations, animation ) );
  4895. }
  4896. }
  4897. if ( isRootObject ) {
  4898. const geometries = extractFromCache( meta.geometries );
  4899. const materials = extractFromCache( meta.materials );
  4900. const textures = extractFromCache( meta.textures );
  4901. const images = extractFromCache( meta.images );
  4902. const shapes = extractFromCache( meta.shapes );
  4903. const skeletons = extractFromCache( meta.skeletons );
  4904. const animations = extractFromCache( meta.animations );
  4905. const nodes = extractFromCache( meta.nodes );
  4906. if ( geometries.length > 0 ) output.geometries = geometries;
  4907. if ( materials.length > 0 ) output.materials = materials;
  4908. if ( textures.length > 0 ) output.textures = textures;
  4909. if ( images.length > 0 ) output.images = images;
  4910. if ( shapes.length > 0 ) output.shapes = shapes;
  4911. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4912. if ( animations.length > 0 ) output.animations = animations;
  4913. if ( nodes.length > 0 ) output.nodes = nodes;
  4914. }
  4915. output.object = object;
  4916. return output;
  4917. // extract data from the cache hash
  4918. // remove metadata on each item
  4919. // and return as array
  4920. function extractFromCache( cache ) {
  4921. const values = [];
  4922. for ( const key in cache ) {
  4923. const data = cache[ key ];
  4924. delete data.metadata;
  4925. values.push( data );
  4926. }
  4927. return values;
  4928. }
  4929. }
  4930. clone( recursive ) {
  4931. return new this.constructor().copy( this, recursive );
  4932. }
  4933. copy( source, recursive = true ) {
  4934. this.name = source.name;
  4935. this.up.copy( source.up );
  4936. this.position.copy( source.position );
  4937. this.rotation.order = source.rotation.order;
  4938. this.quaternion.copy( source.quaternion );
  4939. this.scale.copy( source.scale );
  4940. this.matrix.copy( source.matrix );
  4941. this.matrixWorld.copy( source.matrixWorld );
  4942. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4943. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4944. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4945. this.layers.mask = source.layers.mask;
  4946. this.visible = source.visible;
  4947. this.castShadow = source.castShadow;
  4948. this.receiveShadow = source.receiveShadow;
  4949. this.frustumCulled = source.frustumCulled;
  4950. this.renderOrder = source.renderOrder;
  4951. this.animations = source.animations.slice();
  4952. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4953. if ( recursive === true ) {
  4954. for ( let i = 0; i < source.children.length; i ++ ) {
  4955. const child = source.children[ i ];
  4956. this.add( child.clone() );
  4957. }
  4958. }
  4959. return this;
  4960. }
  4961. }
  4962. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4963. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4964. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4965. const _v0$2 = /*@__PURE__*/ new Vector3();
  4966. const _v1$3 = /*@__PURE__*/ new Vector3();
  4967. const _v2$2 = /*@__PURE__*/ new Vector3();
  4968. const _v3$2 = /*@__PURE__*/ new Vector3();
  4969. const _vab = /*@__PURE__*/ new Vector3();
  4970. const _vac = /*@__PURE__*/ new Vector3();
  4971. const _vbc = /*@__PURE__*/ new Vector3();
  4972. const _vap = /*@__PURE__*/ new Vector3();
  4973. const _vbp = /*@__PURE__*/ new Vector3();
  4974. const _vcp = /*@__PURE__*/ new Vector3();
  4975. const _v40 = /*@__PURE__*/ new Vector4();
  4976. const _v41 = /*@__PURE__*/ new Vector4();
  4977. const _v42 = /*@__PURE__*/ new Vector4();
  4978. class Triangle {
  4979. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4980. this.a = a;
  4981. this.b = b;
  4982. this.c = c;
  4983. }
  4984. static getNormal( a, b, c, target ) {
  4985. target.subVectors( c, b );
  4986. _v0$2.subVectors( a, b );
  4987. target.cross( _v0$2 );
  4988. const targetLengthSq = target.lengthSq();
  4989. if ( targetLengthSq > 0 ) {
  4990. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4991. }
  4992. return target.set( 0, 0, 0 );
  4993. }
  4994. // static/instance method to calculate barycentric coordinates
  4995. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4996. static getBarycoord( point, a, b, c, target ) {
  4997. _v0$2.subVectors( c, a );
  4998. _v1$3.subVectors( b, a );
  4999. _v2$2.subVectors( point, a );
  5000. const dot00 = _v0$2.dot( _v0$2 );
  5001. const dot01 = _v0$2.dot( _v1$3 );
  5002. const dot02 = _v0$2.dot( _v2$2 );
  5003. const dot11 = _v1$3.dot( _v1$3 );
  5004. const dot12 = _v1$3.dot( _v2$2 );
  5005. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5006. // collinear or singular triangle
  5007. if ( denom === 0 ) {
  5008. target.set( 0, 0, 0 );
  5009. return null;
  5010. }
  5011. const invDenom = 1 / denom;
  5012. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5013. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5014. // barycentric coordinates must always sum to 1
  5015. return target.set( 1 - u - v, v, u );
  5016. }
  5017. static containsPoint( point, a, b, c ) {
  5018. // if the triangle is degenerate then we can't contain a point
  5019. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  5020. return false;
  5021. }
  5022. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  5023. }
  5024. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  5025. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  5026. target.x = 0;
  5027. target.y = 0;
  5028. if ( 'z' in target ) target.z = 0;
  5029. if ( 'w' in target ) target.w = 0;
  5030. return null;
  5031. }
  5032. target.setScalar( 0 );
  5033. target.addScaledVector( v1, _v3$2.x );
  5034. target.addScaledVector( v2, _v3$2.y );
  5035. target.addScaledVector( v3, _v3$2.z );
  5036. return target;
  5037. }
  5038. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  5039. _v40.setScalar( 0 );
  5040. _v41.setScalar( 0 );
  5041. _v42.setScalar( 0 );
  5042. _v40.fromBufferAttribute( attr, i1 );
  5043. _v41.fromBufferAttribute( attr, i2 );
  5044. _v42.fromBufferAttribute( attr, i3 );
  5045. target.setScalar( 0 );
  5046. target.addScaledVector( _v40, barycoord.x );
  5047. target.addScaledVector( _v41, barycoord.y );
  5048. target.addScaledVector( _v42, barycoord.z );
  5049. return target;
  5050. }
  5051. static isFrontFacing( a, b, c, direction ) {
  5052. _v0$2.subVectors( c, b );
  5053. _v1$3.subVectors( a, b );
  5054. // strictly front facing
  5055. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5056. }
  5057. set( a, b, c ) {
  5058. this.a.copy( a );
  5059. this.b.copy( b );
  5060. this.c.copy( c );
  5061. return this;
  5062. }
  5063. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5064. this.a.copy( points[ i0 ] );
  5065. this.b.copy( points[ i1 ] );
  5066. this.c.copy( points[ i2 ] );
  5067. return this;
  5068. }
  5069. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5070. this.a.fromBufferAttribute( attribute, i0 );
  5071. this.b.fromBufferAttribute( attribute, i1 );
  5072. this.c.fromBufferAttribute( attribute, i2 );
  5073. return this;
  5074. }
  5075. clone() {
  5076. return new this.constructor().copy( this );
  5077. }
  5078. copy( triangle ) {
  5079. this.a.copy( triangle.a );
  5080. this.b.copy( triangle.b );
  5081. this.c.copy( triangle.c );
  5082. return this;
  5083. }
  5084. getArea() {
  5085. _v0$2.subVectors( this.c, this.b );
  5086. _v1$3.subVectors( this.a, this.b );
  5087. return _v0$2.cross( _v1$3 ).length() * 0.5;
  5088. }
  5089. getMidpoint( target ) {
  5090. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5091. }
  5092. getNormal( target ) {
  5093. return Triangle.getNormal( this.a, this.b, this.c, target );
  5094. }
  5095. getPlane( target ) {
  5096. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5097. }
  5098. getBarycoord( point, target ) {
  5099. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5100. }
  5101. getInterpolation( point, v1, v2, v3, target ) {
  5102. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5103. }
  5104. containsPoint( point ) {
  5105. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5106. }
  5107. isFrontFacing( direction ) {
  5108. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5109. }
  5110. intersectsBox( box ) {
  5111. return box.intersectsTriangle( this );
  5112. }
  5113. closestPointToPoint( p, target ) {
  5114. const a = this.a, b = this.b, c = this.c;
  5115. let v, w;
  5116. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5117. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5118. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5119. // basically, we're distinguishing which of the voronoi regions of the triangle
  5120. // the point lies in with the minimum amount of redundant computation.
  5121. _vab.subVectors( b, a );
  5122. _vac.subVectors( c, a );
  5123. _vap.subVectors( p, a );
  5124. const d1 = _vab.dot( _vap );
  5125. const d2 = _vac.dot( _vap );
  5126. if ( d1 <= 0 && d2 <= 0 ) {
  5127. // vertex region of A; barycentric coords (1, 0, 0)
  5128. return target.copy( a );
  5129. }
  5130. _vbp.subVectors( p, b );
  5131. const d3 = _vab.dot( _vbp );
  5132. const d4 = _vac.dot( _vbp );
  5133. if ( d3 >= 0 && d4 <= d3 ) {
  5134. // vertex region of B; barycentric coords (0, 1, 0)
  5135. return target.copy( b );
  5136. }
  5137. const vc = d1 * d4 - d3 * d2;
  5138. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5139. v = d1 / ( d1 - d3 );
  5140. // edge region of AB; barycentric coords (1-v, v, 0)
  5141. return target.copy( a ).addScaledVector( _vab, v );
  5142. }
  5143. _vcp.subVectors( p, c );
  5144. const d5 = _vab.dot( _vcp );
  5145. const d6 = _vac.dot( _vcp );
  5146. if ( d6 >= 0 && d5 <= d6 ) {
  5147. // vertex region of C; barycentric coords (0, 0, 1)
  5148. return target.copy( c );
  5149. }
  5150. const vb = d5 * d2 - d1 * d6;
  5151. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5152. w = d2 / ( d2 - d6 );
  5153. // edge region of AC; barycentric coords (1-w, 0, w)
  5154. return target.copy( a ).addScaledVector( _vac, w );
  5155. }
  5156. const va = d3 * d6 - d5 * d4;
  5157. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5158. _vbc.subVectors( c, b );
  5159. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5160. // edge region of BC; barycentric coords (0, 1-w, w)
  5161. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5162. }
  5163. // face region
  5164. const denom = 1 / ( va + vb + vc );
  5165. // u = va * denom
  5166. v = vb * denom;
  5167. w = vc * denom;
  5168. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5169. }
  5170. equals( triangle ) {
  5171. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5172. }
  5173. }
  5174. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5175. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5176. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5177. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5178. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5179. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5180. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5181. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5182. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5183. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5184. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5185. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5186. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5187. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5188. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5189. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5190. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5191. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5192. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5193. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5194. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5195. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5196. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5197. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5198. const _hslA = { h: 0, s: 0, l: 0 };
  5199. const _hslB = { h: 0, s: 0, l: 0 };
  5200. function hue2rgb( p, q, t ) {
  5201. if ( t < 0 ) t += 1;
  5202. if ( t > 1 ) t -= 1;
  5203. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5204. if ( t < 1 / 2 ) return q;
  5205. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5206. return p;
  5207. }
  5208. class Color {
  5209. constructor( r, g, b ) {
  5210. this.isColor = true;
  5211. this.r = 1;
  5212. this.g = 1;
  5213. this.b = 1;
  5214. return this.set( r, g, b );
  5215. }
  5216. set( r, g, b ) {
  5217. if ( g === undefined && b === undefined ) {
  5218. // r is THREE.Color, hex or string
  5219. const value = r;
  5220. if ( value && value.isColor ) {
  5221. this.copy( value );
  5222. } else if ( typeof value === 'number' ) {
  5223. this.setHex( value );
  5224. } else if ( typeof value === 'string' ) {
  5225. this.setStyle( value );
  5226. }
  5227. } else {
  5228. this.setRGB( r, g, b );
  5229. }
  5230. return this;
  5231. }
  5232. setScalar( scalar ) {
  5233. this.r = scalar;
  5234. this.g = scalar;
  5235. this.b = scalar;
  5236. return this;
  5237. }
  5238. setHex( hex, colorSpace = SRGBColorSpace ) {
  5239. hex = Math.floor( hex );
  5240. this.r = ( hex >> 16 & 255 ) / 255;
  5241. this.g = ( hex >> 8 & 255 ) / 255;
  5242. this.b = ( hex & 255 ) / 255;
  5243. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5244. return this;
  5245. }
  5246. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5247. this.r = r;
  5248. this.g = g;
  5249. this.b = b;
  5250. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5251. return this;
  5252. }
  5253. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5254. // h,s,l ranges are in 0.0 - 1.0
  5255. h = euclideanModulo( h, 1 );
  5256. s = clamp( s, 0, 1 );
  5257. l = clamp( l, 0, 1 );
  5258. if ( s === 0 ) {
  5259. this.r = this.g = this.b = l;
  5260. } else {
  5261. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5262. const q = ( 2 * l ) - p;
  5263. this.r = hue2rgb( q, p, h + 1 / 3 );
  5264. this.g = hue2rgb( q, p, h );
  5265. this.b = hue2rgb( q, p, h - 1 / 3 );
  5266. }
  5267. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5268. return this;
  5269. }
  5270. setStyle( style, colorSpace = SRGBColorSpace ) {
  5271. function handleAlpha( string ) {
  5272. if ( string === undefined ) return;
  5273. if ( parseFloat( string ) < 1 ) {
  5274. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5275. }
  5276. }
  5277. let m;
  5278. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5279. // rgb / hsl
  5280. let color;
  5281. const name = m[ 1 ];
  5282. const components = m[ 2 ];
  5283. switch ( name ) {
  5284. case 'rgb':
  5285. case 'rgba':
  5286. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5287. // rgb(255,0,0) rgba(255,0,0,0.5)
  5288. handleAlpha( color[ 4 ] );
  5289. return this.setRGB(
  5290. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5291. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5292. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5293. colorSpace
  5294. );
  5295. }
  5296. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5297. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5298. handleAlpha( color[ 4 ] );
  5299. return this.setRGB(
  5300. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5301. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5302. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5303. colorSpace
  5304. );
  5305. }
  5306. break;
  5307. case 'hsl':
  5308. case 'hsla':
  5309. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5310. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5311. handleAlpha( color[ 4 ] );
  5312. return this.setHSL(
  5313. parseFloat( color[ 1 ] ) / 360,
  5314. parseFloat( color[ 2 ] ) / 100,
  5315. parseFloat( color[ 3 ] ) / 100,
  5316. colorSpace
  5317. );
  5318. }
  5319. break;
  5320. default:
  5321. console.warn( 'THREE.Color: Unknown color model ' + style );
  5322. }
  5323. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5324. // hex color
  5325. const hex = m[ 1 ];
  5326. const size = hex.length;
  5327. if ( size === 3 ) {
  5328. // #ff0
  5329. return this.setRGB(
  5330. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5331. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5332. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5333. colorSpace
  5334. );
  5335. } else if ( size === 6 ) {
  5336. // #ff0000
  5337. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5338. } else {
  5339. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5340. }
  5341. } else if ( style && style.length > 0 ) {
  5342. return this.setColorName( style, colorSpace );
  5343. }
  5344. return this;
  5345. }
  5346. setColorName( style, colorSpace = SRGBColorSpace ) {
  5347. // color keywords
  5348. const hex = _colorKeywords[ style.toLowerCase() ];
  5349. if ( hex !== undefined ) {
  5350. // red
  5351. this.setHex( hex, colorSpace );
  5352. } else {
  5353. // unknown color
  5354. console.warn( 'THREE.Color: Unknown color ' + style );
  5355. }
  5356. return this;
  5357. }
  5358. clone() {
  5359. return new this.constructor( this.r, this.g, this.b );
  5360. }
  5361. copy( color ) {
  5362. this.r = color.r;
  5363. this.g = color.g;
  5364. this.b = color.b;
  5365. return this;
  5366. }
  5367. copySRGBToLinear( color ) {
  5368. this.r = SRGBToLinear( color.r );
  5369. this.g = SRGBToLinear( color.g );
  5370. this.b = SRGBToLinear( color.b );
  5371. return this;
  5372. }
  5373. copyLinearToSRGB( color ) {
  5374. this.r = LinearToSRGB( color.r );
  5375. this.g = LinearToSRGB( color.g );
  5376. this.b = LinearToSRGB( color.b );
  5377. return this;
  5378. }
  5379. convertSRGBToLinear() {
  5380. this.copySRGBToLinear( this );
  5381. return this;
  5382. }
  5383. convertLinearToSRGB() {
  5384. this.copyLinearToSRGB( this );
  5385. return this;
  5386. }
  5387. getHex( colorSpace = SRGBColorSpace ) {
  5388. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5389. 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 ) );
  5390. }
  5391. getHexString( colorSpace = SRGBColorSpace ) {
  5392. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5393. }
  5394. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5395. // h,s,l ranges are in 0.0 - 1.0
  5396. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5397. const r = _color.r, g = _color.g, b = _color.b;
  5398. const max = Math.max( r, g, b );
  5399. const min = Math.min( r, g, b );
  5400. let hue, saturation;
  5401. const lightness = ( min + max ) / 2.0;
  5402. if ( min === max ) {
  5403. hue = 0;
  5404. saturation = 0;
  5405. } else {
  5406. const delta = max - min;
  5407. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5408. switch ( max ) {
  5409. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5410. case g: hue = ( b - r ) / delta + 2; break;
  5411. case b: hue = ( r - g ) / delta + 4; break;
  5412. }
  5413. hue /= 6;
  5414. }
  5415. target.h = hue;
  5416. target.s = saturation;
  5417. target.l = lightness;
  5418. return target;
  5419. }
  5420. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5421. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5422. target.r = _color.r;
  5423. target.g = _color.g;
  5424. target.b = _color.b;
  5425. return target;
  5426. }
  5427. getStyle( colorSpace = SRGBColorSpace ) {
  5428. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5429. const r = _color.r, g = _color.g, b = _color.b;
  5430. if ( colorSpace !== SRGBColorSpace ) {
  5431. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5432. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5433. }
  5434. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5435. }
  5436. offsetHSL( h, s, l ) {
  5437. this.getHSL( _hslA );
  5438. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5439. }
  5440. add( color ) {
  5441. this.r += color.r;
  5442. this.g += color.g;
  5443. this.b += color.b;
  5444. return this;
  5445. }
  5446. addColors( color1, color2 ) {
  5447. this.r = color1.r + color2.r;
  5448. this.g = color1.g + color2.g;
  5449. this.b = color1.b + color2.b;
  5450. return this;
  5451. }
  5452. addScalar( s ) {
  5453. this.r += s;
  5454. this.g += s;
  5455. this.b += s;
  5456. return this;
  5457. }
  5458. sub( color ) {
  5459. this.r = Math.max( 0, this.r - color.r );
  5460. this.g = Math.max( 0, this.g - color.g );
  5461. this.b = Math.max( 0, this.b - color.b );
  5462. return this;
  5463. }
  5464. multiply( color ) {
  5465. this.r *= color.r;
  5466. this.g *= color.g;
  5467. this.b *= color.b;
  5468. return this;
  5469. }
  5470. multiplyScalar( s ) {
  5471. this.r *= s;
  5472. this.g *= s;
  5473. this.b *= s;
  5474. return this;
  5475. }
  5476. lerp( color, alpha ) {
  5477. this.r += ( color.r - this.r ) * alpha;
  5478. this.g += ( color.g - this.g ) * alpha;
  5479. this.b += ( color.b - this.b ) * alpha;
  5480. return this;
  5481. }
  5482. lerpColors( color1, color2, alpha ) {
  5483. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5484. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5485. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5486. return this;
  5487. }
  5488. lerpHSL( color, alpha ) {
  5489. this.getHSL( _hslA );
  5490. color.getHSL( _hslB );
  5491. const h = lerp( _hslA.h, _hslB.h, alpha );
  5492. const s = lerp( _hslA.s, _hslB.s, alpha );
  5493. const l = lerp( _hslA.l, _hslB.l, alpha );
  5494. this.setHSL( h, s, l );
  5495. return this;
  5496. }
  5497. setFromVector3( v ) {
  5498. this.r = v.x;
  5499. this.g = v.y;
  5500. this.b = v.z;
  5501. return this;
  5502. }
  5503. applyMatrix3( m ) {
  5504. const r = this.r, g = this.g, b = this.b;
  5505. const e = m.elements;
  5506. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5507. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5508. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5509. return this;
  5510. }
  5511. equals( c ) {
  5512. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5513. }
  5514. fromArray( array, offset = 0 ) {
  5515. this.r = array[ offset ];
  5516. this.g = array[ offset + 1 ];
  5517. this.b = array[ offset + 2 ];
  5518. return this;
  5519. }
  5520. toArray( array = [], offset = 0 ) {
  5521. array[ offset ] = this.r;
  5522. array[ offset + 1 ] = this.g;
  5523. array[ offset + 2 ] = this.b;
  5524. return array;
  5525. }
  5526. fromBufferAttribute( attribute, index ) {
  5527. this.r = attribute.getX( index );
  5528. this.g = attribute.getY( index );
  5529. this.b = attribute.getZ( index );
  5530. return this;
  5531. }
  5532. toJSON() {
  5533. return this.getHex();
  5534. }
  5535. *[ Symbol.iterator ]() {
  5536. yield this.r;
  5537. yield this.g;
  5538. yield this.b;
  5539. }
  5540. }
  5541. const _color = /*@__PURE__*/ new Color();
  5542. Color.NAMES = _colorKeywords;
  5543. let _materialId = 0;
  5544. class Material extends EventDispatcher {
  5545. constructor() {
  5546. super();
  5547. this.isMaterial = true;
  5548. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5549. this.uuid = generateUUID();
  5550. this.name = '';
  5551. this.type = 'Material';
  5552. this.blending = NormalBlending;
  5553. this.side = FrontSide;
  5554. this.vertexColors = false;
  5555. this.opacity = 1;
  5556. this.transparent = false;
  5557. this.alphaHash = false;
  5558. this.blendSrc = SrcAlphaFactor;
  5559. this.blendDst = OneMinusSrcAlphaFactor;
  5560. this.blendEquation = AddEquation;
  5561. this.blendSrcAlpha = null;
  5562. this.blendDstAlpha = null;
  5563. this.blendEquationAlpha = null;
  5564. this.blendColor = new Color( 0, 0, 0 );
  5565. this.blendAlpha = 0;
  5566. this.depthFunc = LessEqualDepth;
  5567. this.depthTest = true;
  5568. this.depthWrite = true;
  5569. this.stencilWriteMask = 0xff;
  5570. this.stencilFunc = AlwaysStencilFunc;
  5571. this.stencilRef = 0;
  5572. this.stencilFuncMask = 0xff;
  5573. this.stencilFail = KeepStencilOp;
  5574. this.stencilZFail = KeepStencilOp;
  5575. this.stencilZPass = KeepStencilOp;
  5576. this.stencilWrite = false;
  5577. this.clippingPlanes = null;
  5578. this.clipIntersection = false;
  5579. this.clipShadows = false;
  5580. this.shadowSide = null;
  5581. this.colorWrite = true;
  5582. this.precision = null; // override the renderer's default precision for this material
  5583. this.polygonOffset = false;
  5584. this.polygonOffsetFactor = 0;
  5585. this.polygonOffsetUnits = 0;
  5586. this.dithering = false;
  5587. this.alphaToCoverage = false;
  5588. this.premultipliedAlpha = false;
  5589. this.forceSinglePass = false;
  5590. this.visible = true;
  5591. this.toneMapped = true;
  5592. this.userData = {};
  5593. this.version = 0;
  5594. this._alphaTest = 0;
  5595. }
  5596. get alphaTest() {
  5597. return this._alphaTest;
  5598. }
  5599. set alphaTest( value ) {
  5600. if ( this._alphaTest > 0 !== value > 0 ) {
  5601. this.version ++;
  5602. }
  5603. this._alphaTest = value;
  5604. }
  5605. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5606. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5607. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5608. customProgramCacheKey() {
  5609. return this.onBeforeCompile.toString();
  5610. }
  5611. setValues( values ) {
  5612. if ( values === undefined ) return;
  5613. for ( const key in values ) {
  5614. const newValue = values[ key ];
  5615. if ( newValue === undefined ) {
  5616. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5617. continue;
  5618. }
  5619. const currentValue = this[ key ];
  5620. if ( currentValue === undefined ) {
  5621. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5622. continue;
  5623. }
  5624. if ( currentValue && currentValue.isColor ) {
  5625. currentValue.set( newValue );
  5626. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5627. currentValue.copy( newValue );
  5628. } else {
  5629. this[ key ] = newValue;
  5630. }
  5631. }
  5632. }
  5633. toJSON( meta ) {
  5634. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5635. if ( isRootObject ) {
  5636. meta = {
  5637. textures: {},
  5638. images: {}
  5639. };
  5640. }
  5641. const data = {
  5642. metadata: {
  5643. version: 4.6,
  5644. type: 'Material',
  5645. generator: 'Material.toJSON'
  5646. }
  5647. };
  5648. // standard Material serialization
  5649. data.uuid = this.uuid;
  5650. data.type = this.type;
  5651. if ( this.name !== '' ) data.name = this.name;
  5652. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5653. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5654. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5655. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5656. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5657. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5658. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5659. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5660. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5661. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5662. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5663. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5664. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5665. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5666. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5667. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5668. }
  5669. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5670. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5671. }
  5672. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5673. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5674. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5675. }
  5676. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5677. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5678. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5679. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5680. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5681. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5682. }
  5683. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5684. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5685. }
  5686. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5687. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5688. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5689. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5690. }
  5691. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5692. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5693. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5694. if ( this.lightMap && this.lightMap.isTexture ) {
  5695. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5696. data.lightMapIntensity = this.lightMapIntensity;
  5697. }
  5698. if ( this.aoMap && this.aoMap.isTexture ) {
  5699. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5700. data.aoMapIntensity = this.aoMapIntensity;
  5701. }
  5702. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5703. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5704. data.bumpScale = this.bumpScale;
  5705. }
  5706. if ( this.normalMap && this.normalMap.isTexture ) {
  5707. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5708. data.normalMapType = this.normalMapType;
  5709. data.normalScale = this.normalScale.toArray();
  5710. }
  5711. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5712. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5713. data.displacementScale = this.displacementScale;
  5714. data.displacementBias = this.displacementBias;
  5715. }
  5716. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5717. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5718. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5719. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5720. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5721. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5722. if ( this.envMap && this.envMap.isTexture ) {
  5723. data.envMap = this.envMap.toJSON( meta ).uuid;
  5724. if ( this.combine !== undefined ) data.combine = this.combine;
  5725. }
  5726. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5727. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5728. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5729. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5730. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5731. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5732. }
  5733. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5734. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5735. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5736. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5737. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5738. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5739. if ( this.size !== undefined ) data.size = this.size;
  5740. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5741. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5742. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5743. if ( this.side !== FrontSide ) data.side = this.side;
  5744. if ( this.vertexColors === true ) data.vertexColors = true;
  5745. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5746. if ( this.transparent === true ) data.transparent = true;
  5747. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5748. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5749. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5750. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5751. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5752. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5753. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5754. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5755. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5756. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5757. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5758. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5759. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5760. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5761. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5762. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5763. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5764. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5765. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5766. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5767. // rotation (SpriteMaterial)
  5768. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5769. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5770. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5771. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5772. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5773. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5774. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5775. if ( this.scale !== undefined ) data.scale = this.scale;
  5776. if ( this.dithering === true ) data.dithering = true;
  5777. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5778. if ( this.alphaHash === true ) data.alphaHash = true;
  5779. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5780. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5781. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5782. if ( this.wireframe === true ) data.wireframe = true;
  5783. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5784. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5785. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5786. if ( this.flatShading === true ) data.flatShading = true;
  5787. if ( this.visible === false ) data.visible = false;
  5788. if ( this.toneMapped === false ) data.toneMapped = false;
  5789. if ( this.fog === false ) data.fog = false;
  5790. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5791. // TODO: Copied from Object3D.toJSON
  5792. function extractFromCache( cache ) {
  5793. const values = [];
  5794. for ( const key in cache ) {
  5795. const data = cache[ key ];
  5796. delete data.metadata;
  5797. values.push( data );
  5798. }
  5799. return values;
  5800. }
  5801. if ( isRootObject ) {
  5802. const textures = extractFromCache( meta.textures );
  5803. const images = extractFromCache( meta.images );
  5804. if ( textures.length > 0 ) data.textures = textures;
  5805. if ( images.length > 0 ) data.images = images;
  5806. }
  5807. return data;
  5808. }
  5809. clone() {
  5810. return new this.constructor().copy( this );
  5811. }
  5812. copy( source ) {
  5813. this.name = source.name;
  5814. this.blending = source.blending;
  5815. this.side = source.side;
  5816. this.vertexColors = source.vertexColors;
  5817. this.opacity = source.opacity;
  5818. this.transparent = source.transparent;
  5819. this.blendSrc = source.blendSrc;
  5820. this.blendDst = source.blendDst;
  5821. this.blendEquation = source.blendEquation;
  5822. this.blendSrcAlpha = source.blendSrcAlpha;
  5823. this.blendDstAlpha = source.blendDstAlpha;
  5824. this.blendEquationAlpha = source.blendEquationAlpha;
  5825. this.blendColor.copy( source.blendColor );
  5826. this.blendAlpha = source.blendAlpha;
  5827. this.depthFunc = source.depthFunc;
  5828. this.depthTest = source.depthTest;
  5829. this.depthWrite = source.depthWrite;
  5830. this.stencilWriteMask = source.stencilWriteMask;
  5831. this.stencilFunc = source.stencilFunc;
  5832. this.stencilRef = source.stencilRef;
  5833. this.stencilFuncMask = source.stencilFuncMask;
  5834. this.stencilFail = source.stencilFail;
  5835. this.stencilZFail = source.stencilZFail;
  5836. this.stencilZPass = source.stencilZPass;
  5837. this.stencilWrite = source.stencilWrite;
  5838. const srcPlanes = source.clippingPlanes;
  5839. let dstPlanes = null;
  5840. if ( srcPlanes !== null ) {
  5841. const n = srcPlanes.length;
  5842. dstPlanes = new Array( n );
  5843. for ( let i = 0; i !== n; ++ i ) {
  5844. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5845. }
  5846. }
  5847. this.clippingPlanes = dstPlanes;
  5848. this.clipIntersection = source.clipIntersection;
  5849. this.clipShadows = source.clipShadows;
  5850. this.shadowSide = source.shadowSide;
  5851. this.colorWrite = source.colorWrite;
  5852. this.precision = source.precision;
  5853. this.polygonOffset = source.polygonOffset;
  5854. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5855. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5856. this.dithering = source.dithering;
  5857. this.alphaTest = source.alphaTest;
  5858. this.alphaHash = source.alphaHash;
  5859. this.alphaToCoverage = source.alphaToCoverage;
  5860. this.premultipliedAlpha = source.premultipliedAlpha;
  5861. this.forceSinglePass = source.forceSinglePass;
  5862. this.visible = source.visible;
  5863. this.toneMapped = source.toneMapped;
  5864. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5865. return this;
  5866. }
  5867. dispose() {
  5868. this.dispatchEvent( { type: 'dispose' } );
  5869. }
  5870. set needsUpdate( value ) {
  5871. if ( value === true ) this.version ++;
  5872. }
  5873. onBuild( /* shaderobject, renderer */ ) {
  5874. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5875. }
  5876. }
  5877. class MeshBasicMaterial extends Material {
  5878. constructor( parameters ) {
  5879. super();
  5880. this.isMeshBasicMaterial = true;
  5881. this.type = 'MeshBasicMaterial';
  5882. this.color = new Color( 0xffffff ); // emissive
  5883. this.map = null;
  5884. this.lightMap = null;
  5885. this.lightMapIntensity = 1.0;
  5886. this.aoMap = null;
  5887. this.aoMapIntensity = 1.0;
  5888. this.specularMap = null;
  5889. this.alphaMap = null;
  5890. this.envMap = null;
  5891. this.envMapRotation = new Euler();
  5892. this.combine = MultiplyOperation;
  5893. this.reflectivity = 1;
  5894. this.refractionRatio = 0.98;
  5895. this.wireframe = false;
  5896. this.wireframeLinewidth = 1;
  5897. this.wireframeLinecap = 'round';
  5898. this.wireframeLinejoin = 'round';
  5899. this.fog = true;
  5900. this.setValues( parameters );
  5901. }
  5902. copy( source ) {
  5903. super.copy( source );
  5904. this.color.copy( source.color );
  5905. this.map = source.map;
  5906. this.lightMap = source.lightMap;
  5907. this.lightMapIntensity = source.lightMapIntensity;
  5908. this.aoMap = source.aoMap;
  5909. this.aoMapIntensity = source.aoMapIntensity;
  5910. this.specularMap = source.specularMap;
  5911. this.alphaMap = source.alphaMap;
  5912. this.envMap = source.envMap;
  5913. this.envMapRotation.copy( source.envMapRotation );
  5914. this.combine = source.combine;
  5915. this.reflectivity = source.reflectivity;
  5916. this.refractionRatio = source.refractionRatio;
  5917. this.wireframe = source.wireframe;
  5918. this.wireframeLinewidth = source.wireframeLinewidth;
  5919. this.wireframeLinecap = source.wireframeLinecap;
  5920. this.wireframeLinejoin = source.wireframeLinejoin;
  5921. this.fog = source.fog;
  5922. return this;
  5923. }
  5924. }
  5925. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5926. const _tables = /*@__PURE__*/ _generateTables();
  5927. function _generateTables() {
  5928. // float32 to float16 helpers
  5929. const buffer = new ArrayBuffer( 4 );
  5930. const floatView = new Float32Array( buffer );
  5931. const uint32View = new Uint32Array( buffer );
  5932. const baseTable = new Uint32Array( 512 );
  5933. const shiftTable = new Uint32Array( 512 );
  5934. for ( let i = 0; i < 256; ++ i ) {
  5935. const e = i - 127;
  5936. // very small number (0, -0)
  5937. if ( e < - 27 ) {
  5938. baseTable[ i ] = 0x0000;
  5939. baseTable[ i | 0x100 ] = 0x8000;
  5940. shiftTable[ i ] = 24;
  5941. shiftTable[ i | 0x100 ] = 24;
  5942. // small number (denorm)
  5943. } else if ( e < - 14 ) {
  5944. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5945. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5946. shiftTable[ i ] = - e - 1;
  5947. shiftTable[ i | 0x100 ] = - e - 1;
  5948. // normal number
  5949. } else if ( e <= 15 ) {
  5950. baseTable[ i ] = ( e + 15 ) << 10;
  5951. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5952. shiftTable[ i ] = 13;
  5953. shiftTable[ i | 0x100 ] = 13;
  5954. // large number (Infinity, -Infinity)
  5955. } else if ( e < 128 ) {
  5956. baseTable[ i ] = 0x7c00;
  5957. baseTable[ i | 0x100 ] = 0xfc00;
  5958. shiftTable[ i ] = 24;
  5959. shiftTable[ i | 0x100 ] = 24;
  5960. // stay (NaN, Infinity, -Infinity)
  5961. } else {
  5962. baseTable[ i ] = 0x7c00;
  5963. baseTable[ i | 0x100 ] = 0xfc00;
  5964. shiftTable[ i ] = 13;
  5965. shiftTable[ i | 0x100 ] = 13;
  5966. }
  5967. }
  5968. // float16 to float32 helpers
  5969. const mantissaTable = new Uint32Array( 2048 );
  5970. const exponentTable = new Uint32Array( 64 );
  5971. const offsetTable = new Uint32Array( 64 );
  5972. for ( let i = 1; i < 1024; ++ i ) {
  5973. let m = i << 13; // zero pad mantissa bits
  5974. let e = 0; // zero exponent
  5975. // normalized
  5976. while ( ( m & 0x00800000 ) === 0 ) {
  5977. m <<= 1;
  5978. e -= 0x00800000; // decrement exponent
  5979. }
  5980. m &= ~ 0x00800000; // clear leading 1 bit
  5981. e += 0x38800000; // adjust bias
  5982. mantissaTable[ i ] = m | e;
  5983. }
  5984. for ( let i = 1024; i < 2048; ++ i ) {
  5985. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5986. }
  5987. for ( let i = 1; i < 31; ++ i ) {
  5988. exponentTable[ i ] = i << 23;
  5989. }
  5990. exponentTable[ 31 ] = 0x47800000;
  5991. exponentTable[ 32 ] = 0x80000000;
  5992. for ( let i = 33; i < 63; ++ i ) {
  5993. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5994. }
  5995. exponentTable[ 63 ] = 0xc7800000;
  5996. for ( let i = 1; i < 64; ++ i ) {
  5997. if ( i !== 32 ) {
  5998. offsetTable[ i ] = 1024;
  5999. }
  6000. }
  6001. return {
  6002. floatView: floatView,
  6003. uint32View: uint32View,
  6004. baseTable: baseTable,
  6005. shiftTable: shiftTable,
  6006. mantissaTable: mantissaTable,
  6007. exponentTable: exponentTable,
  6008. offsetTable: offsetTable
  6009. };
  6010. }
  6011. // float32 to float16
  6012. function toHalfFloat( val ) {
  6013. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  6014. val = clamp( val, - 65504, 65504 );
  6015. _tables.floatView[ 0 ] = val;
  6016. const f = _tables.uint32View[ 0 ];
  6017. const e = ( f >> 23 ) & 0x1ff;
  6018. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  6019. }
  6020. // float16 to float32
  6021. function fromHalfFloat( val ) {
  6022. const m = val >> 10;
  6023. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  6024. return _tables.floatView[ 0 ];
  6025. }
  6026. const DataUtils = {
  6027. toHalfFloat: toHalfFloat,
  6028. fromHalfFloat: fromHalfFloat,
  6029. };
  6030. const _vector$9 = /*@__PURE__*/ new Vector3();
  6031. const _vector2$1 = /*@__PURE__*/ new Vector2();
  6032. class BufferAttribute {
  6033. constructor( array, itemSize, normalized = false ) {
  6034. if ( Array.isArray( array ) ) {
  6035. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  6036. }
  6037. this.isBufferAttribute = true;
  6038. this.name = '';
  6039. this.array = array;
  6040. this.itemSize = itemSize;
  6041. this.count = array !== undefined ? array.length / itemSize : 0;
  6042. this.normalized = normalized;
  6043. this.usage = StaticDrawUsage;
  6044. this.updateRanges = [];
  6045. this.gpuType = FloatType;
  6046. this.version = 0;
  6047. }
  6048. onUploadCallback() {}
  6049. set needsUpdate( value ) {
  6050. if ( value === true ) this.version ++;
  6051. }
  6052. setUsage( value ) {
  6053. this.usage = value;
  6054. return this;
  6055. }
  6056. addUpdateRange( start, count ) {
  6057. this.updateRanges.push( { start, count } );
  6058. }
  6059. clearUpdateRanges() {
  6060. this.updateRanges.length = 0;
  6061. }
  6062. copy( source ) {
  6063. this.name = source.name;
  6064. this.array = new source.array.constructor( source.array );
  6065. this.itemSize = source.itemSize;
  6066. this.count = source.count;
  6067. this.normalized = source.normalized;
  6068. this.usage = source.usage;
  6069. this.gpuType = source.gpuType;
  6070. return this;
  6071. }
  6072. copyAt( index1, attribute, index2 ) {
  6073. index1 *= this.itemSize;
  6074. index2 *= attribute.itemSize;
  6075. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6076. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6077. }
  6078. return this;
  6079. }
  6080. copyArray( array ) {
  6081. this.array.set( array );
  6082. return this;
  6083. }
  6084. applyMatrix3( m ) {
  6085. if ( this.itemSize === 2 ) {
  6086. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6087. _vector2$1.fromBufferAttribute( this, i );
  6088. _vector2$1.applyMatrix3( m );
  6089. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6090. }
  6091. } else if ( this.itemSize === 3 ) {
  6092. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6093. _vector$9.fromBufferAttribute( this, i );
  6094. _vector$9.applyMatrix3( m );
  6095. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6096. }
  6097. }
  6098. return this;
  6099. }
  6100. applyMatrix4( m ) {
  6101. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6102. _vector$9.fromBufferAttribute( this, i );
  6103. _vector$9.applyMatrix4( m );
  6104. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6105. }
  6106. return this;
  6107. }
  6108. applyNormalMatrix( m ) {
  6109. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6110. _vector$9.fromBufferAttribute( this, i );
  6111. _vector$9.applyNormalMatrix( m );
  6112. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6113. }
  6114. return this;
  6115. }
  6116. transformDirection( m ) {
  6117. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6118. _vector$9.fromBufferAttribute( this, i );
  6119. _vector$9.transformDirection( m );
  6120. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6121. }
  6122. return this;
  6123. }
  6124. set( value, offset = 0 ) {
  6125. // Matching BufferAttribute constructor, do not normalize the array.
  6126. this.array.set( value, offset );
  6127. return this;
  6128. }
  6129. getComponent( index, component ) {
  6130. let value = this.array[ index * this.itemSize + component ];
  6131. if ( this.normalized ) value = denormalize( value, this.array );
  6132. return value;
  6133. }
  6134. setComponent( index, component, value ) {
  6135. if ( this.normalized ) value = normalize( value, this.array );
  6136. this.array[ index * this.itemSize + component ] = value;
  6137. return this;
  6138. }
  6139. getX( index ) {
  6140. let x = this.array[ index * this.itemSize ];
  6141. if ( this.normalized ) x = denormalize( x, this.array );
  6142. return x;
  6143. }
  6144. setX( index, x ) {
  6145. if ( this.normalized ) x = normalize( x, this.array );
  6146. this.array[ index * this.itemSize ] = x;
  6147. return this;
  6148. }
  6149. getY( index ) {
  6150. let y = this.array[ index * this.itemSize + 1 ];
  6151. if ( this.normalized ) y = denormalize( y, this.array );
  6152. return y;
  6153. }
  6154. setY( index, y ) {
  6155. if ( this.normalized ) y = normalize( y, this.array );
  6156. this.array[ index * this.itemSize + 1 ] = y;
  6157. return this;
  6158. }
  6159. getZ( index ) {
  6160. let z = this.array[ index * this.itemSize + 2 ];
  6161. if ( this.normalized ) z = denormalize( z, this.array );
  6162. return z;
  6163. }
  6164. setZ( index, z ) {
  6165. if ( this.normalized ) z = normalize( z, this.array );
  6166. this.array[ index * this.itemSize + 2 ] = z;
  6167. return this;
  6168. }
  6169. getW( index ) {
  6170. let w = this.array[ index * this.itemSize + 3 ];
  6171. if ( this.normalized ) w = denormalize( w, this.array );
  6172. return w;
  6173. }
  6174. setW( index, w ) {
  6175. if ( this.normalized ) w = normalize( w, this.array );
  6176. this.array[ index * this.itemSize + 3 ] = w;
  6177. return this;
  6178. }
  6179. setXY( index, x, y ) {
  6180. index *= this.itemSize;
  6181. if ( this.normalized ) {
  6182. x = normalize( x, this.array );
  6183. y = normalize( y, this.array );
  6184. }
  6185. this.array[ index + 0 ] = x;
  6186. this.array[ index + 1 ] = y;
  6187. return this;
  6188. }
  6189. setXYZ( index, x, y, z ) {
  6190. index *= this.itemSize;
  6191. if ( this.normalized ) {
  6192. x = normalize( x, this.array );
  6193. y = normalize( y, this.array );
  6194. z = normalize( z, this.array );
  6195. }
  6196. this.array[ index + 0 ] = x;
  6197. this.array[ index + 1 ] = y;
  6198. this.array[ index + 2 ] = z;
  6199. return this;
  6200. }
  6201. setXYZW( index, x, y, z, w ) {
  6202. index *= this.itemSize;
  6203. if ( this.normalized ) {
  6204. x = normalize( x, this.array );
  6205. y = normalize( y, this.array );
  6206. z = normalize( z, this.array );
  6207. w = normalize( w, this.array );
  6208. }
  6209. this.array[ index + 0 ] = x;
  6210. this.array[ index + 1 ] = y;
  6211. this.array[ index + 2 ] = z;
  6212. this.array[ index + 3 ] = w;
  6213. return this;
  6214. }
  6215. onUpload( callback ) {
  6216. this.onUploadCallback = callback;
  6217. return this;
  6218. }
  6219. clone() {
  6220. return new this.constructor( this.array, this.itemSize ).copy( this );
  6221. }
  6222. toJSON() {
  6223. const data = {
  6224. itemSize: this.itemSize,
  6225. type: this.array.constructor.name,
  6226. array: Array.from( this.array ),
  6227. normalized: this.normalized
  6228. };
  6229. if ( this.name !== '' ) data.name = this.name;
  6230. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6231. return data;
  6232. }
  6233. }
  6234. //
  6235. class Int8BufferAttribute extends BufferAttribute {
  6236. constructor( array, itemSize, normalized ) {
  6237. super( new Int8Array( array ), itemSize, normalized );
  6238. }
  6239. }
  6240. class Uint8BufferAttribute extends BufferAttribute {
  6241. constructor( array, itemSize, normalized ) {
  6242. super( new Uint8Array( array ), itemSize, normalized );
  6243. }
  6244. }
  6245. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6246. constructor( array, itemSize, normalized ) {
  6247. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6248. }
  6249. }
  6250. class Int16BufferAttribute extends BufferAttribute {
  6251. constructor( array, itemSize, normalized ) {
  6252. super( new Int16Array( array ), itemSize, normalized );
  6253. }
  6254. }
  6255. class Uint16BufferAttribute extends BufferAttribute {
  6256. constructor( array, itemSize, normalized ) {
  6257. super( new Uint16Array( array ), itemSize, normalized );
  6258. }
  6259. }
  6260. class Int32BufferAttribute extends BufferAttribute {
  6261. constructor( array, itemSize, normalized ) {
  6262. super( new Int32Array( array ), itemSize, normalized );
  6263. }
  6264. }
  6265. class Uint32BufferAttribute extends BufferAttribute {
  6266. constructor( array, itemSize, normalized ) {
  6267. super( new Uint32Array( array ), itemSize, normalized );
  6268. }
  6269. }
  6270. class Float16BufferAttribute extends BufferAttribute {
  6271. constructor( array, itemSize, normalized ) {
  6272. super( new Uint16Array( array ), itemSize, normalized );
  6273. this.isFloat16BufferAttribute = true;
  6274. }
  6275. getX( index ) {
  6276. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6277. if ( this.normalized ) x = denormalize( x, this.array );
  6278. return x;
  6279. }
  6280. setX( index, x ) {
  6281. if ( this.normalized ) x = normalize( x, this.array );
  6282. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6283. return this;
  6284. }
  6285. getY( index ) {
  6286. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6287. if ( this.normalized ) y = denormalize( y, this.array );
  6288. return y;
  6289. }
  6290. setY( index, y ) {
  6291. if ( this.normalized ) y = normalize( y, this.array );
  6292. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6293. return this;
  6294. }
  6295. getZ( index ) {
  6296. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6297. if ( this.normalized ) z = denormalize( z, this.array );
  6298. return z;
  6299. }
  6300. setZ( index, z ) {
  6301. if ( this.normalized ) z = normalize( z, this.array );
  6302. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6303. return this;
  6304. }
  6305. getW( index ) {
  6306. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6307. if ( this.normalized ) w = denormalize( w, this.array );
  6308. return w;
  6309. }
  6310. setW( index, w ) {
  6311. if ( this.normalized ) w = normalize( w, this.array );
  6312. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6313. return this;
  6314. }
  6315. setXY( index, x, y ) {
  6316. index *= this.itemSize;
  6317. if ( this.normalized ) {
  6318. x = normalize( x, this.array );
  6319. y = normalize( y, this.array );
  6320. }
  6321. this.array[ index + 0 ] = toHalfFloat( x );
  6322. this.array[ index + 1 ] = toHalfFloat( y );
  6323. return this;
  6324. }
  6325. setXYZ( index, x, y, z ) {
  6326. index *= this.itemSize;
  6327. if ( this.normalized ) {
  6328. x = normalize( x, this.array );
  6329. y = normalize( y, this.array );
  6330. z = normalize( z, this.array );
  6331. }
  6332. this.array[ index + 0 ] = toHalfFloat( x );
  6333. this.array[ index + 1 ] = toHalfFloat( y );
  6334. this.array[ index + 2 ] = toHalfFloat( z );
  6335. return this;
  6336. }
  6337. setXYZW( index, x, y, z, w ) {
  6338. index *= this.itemSize;
  6339. if ( this.normalized ) {
  6340. x = normalize( x, this.array );
  6341. y = normalize( y, this.array );
  6342. z = normalize( z, this.array );
  6343. w = normalize( w, this.array );
  6344. }
  6345. this.array[ index + 0 ] = toHalfFloat( x );
  6346. this.array[ index + 1 ] = toHalfFloat( y );
  6347. this.array[ index + 2 ] = toHalfFloat( z );
  6348. this.array[ index + 3 ] = toHalfFloat( w );
  6349. return this;
  6350. }
  6351. }
  6352. class Float32BufferAttribute extends BufferAttribute {
  6353. constructor( array, itemSize, normalized ) {
  6354. super( new Float32Array( array ), itemSize, normalized );
  6355. }
  6356. }
  6357. let _id$2 = 0;
  6358. const _m1$2 = /*@__PURE__*/ new Matrix4();
  6359. const _obj = /*@__PURE__*/ new Object3D();
  6360. const _offset = /*@__PURE__*/ new Vector3();
  6361. const _box$2 = /*@__PURE__*/ new Box3();
  6362. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6363. const _vector$8 = /*@__PURE__*/ new Vector3();
  6364. class BufferGeometry extends EventDispatcher {
  6365. constructor() {
  6366. super();
  6367. this.isBufferGeometry = true;
  6368. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  6369. this.uuid = generateUUID();
  6370. this.name = '';
  6371. this.type = 'BufferGeometry';
  6372. this.index = null;
  6373. this.indirect = null;
  6374. this.attributes = {};
  6375. this.morphAttributes = {};
  6376. this.morphTargetsRelative = false;
  6377. this.groups = [];
  6378. this.boundingBox = null;
  6379. this.boundingSphere = null;
  6380. this.drawRange = { start: 0, count: Infinity };
  6381. this.userData = {};
  6382. }
  6383. getIndex() {
  6384. return this.index;
  6385. }
  6386. setIndex( index ) {
  6387. if ( Array.isArray( index ) ) {
  6388. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6389. } else {
  6390. this.index = index;
  6391. }
  6392. return this;
  6393. }
  6394. setIndirect( indirect ) {
  6395. this.indirect = indirect;
  6396. return this;
  6397. }
  6398. getIndirect() {
  6399. return this.indirect;
  6400. }
  6401. getAttribute( name ) {
  6402. return this.attributes[ name ];
  6403. }
  6404. setAttribute( name, attribute ) {
  6405. this.attributes[ name ] = attribute;
  6406. return this;
  6407. }
  6408. deleteAttribute( name ) {
  6409. delete this.attributes[ name ];
  6410. return this;
  6411. }
  6412. hasAttribute( name ) {
  6413. return this.attributes[ name ] !== undefined;
  6414. }
  6415. addGroup( start, count, materialIndex = 0 ) {
  6416. this.groups.push( {
  6417. start: start,
  6418. count: count,
  6419. materialIndex: materialIndex
  6420. } );
  6421. }
  6422. clearGroups() {
  6423. this.groups = [];
  6424. }
  6425. setDrawRange( start, count ) {
  6426. this.drawRange.start = start;
  6427. this.drawRange.count = count;
  6428. }
  6429. applyMatrix4( matrix ) {
  6430. const position = this.attributes.position;
  6431. if ( position !== undefined ) {
  6432. position.applyMatrix4( matrix );
  6433. position.needsUpdate = true;
  6434. }
  6435. const normal = this.attributes.normal;
  6436. if ( normal !== undefined ) {
  6437. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6438. normal.applyNormalMatrix( normalMatrix );
  6439. normal.needsUpdate = true;
  6440. }
  6441. const tangent = this.attributes.tangent;
  6442. if ( tangent !== undefined ) {
  6443. tangent.transformDirection( matrix );
  6444. tangent.needsUpdate = true;
  6445. }
  6446. if ( this.boundingBox !== null ) {
  6447. this.computeBoundingBox();
  6448. }
  6449. if ( this.boundingSphere !== null ) {
  6450. this.computeBoundingSphere();
  6451. }
  6452. return this;
  6453. }
  6454. applyQuaternion( q ) {
  6455. _m1$2.makeRotationFromQuaternion( q );
  6456. this.applyMatrix4( _m1$2 );
  6457. return this;
  6458. }
  6459. rotateX( angle ) {
  6460. // rotate geometry around world x-axis
  6461. _m1$2.makeRotationX( angle );
  6462. this.applyMatrix4( _m1$2 );
  6463. return this;
  6464. }
  6465. rotateY( angle ) {
  6466. // rotate geometry around world y-axis
  6467. _m1$2.makeRotationY( angle );
  6468. this.applyMatrix4( _m1$2 );
  6469. return this;
  6470. }
  6471. rotateZ( angle ) {
  6472. // rotate geometry around world z-axis
  6473. _m1$2.makeRotationZ( angle );
  6474. this.applyMatrix4( _m1$2 );
  6475. return this;
  6476. }
  6477. translate( x, y, z ) {
  6478. // translate geometry
  6479. _m1$2.makeTranslation( x, y, z );
  6480. this.applyMatrix4( _m1$2 );
  6481. return this;
  6482. }
  6483. scale( x, y, z ) {
  6484. // scale geometry
  6485. _m1$2.makeScale( x, y, z );
  6486. this.applyMatrix4( _m1$2 );
  6487. return this;
  6488. }
  6489. lookAt( vector ) {
  6490. _obj.lookAt( vector );
  6491. _obj.updateMatrix();
  6492. this.applyMatrix4( _obj.matrix );
  6493. return this;
  6494. }
  6495. center() {
  6496. this.computeBoundingBox();
  6497. this.boundingBox.getCenter( _offset ).negate();
  6498. this.translate( _offset.x, _offset.y, _offset.z );
  6499. return this;
  6500. }
  6501. setFromPoints( points ) {
  6502. const positionAttribute = this.getAttribute( 'position' );
  6503. if ( positionAttribute === undefined ) {
  6504. const position = [];
  6505. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6506. const point = points[ i ];
  6507. position.push( point.x, point.y, point.z || 0 );
  6508. }
  6509. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6510. } else {
  6511. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  6512. for ( let i = 0; i < l; i ++ ) {
  6513. const point = points[ i ];
  6514. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  6515. }
  6516. if ( points.length > positionAttribute.count ) {
  6517. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  6518. }
  6519. positionAttribute.needsUpdate = true;
  6520. }
  6521. return this;
  6522. }
  6523. computeBoundingBox() {
  6524. if ( this.boundingBox === null ) {
  6525. this.boundingBox = new Box3();
  6526. }
  6527. const position = this.attributes.position;
  6528. const morphAttributesPosition = this.morphAttributes.position;
  6529. if ( position && position.isGLBufferAttribute ) {
  6530. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6531. this.boundingBox.set(
  6532. new Vector3( - Infinity, - Infinity, - Infinity ),
  6533. new Vector3( + Infinity, + Infinity, + Infinity )
  6534. );
  6535. return;
  6536. }
  6537. if ( position !== undefined ) {
  6538. this.boundingBox.setFromBufferAttribute( position );
  6539. // process morph attributes if present
  6540. if ( morphAttributesPosition ) {
  6541. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6542. const morphAttribute = morphAttributesPosition[ i ];
  6543. _box$2.setFromBufferAttribute( morphAttribute );
  6544. if ( this.morphTargetsRelative ) {
  6545. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6546. this.boundingBox.expandByPoint( _vector$8 );
  6547. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6548. this.boundingBox.expandByPoint( _vector$8 );
  6549. } else {
  6550. this.boundingBox.expandByPoint( _box$2.min );
  6551. this.boundingBox.expandByPoint( _box$2.max );
  6552. }
  6553. }
  6554. }
  6555. } else {
  6556. this.boundingBox.makeEmpty();
  6557. }
  6558. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6559. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6560. }
  6561. }
  6562. computeBoundingSphere() {
  6563. if ( this.boundingSphere === null ) {
  6564. this.boundingSphere = new Sphere();
  6565. }
  6566. const position = this.attributes.position;
  6567. const morphAttributesPosition = this.morphAttributes.position;
  6568. if ( position && position.isGLBufferAttribute ) {
  6569. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6570. this.boundingSphere.set( new Vector3(), Infinity );
  6571. return;
  6572. }
  6573. if ( position ) {
  6574. // first, find the center of the bounding sphere
  6575. const center = this.boundingSphere.center;
  6576. _box$2.setFromBufferAttribute( position );
  6577. // process morph attributes if present
  6578. if ( morphAttributesPosition ) {
  6579. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6580. const morphAttribute = morphAttributesPosition[ i ];
  6581. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6582. if ( this.morphTargetsRelative ) {
  6583. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6584. _box$2.expandByPoint( _vector$8 );
  6585. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6586. _box$2.expandByPoint( _vector$8 );
  6587. } else {
  6588. _box$2.expandByPoint( _boxMorphTargets.min );
  6589. _box$2.expandByPoint( _boxMorphTargets.max );
  6590. }
  6591. }
  6592. }
  6593. _box$2.getCenter( center );
  6594. // second, try to find a boundingSphere with a radius smaller than the
  6595. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6596. let maxRadiusSq = 0;
  6597. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6598. _vector$8.fromBufferAttribute( position, i );
  6599. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6600. }
  6601. // process morph attributes if present
  6602. if ( morphAttributesPosition ) {
  6603. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6604. const morphAttribute = morphAttributesPosition[ i ];
  6605. const morphTargetsRelative = this.morphTargetsRelative;
  6606. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6607. _vector$8.fromBufferAttribute( morphAttribute, j );
  6608. if ( morphTargetsRelative ) {
  6609. _offset.fromBufferAttribute( position, j );
  6610. _vector$8.add( _offset );
  6611. }
  6612. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6613. }
  6614. }
  6615. }
  6616. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6617. if ( isNaN( this.boundingSphere.radius ) ) {
  6618. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6619. }
  6620. }
  6621. }
  6622. computeTangents() {
  6623. const index = this.index;
  6624. const attributes = this.attributes;
  6625. // based on http://www.terathon.com/code/tangent.html
  6626. // (per vertex tangents)
  6627. if ( index === null ||
  6628. attributes.position === undefined ||
  6629. attributes.normal === undefined ||
  6630. attributes.uv === undefined ) {
  6631. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6632. return;
  6633. }
  6634. const positionAttribute = attributes.position;
  6635. const normalAttribute = attributes.normal;
  6636. const uvAttribute = attributes.uv;
  6637. if ( this.hasAttribute( 'tangent' ) === false ) {
  6638. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6639. }
  6640. const tangentAttribute = this.getAttribute( 'tangent' );
  6641. const tan1 = [], tan2 = [];
  6642. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6643. tan1[ i ] = new Vector3();
  6644. tan2[ i ] = new Vector3();
  6645. }
  6646. const vA = new Vector3(),
  6647. vB = new Vector3(),
  6648. vC = new Vector3(),
  6649. uvA = new Vector2(),
  6650. uvB = new Vector2(),
  6651. uvC = new Vector2(),
  6652. sdir = new Vector3(),
  6653. tdir = new Vector3();
  6654. function handleTriangle( a, b, c ) {
  6655. vA.fromBufferAttribute( positionAttribute, a );
  6656. vB.fromBufferAttribute( positionAttribute, b );
  6657. vC.fromBufferAttribute( positionAttribute, c );
  6658. uvA.fromBufferAttribute( uvAttribute, a );
  6659. uvB.fromBufferAttribute( uvAttribute, b );
  6660. uvC.fromBufferAttribute( uvAttribute, c );
  6661. vB.sub( vA );
  6662. vC.sub( vA );
  6663. uvB.sub( uvA );
  6664. uvC.sub( uvA );
  6665. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6666. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6667. if ( ! isFinite( r ) ) return;
  6668. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6669. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6670. tan1[ a ].add( sdir );
  6671. tan1[ b ].add( sdir );
  6672. tan1[ c ].add( sdir );
  6673. tan2[ a ].add( tdir );
  6674. tan2[ b ].add( tdir );
  6675. tan2[ c ].add( tdir );
  6676. }
  6677. let groups = this.groups;
  6678. if ( groups.length === 0 ) {
  6679. groups = [ {
  6680. start: 0,
  6681. count: index.count
  6682. } ];
  6683. }
  6684. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6685. const group = groups[ i ];
  6686. const start = group.start;
  6687. const count = group.count;
  6688. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6689. handleTriangle(
  6690. index.getX( j + 0 ),
  6691. index.getX( j + 1 ),
  6692. index.getX( j + 2 )
  6693. );
  6694. }
  6695. }
  6696. const tmp = new Vector3(), tmp2 = new Vector3();
  6697. const n = new Vector3(), n2 = new Vector3();
  6698. function handleVertex( v ) {
  6699. n.fromBufferAttribute( normalAttribute, v );
  6700. n2.copy( n );
  6701. const t = tan1[ v ];
  6702. // Gram-Schmidt orthogonalize
  6703. tmp.copy( t );
  6704. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6705. // Calculate handedness
  6706. tmp2.crossVectors( n2, t );
  6707. const test = tmp2.dot( tan2[ v ] );
  6708. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6709. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6710. }
  6711. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6712. const group = groups[ i ];
  6713. const start = group.start;
  6714. const count = group.count;
  6715. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6716. handleVertex( index.getX( j + 0 ) );
  6717. handleVertex( index.getX( j + 1 ) );
  6718. handleVertex( index.getX( j + 2 ) );
  6719. }
  6720. }
  6721. }
  6722. computeVertexNormals() {
  6723. const index = this.index;
  6724. const positionAttribute = this.getAttribute( 'position' );
  6725. if ( positionAttribute !== undefined ) {
  6726. let normalAttribute = this.getAttribute( 'normal' );
  6727. if ( normalAttribute === undefined ) {
  6728. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6729. this.setAttribute( 'normal', normalAttribute );
  6730. } else {
  6731. // reset existing normals to zero
  6732. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6733. normalAttribute.setXYZ( i, 0, 0, 0 );
  6734. }
  6735. }
  6736. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6737. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6738. const cb = new Vector3(), ab = new Vector3();
  6739. // indexed elements
  6740. if ( index ) {
  6741. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6742. const vA = index.getX( i + 0 );
  6743. const vB = index.getX( i + 1 );
  6744. const vC = index.getX( i + 2 );
  6745. pA.fromBufferAttribute( positionAttribute, vA );
  6746. pB.fromBufferAttribute( positionAttribute, vB );
  6747. pC.fromBufferAttribute( positionAttribute, vC );
  6748. cb.subVectors( pC, pB );
  6749. ab.subVectors( pA, pB );
  6750. cb.cross( ab );
  6751. nA.fromBufferAttribute( normalAttribute, vA );
  6752. nB.fromBufferAttribute( normalAttribute, vB );
  6753. nC.fromBufferAttribute( normalAttribute, vC );
  6754. nA.add( cb );
  6755. nB.add( cb );
  6756. nC.add( cb );
  6757. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6758. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6759. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6760. }
  6761. } else {
  6762. // non-indexed elements (unconnected triangle soup)
  6763. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6764. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6765. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6766. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6767. cb.subVectors( pC, pB );
  6768. ab.subVectors( pA, pB );
  6769. cb.cross( ab );
  6770. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6771. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6772. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6773. }
  6774. }
  6775. this.normalizeNormals();
  6776. normalAttribute.needsUpdate = true;
  6777. }
  6778. }
  6779. normalizeNormals() {
  6780. const normals = this.attributes.normal;
  6781. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6782. _vector$8.fromBufferAttribute( normals, i );
  6783. _vector$8.normalize();
  6784. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6785. }
  6786. }
  6787. toNonIndexed() {
  6788. function convertBufferAttribute( attribute, indices ) {
  6789. const array = attribute.array;
  6790. const itemSize = attribute.itemSize;
  6791. const normalized = attribute.normalized;
  6792. const array2 = new array.constructor( indices.length * itemSize );
  6793. let index = 0, index2 = 0;
  6794. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6795. if ( attribute.isInterleavedBufferAttribute ) {
  6796. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6797. } else {
  6798. index = indices[ i ] * itemSize;
  6799. }
  6800. for ( let j = 0; j < itemSize; j ++ ) {
  6801. array2[ index2 ++ ] = array[ index ++ ];
  6802. }
  6803. }
  6804. return new BufferAttribute( array2, itemSize, normalized );
  6805. }
  6806. //
  6807. if ( this.index === null ) {
  6808. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6809. return this;
  6810. }
  6811. const geometry2 = new BufferGeometry();
  6812. const indices = this.index.array;
  6813. const attributes = this.attributes;
  6814. // attributes
  6815. for ( const name in attributes ) {
  6816. const attribute = attributes[ name ];
  6817. const newAttribute = convertBufferAttribute( attribute, indices );
  6818. geometry2.setAttribute( name, newAttribute );
  6819. }
  6820. // morph attributes
  6821. const morphAttributes = this.morphAttributes;
  6822. for ( const name in morphAttributes ) {
  6823. const morphArray = [];
  6824. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6825. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6826. const attribute = morphAttribute[ i ];
  6827. const newAttribute = convertBufferAttribute( attribute, indices );
  6828. morphArray.push( newAttribute );
  6829. }
  6830. geometry2.morphAttributes[ name ] = morphArray;
  6831. }
  6832. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6833. // groups
  6834. const groups = this.groups;
  6835. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6836. const group = groups[ i ];
  6837. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6838. }
  6839. return geometry2;
  6840. }
  6841. toJSON() {
  6842. const data = {
  6843. metadata: {
  6844. version: 4.6,
  6845. type: 'BufferGeometry',
  6846. generator: 'BufferGeometry.toJSON'
  6847. }
  6848. };
  6849. // standard BufferGeometry serialization
  6850. data.uuid = this.uuid;
  6851. data.type = this.type;
  6852. if ( this.name !== '' ) data.name = this.name;
  6853. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6854. if ( this.parameters !== undefined ) {
  6855. const parameters = this.parameters;
  6856. for ( const key in parameters ) {
  6857. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6858. }
  6859. return data;
  6860. }
  6861. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6862. data.data = { attributes: {} };
  6863. const index = this.index;
  6864. if ( index !== null ) {
  6865. data.data.index = {
  6866. type: index.array.constructor.name,
  6867. array: Array.prototype.slice.call( index.array )
  6868. };
  6869. }
  6870. const attributes = this.attributes;
  6871. for ( const key in attributes ) {
  6872. const attribute = attributes[ key ];
  6873. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6874. }
  6875. const morphAttributes = {};
  6876. let hasMorphAttributes = false;
  6877. for ( const key in this.morphAttributes ) {
  6878. const attributeArray = this.morphAttributes[ key ];
  6879. const array = [];
  6880. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6881. const attribute = attributeArray[ i ];
  6882. array.push( attribute.toJSON( data.data ) );
  6883. }
  6884. if ( array.length > 0 ) {
  6885. morphAttributes[ key ] = array;
  6886. hasMorphAttributes = true;
  6887. }
  6888. }
  6889. if ( hasMorphAttributes ) {
  6890. data.data.morphAttributes = morphAttributes;
  6891. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6892. }
  6893. const groups = this.groups;
  6894. if ( groups.length > 0 ) {
  6895. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6896. }
  6897. const boundingSphere = this.boundingSphere;
  6898. if ( boundingSphere !== null ) {
  6899. data.data.boundingSphere = {
  6900. center: boundingSphere.center.toArray(),
  6901. radius: boundingSphere.radius
  6902. };
  6903. }
  6904. return data;
  6905. }
  6906. clone() {
  6907. return new this.constructor().copy( this );
  6908. }
  6909. copy( source ) {
  6910. // reset
  6911. this.index = null;
  6912. this.attributes = {};
  6913. this.morphAttributes = {};
  6914. this.groups = [];
  6915. this.boundingBox = null;
  6916. this.boundingSphere = null;
  6917. // used for storing cloned, shared data
  6918. const data = {};
  6919. // name
  6920. this.name = source.name;
  6921. // index
  6922. const index = source.index;
  6923. if ( index !== null ) {
  6924. this.setIndex( index.clone( data ) );
  6925. }
  6926. // attributes
  6927. const attributes = source.attributes;
  6928. for ( const name in attributes ) {
  6929. const attribute = attributes[ name ];
  6930. this.setAttribute( name, attribute.clone( data ) );
  6931. }
  6932. // morph attributes
  6933. const morphAttributes = source.morphAttributes;
  6934. for ( const name in morphAttributes ) {
  6935. const array = [];
  6936. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6937. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6938. array.push( morphAttribute[ i ].clone( data ) );
  6939. }
  6940. this.morphAttributes[ name ] = array;
  6941. }
  6942. this.morphTargetsRelative = source.morphTargetsRelative;
  6943. // groups
  6944. const groups = source.groups;
  6945. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6946. const group = groups[ i ];
  6947. this.addGroup( group.start, group.count, group.materialIndex );
  6948. }
  6949. // bounding box
  6950. const boundingBox = source.boundingBox;
  6951. if ( boundingBox !== null ) {
  6952. this.boundingBox = boundingBox.clone();
  6953. }
  6954. // bounding sphere
  6955. const boundingSphere = source.boundingSphere;
  6956. if ( boundingSphere !== null ) {
  6957. this.boundingSphere = boundingSphere.clone();
  6958. }
  6959. // draw range
  6960. this.drawRange.start = source.drawRange.start;
  6961. this.drawRange.count = source.drawRange.count;
  6962. // user data
  6963. this.userData = source.userData;
  6964. return this;
  6965. }
  6966. dispose() {
  6967. this.dispatchEvent( { type: 'dispose' } );
  6968. }
  6969. }
  6970. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6971. const _ray$3 = /*@__PURE__*/ new Ray();
  6972. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6973. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6974. const _vA$1 = /*@__PURE__*/ new Vector3();
  6975. const _vB$1 = /*@__PURE__*/ new Vector3();
  6976. const _vC$1 = /*@__PURE__*/ new Vector3();
  6977. const _tempA = /*@__PURE__*/ new Vector3();
  6978. const _morphA = /*@__PURE__*/ new Vector3();
  6979. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6980. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6981. class Mesh extends Object3D {
  6982. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6983. super();
  6984. this.isMesh = true;
  6985. this.type = 'Mesh';
  6986. this.geometry = geometry;
  6987. this.material = material;
  6988. this.updateMorphTargets();
  6989. }
  6990. copy( source, recursive ) {
  6991. super.copy( source, recursive );
  6992. if ( source.morphTargetInfluences !== undefined ) {
  6993. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6994. }
  6995. if ( source.morphTargetDictionary !== undefined ) {
  6996. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6997. }
  6998. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6999. this.geometry = source.geometry;
  7000. return this;
  7001. }
  7002. updateMorphTargets() {
  7003. const geometry = this.geometry;
  7004. const morphAttributes = geometry.morphAttributes;
  7005. const keys = Object.keys( morphAttributes );
  7006. if ( keys.length > 0 ) {
  7007. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  7008. if ( morphAttribute !== undefined ) {
  7009. this.morphTargetInfluences = [];
  7010. this.morphTargetDictionary = {};
  7011. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  7012. const name = morphAttribute[ m ].name || String( m );
  7013. this.morphTargetInfluences.push( 0 );
  7014. this.morphTargetDictionary[ name ] = m;
  7015. }
  7016. }
  7017. }
  7018. }
  7019. getVertexPosition( index, target ) {
  7020. const geometry = this.geometry;
  7021. const position = geometry.attributes.position;
  7022. const morphPosition = geometry.morphAttributes.position;
  7023. const morphTargetsRelative = geometry.morphTargetsRelative;
  7024. target.fromBufferAttribute( position, index );
  7025. const morphInfluences = this.morphTargetInfluences;
  7026. if ( morphPosition && morphInfluences ) {
  7027. _morphA.set( 0, 0, 0 );
  7028. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  7029. const influence = morphInfluences[ i ];
  7030. const morphAttribute = morphPosition[ i ];
  7031. if ( influence === 0 ) continue;
  7032. _tempA.fromBufferAttribute( morphAttribute, index );
  7033. if ( morphTargetsRelative ) {
  7034. _morphA.addScaledVector( _tempA, influence );
  7035. } else {
  7036. _morphA.addScaledVector( _tempA.sub( target ), influence );
  7037. }
  7038. }
  7039. target.add( _morphA );
  7040. }
  7041. return target;
  7042. }
  7043. raycast( raycaster, intersects ) {
  7044. const geometry = this.geometry;
  7045. const material = this.material;
  7046. const matrixWorld = this.matrixWorld;
  7047. if ( material === undefined ) return;
  7048. // test with bounding sphere in world space
  7049. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7050. _sphere$6.copy( geometry.boundingSphere );
  7051. _sphere$6.applyMatrix4( matrixWorld );
  7052. // check distance from ray origin to bounding sphere
  7053. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  7054. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  7055. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  7056. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  7057. }
  7058. // convert ray to local space of mesh
  7059. _inverseMatrix$3.copy( matrixWorld ).invert();
  7060. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  7061. // test with bounding box in local space
  7062. if ( geometry.boundingBox !== null ) {
  7063. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  7064. }
  7065. // test for intersections with geometry
  7066. this._computeIntersections( raycaster, intersects, _ray$3 );
  7067. }
  7068. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  7069. let intersection;
  7070. const geometry = this.geometry;
  7071. const material = this.material;
  7072. const index = geometry.index;
  7073. const position = geometry.attributes.position;
  7074. const uv = geometry.attributes.uv;
  7075. const uv1 = geometry.attributes.uv1;
  7076. const normal = geometry.attributes.normal;
  7077. const groups = geometry.groups;
  7078. const drawRange = geometry.drawRange;
  7079. if ( index !== null ) {
  7080. // indexed buffer geometry
  7081. if ( Array.isArray( material ) ) {
  7082. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7083. const group = groups[ i ];
  7084. const groupMaterial = material[ group.materialIndex ];
  7085. const start = Math.max( group.start, drawRange.start );
  7086. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7087. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7088. const a = index.getX( j );
  7089. const b = index.getX( j + 1 );
  7090. const c = index.getX( j + 2 );
  7091. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7092. if ( intersection ) {
  7093. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7094. intersection.face.materialIndex = group.materialIndex;
  7095. intersects.push( intersection );
  7096. }
  7097. }
  7098. }
  7099. } else {
  7100. const start = Math.max( 0, drawRange.start );
  7101. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7102. for ( let i = start, il = end; i < il; i += 3 ) {
  7103. const a = index.getX( i );
  7104. const b = index.getX( i + 1 );
  7105. const c = index.getX( i + 2 );
  7106. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7107. if ( intersection ) {
  7108. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7109. intersects.push( intersection );
  7110. }
  7111. }
  7112. }
  7113. } else if ( position !== undefined ) {
  7114. // non-indexed buffer geometry
  7115. if ( Array.isArray( material ) ) {
  7116. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7117. const group = groups[ i ];
  7118. const groupMaterial = material[ group.materialIndex ];
  7119. const start = Math.max( group.start, drawRange.start );
  7120. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7121. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7122. const a = j;
  7123. const b = j + 1;
  7124. const c = j + 2;
  7125. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7126. if ( intersection ) {
  7127. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7128. intersection.face.materialIndex = group.materialIndex;
  7129. intersects.push( intersection );
  7130. }
  7131. }
  7132. }
  7133. } else {
  7134. const start = Math.max( 0, drawRange.start );
  7135. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7136. for ( let i = start, il = end; i < il; i += 3 ) {
  7137. const a = i;
  7138. const b = i + 1;
  7139. const c = i + 2;
  7140. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7141. if ( intersection ) {
  7142. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7143. intersects.push( intersection );
  7144. }
  7145. }
  7146. }
  7147. }
  7148. }
  7149. }
  7150. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7151. let intersect;
  7152. if ( material.side === BackSide ) {
  7153. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7154. } else {
  7155. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7156. }
  7157. if ( intersect === null ) return null;
  7158. _intersectionPointWorld.copy( point );
  7159. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7160. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7161. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7162. return {
  7163. distance: distance,
  7164. point: _intersectionPointWorld.clone(),
  7165. object: object
  7166. };
  7167. }
  7168. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7169. object.getVertexPosition( a, _vA$1 );
  7170. object.getVertexPosition( b, _vB$1 );
  7171. object.getVertexPosition( c, _vC$1 );
  7172. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7173. if ( intersection ) {
  7174. const barycoord = new Vector3();
  7175. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  7176. if ( uv ) {
  7177. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  7178. }
  7179. if ( uv1 ) {
  7180. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  7181. }
  7182. if ( normal ) {
  7183. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  7184. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7185. intersection.normal.multiplyScalar( - 1 );
  7186. }
  7187. }
  7188. const face = {
  7189. a: a,
  7190. b: b,
  7191. c: c,
  7192. normal: new Vector3(),
  7193. materialIndex: 0
  7194. };
  7195. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7196. intersection.face = face;
  7197. intersection.barycoord = barycoord;
  7198. }
  7199. return intersection;
  7200. }
  7201. class BoxGeometry extends BufferGeometry {
  7202. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7203. super();
  7204. this.type = 'BoxGeometry';
  7205. this.parameters = {
  7206. width: width,
  7207. height: height,
  7208. depth: depth,
  7209. widthSegments: widthSegments,
  7210. heightSegments: heightSegments,
  7211. depthSegments: depthSegments
  7212. };
  7213. const scope = this;
  7214. // segments
  7215. widthSegments = Math.floor( widthSegments );
  7216. heightSegments = Math.floor( heightSegments );
  7217. depthSegments = Math.floor( depthSegments );
  7218. // buffers
  7219. const indices = [];
  7220. const vertices = [];
  7221. const normals = [];
  7222. const uvs = [];
  7223. // helper variables
  7224. let numberOfVertices = 0;
  7225. let groupStart = 0;
  7226. // build each side of the box geometry
  7227. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7228. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7229. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7230. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7231. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7232. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7233. // build geometry
  7234. this.setIndex( indices );
  7235. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7236. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7237. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7238. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7239. const segmentWidth = width / gridX;
  7240. const segmentHeight = height / gridY;
  7241. const widthHalf = width / 2;
  7242. const heightHalf = height / 2;
  7243. const depthHalf = depth / 2;
  7244. const gridX1 = gridX + 1;
  7245. const gridY1 = gridY + 1;
  7246. let vertexCounter = 0;
  7247. let groupCount = 0;
  7248. const vector = new Vector3();
  7249. // generate vertices, normals and uvs
  7250. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7251. const y = iy * segmentHeight - heightHalf;
  7252. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7253. const x = ix * segmentWidth - widthHalf;
  7254. // set values to correct vector component
  7255. vector[ u ] = x * udir;
  7256. vector[ v ] = y * vdir;
  7257. vector[ w ] = depthHalf;
  7258. // now apply vector to vertex buffer
  7259. vertices.push( vector.x, vector.y, vector.z );
  7260. // set values to correct vector component
  7261. vector[ u ] = 0;
  7262. vector[ v ] = 0;
  7263. vector[ w ] = depth > 0 ? 1 : - 1;
  7264. // now apply vector to normal buffer
  7265. normals.push( vector.x, vector.y, vector.z );
  7266. // uvs
  7267. uvs.push( ix / gridX );
  7268. uvs.push( 1 - ( iy / gridY ) );
  7269. // counters
  7270. vertexCounter += 1;
  7271. }
  7272. }
  7273. // indices
  7274. // 1. you need three indices to draw a single face
  7275. // 2. a single segment consists of two faces
  7276. // 3. so we need to generate six (2*3) indices per segment
  7277. for ( let iy = 0; iy < gridY; iy ++ ) {
  7278. for ( let ix = 0; ix < gridX; ix ++ ) {
  7279. const a = numberOfVertices + ix + gridX1 * iy;
  7280. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7281. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7282. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7283. // faces
  7284. indices.push( a, b, d );
  7285. indices.push( b, c, d );
  7286. // increase counter
  7287. groupCount += 6;
  7288. }
  7289. }
  7290. // add a group to the geometry. this will ensure multi material support
  7291. scope.addGroup( groupStart, groupCount, materialIndex );
  7292. // calculate new start value for groups
  7293. groupStart += groupCount;
  7294. // update total number of vertices
  7295. numberOfVertices += vertexCounter;
  7296. }
  7297. }
  7298. copy( source ) {
  7299. super.copy( source );
  7300. this.parameters = Object.assign( {}, source.parameters );
  7301. return this;
  7302. }
  7303. static fromJSON( data ) {
  7304. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7305. }
  7306. }
  7307. /**
  7308. * Uniform Utilities
  7309. */
  7310. function cloneUniforms( src ) {
  7311. const dst = {};
  7312. for ( const u in src ) {
  7313. dst[ u ] = {};
  7314. for ( const p in src[ u ] ) {
  7315. const property = src[ u ][ p ];
  7316. if ( property && ( property.isColor ||
  7317. property.isMatrix3 || property.isMatrix4 ||
  7318. property.isVector2 || property.isVector3 || property.isVector4 ||
  7319. property.isTexture || property.isQuaternion ) ) {
  7320. if ( property.isRenderTargetTexture ) {
  7321. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7322. dst[ u ][ p ] = null;
  7323. } else {
  7324. dst[ u ][ p ] = property.clone();
  7325. }
  7326. } else if ( Array.isArray( property ) ) {
  7327. dst[ u ][ p ] = property.slice();
  7328. } else {
  7329. dst[ u ][ p ] = property;
  7330. }
  7331. }
  7332. }
  7333. return dst;
  7334. }
  7335. function mergeUniforms( uniforms ) {
  7336. const merged = {};
  7337. for ( let u = 0; u < uniforms.length; u ++ ) {
  7338. const tmp = cloneUniforms( uniforms[ u ] );
  7339. for ( const p in tmp ) {
  7340. merged[ p ] = tmp[ p ];
  7341. }
  7342. }
  7343. return merged;
  7344. }
  7345. function cloneUniformsGroups( src ) {
  7346. const dst = [];
  7347. for ( let u = 0; u < src.length; u ++ ) {
  7348. dst.push( src[ u ].clone() );
  7349. }
  7350. return dst;
  7351. }
  7352. function getUnlitUniformColorSpace( renderer ) {
  7353. const currentRenderTarget = renderer.getRenderTarget();
  7354. if ( currentRenderTarget === null ) {
  7355. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7356. return renderer.outputColorSpace;
  7357. }
  7358. // https://github.com/mrdoob/three.js/issues/27868
  7359. if ( currentRenderTarget.isXRRenderTarget === true ) {
  7360. return currentRenderTarget.texture.colorSpace;
  7361. }
  7362. return ColorManagement.workingColorSpace;
  7363. }
  7364. // Legacy
  7365. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7366. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7367. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7368. class ShaderMaterial extends Material {
  7369. constructor( parameters ) {
  7370. super();
  7371. this.isShaderMaterial = true;
  7372. this.type = 'ShaderMaterial';
  7373. this.defines = {};
  7374. this.uniforms = {};
  7375. this.uniformsGroups = [];
  7376. this.vertexShader = default_vertex;
  7377. this.fragmentShader = default_fragment;
  7378. this.linewidth = 1;
  7379. this.wireframe = false;
  7380. this.wireframeLinewidth = 1;
  7381. this.fog = false; // set to use scene fog
  7382. this.lights = false; // set to use scene lights
  7383. this.clipping = false; // set to use user-defined clipping planes
  7384. this.forceSinglePass = true;
  7385. this.extensions = {
  7386. clipCullDistance: false, // set to use vertex shader clipping
  7387. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7388. };
  7389. // When rendered geometry doesn't include these attributes but the material does,
  7390. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7391. this.defaultAttributeValues = {
  7392. 'color': [ 1, 1, 1 ],
  7393. 'uv': [ 0, 0 ],
  7394. 'uv1': [ 0, 0 ]
  7395. };
  7396. this.index0AttributeName = undefined;
  7397. this.uniformsNeedUpdate = false;
  7398. this.glslVersion = null;
  7399. if ( parameters !== undefined ) {
  7400. this.setValues( parameters );
  7401. }
  7402. }
  7403. copy( source ) {
  7404. super.copy( source );
  7405. this.fragmentShader = source.fragmentShader;
  7406. this.vertexShader = source.vertexShader;
  7407. this.uniforms = cloneUniforms( source.uniforms );
  7408. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7409. this.defines = Object.assign( {}, source.defines );
  7410. this.wireframe = source.wireframe;
  7411. this.wireframeLinewidth = source.wireframeLinewidth;
  7412. this.fog = source.fog;
  7413. this.lights = source.lights;
  7414. this.clipping = source.clipping;
  7415. this.extensions = Object.assign( {}, source.extensions );
  7416. this.glslVersion = source.glslVersion;
  7417. return this;
  7418. }
  7419. toJSON( meta ) {
  7420. const data = super.toJSON( meta );
  7421. data.glslVersion = this.glslVersion;
  7422. data.uniforms = {};
  7423. for ( const name in this.uniforms ) {
  7424. const uniform = this.uniforms[ name ];
  7425. const value = uniform.value;
  7426. if ( value && value.isTexture ) {
  7427. data.uniforms[ name ] = {
  7428. type: 't',
  7429. value: value.toJSON( meta ).uuid
  7430. };
  7431. } else if ( value && value.isColor ) {
  7432. data.uniforms[ name ] = {
  7433. type: 'c',
  7434. value: value.getHex()
  7435. };
  7436. } else if ( value && value.isVector2 ) {
  7437. data.uniforms[ name ] = {
  7438. type: 'v2',
  7439. value: value.toArray()
  7440. };
  7441. } else if ( value && value.isVector3 ) {
  7442. data.uniforms[ name ] = {
  7443. type: 'v3',
  7444. value: value.toArray()
  7445. };
  7446. } else if ( value && value.isVector4 ) {
  7447. data.uniforms[ name ] = {
  7448. type: 'v4',
  7449. value: value.toArray()
  7450. };
  7451. } else if ( value && value.isMatrix3 ) {
  7452. data.uniforms[ name ] = {
  7453. type: 'm3',
  7454. value: value.toArray()
  7455. };
  7456. } else if ( value && value.isMatrix4 ) {
  7457. data.uniforms[ name ] = {
  7458. type: 'm4',
  7459. value: value.toArray()
  7460. };
  7461. } else {
  7462. data.uniforms[ name ] = {
  7463. value: value
  7464. };
  7465. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7466. }
  7467. }
  7468. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7469. data.vertexShader = this.vertexShader;
  7470. data.fragmentShader = this.fragmentShader;
  7471. data.lights = this.lights;
  7472. data.clipping = this.clipping;
  7473. const extensions = {};
  7474. for ( const key in this.extensions ) {
  7475. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7476. }
  7477. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7478. return data;
  7479. }
  7480. }
  7481. class Camera extends Object3D {
  7482. constructor() {
  7483. super();
  7484. this.isCamera = true;
  7485. this.type = 'Camera';
  7486. this.matrixWorldInverse = new Matrix4();
  7487. this.projectionMatrix = new Matrix4();
  7488. this.projectionMatrixInverse = new Matrix4();
  7489. this.coordinateSystem = WebGLCoordinateSystem;
  7490. }
  7491. copy( source, recursive ) {
  7492. super.copy( source, recursive );
  7493. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7494. this.projectionMatrix.copy( source.projectionMatrix );
  7495. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7496. this.coordinateSystem = source.coordinateSystem;
  7497. return this;
  7498. }
  7499. getWorldDirection( target ) {
  7500. return super.getWorldDirection( target ).negate();
  7501. }
  7502. updateMatrixWorld( force ) {
  7503. super.updateMatrixWorld( force );
  7504. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7505. }
  7506. updateWorldMatrix( updateParents, updateChildren ) {
  7507. super.updateWorldMatrix( updateParents, updateChildren );
  7508. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7509. }
  7510. clone() {
  7511. return new this.constructor().copy( this );
  7512. }
  7513. }
  7514. const _v3$1 = /*@__PURE__*/ new Vector3();
  7515. const _minTarget = /*@__PURE__*/ new Vector2();
  7516. const _maxTarget = /*@__PURE__*/ new Vector2();
  7517. class PerspectiveCamera extends Camera {
  7518. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7519. super();
  7520. this.isPerspectiveCamera = true;
  7521. this.type = 'PerspectiveCamera';
  7522. this.fov = fov;
  7523. this.zoom = 1;
  7524. this.near = near;
  7525. this.far = far;
  7526. this.focus = 10;
  7527. this.aspect = aspect;
  7528. this.view = null;
  7529. this.filmGauge = 35; // width of the film (default in millimeters)
  7530. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7531. this.updateProjectionMatrix();
  7532. }
  7533. copy( source, recursive ) {
  7534. super.copy( source, recursive );
  7535. this.fov = source.fov;
  7536. this.zoom = source.zoom;
  7537. this.near = source.near;
  7538. this.far = source.far;
  7539. this.focus = source.focus;
  7540. this.aspect = source.aspect;
  7541. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7542. this.filmGauge = source.filmGauge;
  7543. this.filmOffset = source.filmOffset;
  7544. return this;
  7545. }
  7546. /**
  7547. * Sets the FOV by focal length in respect to the current .filmGauge.
  7548. *
  7549. * The default film gauge is 35, so that the focal length can be specified for
  7550. * a 35mm (full frame) camera.
  7551. *
  7552. * Values for focal length and film gauge must have the same unit.
  7553. */
  7554. setFocalLength( focalLength ) {
  7555. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7556. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7557. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7558. this.updateProjectionMatrix();
  7559. }
  7560. /**
  7561. * Calculates the focal length from the current .fov and .filmGauge.
  7562. */
  7563. getFocalLength() {
  7564. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7565. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7566. }
  7567. getEffectiveFOV() {
  7568. return RAD2DEG * 2 * Math.atan(
  7569. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7570. }
  7571. getFilmWidth() {
  7572. // film not completely covered in portrait format (aspect < 1)
  7573. return this.filmGauge * Math.min( this.aspect, 1 );
  7574. }
  7575. getFilmHeight() {
  7576. // film not completely covered in landscape format (aspect > 1)
  7577. return this.filmGauge / Math.max( this.aspect, 1 );
  7578. }
  7579. /**
  7580. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7581. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7582. */
  7583. getViewBounds( distance, minTarget, maxTarget ) {
  7584. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7585. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7586. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7587. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7588. }
  7589. /**
  7590. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7591. * Copies the result into the target Vector2, where x is width and y is height.
  7592. */
  7593. getViewSize( distance, target ) {
  7594. this.getViewBounds( distance, _minTarget, _maxTarget );
  7595. return target.subVectors( _maxTarget, _minTarget );
  7596. }
  7597. /**
  7598. * Sets an offset in a larger frustum. This is useful for multi-window or
  7599. * multi-monitor/multi-machine setups.
  7600. *
  7601. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7602. * the monitors are in grid like this
  7603. *
  7604. * +---+---+---+
  7605. * | A | B | C |
  7606. * +---+---+---+
  7607. * | D | E | F |
  7608. * +---+---+---+
  7609. *
  7610. * then for each monitor you would call it like this
  7611. *
  7612. * const w = 1920;
  7613. * const h = 1080;
  7614. * const fullWidth = w * 3;
  7615. * const fullHeight = h * 2;
  7616. *
  7617. * --A--
  7618. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7619. * --B--
  7620. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7621. * --C--
  7622. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7623. * --D--
  7624. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7625. * --E--
  7626. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7627. * --F--
  7628. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7629. *
  7630. * Note there is no reason monitors have to be the same size or in a grid.
  7631. */
  7632. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7633. this.aspect = fullWidth / fullHeight;
  7634. if ( this.view === null ) {
  7635. this.view = {
  7636. enabled: true,
  7637. fullWidth: 1,
  7638. fullHeight: 1,
  7639. offsetX: 0,
  7640. offsetY: 0,
  7641. width: 1,
  7642. height: 1
  7643. };
  7644. }
  7645. this.view.enabled = true;
  7646. this.view.fullWidth = fullWidth;
  7647. this.view.fullHeight = fullHeight;
  7648. this.view.offsetX = x;
  7649. this.view.offsetY = y;
  7650. this.view.width = width;
  7651. this.view.height = height;
  7652. this.updateProjectionMatrix();
  7653. }
  7654. clearViewOffset() {
  7655. if ( this.view !== null ) {
  7656. this.view.enabled = false;
  7657. }
  7658. this.updateProjectionMatrix();
  7659. }
  7660. updateProjectionMatrix() {
  7661. const near = this.near;
  7662. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7663. let height = 2 * top;
  7664. let width = this.aspect * height;
  7665. let left = - 0.5 * width;
  7666. const view = this.view;
  7667. if ( this.view !== null && this.view.enabled ) {
  7668. const fullWidth = view.fullWidth,
  7669. fullHeight = view.fullHeight;
  7670. left += view.offsetX * width / fullWidth;
  7671. top -= view.offsetY * height / fullHeight;
  7672. width *= view.width / fullWidth;
  7673. height *= view.height / fullHeight;
  7674. }
  7675. const skew = this.filmOffset;
  7676. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7677. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7678. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7679. }
  7680. toJSON( meta ) {
  7681. const data = super.toJSON( meta );
  7682. data.object.fov = this.fov;
  7683. data.object.zoom = this.zoom;
  7684. data.object.near = this.near;
  7685. data.object.far = this.far;
  7686. data.object.focus = this.focus;
  7687. data.object.aspect = this.aspect;
  7688. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7689. data.object.filmGauge = this.filmGauge;
  7690. data.object.filmOffset = this.filmOffset;
  7691. return data;
  7692. }
  7693. }
  7694. const fov = - 90; // negative fov is not an error
  7695. const aspect = 1;
  7696. class CubeCamera extends Object3D {
  7697. constructor( near, far, renderTarget ) {
  7698. super();
  7699. this.type = 'CubeCamera';
  7700. this.renderTarget = renderTarget;
  7701. this.coordinateSystem = null;
  7702. this.activeMipmapLevel = 0;
  7703. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7704. cameraPX.layers = this.layers;
  7705. this.add( cameraPX );
  7706. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7707. cameraNX.layers = this.layers;
  7708. this.add( cameraNX );
  7709. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7710. cameraPY.layers = this.layers;
  7711. this.add( cameraPY );
  7712. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7713. cameraNY.layers = this.layers;
  7714. this.add( cameraNY );
  7715. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7716. cameraPZ.layers = this.layers;
  7717. this.add( cameraPZ );
  7718. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7719. cameraNZ.layers = this.layers;
  7720. this.add( cameraNZ );
  7721. }
  7722. updateCoordinateSystem() {
  7723. const coordinateSystem = this.coordinateSystem;
  7724. const cameras = this.children.concat();
  7725. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7726. for ( const camera of cameras ) this.remove( camera );
  7727. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7728. cameraPX.up.set( 0, 1, 0 );
  7729. cameraPX.lookAt( 1, 0, 0 );
  7730. cameraNX.up.set( 0, 1, 0 );
  7731. cameraNX.lookAt( - 1, 0, 0 );
  7732. cameraPY.up.set( 0, 0, - 1 );
  7733. cameraPY.lookAt( 0, 1, 0 );
  7734. cameraNY.up.set( 0, 0, 1 );
  7735. cameraNY.lookAt( 0, - 1, 0 );
  7736. cameraPZ.up.set( 0, 1, 0 );
  7737. cameraPZ.lookAt( 0, 0, 1 );
  7738. cameraNZ.up.set( 0, 1, 0 );
  7739. cameraNZ.lookAt( 0, 0, - 1 );
  7740. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7741. cameraPX.up.set( 0, - 1, 0 );
  7742. cameraPX.lookAt( - 1, 0, 0 );
  7743. cameraNX.up.set( 0, - 1, 0 );
  7744. cameraNX.lookAt( 1, 0, 0 );
  7745. cameraPY.up.set( 0, 0, 1 );
  7746. cameraPY.lookAt( 0, 1, 0 );
  7747. cameraNY.up.set( 0, 0, - 1 );
  7748. cameraNY.lookAt( 0, - 1, 0 );
  7749. cameraPZ.up.set( 0, - 1, 0 );
  7750. cameraPZ.lookAt( 0, 0, 1 );
  7751. cameraNZ.up.set( 0, - 1, 0 );
  7752. cameraNZ.lookAt( 0, 0, - 1 );
  7753. } else {
  7754. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7755. }
  7756. for ( const camera of cameras ) {
  7757. this.add( camera );
  7758. camera.updateMatrixWorld();
  7759. }
  7760. }
  7761. update( renderer, scene ) {
  7762. if ( this.parent === null ) this.updateMatrixWorld();
  7763. const { renderTarget, activeMipmapLevel } = this;
  7764. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7765. this.coordinateSystem = renderer.coordinateSystem;
  7766. this.updateCoordinateSystem();
  7767. }
  7768. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7769. const currentRenderTarget = renderer.getRenderTarget();
  7770. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7771. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7772. const currentXrEnabled = renderer.xr.enabled;
  7773. renderer.xr.enabled = false;
  7774. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7775. renderTarget.texture.generateMipmaps = false;
  7776. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7777. renderer.render( scene, cameraPX );
  7778. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7779. renderer.render( scene, cameraNX );
  7780. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7781. renderer.render( scene, cameraPY );
  7782. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7783. renderer.render( scene, cameraNY );
  7784. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7785. renderer.render( scene, cameraPZ );
  7786. // mipmaps are generated during the last call of render()
  7787. // at this point, all sides of the cube render target are defined
  7788. renderTarget.texture.generateMipmaps = generateMipmaps;
  7789. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7790. renderer.render( scene, cameraNZ );
  7791. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7792. renderer.xr.enabled = currentXrEnabled;
  7793. renderTarget.texture.needsPMREMUpdate = true;
  7794. }
  7795. }
  7796. class CubeTexture extends Texture {
  7797. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7798. images = images !== undefined ? images : [];
  7799. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7800. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7801. this.isCubeTexture = true;
  7802. this.flipY = false;
  7803. }
  7804. get images() {
  7805. return this.image;
  7806. }
  7807. set images( value ) {
  7808. this.image = value;
  7809. }
  7810. }
  7811. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7812. constructor( size = 1, options = {} ) {
  7813. super( size, size, options );
  7814. this.isWebGLCubeRenderTarget = true;
  7815. const image = { width: size, height: size, depth: 1 };
  7816. const images = [ image, image, image, image, image, image ];
  7817. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7818. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7819. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7820. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7821. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7822. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7823. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7824. this.texture.isRenderTargetTexture = true;
  7825. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7826. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7827. }
  7828. fromEquirectangularTexture( renderer, texture ) {
  7829. this.texture.type = texture.type;
  7830. this.texture.colorSpace = texture.colorSpace;
  7831. this.texture.generateMipmaps = texture.generateMipmaps;
  7832. this.texture.minFilter = texture.minFilter;
  7833. this.texture.magFilter = texture.magFilter;
  7834. const shader = {
  7835. uniforms: {
  7836. tEquirect: { value: null },
  7837. },
  7838. vertexShader: /* glsl */`
  7839. varying vec3 vWorldDirection;
  7840. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7841. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7842. }
  7843. void main() {
  7844. vWorldDirection = transformDirection( position, modelMatrix );
  7845. #include <begin_vertex>
  7846. #include <project_vertex>
  7847. }
  7848. `,
  7849. fragmentShader: /* glsl */`
  7850. uniform sampler2D tEquirect;
  7851. varying vec3 vWorldDirection;
  7852. #include <common>
  7853. void main() {
  7854. vec3 direction = normalize( vWorldDirection );
  7855. vec2 sampleUV = equirectUv( direction );
  7856. gl_FragColor = texture2D( tEquirect, sampleUV );
  7857. }
  7858. `
  7859. };
  7860. const geometry = new BoxGeometry( 5, 5, 5 );
  7861. const material = new ShaderMaterial( {
  7862. name: 'CubemapFromEquirect',
  7863. uniforms: cloneUniforms( shader.uniforms ),
  7864. vertexShader: shader.vertexShader,
  7865. fragmentShader: shader.fragmentShader,
  7866. side: BackSide,
  7867. blending: NoBlending
  7868. } );
  7869. material.uniforms.tEquirect.value = texture;
  7870. const mesh = new Mesh( geometry, material );
  7871. const currentMinFilter = texture.minFilter;
  7872. // Avoid blurred poles
  7873. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7874. const camera = new CubeCamera( 1, 10, this );
  7875. camera.update( renderer, mesh );
  7876. texture.minFilter = currentMinFilter;
  7877. mesh.geometry.dispose();
  7878. mesh.material.dispose();
  7879. return this;
  7880. }
  7881. clear( renderer, color, depth, stencil ) {
  7882. const currentRenderTarget = renderer.getRenderTarget();
  7883. for ( let i = 0; i < 6; i ++ ) {
  7884. renderer.setRenderTarget( this, i );
  7885. renderer.clear( color, depth, stencil );
  7886. }
  7887. renderer.setRenderTarget( currentRenderTarget );
  7888. }
  7889. }
  7890. class FogExp2 {
  7891. constructor( color, density = 0.00025 ) {
  7892. this.isFogExp2 = true;
  7893. this.name = '';
  7894. this.color = new Color( color );
  7895. this.density = density;
  7896. }
  7897. clone() {
  7898. return new FogExp2( this.color, this.density );
  7899. }
  7900. toJSON( /* meta */ ) {
  7901. return {
  7902. type: 'FogExp2',
  7903. name: this.name,
  7904. color: this.color.getHex(),
  7905. density: this.density
  7906. };
  7907. }
  7908. }
  7909. class Fog {
  7910. constructor( color, near = 1, far = 1000 ) {
  7911. this.isFog = true;
  7912. this.name = '';
  7913. this.color = new Color( color );
  7914. this.near = near;
  7915. this.far = far;
  7916. }
  7917. clone() {
  7918. return new Fog( this.color, this.near, this.far );
  7919. }
  7920. toJSON( /* meta */ ) {
  7921. return {
  7922. type: 'Fog',
  7923. name: this.name,
  7924. color: this.color.getHex(),
  7925. near: this.near,
  7926. far: this.far
  7927. };
  7928. }
  7929. }
  7930. class Scene extends Object3D {
  7931. constructor() {
  7932. super();
  7933. this.isScene = true;
  7934. this.type = 'Scene';
  7935. this.background = null;
  7936. this.environment = null;
  7937. this.fog = null;
  7938. this.backgroundBlurriness = 0;
  7939. this.backgroundIntensity = 1;
  7940. this.backgroundRotation = new Euler();
  7941. this.environmentIntensity = 1;
  7942. this.environmentRotation = new Euler();
  7943. this.overrideMaterial = null;
  7944. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7945. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7946. }
  7947. }
  7948. copy( source, recursive ) {
  7949. super.copy( source, recursive );
  7950. if ( source.background !== null ) this.background = source.background.clone();
  7951. if ( source.environment !== null ) this.environment = source.environment.clone();
  7952. if ( source.fog !== null ) this.fog = source.fog.clone();
  7953. this.backgroundBlurriness = source.backgroundBlurriness;
  7954. this.backgroundIntensity = source.backgroundIntensity;
  7955. this.backgroundRotation.copy( source.backgroundRotation );
  7956. this.environmentIntensity = source.environmentIntensity;
  7957. this.environmentRotation.copy( source.environmentRotation );
  7958. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7959. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7960. return this;
  7961. }
  7962. toJSON( meta ) {
  7963. const data = super.toJSON( meta );
  7964. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7965. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7966. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7967. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7968. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7969. data.object.environmentRotation = this.environmentRotation.toArray();
  7970. return data;
  7971. }
  7972. }
  7973. class InterleavedBuffer {
  7974. constructor( array, stride ) {
  7975. this.isInterleavedBuffer = true;
  7976. this.array = array;
  7977. this.stride = stride;
  7978. this.count = array !== undefined ? array.length / stride : 0;
  7979. this.usage = StaticDrawUsage;
  7980. this.updateRanges = [];
  7981. this.version = 0;
  7982. this.uuid = generateUUID();
  7983. }
  7984. onUploadCallback() {}
  7985. set needsUpdate( value ) {
  7986. if ( value === true ) this.version ++;
  7987. }
  7988. setUsage( value ) {
  7989. this.usage = value;
  7990. return this;
  7991. }
  7992. addUpdateRange( start, count ) {
  7993. this.updateRanges.push( { start, count } );
  7994. }
  7995. clearUpdateRanges() {
  7996. this.updateRanges.length = 0;
  7997. }
  7998. copy( source ) {
  7999. this.array = new source.array.constructor( source.array );
  8000. this.count = source.count;
  8001. this.stride = source.stride;
  8002. this.usage = source.usage;
  8003. return this;
  8004. }
  8005. copyAt( index1, attribute, index2 ) {
  8006. index1 *= this.stride;
  8007. index2 *= attribute.stride;
  8008. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  8009. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  8010. }
  8011. return this;
  8012. }
  8013. set( value, offset = 0 ) {
  8014. this.array.set( value, offset );
  8015. return this;
  8016. }
  8017. clone( data ) {
  8018. if ( data.arrayBuffers === undefined ) {
  8019. data.arrayBuffers = {};
  8020. }
  8021. if ( this.array.buffer._uuid === undefined ) {
  8022. this.array.buffer._uuid = generateUUID();
  8023. }
  8024. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  8025. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  8026. }
  8027. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  8028. const ib = new this.constructor( array, this.stride );
  8029. ib.setUsage( this.usage );
  8030. return ib;
  8031. }
  8032. onUpload( callback ) {
  8033. this.onUploadCallback = callback;
  8034. return this;
  8035. }
  8036. toJSON( data ) {
  8037. if ( data.arrayBuffers === undefined ) {
  8038. data.arrayBuffers = {};
  8039. }
  8040. // generate UUID for array buffer if necessary
  8041. if ( this.array.buffer._uuid === undefined ) {
  8042. this.array.buffer._uuid = generateUUID();
  8043. }
  8044. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  8045. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  8046. }
  8047. //
  8048. return {
  8049. uuid: this.uuid,
  8050. buffer: this.array.buffer._uuid,
  8051. type: this.array.constructor.name,
  8052. stride: this.stride
  8053. };
  8054. }
  8055. }
  8056. const _vector$7 = /*@__PURE__*/ new Vector3();
  8057. class InterleavedBufferAttribute {
  8058. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  8059. this.isInterleavedBufferAttribute = true;
  8060. this.name = '';
  8061. this.data = interleavedBuffer;
  8062. this.itemSize = itemSize;
  8063. this.offset = offset;
  8064. this.normalized = normalized;
  8065. }
  8066. get count() {
  8067. return this.data.count;
  8068. }
  8069. get array() {
  8070. return this.data.array;
  8071. }
  8072. set needsUpdate( value ) {
  8073. this.data.needsUpdate = value;
  8074. }
  8075. applyMatrix4( m ) {
  8076. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  8077. _vector$7.fromBufferAttribute( this, i );
  8078. _vector$7.applyMatrix4( m );
  8079. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8080. }
  8081. return this;
  8082. }
  8083. applyNormalMatrix( m ) {
  8084. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8085. _vector$7.fromBufferAttribute( this, i );
  8086. _vector$7.applyNormalMatrix( m );
  8087. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8088. }
  8089. return this;
  8090. }
  8091. transformDirection( m ) {
  8092. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8093. _vector$7.fromBufferAttribute( this, i );
  8094. _vector$7.transformDirection( m );
  8095. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8096. }
  8097. return this;
  8098. }
  8099. getComponent( index, component ) {
  8100. let value = this.array[ index * this.data.stride + this.offset + component ];
  8101. if ( this.normalized ) value = denormalize( value, this.array );
  8102. return value;
  8103. }
  8104. setComponent( index, component, value ) {
  8105. if ( this.normalized ) value = normalize( value, this.array );
  8106. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  8107. return this;
  8108. }
  8109. setX( index, x ) {
  8110. if ( this.normalized ) x = normalize( x, this.array );
  8111. this.data.array[ index * this.data.stride + this.offset ] = x;
  8112. return this;
  8113. }
  8114. setY( index, y ) {
  8115. if ( this.normalized ) y = normalize( y, this.array );
  8116. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8117. return this;
  8118. }
  8119. setZ( index, z ) {
  8120. if ( this.normalized ) z = normalize( z, this.array );
  8121. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8122. return this;
  8123. }
  8124. setW( index, w ) {
  8125. if ( this.normalized ) w = normalize( w, this.array );
  8126. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8127. return this;
  8128. }
  8129. getX( index ) {
  8130. let x = this.data.array[ index * this.data.stride + this.offset ];
  8131. if ( this.normalized ) x = denormalize( x, this.array );
  8132. return x;
  8133. }
  8134. getY( index ) {
  8135. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8136. if ( this.normalized ) y = denormalize( y, this.array );
  8137. return y;
  8138. }
  8139. getZ( index ) {
  8140. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8141. if ( this.normalized ) z = denormalize( z, this.array );
  8142. return z;
  8143. }
  8144. getW( index ) {
  8145. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8146. if ( this.normalized ) w = denormalize( w, this.array );
  8147. return w;
  8148. }
  8149. setXY( index, x, y ) {
  8150. index = index * this.data.stride + this.offset;
  8151. if ( this.normalized ) {
  8152. x = normalize( x, this.array );
  8153. y = normalize( y, this.array );
  8154. }
  8155. this.data.array[ index + 0 ] = x;
  8156. this.data.array[ index + 1 ] = y;
  8157. return this;
  8158. }
  8159. setXYZ( index, x, y, z ) {
  8160. index = index * this.data.stride + this.offset;
  8161. if ( this.normalized ) {
  8162. x = normalize( x, this.array );
  8163. y = normalize( y, this.array );
  8164. z = normalize( z, this.array );
  8165. }
  8166. this.data.array[ index + 0 ] = x;
  8167. this.data.array[ index + 1 ] = y;
  8168. this.data.array[ index + 2 ] = z;
  8169. return this;
  8170. }
  8171. setXYZW( index, x, y, z, w ) {
  8172. index = index * this.data.stride + this.offset;
  8173. if ( this.normalized ) {
  8174. x = normalize( x, this.array );
  8175. y = normalize( y, this.array );
  8176. z = normalize( z, this.array );
  8177. w = normalize( w, this.array );
  8178. }
  8179. this.data.array[ index + 0 ] = x;
  8180. this.data.array[ index + 1 ] = y;
  8181. this.data.array[ index + 2 ] = z;
  8182. this.data.array[ index + 3 ] = w;
  8183. return this;
  8184. }
  8185. clone( data ) {
  8186. if ( data === undefined ) {
  8187. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8188. const array = [];
  8189. for ( let i = 0; i < this.count; i ++ ) {
  8190. const index = i * this.data.stride + this.offset;
  8191. for ( let j = 0; j < this.itemSize; j ++ ) {
  8192. array.push( this.data.array[ index + j ] );
  8193. }
  8194. }
  8195. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8196. } else {
  8197. if ( data.interleavedBuffers === undefined ) {
  8198. data.interleavedBuffers = {};
  8199. }
  8200. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8201. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8202. }
  8203. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8204. }
  8205. }
  8206. toJSON( data ) {
  8207. if ( data === undefined ) {
  8208. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8209. const array = [];
  8210. for ( let i = 0; i < this.count; i ++ ) {
  8211. const index = i * this.data.stride + this.offset;
  8212. for ( let j = 0; j < this.itemSize; j ++ ) {
  8213. array.push( this.data.array[ index + j ] );
  8214. }
  8215. }
  8216. // de-interleave data and save it as an ordinary buffer attribute for now
  8217. return {
  8218. itemSize: this.itemSize,
  8219. type: this.array.constructor.name,
  8220. array: array,
  8221. normalized: this.normalized
  8222. };
  8223. } else {
  8224. // save as true interleaved attribute
  8225. if ( data.interleavedBuffers === undefined ) {
  8226. data.interleavedBuffers = {};
  8227. }
  8228. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8229. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8230. }
  8231. return {
  8232. isInterleavedBufferAttribute: true,
  8233. itemSize: this.itemSize,
  8234. data: this.data.uuid,
  8235. offset: this.offset,
  8236. normalized: this.normalized
  8237. };
  8238. }
  8239. }
  8240. }
  8241. class SpriteMaterial extends Material {
  8242. constructor( parameters ) {
  8243. super();
  8244. this.isSpriteMaterial = true;
  8245. this.type = 'SpriteMaterial';
  8246. this.color = new Color( 0xffffff );
  8247. this.map = null;
  8248. this.alphaMap = null;
  8249. this.rotation = 0;
  8250. this.sizeAttenuation = true;
  8251. this.transparent = true;
  8252. this.fog = true;
  8253. this.setValues( parameters );
  8254. }
  8255. copy( source ) {
  8256. super.copy( source );
  8257. this.color.copy( source.color );
  8258. this.map = source.map;
  8259. this.alphaMap = source.alphaMap;
  8260. this.rotation = source.rotation;
  8261. this.sizeAttenuation = source.sizeAttenuation;
  8262. this.fog = source.fog;
  8263. return this;
  8264. }
  8265. }
  8266. let _geometry;
  8267. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8268. const _worldScale = /*@__PURE__*/ new Vector3();
  8269. const _mvPosition = /*@__PURE__*/ new Vector3();
  8270. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8271. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8272. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8273. const _vA = /*@__PURE__*/ new Vector3();
  8274. const _vB = /*@__PURE__*/ new Vector3();
  8275. const _vC = /*@__PURE__*/ new Vector3();
  8276. const _uvA = /*@__PURE__*/ new Vector2();
  8277. const _uvB = /*@__PURE__*/ new Vector2();
  8278. const _uvC = /*@__PURE__*/ new Vector2();
  8279. class Sprite extends Object3D {
  8280. constructor( material = new SpriteMaterial() ) {
  8281. super();
  8282. this.isSprite = true;
  8283. this.type = 'Sprite';
  8284. if ( _geometry === undefined ) {
  8285. _geometry = new BufferGeometry();
  8286. const float32Array = new Float32Array( [
  8287. - 0.5, - 0.5, 0, 0, 0,
  8288. 0.5, - 0.5, 0, 1, 0,
  8289. 0.5, 0.5, 0, 1, 1,
  8290. - 0.5, 0.5, 0, 0, 1
  8291. ] );
  8292. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8293. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8294. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8295. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8296. }
  8297. this.geometry = _geometry;
  8298. this.material = material;
  8299. this.center = new Vector2( 0.5, 0.5 );
  8300. }
  8301. raycast( raycaster, intersects ) {
  8302. if ( raycaster.camera === null ) {
  8303. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8304. }
  8305. _worldScale.setFromMatrixScale( this.matrixWorld );
  8306. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8307. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8308. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8309. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8310. _worldScale.multiplyScalar( - _mvPosition.z );
  8311. }
  8312. const rotation = this.material.rotation;
  8313. let sin, cos;
  8314. if ( rotation !== 0 ) {
  8315. cos = Math.cos( rotation );
  8316. sin = Math.sin( rotation );
  8317. }
  8318. const center = this.center;
  8319. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8320. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8321. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8322. _uvA.set( 0, 0 );
  8323. _uvB.set( 1, 0 );
  8324. _uvC.set( 1, 1 );
  8325. // check first triangle
  8326. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8327. if ( intersect === null ) {
  8328. // check second triangle
  8329. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8330. _uvB.set( 0, 1 );
  8331. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8332. if ( intersect === null ) {
  8333. return;
  8334. }
  8335. }
  8336. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8337. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8338. intersects.push( {
  8339. distance: distance,
  8340. point: _intersectPoint.clone(),
  8341. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8342. face: null,
  8343. object: this
  8344. } );
  8345. }
  8346. copy( source, recursive ) {
  8347. super.copy( source, recursive );
  8348. if ( source.center !== undefined ) this.center.copy( source.center );
  8349. this.material = source.material;
  8350. return this;
  8351. }
  8352. }
  8353. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8354. // compute position in camera space
  8355. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8356. // to check if rotation is not zero
  8357. if ( sin !== undefined ) {
  8358. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8359. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8360. } else {
  8361. _rotatedPosition.copy( _alignedPosition );
  8362. }
  8363. vertexPosition.copy( mvPosition );
  8364. vertexPosition.x += _rotatedPosition.x;
  8365. vertexPosition.y += _rotatedPosition.y;
  8366. // transform to world space
  8367. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8368. }
  8369. const _v1$2 = /*@__PURE__*/ new Vector3();
  8370. const _v2$1 = /*@__PURE__*/ new Vector3();
  8371. class LOD extends Object3D {
  8372. constructor() {
  8373. super();
  8374. this._currentLevel = 0;
  8375. this.type = 'LOD';
  8376. Object.defineProperties( this, {
  8377. levels: {
  8378. enumerable: true,
  8379. value: []
  8380. },
  8381. isLOD: {
  8382. value: true,
  8383. }
  8384. } );
  8385. this.autoUpdate = true;
  8386. }
  8387. copy( source ) {
  8388. super.copy( source, false );
  8389. const levels = source.levels;
  8390. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8391. const level = levels[ i ];
  8392. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8393. }
  8394. this.autoUpdate = source.autoUpdate;
  8395. return this;
  8396. }
  8397. addLevel( object, distance = 0, hysteresis = 0 ) {
  8398. distance = Math.abs( distance );
  8399. const levels = this.levels;
  8400. let l;
  8401. for ( l = 0; l < levels.length; l ++ ) {
  8402. if ( distance < levels[ l ].distance ) {
  8403. break;
  8404. }
  8405. }
  8406. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8407. this.add( object );
  8408. return this;
  8409. }
  8410. removeLevel( distance ) {
  8411. const levels = this.levels;
  8412. for ( let i = 0; i < levels.length; i ++ ) {
  8413. if ( levels[ i ].distance === distance ) {
  8414. const removedElements = levels.splice( i, 1 );
  8415. this.remove( removedElements[ 0 ].object );
  8416. return true;
  8417. }
  8418. }
  8419. return false;
  8420. }
  8421. getCurrentLevel() {
  8422. return this._currentLevel;
  8423. }
  8424. getObjectForDistance( distance ) {
  8425. const levels = this.levels;
  8426. if ( levels.length > 0 ) {
  8427. let i, l;
  8428. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8429. let levelDistance = levels[ i ].distance;
  8430. if ( levels[ i ].object.visible ) {
  8431. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8432. }
  8433. if ( distance < levelDistance ) {
  8434. break;
  8435. }
  8436. }
  8437. return levels[ i - 1 ].object;
  8438. }
  8439. return null;
  8440. }
  8441. raycast( raycaster, intersects ) {
  8442. const levels = this.levels;
  8443. if ( levels.length > 0 ) {
  8444. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8445. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8446. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8447. }
  8448. }
  8449. update( camera ) {
  8450. const levels = this.levels;
  8451. if ( levels.length > 1 ) {
  8452. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8453. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8454. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8455. levels[ 0 ].object.visible = true;
  8456. let i, l;
  8457. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8458. let levelDistance = levels[ i ].distance;
  8459. if ( levels[ i ].object.visible ) {
  8460. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8461. }
  8462. if ( distance >= levelDistance ) {
  8463. levels[ i - 1 ].object.visible = false;
  8464. levels[ i ].object.visible = true;
  8465. } else {
  8466. break;
  8467. }
  8468. }
  8469. this._currentLevel = i - 1;
  8470. for ( ; i < l; i ++ ) {
  8471. levels[ i ].object.visible = false;
  8472. }
  8473. }
  8474. }
  8475. toJSON( meta ) {
  8476. const data = super.toJSON( meta );
  8477. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8478. data.object.levels = [];
  8479. const levels = this.levels;
  8480. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8481. const level = levels[ i ];
  8482. data.object.levels.push( {
  8483. object: level.object.uuid,
  8484. distance: level.distance,
  8485. hysteresis: level.hysteresis
  8486. } );
  8487. }
  8488. return data;
  8489. }
  8490. }
  8491. const _basePosition = /*@__PURE__*/ new Vector3();
  8492. const _skinIndex = /*@__PURE__*/ new Vector4();
  8493. const _skinWeight = /*@__PURE__*/ new Vector4();
  8494. const _vector3 = /*@__PURE__*/ new Vector3();
  8495. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8496. const _vertex = /*@__PURE__*/ new Vector3();
  8497. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8498. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8499. const _ray$2 = /*@__PURE__*/ new Ray();
  8500. class SkinnedMesh extends Mesh {
  8501. constructor( geometry, material ) {
  8502. super( geometry, material );
  8503. this.isSkinnedMesh = true;
  8504. this.type = 'SkinnedMesh';
  8505. this.bindMode = AttachedBindMode;
  8506. this.bindMatrix = new Matrix4();
  8507. this.bindMatrixInverse = new Matrix4();
  8508. this.boundingBox = null;
  8509. this.boundingSphere = null;
  8510. }
  8511. computeBoundingBox() {
  8512. const geometry = this.geometry;
  8513. if ( this.boundingBox === null ) {
  8514. this.boundingBox = new Box3();
  8515. }
  8516. this.boundingBox.makeEmpty();
  8517. const positionAttribute = geometry.getAttribute( 'position' );
  8518. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8519. this.getVertexPosition( i, _vertex );
  8520. this.boundingBox.expandByPoint( _vertex );
  8521. }
  8522. }
  8523. computeBoundingSphere() {
  8524. const geometry = this.geometry;
  8525. if ( this.boundingSphere === null ) {
  8526. this.boundingSphere = new Sphere();
  8527. }
  8528. this.boundingSphere.makeEmpty();
  8529. const positionAttribute = geometry.getAttribute( 'position' );
  8530. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8531. this.getVertexPosition( i, _vertex );
  8532. this.boundingSphere.expandByPoint( _vertex );
  8533. }
  8534. }
  8535. copy( source, recursive ) {
  8536. super.copy( source, recursive );
  8537. this.bindMode = source.bindMode;
  8538. this.bindMatrix.copy( source.bindMatrix );
  8539. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8540. this.skeleton = source.skeleton;
  8541. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8542. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8543. return this;
  8544. }
  8545. raycast( raycaster, intersects ) {
  8546. const material = this.material;
  8547. const matrixWorld = this.matrixWorld;
  8548. if ( material === undefined ) return;
  8549. // test with bounding sphere in world space
  8550. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8551. _sphere$5.copy( this.boundingSphere );
  8552. _sphere$5.applyMatrix4( matrixWorld );
  8553. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8554. // convert ray to local space of skinned mesh
  8555. _inverseMatrix$2.copy( matrixWorld ).invert();
  8556. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8557. // test with bounding box in local space
  8558. if ( this.boundingBox !== null ) {
  8559. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8560. }
  8561. // test for intersections with geometry
  8562. this._computeIntersections( raycaster, intersects, _ray$2 );
  8563. }
  8564. getVertexPosition( index, target ) {
  8565. super.getVertexPosition( index, target );
  8566. this.applyBoneTransform( index, target );
  8567. return target;
  8568. }
  8569. bind( skeleton, bindMatrix ) {
  8570. this.skeleton = skeleton;
  8571. if ( bindMatrix === undefined ) {
  8572. this.updateMatrixWorld( true );
  8573. this.skeleton.calculateInverses();
  8574. bindMatrix = this.matrixWorld;
  8575. }
  8576. this.bindMatrix.copy( bindMatrix );
  8577. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8578. }
  8579. pose() {
  8580. this.skeleton.pose();
  8581. }
  8582. normalizeSkinWeights() {
  8583. const vector = new Vector4();
  8584. const skinWeight = this.geometry.attributes.skinWeight;
  8585. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8586. vector.fromBufferAttribute( skinWeight, i );
  8587. const scale = 1.0 / vector.manhattanLength();
  8588. if ( scale !== Infinity ) {
  8589. vector.multiplyScalar( scale );
  8590. } else {
  8591. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8592. }
  8593. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8594. }
  8595. }
  8596. updateMatrixWorld( force ) {
  8597. super.updateMatrixWorld( force );
  8598. if ( this.bindMode === AttachedBindMode ) {
  8599. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8600. } else if ( this.bindMode === DetachedBindMode ) {
  8601. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8602. } else {
  8603. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8604. }
  8605. }
  8606. applyBoneTransform( index, vector ) {
  8607. const skeleton = this.skeleton;
  8608. const geometry = this.geometry;
  8609. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8610. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8611. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8612. vector.set( 0, 0, 0 );
  8613. for ( let i = 0; i < 4; i ++ ) {
  8614. const weight = _skinWeight.getComponent( i );
  8615. if ( weight !== 0 ) {
  8616. const boneIndex = _skinIndex.getComponent( i );
  8617. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8618. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8619. }
  8620. }
  8621. return vector.applyMatrix4( this.bindMatrixInverse );
  8622. }
  8623. }
  8624. class Bone extends Object3D {
  8625. constructor() {
  8626. super();
  8627. this.isBone = true;
  8628. this.type = 'Bone';
  8629. }
  8630. }
  8631. class DataTexture extends Texture {
  8632. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8633. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8634. this.isDataTexture = true;
  8635. this.image = { data: data, width: width, height: height };
  8636. this.generateMipmaps = false;
  8637. this.flipY = false;
  8638. this.unpackAlignment = 1;
  8639. }
  8640. }
  8641. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8642. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  8643. class Skeleton {
  8644. constructor( bones = [], boneInverses = [] ) {
  8645. this.uuid = generateUUID();
  8646. this.bones = bones.slice( 0 );
  8647. this.boneInverses = boneInverses;
  8648. this.boneMatrices = null;
  8649. this.boneTexture = null;
  8650. this.init();
  8651. }
  8652. init() {
  8653. const bones = this.bones;
  8654. const boneInverses = this.boneInverses;
  8655. this.boneMatrices = new Float32Array( bones.length * 16 );
  8656. // calculate inverse bone matrices if necessary
  8657. if ( boneInverses.length === 0 ) {
  8658. this.calculateInverses();
  8659. } else {
  8660. // handle special case
  8661. if ( bones.length !== boneInverses.length ) {
  8662. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8663. this.boneInverses = [];
  8664. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8665. this.boneInverses.push( new Matrix4() );
  8666. }
  8667. }
  8668. }
  8669. }
  8670. calculateInverses() {
  8671. this.boneInverses.length = 0;
  8672. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8673. const inverse = new Matrix4();
  8674. if ( this.bones[ i ] ) {
  8675. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8676. }
  8677. this.boneInverses.push( inverse );
  8678. }
  8679. }
  8680. pose() {
  8681. // recover the bind-time world matrices
  8682. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8683. const bone = this.bones[ i ];
  8684. if ( bone ) {
  8685. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8686. }
  8687. }
  8688. // compute the local matrices, positions, rotations and scales
  8689. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8690. const bone = this.bones[ i ];
  8691. if ( bone ) {
  8692. if ( bone.parent && bone.parent.isBone ) {
  8693. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8694. bone.matrix.multiply( bone.matrixWorld );
  8695. } else {
  8696. bone.matrix.copy( bone.matrixWorld );
  8697. }
  8698. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8699. }
  8700. }
  8701. }
  8702. update() {
  8703. const bones = this.bones;
  8704. const boneInverses = this.boneInverses;
  8705. const boneMatrices = this.boneMatrices;
  8706. const boneTexture = this.boneTexture;
  8707. // flatten bone matrices to array
  8708. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8709. // compute the offset between the current and the original transform
  8710. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  8711. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8712. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8713. }
  8714. if ( boneTexture !== null ) {
  8715. boneTexture.needsUpdate = true;
  8716. }
  8717. }
  8718. clone() {
  8719. return new Skeleton( this.bones, this.boneInverses );
  8720. }
  8721. computeBoneTexture() {
  8722. // layout (1 matrix = 4 pixels)
  8723. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8724. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8725. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8726. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8727. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8728. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8729. size = Math.ceil( size / 4 ) * 4;
  8730. size = Math.max( size, 4 );
  8731. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8732. boneMatrices.set( this.boneMatrices ); // copy current values
  8733. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8734. boneTexture.needsUpdate = true;
  8735. this.boneMatrices = boneMatrices;
  8736. this.boneTexture = boneTexture;
  8737. return this;
  8738. }
  8739. getBoneByName( name ) {
  8740. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8741. const bone = this.bones[ i ];
  8742. if ( bone.name === name ) {
  8743. return bone;
  8744. }
  8745. }
  8746. return undefined;
  8747. }
  8748. dispose( ) {
  8749. if ( this.boneTexture !== null ) {
  8750. this.boneTexture.dispose();
  8751. this.boneTexture = null;
  8752. }
  8753. }
  8754. fromJSON( json, bones ) {
  8755. this.uuid = json.uuid;
  8756. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8757. const uuid = json.bones[ i ];
  8758. let bone = bones[ uuid ];
  8759. if ( bone === undefined ) {
  8760. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8761. bone = new Bone();
  8762. }
  8763. this.bones.push( bone );
  8764. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8765. }
  8766. this.init();
  8767. return this;
  8768. }
  8769. toJSON() {
  8770. const data = {
  8771. metadata: {
  8772. version: 4.6,
  8773. type: 'Skeleton',
  8774. generator: 'Skeleton.toJSON'
  8775. },
  8776. bones: [],
  8777. boneInverses: []
  8778. };
  8779. data.uuid = this.uuid;
  8780. const bones = this.bones;
  8781. const boneInverses = this.boneInverses;
  8782. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8783. const bone = bones[ i ];
  8784. data.bones.push( bone.uuid );
  8785. const boneInverse = boneInverses[ i ];
  8786. data.boneInverses.push( boneInverse.toArray() );
  8787. }
  8788. return data;
  8789. }
  8790. }
  8791. class InstancedBufferAttribute extends BufferAttribute {
  8792. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8793. super( array, itemSize, normalized );
  8794. this.isInstancedBufferAttribute = true;
  8795. this.meshPerAttribute = meshPerAttribute;
  8796. }
  8797. copy( source ) {
  8798. super.copy( source );
  8799. this.meshPerAttribute = source.meshPerAttribute;
  8800. return this;
  8801. }
  8802. toJSON() {
  8803. const data = super.toJSON();
  8804. data.meshPerAttribute = this.meshPerAttribute;
  8805. data.isInstancedBufferAttribute = true;
  8806. return data;
  8807. }
  8808. }
  8809. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8810. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8811. const _instanceIntersects = [];
  8812. const _box3 = /*@__PURE__*/ new Box3();
  8813. const _identity = /*@__PURE__*/ new Matrix4();
  8814. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8815. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8816. class InstancedMesh extends Mesh {
  8817. constructor( geometry, material, count ) {
  8818. super( geometry, material );
  8819. this.isInstancedMesh = true;
  8820. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8821. this.instanceColor = null;
  8822. this.morphTexture = null;
  8823. this.count = count;
  8824. this.boundingBox = null;
  8825. this.boundingSphere = null;
  8826. for ( let i = 0; i < count; i ++ ) {
  8827. this.setMatrixAt( i, _identity );
  8828. }
  8829. }
  8830. computeBoundingBox() {
  8831. const geometry = this.geometry;
  8832. const count = this.count;
  8833. if ( this.boundingBox === null ) {
  8834. this.boundingBox = new Box3();
  8835. }
  8836. if ( geometry.boundingBox === null ) {
  8837. geometry.computeBoundingBox();
  8838. }
  8839. this.boundingBox.makeEmpty();
  8840. for ( let i = 0; i < count; i ++ ) {
  8841. this.getMatrixAt( i, _instanceLocalMatrix );
  8842. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8843. this.boundingBox.union( _box3 );
  8844. }
  8845. }
  8846. computeBoundingSphere() {
  8847. const geometry = this.geometry;
  8848. const count = this.count;
  8849. if ( this.boundingSphere === null ) {
  8850. this.boundingSphere = new Sphere();
  8851. }
  8852. if ( geometry.boundingSphere === null ) {
  8853. geometry.computeBoundingSphere();
  8854. }
  8855. this.boundingSphere.makeEmpty();
  8856. for ( let i = 0; i < count; i ++ ) {
  8857. this.getMatrixAt( i, _instanceLocalMatrix );
  8858. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8859. this.boundingSphere.union( _sphere$4 );
  8860. }
  8861. }
  8862. copy( source, recursive ) {
  8863. super.copy( source, recursive );
  8864. this.instanceMatrix.copy( source.instanceMatrix );
  8865. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8866. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8867. this.count = source.count;
  8868. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8869. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8870. return this;
  8871. }
  8872. getColorAt( index, color ) {
  8873. color.fromArray( this.instanceColor.array, index * 3 );
  8874. }
  8875. getMatrixAt( index, matrix ) {
  8876. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8877. }
  8878. getMorphAt( index, object ) {
  8879. const objectInfluences = object.morphTargetInfluences;
  8880. const array = this.morphTexture.source.data.data;
  8881. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8882. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8883. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8884. objectInfluences[ i ] = array[ dataIndex + i ];
  8885. }
  8886. }
  8887. raycast( raycaster, intersects ) {
  8888. const matrixWorld = this.matrixWorld;
  8889. const raycastTimes = this.count;
  8890. _mesh$1.geometry = this.geometry;
  8891. _mesh$1.material = this.material;
  8892. if ( _mesh$1.material === undefined ) return;
  8893. // test with bounding sphere first
  8894. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8895. _sphere$4.copy( this.boundingSphere );
  8896. _sphere$4.applyMatrix4( matrixWorld );
  8897. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8898. // now test each instance
  8899. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8900. // calculate the world matrix for each instance
  8901. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8902. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8903. // the mesh represents this single instance
  8904. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8905. _mesh$1.raycast( raycaster, _instanceIntersects );
  8906. // process the result of raycast
  8907. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8908. const intersect = _instanceIntersects[ i ];
  8909. intersect.instanceId = instanceId;
  8910. intersect.object = this;
  8911. intersects.push( intersect );
  8912. }
  8913. _instanceIntersects.length = 0;
  8914. }
  8915. }
  8916. setColorAt( index, color ) {
  8917. if ( this.instanceColor === null ) {
  8918. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8919. }
  8920. color.toArray( this.instanceColor.array, index * 3 );
  8921. }
  8922. setMatrixAt( index, matrix ) {
  8923. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8924. }
  8925. setMorphAt( index, object ) {
  8926. const objectInfluences = object.morphTargetInfluences;
  8927. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8928. if ( this.morphTexture === null ) {
  8929. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8930. }
  8931. const array = this.morphTexture.source.data.data;
  8932. let morphInfluencesSum = 0;
  8933. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8934. morphInfluencesSum += objectInfluences[ i ];
  8935. }
  8936. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8937. const dataIndex = len * index;
  8938. array[ dataIndex ] = morphBaseInfluence;
  8939. array.set( objectInfluences, dataIndex + 1 );
  8940. }
  8941. updateMorphTargets() {
  8942. }
  8943. dispose() {
  8944. this.dispatchEvent( { type: 'dispose' } );
  8945. if ( this.morphTexture !== null ) {
  8946. this.morphTexture.dispose();
  8947. this.morphTexture = null;
  8948. }
  8949. return this;
  8950. }
  8951. }
  8952. const _vector1 = /*@__PURE__*/ new Vector3();
  8953. const _vector2 = /*@__PURE__*/ new Vector3();
  8954. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8955. class Plane {
  8956. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8957. this.isPlane = true;
  8958. // normal is assumed to be normalized
  8959. this.normal = normal;
  8960. this.constant = constant;
  8961. }
  8962. set( normal, constant ) {
  8963. this.normal.copy( normal );
  8964. this.constant = constant;
  8965. return this;
  8966. }
  8967. setComponents( x, y, z, w ) {
  8968. this.normal.set( x, y, z );
  8969. this.constant = w;
  8970. return this;
  8971. }
  8972. setFromNormalAndCoplanarPoint( normal, point ) {
  8973. this.normal.copy( normal );
  8974. this.constant = - point.dot( this.normal );
  8975. return this;
  8976. }
  8977. setFromCoplanarPoints( a, b, c ) {
  8978. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8979. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8980. this.setFromNormalAndCoplanarPoint( normal, a );
  8981. return this;
  8982. }
  8983. copy( plane ) {
  8984. this.normal.copy( plane.normal );
  8985. this.constant = plane.constant;
  8986. return this;
  8987. }
  8988. normalize() {
  8989. // Note: will lead to a divide by zero if the plane is invalid.
  8990. const inverseNormalLength = 1.0 / this.normal.length();
  8991. this.normal.multiplyScalar( inverseNormalLength );
  8992. this.constant *= inverseNormalLength;
  8993. return this;
  8994. }
  8995. negate() {
  8996. this.constant *= - 1;
  8997. this.normal.negate();
  8998. return this;
  8999. }
  9000. distanceToPoint( point ) {
  9001. return this.normal.dot( point ) + this.constant;
  9002. }
  9003. distanceToSphere( sphere ) {
  9004. return this.distanceToPoint( sphere.center ) - sphere.radius;
  9005. }
  9006. projectPoint( point, target ) {
  9007. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  9008. }
  9009. intersectLine( line, target ) {
  9010. const direction = line.delta( _vector1 );
  9011. const denominator = this.normal.dot( direction );
  9012. if ( denominator === 0 ) {
  9013. // line is coplanar, return origin
  9014. if ( this.distanceToPoint( line.start ) === 0 ) {
  9015. return target.copy( line.start );
  9016. }
  9017. // Unsure if this is the correct method to handle this case.
  9018. return null;
  9019. }
  9020. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  9021. if ( t < 0 || t > 1 ) {
  9022. return null;
  9023. }
  9024. return target.copy( line.start ).addScaledVector( direction, t );
  9025. }
  9026. intersectsLine( line ) {
  9027. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  9028. const startSign = this.distanceToPoint( line.start );
  9029. const endSign = this.distanceToPoint( line.end );
  9030. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  9031. }
  9032. intersectsBox( box ) {
  9033. return box.intersectsPlane( this );
  9034. }
  9035. intersectsSphere( sphere ) {
  9036. return sphere.intersectsPlane( this );
  9037. }
  9038. coplanarPoint( target ) {
  9039. return target.copy( this.normal ).multiplyScalar( - this.constant );
  9040. }
  9041. applyMatrix4( matrix, optionalNormalMatrix ) {
  9042. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  9043. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  9044. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  9045. this.constant = - referencePoint.dot( normal );
  9046. return this;
  9047. }
  9048. translate( offset ) {
  9049. this.constant -= offset.dot( this.normal );
  9050. return this;
  9051. }
  9052. equals( plane ) {
  9053. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  9054. }
  9055. clone() {
  9056. return new this.constructor().copy( this );
  9057. }
  9058. }
  9059. const _sphere$3 = /*@__PURE__*/ new Sphere();
  9060. const _vector$6 = /*@__PURE__*/ new Vector3();
  9061. class Frustum {
  9062. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  9063. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  9064. }
  9065. set( p0, p1, p2, p3, p4, p5 ) {
  9066. const planes = this.planes;
  9067. planes[ 0 ].copy( p0 );
  9068. planes[ 1 ].copy( p1 );
  9069. planes[ 2 ].copy( p2 );
  9070. planes[ 3 ].copy( p3 );
  9071. planes[ 4 ].copy( p4 );
  9072. planes[ 5 ].copy( p5 );
  9073. return this;
  9074. }
  9075. copy( frustum ) {
  9076. const planes = this.planes;
  9077. for ( let i = 0; i < 6; i ++ ) {
  9078. planes[ i ].copy( frustum.planes[ i ] );
  9079. }
  9080. return this;
  9081. }
  9082. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  9083. const planes = this.planes;
  9084. const me = m.elements;
  9085. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9086. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9087. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9088. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9089. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9090. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9091. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9092. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9093. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9094. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9095. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9096. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9097. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  9098. } else {
  9099. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  9100. }
  9101. return this;
  9102. }
  9103. intersectsObject( object ) {
  9104. if ( object.boundingSphere !== undefined ) {
  9105. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  9106. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  9107. } else {
  9108. const geometry = object.geometry;
  9109. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9110. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9111. }
  9112. return this.intersectsSphere( _sphere$3 );
  9113. }
  9114. intersectsSprite( sprite ) {
  9115. _sphere$3.center.set( 0, 0, 0 );
  9116. _sphere$3.radius = 0.7071067811865476;
  9117. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9118. return this.intersectsSphere( _sphere$3 );
  9119. }
  9120. intersectsSphere( sphere ) {
  9121. const planes = this.planes;
  9122. const center = sphere.center;
  9123. const negRadius = - sphere.radius;
  9124. for ( let i = 0; i < 6; i ++ ) {
  9125. const distance = planes[ i ].distanceToPoint( center );
  9126. if ( distance < negRadius ) {
  9127. return false;
  9128. }
  9129. }
  9130. return true;
  9131. }
  9132. intersectsBox( box ) {
  9133. const planes = this.planes;
  9134. for ( let i = 0; i < 6; i ++ ) {
  9135. const plane = planes[ i ];
  9136. // corner at max distance
  9137. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9138. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9139. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9140. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9141. return false;
  9142. }
  9143. }
  9144. return true;
  9145. }
  9146. containsPoint( point ) {
  9147. const planes = this.planes;
  9148. for ( let i = 0; i < 6; i ++ ) {
  9149. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9150. return false;
  9151. }
  9152. }
  9153. return true;
  9154. }
  9155. clone() {
  9156. return new this.constructor().copy( this );
  9157. }
  9158. }
  9159. function ascIdSort( a, b ) {
  9160. return a - b;
  9161. }
  9162. function sortOpaque( a, b ) {
  9163. return a.z - b.z;
  9164. }
  9165. function sortTransparent( a, b ) {
  9166. return b.z - a.z;
  9167. }
  9168. class MultiDrawRenderList {
  9169. constructor() {
  9170. this.index = 0;
  9171. this.pool = [];
  9172. this.list = [];
  9173. }
  9174. push( start, count, z, index ) {
  9175. const pool = this.pool;
  9176. const list = this.list;
  9177. if ( this.index >= pool.length ) {
  9178. pool.push( {
  9179. start: - 1,
  9180. count: - 1,
  9181. z: - 1,
  9182. index: - 1,
  9183. } );
  9184. }
  9185. const item = pool[ this.index ];
  9186. list.push( item );
  9187. this.index ++;
  9188. item.start = start;
  9189. item.count = count;
  9190. item.z = z;
  9191. item.index = index;
  9192. }
  9193. reset() {
  9194. this.list.length = 0;
  9195. this.index = 0;
  9196. }
  9197. }
  9198. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9199. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9200. const _frustum = /*@__PURE__*/ new Frustum();
  9201. const _box$1 = /*@__PURE__*/ new Box3();
  9202. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9203. const _vector$5 = /*@__PURE__*/ new Vector3();
  9204. const _forward = /*@__PURE__*/ new Vector3();
  9205. const _temp = /*@__PURE__*/ new Vector3();
  9206. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9207. const _mesh = /*@__PURE__*/ new Mesh();
  9208. const _batchIntersects = [];
  9209. // copies data from attribute "src" into "target" starting at "targetOffset"
  9210. function copyAttributeData( src, target, targetOffset = 0 ) {
  9211. const itemSize = target.itemSize;
  9212. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9213. // use the component getters and setters if the array data cannot
  9214. // be copied directly
  9215. const vertexCount = src.count;
  9216. for ( let i = 0; i < vertexCount; i ++ ) {
  9217. for ( let c = 0; c < itemSize; c ++ ) {
  9218. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9219. }
  9220. }
  9221. } else {
  9222. // faster copy approach using typed array set function
  9223. target.array.set( src.array, targetOffset * itemSize );
  9224. }
  9225. target.needsUpdate = true;
  9226. }
  9227. // safely copies array contents to a potentially smaller array
  9228. function copyArrayContents( src, target ) {
  9229. if ( src.constructor !== target.constructor ) {
  9230. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  9231. const len = Math.min( src.length, target.length );
  9232. for ( let i = 0; i < len; i ++ ) {
  9233. target[ i ] = src[ i ];
  9234. }
  9235. } else {
  9236. // if the arrays use the same data layout we can use a fast block copy
  9237. const len = Math.min( src.length, target.length );
  9238. target.set( new src.constructor( src.buffer, 0, len ) );
  9239. }
  9240. }
  9241. class BatchedMesh extends Mesh {
  9242. get maxInstanceCount() {
  9243. return this._maxInstanceCount;
  9244. }
  9245. get instanceCount() {
  9246. return this._instanceInfo.length - this._availableInstanceIds.length;
  9247. }
  9248. get unusedVertexCount() {
  9249. return this._maxVertexCount - this._nextVertexStart;
  9250. }
  9251. get unusedIndexCount() {
  9252. return this._maxIndexCount - this._nextIndexStart;
  9253. }
  9254. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9255. super( new BufferGeometry(), material );
  9256. this.isBatchedMesh = true;
  9257. this.perObjectFrustumCulled = true;
  9258. this.sortObjects = true;
  9259. this.boundingBox = null;
  9260. this.boundingSphere = null;
  9261. this.customSort = null;
  9262. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  9263. this._instanceInfo = [];
  9264. this._geometryInfo = [];
  9265. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  9266. this._availableInstanceIds = [];
  9267. this._availableGeometryIds = [];
  9268. // used to track where the next point is that geometry should be inserted
  9269. this._nextIndexStart = 0;
  9270. this._nextVertexStart = 0;
  9271. this._geometryCount = 0;
  9272. // flags
  9273. this._visibilityChanged = true;
  9274. this._geometryInitialized = false;
  9275. // cached user options
  9276. this._maxInstanceCount = maxInstanceCount;
  9277. this._maxVertexCount = maxVertexCount;
  9278. this._maxIndexCount = maxIndexCount;
  9279. // buffers for multi draw
  9280. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9281. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9282. this._multiDrawCount = 0;
  9283. this._multiDrawInstances = null;
  9284. // Local matrix per geometry by using data texture
  9285. this._matricesTexture = null;
  9286. this._indirectTexture = null;
  9287. this._colorsTexture = null;
  9288. this._initMatricesTexture();
  9289. this._initIndirectTexture();
  9290. }
  9291. _initMatricesTexture() {
  9292. // layout (1 matrix = 4 pixels)
  9293. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9294. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9295. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9296. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9297. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9298. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9299. size = Math.ceil( size / 4 ) * 4;
  9300. size = Math.max( size, 4 );
  9301. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9302. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9303. this._matricesTexture = matricesTexture;
  9304. }
  9305. _initIndirectTexture() {
  9306. let size = Math.sqrt( this._maxInstanceCount );
  9307. size = Math.ceil( size );
  9308. const indirectArray = new Uint32Array( size * size );
  9309. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9310. this._indirectTexture = indirectTexture;
  9311. }
  9312. _initColorsTexture() {
  9313. let size = Math.sqrt( this._maxInstanceCount );
  9314. size = Math.ceil( size );
  9315. // 4 floats per RGBA pixel initialized to white
  9316. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9317. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9318. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9319. this._colorsTexture = colorsTexture;
  9320. }
  9321. _initializeGeometry( reference ) {
  9322. const geometry = this.geometry;
  9323. const maxVertexCount = this._maxVertexCount;
  9324. const maxIndexCount = this._maxIndexCount;
  9325. if ( this._geometryInitialized === false ) {
  9326. for ( const attributeName in reference.attributes ) {
  9327. const srcAttribute = reference.getAttribute( attributeName );
  9328. const { array, itemSize, normalized } = srcAttribute;
  9329. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9330. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9331. geometry.setAttribute( attributeName, dstAttribute );
  9332. }
  9333. if ( reference.getIndex() !== null ) {
  9334. // Reserve last u16 index for primitive restart.
  9335. const indexArray = maxVertexCount > 65535
  9336. ? new Uint32Array( maxIndexCount )
  9337. : new Uint16Array( maxIndexCount );
  9338. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9339. }
  9340. this._geometryInitialized = true;
  9341. }
  9342. }
  9343. // Make sure the geometry is compatible with the existing combined geometry attributes
  9344. _validateGeometry( geometry ) {
  9345. // check to ensure the geometries are using consistent attributes and indices
  9346. const batchGeometry = this.geometry;
  9347. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9348. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  9349. }
  9350. for ( const attributeName in batchGeometry.attributes ) {
  9351. if ( ! geometry.hasAttribute( attributeName ) ) {
  9352. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9353. }
  9354. const srcAttribute = geometry.getAttribute( attributeName );
  9355. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9356. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9357. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9358. }
  9359. }
  9360. }
  9361. validateInstanceId( instanceId ) {
  9362. const instanceInfo = this._instanceInfo;
  9363. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9364. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  9365. }
  9366. }
  9367. validateGeometryId( geometryId ) {
  9368. const geometryInfoList = this._geometryInfo;
  9369. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  9370. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  9371. }
  9372. }
  9373. setCustomSort( func ) {
  9374. this.customSort = func;
  9375. return this;
  9376. }
  9377. computeBoundingBox() {
  9378. if ( this.boundingBox === null ) {
  9379. this.boundingBox = new Box3();
  9380. }
  9381. const boundingBox = this.boundingBox;
  9382. const instanceInfo = this._instanceInfo;
  9383. boundingBox.makeEmpty();
  9384. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9385. if ( instanceInfo[ i ].active === false ) continue;
  9386. const geometryId = instanceInfo[ i ].geometryIndex;
  9387. this.getMatrixAt( i, _matrix$1 );
  9388. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9389. boundingBox.union( _box$1 );
  9390. }
  9391. }
  9392. computeBoundingSphere() {
  9393. if ( this.boundingSphere === null ) {
  9394. this.boundingSphere = new Sphere();
  9395. }
  9396. const boundingSphere = this.boundingSphere;
  9397. const instanceInfo = this._instanceInfo;
  9398. boundingSphere.makeEmpty();
  9399. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9400. if ( instanceInfo[ i ].active === false ) continue;
  9401. const geometryId = instanceInfo[ i ].geometryIndex;
  9402. this.getMatrixAt( i, _matrix$1 );
  9403. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9404. boundingSphere.union( _sphere$2 );
  9405. }
  9406. }
  9407. addInstance( geometryId ) {
  9408. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  9409. // ensure we're not over geometry
  9410. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  9411. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  9412. }
  9413. const instanceInfo = {
  9414. visible: true,
  9415. active: true,
  9416. geometryIndex: geometryId,
  9417. };
  9418. let drawId = null;
  9419. // Prioritize using previously freed instance ids
  9420. if ( this._availableInstanceIds.length > 0 ) {
  9421. this._availableInstanceIds.sort( ascIdSort );
  9422. drawId = this._availableInstanceIds.shift();
  9423. this._instanceInfo[ drawId ] = instanceInfo;
  9424. } else {
  9425. drawId = this._instanceInfo.length;
  9426. this._instanceInfo.push( instanceInfo );
  9427. }
  9428. const matricesTexture = this._matricesTexture;
  9429. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  9430. matricesTexture.needsUpdate = true;
  9431. const colorsTexture = this._colorsTexture;
  9432. if ( colorsTexture ) {
  9433. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9434. colorsTexture.needsUpdate = true;
  9435. }
  9436. this._visibilityChanged = true;
  9437. return drawId;
  9438. }
  9439. addGeometry( geometry, reservedVertexCount = - 1, reservedIndexCount = - 1 ) {
  9440. this._initializeGeometry( geometry );
  9441. this._validateGeometry( geometry );
  9442. const geometryInfo = {
  9443. // geometry information
  9444. vertexStart: - 1,
  9445. vertexCount: - 1,
  9446. reservedVertexCount: - 1,
  9447. indexStart: - 1,
  9448. indexCount: - 1,
  9449. reservedIndexCount: - 1,
  9450. // draw range information
  9451. start: - 1,
  9452. count: - 1,
  9453. // state
  9454. boundingBox: null,
  9455. boundingSphere: null,
  9456. active: true,
  9457. };
  9458. const geometryInfoList = this._geometryInfo;
  9459. geometryInfo.vertexStart = this._nextVertexStart;
  9460. geometryInfo.reservedVertexCount = reservedVertexCount === - 1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  9461. const index = geometry.getIndex();
  9462. const hasIndex = index !== null;
  9463. if ( hasIndex ) {
  9464. geometryInfo.indexStart = this._nextIndexStart;
  9465. geometryInfo.reservedIndexCount = reservedIndexCount === - 1 ? index.count : reservedIndexCount;
  9466. }
  9467. if (
  9468. geometryInfo.indexStart !== - 1 &&
  9469. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  9470. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  9471. ) {
  9472. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9473. }
  9474. // update id
  9475. let geometryId;
  9476. if ( this._availableGeometryIds.length > 0 ) {
  9477. this._availableGeometryIds.sort( ascIdSort );
  9478. geometryId = this._availableGeometryIds.shift();
  9479. geometryInfoList[ geometryId ] = geometryInfo;
  9480. } else {
  9481. geometryId = this._geometryCount;
  9482. this._geometryCount ++;
  9483. geometryInfoList.push( geometryInfo );
  9484. }
  9485. // update the geometry
  9486. this.setGeometryAt( geometryId, geometry );
  9487. // increment the next geometry position
  9488. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  9489. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  9490. return geometryId;
  9491. }
  9492. setGeometryAt( geometryId, geometry ) {
  9493. if ( geometryId >= this._geometryCount ) {
  9494. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  9495. }
  9496. this._validateGeometry( geometry );
  9497. const batchGeometry = this.geometry;
  9498. const hasIndex = batchGeometry.getIndex() !== null;
  9499. const dstIndex = batchGeometry.getIndex();
  9500. const srcIndex = geometry.getIndex();
  9501. const geometryInfo = this._geometryInfo[ geometryId ];
  9502. if (
  9503. hasIndex &&
  9504. srcIndex.count > geometryInfo.reservedIndexCount ||
  9505. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  9506. ) {
  9507. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  9508. }
  9509. // copy geometry buffer data over
  9510. const vertexStart = geometryInfo.vertexStart;
  9511. const reservedVertexCount = geometryInfo.reservedVertexCount;
  9512. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  9513. for ( const attributeName in batchGeometry.attributes ) {
  9514. // copy attribute data
  9515. const srcAttribute = geometry.getAttribute( attributeName );
  9516. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9517. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9518. // fill the rest in with zeroes
  9519. const itemSize = srcAttribute.itemSize;
  9520. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  9521. const index = vertexStart + i;
  9522. for ( let c = 0; c < itemSize; c ++ ) {
  9523. dstAttribute.setComponent( index, c, 0 );
  9524. }
  9525. }
  9526. dstAttribute.needsUpdate = true;
  9527. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  9528. }
  9529. // copy index
  9530. if ( hasIndex ) {
  9531. const indexStart = geometryInfo.indexStart;
  9532. const reservedIndexCount = geometryInfo.reservedIndexCount;
  9533. geometryInfo.indexCount = geometry.getIndex().count;
  9534. // copy index data over
  9535. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9536. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9537. }
  9538. // fill the rest in with zeroes
  9539. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  9540. dstIndex.setX( indexStart + i, vertexStart );
  9541. }
  9542. dstIndex.needsUpdate = true;
  9543. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  9544. }
  9545. // update the draw range
  9546. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  9547. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  9548. // store the bounding boxes
  9549. geometryInfo.boundingBox = null;
  9550. if ( geometry.boundingBox !== null ) {
  9551. geometryInfo.boundingBox = geometry.boundingBox.clone();
  9552. }
  9553. geometryInfo.boundingSphere = null;
  9554. if ( geometry.boundingSphere !== null ) {
  9555. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  9556. }
  9557. this._visibilityChanged = true;
  9558. return geometryId;
  9559. }
  9560. deleteGeometry( geometryId ) {
  9561. const geometryInfoList = this._geometryInfo;
  9562. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  9563. return this;
  9564. }
  9565. // delete any instances associated with this geometry
  9566. const instanceInfo = this._instanceInfo;
  9567. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9568. if ( instanceInfo[ i ].geometryIndex === geometryId ) {
  9569. this.deleteInstance( i );
  9570. }
  9571. }
  9572. geometryInfoList[ geometryId ].active = false;
  9573. this._availableGeometryIds.push( geometryId );
  9574. this._visibilityChanged = true;
  9575. return this;
  9576. }
  9577. deleteInstance( instanceId ) {
  9578. this.validateInstanceId( instanceId );
  9579. this._instanceInfo[ instanceId ].active = false;
  9580. this._availableInstanceIds.push( instanceId );
  9581. this._visibilityChanged = true;
  9582. return this;
  9583. }
  9584. optimize() {
  9585. // track the next indices to copy data to
  9586. let nextVertexStart = 0;
  9587. let nextIndexStart = 0;
  9588. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  9589. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  9590. const geometryInfoList = this._geometryInfo;
  9591. const indices = geometryInfoList
  9592. .map( ( e, i ) => i )
  9593. .sort( ( a, b ) => {
  9594. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  9595. } );
  9596. const geometry = this.geometry;
  9597. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  9598. // if a geometry range is inactive then don't copy anything
  9599. const index = indices[ i ];
  9600. const geometryInfo = geometryInfoList[ index ];
  9601. if ( geometryInfo.active === false ) {
  9602. continue;
  9603. }
  9604. // if a geometry contains an index buffer then shift it, as well
  9605. if ( geometry.index !== null ) {
  9606. if ( geometryInfo.indexStart !== nextIndexStart ) {
  9607. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  9608. const index = geometry.index;
  9609. const array = index.array;
  9610. // shift the index pointers based on how the vertex data will shift
  9611. // adjusting the index must happen first so the original vertex start value is available
  9612. const elementDelta = nextVertexStart - vertexStart;
  9613. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  9614. array[ j ] = array[ j ] + elementDelta;
  9615. }
  9616. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  9617. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  9618. geometryInfo.indexStart = nextIndexStart;
  9619. }
  9620. nextIndexStart += geometryInfo.reservedIndexCount;
  9621. }
  9622. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  9623. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  9624. const { vertexStart, reservedVertexCount } = geometryInfo;
  9625. const attributes = geometry.attributes;
  9626. for ( const key in attributes ) {
  9627. const attribute = attributes[ key ];
  9628. const { array, itemSize } = attribute;
  9629. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  9630. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  9631. }
  9632. geometryInfo.vertexStart = nextVertexStart;
  9633. }
  9634. nextVertexStart += geometryInfo.reservedVertexCount;
  9635. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  9636. // step the next geometry points to the shifted position
  9637. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  9638. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  9639. }
  9640. return this;
  9641. }
  9642. // get bounding box and compute it if it doesn't exist
  9643. getBoundingBoxAt( geometryId, target ) {
  9644. if ( geometryId >= this._geometryCount ) {
  9645. return null;
  9646. }
  9647. // compute bounding box
  9648. const geometry = this.geometry;
  9649. const geometryInfo = this._geometryInfo[ geometryId ];
  9650. if ( geometryInfo.boundingBox === null ) {
  9651. const box = new Box3();
  9652. const index = geometry.index;
  9653. const position = geometry.attributes.position;
  9654. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  9655. let iv = i;
  9656. if ( index ) {
  9657. iv = index.getX( iv );
  9658. }
  9659. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9660. }
  9661. geometryInfo.boundingBox = box;
  9662. }
  9663. target.copy( geometryInfo.boundingBox );
  9664. return target;
  9665. }
  9666. // get bounding sphere and compute it if it doesn't exist
  9667. getBoundingSphereAt( geometryId, target ) {
  9668. if ( geometryId >= this._geometryCount ) {
  9669. return null;
  9670. }
  9671. // compute bounding sphere
  9672. const geometry = this.geometry;
  9673. const geometryInfo = this._geometryInfo[ geometryId ];
  9674. if ( geometryInfo.boundingSphere === null ) {
  9675. const sphere = new Sphere();
  9676. this.getBoundingBoxAt( geometryId, _box$1 );
  9677. _box$1.getCenter( sphere.center );
  9678. const index = geometry.index;
  9679. const position = geometry.attributes.position;
  9680. let maxRadiusSq = 0;
  9681. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  9682. let iv = i;
  9683. if ( index ) {
  9684. iv = index.getX( iv );
  9685. }
  9686. _vector$5.fromBufferAttribute( position, iv );
  9687. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9688. }
  9689. sphere.radius = Math.sqrt( maxRadiusSq );
  9690. geometryInfo.boundingSphere = sphere;
  9691. }
  9692. target.copy( geometryInfo.boundingSphere );
  9693. return target;
  9694. }
  9695. setMatrixAt( instanceId, matrix ) {
  9696. this.validateInstanceId( instanceId );
  9697. const matricesTexture = this._matricesTexture;
  9698. const matricesArray = this._matricesTexture.image.data;
  9699. matrix.toArray( matricesArray, instanceId * 16 );
  9700. matricesTexture.needsUpdate = true;
  9701. return this;
  9702. }
  9703. getMatrixAt( instanceId, matrix ) {
  9704. this.validateInstanceId( instanceId );
  9705. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  9706. }
  9707. setColorAt( instanceId, color ) {
  9708. this.validateInstanceId( instanceId );
  9709. if ( this._colorsTexture === null ) {
  9710. this._initColorsTexture();
  9711. }
  9712. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  9713. this._colorsTexture.needsUpdate = true;
  9714. return this;
  9715. }
  9716. getColorAt( instanceId, color ) {
  9717. this.validateInstanceId( instanceId );
  9718. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  9719. }
  9720. setVisibleAt( instanceId, value ) {
  9721. this.validateInstanceId( instanceId );
  9722. if ( this._instanceInfo[ instanceId ].visible === value ) {
  9723. return this;
  9724. }
  9725. this._instanceInfo[ instanceId ].visible = value;
  9726. this._visibilityChanged = true;
  9727. return this;
  9728. }
  9729. getVisibleAt( instanceId ) {
  9730. this.validateInstanceId( instanceId );
  9731. return this._instanceInfo[ instanceId ].visible;
  9732. }
  9733. setGeometryIdAt( instanceId, geometryId ) {
  9734. this.validateInstanceId( instanceId );
  9735. this.validateGeometryId( geometryId );
  9736. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  9737. return this;
  9738. }
  9739. getGeometryIdAt( instanceId ) {
  9740. this.validateInstanceId( instanceId );
  9741. return this._instanceInfo[ instanceId ].geometryIndex;
  9742. }
  9743. getGeometryRangeAt( geometryId, target = {} ) {
  9744. this.validateGeometryId( geometryId );
  9745. const geometryInfo = this._geometryInfo[ geometryId ];
  9746. target.vertexStart = geometryInfo.vertexStart;
  9747. target.vertexCount = geometryInfo.vertexCount;
  9748. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  9749. target.indexStart = geometryInfo.indexStart;
  9750. target.indexCount = geometryInfo.indexCount;
  9751. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  9752. target.start = geometryInfo.start;
  9753. target.count = geometryInfo.count;
  9754. return target;
  9755. }
  9756. setInstanceCount( maxInstanceCount ) {
  9757. // shrink the available instances as much as possible
  9758. const availableInstanceIds = this._availableInstanceIds;
  9759. const instanceInfo = this._instanceInfo;
  9760. availableInstanceIds.sort( ascIdSort );
  9761. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  9762. instanceInfo.pop();
  9763. availableInstanceIds.pop();
  9764. }
  9765. // throw an error if it can't be shrunk to the desired size
  9766. if ( maxInstanceCount < instanceInfo.length ) {
  9767. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  9768. }
  9769. // copy the multi draw counts
  9770. const multiDrawCounts = new Int32Array( maxInstanceCount );
  9771. const multiDrawStarts = new Int32Array( maxInstanceCount );
  9772. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  9773. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  9774. this._multiDrawCounts = multiDrawCounts;
  9775. this._multiDrawStarts = multiDrawStarts;
  9776. this._maxInstanceCount = maxInstanceCount;
  9777. // update texture data for instance sampling
  9778. const indirectTexture = this._indirectTexture;
  9779. const matricesTexture = this._matricesTexture;
  9780. const colorsTexture = this._colorsTexture;
  9781. indirectTexture.dispose();
  9782. this._initIndirectTexture();
  9783. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  9784. matricesTexture.dispose();
  9785. this._initMatricesTexture();
  9786. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  9787. if ( colorsTexture ) {
  9788. colorsTexture.dispose();
  9789. this._initColorsTexture();
  9790. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  9791. }
  9792. }
  9793. setGeometrySize( maxVertexCount, maxIndexCount ) {
  9794. // Check if we can shrink to the requested vertex attribute size
  9795. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  9796. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  9797. if ( requiredVertexLength > maxVertexCount ) {
  9798. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9799. }
  9800. // Check if we can shrink to the requested index attribute size
  9801. if ( this.geometry.index ) {
  9802. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  9803. if ( requiredIndexLength > maxIndexCount ) {
  9804. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9805. }
  9806. }
  9807. //
  9808. // dispose of the previous geometry
  9809. const oldGeometry = this.geometry;
  9810. oldGeometry.dispose();
  9811. // recreate the geometry needed based on the previous variant
  9812. this._maxVertexCount = maxVertexCount;
  9813. this._maxIndexCount = maxIndexCount;
  9814. if ( this._geometryInitialized ) {
  9815. this._geometryInitialized = false;
  9816. this.geometry = new BufferGeometry();
  9817. this._initializeGeometry( oldGeometry );
  9818. }
  9819. // copy data from the previous geometry
  9820. const geometry = this.geometry;
  9821. if ( oldGeometry.index ) {
  9822. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  9823. }
  9824. for ( const key in oldGeometry.attributes ) {
  9825. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  9826. }
  9827. }
  9828. raycast( raycaster, intersects ) {
  9829. const instanceInfo = this._instanceInfo;
  9830. const geometryInfoList = this._geometryInfo;
  9831. const matrixWorld = this.matrixWorld;
  9832. const batchGeometry = this.geometry;
  9833. // iterate over each geometry
  9834. _mesh.material = this.material;
  9835. _mesh.geometry.index = batchGeometry.index;
  9836. _mesh.geometry.attributes = batchGeometry.attributes;
  9837. if ( _mesh.geometry.boundingBox === null ) {
  9838. _mesh.geometry.boundingBox = new Box3();
  9839. }
  9840. if ( _mesh.geometry.boundingSphere === null ) {
  9841. _mesh.geometry.boundingSphere = new Sphere();
  9842. }
  9843. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9844. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  9845. continue;
  9846. }
  9847. const geometryId = instanceInfo[ i ].geometryIndex;
  9848. const geometryInfo = geometryInfoList[ geometryId ];
  9849. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  9850. // get the intersects
  9851. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9852. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9853. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9854. _mesh.raycast( raycaster, _batchIntersects );
  9855. // add batch id to the intersects
  9856. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9857. const intersect = _batchIntersects[ j ];
  9858. intersect.object = this;
  9859. intersect.batchId = i;
  9860. intersects.push( intersect );
  9861. }
  9862. _batchIntersects.length = 0;
  9863. }
  9864. _mesh.material = null;
  9865. _mesh.geometry.index = null;
  9866. _mesh.geometry.attributes = {};
  9867. _mesh.geometry.setDrawRange( 0, Infinity );
  9868. }
  9869. copy( source ) {
  9870. super.copy( source );
  9871. this.geometry = source.geometry.clone();
  9872. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9873. this.sortObjects = source.sortObjects;
  9874. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9875. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9876. this._geometryInfo = source._geometryInfo.map( info => ( {
  9877. ...info,
  9878. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  9879. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  9880. } ) );
  9881. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  9882. this._maxInstanceCount = source._maxInstanceCount;
  9883. this._maxVertexCount = source._maxVertexCount;
  9884. this._maxIndexCount = source._maxIndexCount;
  9885. this._geometryInitialized = source._geometryInitialized;
  9886. this._geometryCount = source._geometryCount;
  9887. this._multiDrawCounts = source._multiDrawCounts.slice();
  9888. this._multiDrawStarts = source._multiDrawStarts.slice();
  9889. this._matricesTexture = source._matricesTexture.clone();
  9890. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9891. if ( this._colorsTexture !== null ) {
  9892. this._colorsTexture = source._colorsTexture.clone();
  9893. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9894. }
  9895. return this;
  9896. }
  9897. dispose() {
  9898. // Assuming the geometry is not shared with other meshes
  9899. this.geometry.dispose();
  9900. this._matricesTexture.dispose();
  9901. this._matricesTexture = null;
  9902. this._indirectTexture.dispose();
  9903. this._indirectTexture = null;
  9904. if ( this._colorsTexture !== null ) {
  9905. this._colorsTexture.dispose();
  9906. this._colorsTexture = null;
  9907. }
  9908. return this;
  9909. }
  9910. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9911. // if visibility has not changed and frustum culling and object sorting is not required
  9912. // then skip iterating over all items
  9913. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9914. return;
  9915. }
  9916. // the indexed version of the multi draw function requires specifying the start
  9917. // offset in bytes.
  9918. const index = geometry.getIndex();
  9919. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9920. const instanceInfo = this._instanceInfo;
  9921. const multiDrawStarts = this._multiDrawStarts;
  9922. const multiDrawCounts = this._multiDrawCounts;
  9923. const geometryInfoList = this._geometryInfo;
  9924. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9925. const indirectTexture = this._indirectTexture;
  9926. const indirectArray = indirectTexture.image.data;
  9927. // prepare the frustum in the local frame
  9928. if ( perObjectFrustumCulled ) {
  9929. _matrix$1
  9930. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9931. .multiply( this.matrixWorld );
  9932. _frustum.setFromProjectionMatrix(
  9933. _matrix$1,
  9934. renderer.coordinateSystem
  9935. );
  9936. }
  9937. let multiDrawCount = 0;
  9938. if ( this.sortObjects ) {
  9939. // get the camera position in the local frame
  9940. _matrix$1.copy( this.matrixWorld ).invert();
  9941. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  9942. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  9943. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9944. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  9945. const geometryId = instanceInfo[ i ].geometryIndex;
  9946. // get the bounds in world space
  9947. this.getMatrixAt( i, _matrix$1 );
  9948. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9949. // determine whether the batched geometry is within the frustum
  9950. let culled = false;
  9951. if ( perObjectFrustumCulled ) {
  9952. culled = ! _frustum.intersectsSphere( _sphere$2 );
  9953. }
  9954. if ( ! culled ) {
  9955. // get the distance from camera used for sorting
  9956. const geometryInfo = geometryInfoList[ geometryId ];
  9957. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9958. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  9959. }
  9960. }
  9961. }
  9962. // Sort the draw ranges and prep for rendering
  9963. const list = _renderList.list;
  9964. const customSort = this.customSort;
  9965. if ( customSort === null ) {
  9966. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9967. } else {
  9968. customSort.call( this, list, camera );
  9969. }
  9970. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9971. const item = list[ i ];
  9972. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  9973. multiDrawCounts[ multiDrawCount ] = item.count;
  9974. indirectArray[ multiDrawCount ] = item.index;
  9975. multiDrawCount ++;
  9976. }
  9977. _renderList.reset();
  9978. } else {
  9979. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9980. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  9981. const geometryId = instanceInfo[ i ].geometryIndex;
  9982. // determine whether the batched geometry is within the frustum
  9983. let culled = false;
  9984. if ( perObjectFrustumCulled ) {
  9985. // get the bounds in world space
  9986. this.getMatrixAt( i, _matrix$1 );
  9987. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9988. culled = ! _frustum.intersectsSphere( _sphere$2 );
  9989. }
  9990. if ( ! culled ) {
  9991. const geometryInfo = geometryInfoList[ geometryId ];
  9992. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  9993. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  9994. indirectArray[ multiDrawCount ] = i;
  9995. multiDrawCount ++;
  9996. }
  9997. }
  9998. }
  9999. }
  10000. indirectTexture.needsUpdate = true;
  10001. this._multiDrawCount = multiDrawCount;
  10002. this._visibilityChanged = false;
  10003. }
  10004. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  10005. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  10006. }
  10007. }
  10008. class LineBasicMaterial extends Material {
  10009. constructor( parameters ) {
  10010. super();
  10011. this.isLineBasicMaterial = true;
  10012. this.type = 'LineBasicMaterial';
  10013. this.color = new Color( 0xffffff );
  10014. this.map = null;
  10015. this.linewidth = 1;
  10016. this.linecap = 'round';
  10017. this.linejoin = 'round';
  10018. this.fog = true;
  10019. this.setValues( parameters );
  10020. }
  10021. copy( source ) {
  10022. super.copy( source );
  10023. this.color.copy( source.color );
  10024. this.map = source.map;
  10025. this.linewidth = source.linewidth;
  10026. this.linecap = source.linecap;
  10027. this.linejoin = source.linejoin;
  10028. this.fog = source.fog;
  10029. return this;
  10030. }
  10031. }
  10032. const _vStart = /*@__PURE__*/ new Vector3();
  10033. const _vEnd = /*@__PURE__*/ new Vector3();
  10034. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  10035. const _ray$1 = /*@__PURE__*/ new Ray();
  10036. const _sphere$1 = /*@__PURE__*/ new Sphere();
  10037. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  10038. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  10039. class Line extends Object3D {
  10040. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  10041. super();
  10042. this.isLine = true;
  10043. this.type = 'Line';
  10044. this.geometry = geometry;
  10045. this.material = material;
  10046. this.updateMorphTargets();
  10047. }
  10048. copy( source, recursive ) {
  10049. super.copy( source, recursive );
  10050. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10051. this.geometry = source.geometry;
  10052. return this;
  10053. }
  10054. computeLineDistances() {
  10055. const geometry = this.geometry;
  10056. // we assume non-indexed geometry
  10057. if ( geometry.index === null ) {
  10058. const positionAttribute = geometry.attributes.position;
  10059. const lineDistances = [ 0 ];
  10060. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  10061. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  10062. _vEnd.fromBufferAttribute( positionAttribute, i );
  10063. lineDistances[ i ] = lineDistances[ i - 1 ];
  10064. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  10065. }
  10066. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10067. } else {
  10068. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10069. }
  10070. return this;
  10071. }
  10072. raycast( raycaster, intersects ) {
  10073. const geometry = this.geometry;
  10074. const matrixWorld = this.matrixWorld;
  10075. const threshold = raycaster.params.Line.threshold;
  10076. const drawRange = geometry.drawRange;
  10077. // Checking boundingSphere distance to ray
  10078. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10079. _sphere$1.copy( geometry.boundingSphere );
  10080. _sphere$1.applyMatrix4( matrixWorld );
  10081. _sphere$1.radius += threshold;
  10082. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  10083. //
  10084. _inverseMatrix$1.copy( matrixWorld ).invert();
  10085. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  10086. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10087. const localThresholdSq = localThreshold * localThreshold;
  10088. const step = this.isLineSegments ? 2 : 1;
  10089. const index = geometry.index;
  10090. const attributes = geometry.attributes;
  10091. const positionAttribute = attributes.position;
  10092. if ( index !== null ) {
  10093. const start = Math.max( 0, drawRange.start );
  10094. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10095. for ( let i = start, l = end - 1; i < l; i += step ) {
  10096. const a = index.getX( i );
  10097. const b = index.getX( i + 1 );
  10098. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10099. if ( intersect ) {
  10100. intersects.push( intersect );
  10101. }
  10102. }
  10103. if ( this.isLineLoop ) {
  10104. const a = index.getX( end - 1 );
  10105. const b = index.getX( start );
  10106. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10107. if ( intersect ) {
  10108. intersects.push( intersect );
  10109. }
  10110. }
  10111. } else {
  10112. const start = Math.max( 0, drawRange.start );
  10113. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10114. for ( let i = start, l = end - 1; i < l; i += step ) {
  10115. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  10116. if ( intersect ) {
  10117. intersects.push( intersect );
  10118. }
  10119. }
  10120. if ( this.isLineLoop ) {
  10121. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  10122. if ( intersect ) {
  10123. intersects.push( intersect );
  10124. }
  10125. }
  10126. }
  10127. }
  10128. updateMorphTargets() {
  10129. const geometry = this.geometry;
  10130. const morphAttributes = geometry.morphAttributes;
  10131. const keys = Object.keys( morphAttributes );
  10132. if ( keys.length > 0 ) {
  10133. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10134. if ( morphAttribute !== undefined ) {
  10135. this.morphTargetInfluences = [];
  10136. this.morphTargetDictionary = {};
  10137. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10138. const name = morphAttribute[ m ].name || String( m );
  10139. this.morphTargetInfluences.push( 0 );
  10140. this.morphTargetDictionary[ name ] = m;
  10141. }
  10142. }
  10143. }
  10144. }
  10145. }
  10146. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  10147. const positionAttribute = object.geometry.attributes.position;
  10148. _vStart.fromBufferAttribute( positionAttribute, a );
  10149. _vEnd.fromBufferAttribute( positionAttribute, b );
  10150. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  10151. if ( distSq > thresholdSq ) return;
  10152. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  10153. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  10154. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10155. return {
  10156. distance: distance,
  10157. // What do we want? intersection point on the ray or on the segment??
  10158. // point: raycaster.ray.at( distance ),
  10159. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  10160. index: a,
  10161. face: null,
  10162. faceIndex: null,
  10163. barycoord: null,
  10164. object: object
  10165. };
  10166. }
  10167. const _start = /*@__PURE__*/ new Vector3();
  10168. const _end = /*@__PURE__*/ new Vector3();
  10169. class LineSegments extends Line {
  10170. constructor( geometry, material ) {
  10171. super( geometry, material );
  10172. this.isLineSegments = true;
  10173. this.type = 'LineSegments';
  10174. }
  10175. computeLineDistances() {
  10176. const geometry = this.geometry;
  10177. // we assume non-indexed geometry
  10178. if ( geometry.index === null ) {
  10179. const positionAttribute = geometry.attributes.position;
  10180. const lineDistances = [];
  10181. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  10182. _start.fromBufferAttribute( positionAttribute, i );
  10183. _end.fromBufferAttribute( positionAttribute, i + 1 );
  10184. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  10185. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  10186. }
  10187. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10188. } else {
  10189. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10190. }
  10191. return this;
  10192. }
  10193. }
  10194. class LineLoop extends Line {
  10195. constructor( geometry, material ) {
  10196. super( geometry, material );
  10197. this.isLineLoop = true;
  10198. this.type = 'LineLoop';
  10199. }
  10200. }
  10201. class PointsMaterial extends Material {
  10202. constructor( parameters ) {
  10203. super();
  10204. this.isPointsMaterial = true;
  10205. this.type = 'PointsMaterial';
  10206. this.color = new Color( 0xffffff );
  10207. this.map = null;
  10208. this.alphaMap = null;
  10209. this.size = 1;
  10210. this.sizeAttenuation = true;
  10211. this.fog = true;
  10212. this.setValues( parameters );
  10213. }
  10214. copy( source ) {
  10215. super.copy( source );
  10216. this.color.copy( source.color );
  10217. this.map = source.map;
  10218. this.alphaMap = source.alphaMap;
  10219. this.size = source.size;
  10220. this.sizeAttenuation = source.sizeAttenuation;
  10221. this.fog = source.fog;
  10222. return this;
  10223. }
  10224. }
  10225. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  10226. const _ray = /*@__PURE__*/ new Ray();
  10227. const _sphere = /*@__PURE__*/ new Sphere();
  10228. const _position$2 = /*@__PURE__*/ new Vector3();
  10229. class Points extends Object3D {
  10230. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  10231. super();
  10232. this.isPoints = true;
  10233. this.type = 'Points';
  10234. this.geometry = geometry;
  10235. this.material = material;
  10236. this.updateMorphTargets();
  10237. }
  10238. copy( source, recursive ) {
  10239. super.copy( source, recursive );
  10240. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10241. this.geometry = source.geometry;
  10242. return this;
  10243. }
  10244. raycast( raycaster, intersects ) {
  10245. const geometry = this.geometry;
  10246. const matrixWorld = this.matrixWorld;
  10247. const threshold = raycaster.params.Points.threshold;
  10248. const drawRange = geometry.drawRange;
  10249. // Checking boundingSphere distance to ray
  10250. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10251. _sphere.copy( geometry.boundingSphere );
  10252. _sphere.applyMatrix4( matrixWorld );
  10253. _sphere.radius += threshold;
  10254. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  10255. //
  10256. _inverseMatrix.copy( matrixWorld ).invert();
  10257. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  10258. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10259. const localThresholdSq = localThreshold * localThreshold;
  10260. const index = geometry.index;
  10261. const attributes = geometry.attributes;
  10262. const positionAttribute = attributes.position;
  10263. if ( index !== null ) {
  10264. const start = Math.max( 0, drawRange.start );
  10265. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10266. for ( let i = start, il = end; i < il; i ++ ) {
  10267. const a = index.getX( i );
  10268. _position$2.fromBufferAttribute( positionAttribute, a );
  10269. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10270. }
  10271. } else {
  10272. const start = Math.max( 0, drawRange.start );
  10273. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10274. for ( let i = start, l = end; i < l; i ++ ) {
  10275. _position$2.fromBufferAttribute( positionAttribute, i );
  10276. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10277. }
  10278. }
  10279. }
  10280. updateMorphTargets() {
  10281. const geometry = this.geometry;
  10282. const morphAttributes = geometry.morphAttributes;
  10283. const keys = Object.keys( morphAttributes );
  10284. if ( keys.length > 0 ) {
  10285. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10286. if ( morphAttribute !== undefined ) {
  10287. this.morphTargetInfluences = [];
  10288. this.morphTargetDictionary = {};
  10289. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10290. const name = morphAttribute[ m ].name || String( m );
  10291. this.morphTargetInfluences.push( 0 );
  10292. this.morphTargetDictionary[ name ] = m;
  10293. }
  10294. }
  10295. }
  10296. }
  10297. }
  10298. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10299. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10300. if ( rayPointDistanceSq < localThresholdSq ) {
  10301. const intersectPoint = new Vector3();
  10302. _ray.closestPointToPoint( point, intersectPoint );
  10303. intersectPoint.applyMatrix4( matrixWorld );
  10304. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10305. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10306. intersects.push( {
  10307. distance: distance,
  10308. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10309. point: intersectPoint,
  10310. index: index,
  10311. face: null,
  10312. faceIndex: null,
  10313. barycoord: null,
  10314. object: object
  10315. } );
  10316. }
  10317. }
  10318. class Group extends Object3D {
  10319. constructor() {
  10320. super();
  10321. this.isGroup = true;
  10322. this.type = 'Group';
  10323. }
  10324. }
  10325. class VideoTexture extends Texture {
  10326. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10327. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10328. this.isVideoTexture = true;
  10329. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10330. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10331. this.generateMipmaps = false;
  10332. const scope = this;
  10333. function updateVideo() {
  10334. scope.needsUpdate = true;
  10335. video.requestVideoFrameCallback( updateVideo );
  10336. }
  10337. if ( 'requestVideoFrameCallback' in video ) {
  10338. video.requestVideoFrameCallback( updateVideo );
  10339. }
  10340. }
  10341. clone() {
  10342. return new this.constructor( this.image ).copy( this );
  10343. }
  10344. update() {
  10345. const video = this.image;
  10346. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10347. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10348. this.needsUpdate = true;
  10349. }
  10350. }
  10351. }
  10352. class FramebufferTexture extends Texture {
  10353. constructor( width, height ) {
  10354. super( { width, height } );
  10355. this.isFramebufferTexture = true;
  10356. this.magFilter = NearestFilter;
  10357. this.minFilter = NearestFilter;
  10358. this.generateMipmaps = false;
  10359. this.needsUpdate = true;
  10360. }
  10361. }
  10362. class CompressedTexture extends Texture {
  10363. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10364. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10365. this.isCompressedTexture = true;
  10366. this.image = { width: width, height: height };
  10367. this.mipmaps = mipmaps;
  10368. // no flipping for cube textures
  10369. // (also flipping doesn't work for compressed textures )
  10370. this.flipY = false;
  10371. // can't generate mipmaps for compressed textures
  10372. // mips must be embedded in DDS files
  10373. this.generateMipmaps = false;
  10374. }
  10375. }
  10376. class CompressedArrayTexture extends CompressedTexture {
  10377. constructor( mipmaps, width, height, depth, format, type ) {
  10378. super( mipmaps, width, height, format, type );
  10379. this.isCompressedArrayTexture = true;
  10380. this.image.depth = depth;
  10381. this.wrapR = ClampToEdgeWrapping;
  10382. this.layerUpdates = new Set();
  10383. }
  10384. addLayerUpdate( layerIndex ) {
  10385. this.layerUpdates.add( layerIndex );
  10386. }
  10387. clearLayerUpdates() {
  10388. this.layerUpdates.clear();
  10389. }
  10390. }
  10391. class CompressedCubeTexture extends CompressedTexture {
  10392. constructor( images, format, type ) {
  10393. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10394. this.isCompressedCubeTexture = true;
  10395. this.isCubeTexture = true;
  10396. this.image = images;
  10397. }
  10398. }
  10399. class CanvasTexture extends Texture {
  10400. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10401. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10402. this.isCanvasTexture = true;
  10403. this.needsUpdate = true;
  10404. }
  10405. }
  10406. class DepthTexture extends Texture {
  10407. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10408. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10409. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10410. }
  10411. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10412. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10413. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10414. this.isDepthTexture = true;
  10415. this.image = { width: width, height: height };
  10416. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10417. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10418. this.flipY = false;
  10419. this.generateMipmaps = false;
  10420. this.compareFunction = null;
  10421. }
  10422. copy( source ) {
  10423. super.copy( source );
  10424. this.compareFunction = source.compareFunction;
  10425. return this;
  10426. }
  10427. toJSON( meta ) {
  10428. const data = super.toJSON( meta );
  10429. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10430. return data;
  10431. }
  10432. }
  10433. /**
  10434. * Extensible curve object.
  10435. *
  10436. * Some common of curve methods:
  10437. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10438. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10439. * .getPoints(), .getSpacedPoints()
  10440. * .getLength()
  10441. * .updateArcLengths()
  10442. *
  10443. * This following curves inherit from THREE.Curve:
  10444. *
  10445. * -- 2D curves --
  10446. * THREE.ArcCurve
  10447. * THREE.CubicBezierCurve
  10448. * THREE.EllipseCurve
  10449. * THREE.LineCurve
  10450. * THREE.QuadraticBezierCurve
  10451. * THREE.SplineCurve
  10452. *
  10453. * -- 3D curves --
  10454. * THREE.CatmullRomCurve3
  10455. * THREE.CubicBezierCurve3
  10456. * THREE.LineCurve3
  10457. * THREE.QuadraticBezierCurve3
  10458. *
  10459. * A series of curves can be represented as a THREE.CurvePath.
  10460. *
  10461. **/
  10462. class Curve {
  10463. constructor() {
  10464. this.type = 'Curve';
  10465. this.arcLengthDivisions = 200;
  10466. }
  10467. // Virtual base class method to overwrite and implement in subclasses
  10468. // - t [0 .. 1]
  10469. getPoint( /* t, optionalTarget */ ) {
  10470. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10471. return null;
  10472. }
  10473. // Get point at relative position in curve according to arc length
  10474. // - u [0 .. 1]
  10475. getPointAt( u, optionalTarget ) {
  10476. const t = this.getUtoTmapping( u );
  10477. return this.getPoint( t, optionalTarget );
  10478. }
  10479. // Get sequence of points using getPoint( t )
  10480. getPoints( divisions = 5 ) {
  10481. const points = [];
  10482. for ( let d = 0; d <= divisions; d ++ ) {
  10483. points.push( this.getPoint( d / divisions ) );
  10484. }
  10485. return points;
  10486. }
  10487. // Get sequence of points using getPointAt( u )
  10488. getSpacedPoints( divisions = 5 ) {
  10489. const points = [];
  10490. for ( let d = 0; d <= divisions; d ++ ) {
  10491. points.push( this.getPointAt( d / divisions ) );
  10492. }
  10493. return points;
  10494. }
  10495. // Get total curve arc length
  10496. getLength() {
  10497. const lengths = this.getLengths();
  10498. return lengths[ lengths.length - 1 ];
  10499. }
  10500. // Get list of cumulative segment lengths
  10501. getLengths( divisions = this.arcLengthDivisions ) {
  10502. if ( this.cacheArcLengths &&
  10503. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10504. ! this.needsUpdate ) {
  10505. return this.cacheArcLengths;
  10506. }
  10507. this.needsUpdate = false;
  10508. const cache = [];
  10509. let current, last = this.getPoint( 0 );
  10510. let sum = 0;
  10511. cache.push( 0 );
  10512. for ( let p = 1; p <= divisions; p ++ ) {
  10513. current = this.getPoint( p / divisions );
  10514. sum += current.distanceTo( last );
  10515. cache.push( sum );
  10516. last = current;
  10517. }
  10518. this.cacheArcLengths = cache;
  10519. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10520. }
  10521. updateArcLengths() {
  10522. this.needsUpdate = true;
  10523. this.getLengths();
  10524. }
  10525. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10526. getUtoTmapping( u, distance ) {
  10527. const arcLengths = this.getLengths();
  10528. let i = 0;
  10529. const il = arcLengths.length;
  10530. let targetArcLength; // The targeted u distance value to get
  10531. if ( distance ) {
  10532. targetArcLength = distance;
  10533. } else {
  10534. targetArcLength = u * arcLengths[ il - 1 ];
  10535. }
  10536. // binary search for the index with largest value smaller than target u distance
  10537. let low = 0, high = il - 1, comparison;
  10538. while ( low <= high ) {
  10539. 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
  10540. comparison = arcLengths[ i ] - targetArcLength;
  10541. if ( comparison < 0 ) {
  10542. low = i + 1;
  10543. } else if ( comparison > 0 ) {
  10544. high = i - 1;
  10545. } else {
  10546. high = i;
  10547. break;
  10548. // DONE
  10549. }
  10550. }
  10551. i = high;
  10552. if ( arcLengths[ i ] === targetArcLength ) {
  10553. return i / ( il - 1 );
  10554. }
  10555. // we could get finer grain at lengths, or use simple interpolation between two points
  10556. const lengthBefore = arcLengths[ i ];
  10557. const lengthAfter = arcLengths[ i + 1 ];
  10558. const segmentLength = lengthAfter - lengthBefore;
  10559. // determine where we are between the 'before' and 'after' points
  10560. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10561. // add that fractional amount to t
  10562. const t = ( i + segmentFraction ) / ( il - 1 );
  10563. return t;
  10564. }
  10565. // Returns a unit vector tangent at t
  10566. // In case any sub curve does not implement its tangent derivation,
  10567. // 2 points a small delta apart will be used to find its gradient
  10568. // which seems to give a reasonable approximation
  10569. getTangent( t, optionalTarget ) {
  10570. const delta = 0.0001;
  10571. let t1 = t - delta;
  10572. let t2 = t + delta;
  10573. // Capping in case of danger
  10574. if ( t1 < 0 ) t1 = 0;
  10575. if ( t2 > 1 ) t2 = 1;
  10576. const pt1 = this.getPoint( t1 );
  10577. const pt2 = this.getPoint( t2 );
  10578. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10579. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10580. return tangent;
  10581. }
  10582. getTangentAt( u, optionalTarget ) {
  10583. const t = this.getUtoTmapping( u );
  10584. return this.getTangent( t, optionalTarget );
  10585. }
  10586. computeFrenetFrames( segments, closed ) {
  10587. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10588. const normal = new Vector3();
  10589. const tangents = [];
  10590. const normals = [];
  10591. const binormals = [];
  10592. const vec = new Vector3();
  10593. const mat = new Matrix4();
  10594. // compute the tangent vectors for each segment on the curve
  10595. for ( let i = 0; i <= segments; i ++ ) {
  10596. const u = i / segments;
  10597. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10598. }
  10599. // select an initial normal vector perpendicular to the first tangent vector,
  10600. // and in the direction of the minimum tangent xyz component
  10601. normals[ 0 ] = new Vector3();
  10602. binormals[ 0 ] = new Vector3();
  10603. let min = Number.MAX_VALUE;
  10604. const tx = Math.abs( tangents[ 0 ].x );
  10605. const ty = Math.abs( tangents[ 0 ].y );
  10606. const tz = Math.abs( tangents[ 0 ].z );
  10607. if ( tx <= min ) {
  10608. min = tx;
  10609. normal.set( 1, 0, 0 );
  10610. }
  10611. if ( ty <= min ) {
  10612. min = ty;
  10613. normal.set( 0, 1, 0 );
  10614. }
  10615. if ( tz <= min ) {
  10616. normal.set( 0, 0, 1 );
  10617. }
  10618. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10619. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10620. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10621. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10622. for ( let i = 1; i <= segments; i ++ ) {
  10623. normals[ i ] = normals[ i - 1 ].clone();
  10624. binormals[ i ] = binormals[ i - 1 ].clone();
  10625. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10626. if ( vec.length() > Number.EPSILON ) {
  10627. vec.normalize();
  10628. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10629. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10630. }
  10631. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10632. }
  10633. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10634. if ( closed === true ) {
  10635. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10636. theta /= segments;
  10637. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10638. theta = - theta;
  10639. }
  10640. for ( let i = 1; i <= segments; i ++ ) {
  10641. // twist a little...
  10642. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10643. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10644. }
  10645. }
  10646. return {
  10647. tangents: tangents,
  10648. normals: normals,
  10649. binormals: binormals
  10650. };
  10651. }
  10652. clone() {
  10653. return new this.constructor().copy( this );
  10654. }
  10655. copy( source ) {
  10656. this.arcLengthDivisions = source.arcLengthDivisions;
  10657. return this;
  10658. }
  10659. toJSON() {
  10660. const data = {
  10661. metadata: {
  10662. version: 4.6,
  10663. type: 'Curve',
  10664. generator: 'Curve.toJSON'
  10665. }
  10666. };
  10667. data.arcLengthDivisions = this.arcLengthDivisions;
  10668. data.type = this.type;
  10669. return data;
  10670. }
  10671. fromJSON( json ) {
  10672. this.arcLengthDivisions = json.arcLengthDivisions;
  10673. return this;
  10674. }
  10675. }
  10676. class EllipseCurve extends Curve {
  10677. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10678. super();
  10679. this.isEllipseCurve = true;
  10680. this.type = 'EllipseCurve';
  10681. this.aX = aX;
  10682. this.aY = aY;
  10683. this.xRadius = xRadius;
  10684. this.yRadius = yRadius;
  10685. this.aStartAngle = aStartAngle;
  10686. this.aEndAngle = aEndAngle;
  10687. this.aClockwise = aClockwise;
  10688. this.aRotation = aRotation;
  10689. }
  10690. getPoint( t, optionalTarget = new Vector2() ) {
  10691. const point = optionalTarget;
  10692. const twoPi = Math.PI * 2;
  10693. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10694. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10695. // ensures that deltaAngle is 0 .. 2 PI
  10696. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10697. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10698. if ( deltaAngle < Number.EPSILON ) {
  10699. if ( samePoints ) {
  10700. deltaAngle = 0;
  10701. } else {
  10702. deltaAngle = twoPi;
  10703. }
  10704. }
  10705. if ( this.aClockwise === true && ! samePoints ) {
  10706. if ( deltaAngle === twoPi ) {
  10707. deltaAngle = - twoPi;
  10708. } else {
  10709. deltaAngle = deltaAngle - twoPi;
  10710. }
  10711. }
  10712. const angle = this.aStartAngle + t * deltaAngle;
  10713. let x = this.aX + this.xRadius * Math.cos( angle );
  10714. let y = this.aY + this.yRadius * Math.sin( angle );
  10715. if ( this.aRotation !== 0 ) {
  10716. const cos = Math.cos( this.aRotation );
  10717. const sin = Math.sin( this.aRotation );
  10718. const tx = x - this.aX;
  10719. const ty = y - this.aY;
  10720. // Rotate the point about the center of the ellipse.
  10721. x = tx * cos - ty * sin + this.aX;
  10722. y = tx * sin + ty * cos + this.aY;
  10723. }
  10724. return point.set( x, y );
  10725. }
  10726. copy( source ) {
  10727. super.copy( source );
  10728. this.aX = source.aX;
  10729. this.aY = source.aY;
  10730. this.xRadius = source.xRadius;
  10731. this.yRadius = source.yRadius;
  10732. this.aStartAngle = source.aStartAngle;
  10733. this.aEndAngle = source.aEndAngle;
  10734. this.aClockwise = source.aClockwise;
  10735. this.aRotation = source.aRotation;
  10736. return this;
  10737. }
  10738. toJSON() {
  10739. const data = super.toJSON();
  10740. data.aX = this.aX;
  10741. data.aY = this.aY;
  10742. data.xRadius = this.xRadius;
  10743. data.yRadius = this.yRadius;
  10744. data.aStartAngle = this.aStartAngle;
  10745. data.aEndAngle = this.aEndAngle;
  10746. data.aClockwise = this.aClockwise;
  10747. data.aRotation = this.aRotation;
  10748. return data;
  10749. }
  10750. fromJSON( json ) {
  10751. super.fromJSON( json );
  10752. this.aX = json.aX;
  10753. this.aY = json.aY;
  10754. this.xRadius = json.xRadius;
  10755. this.yRadius = json.yRadius;
  10756. this.aStartAngle = json.aStartAngle;
  10757. this.aEndAngle = json.aEndAngle;
  10758. this.aClockwise = json.aClockwise;
  10759. this.aRotation = json.aRotation;
  10760. return this;
  10761. }
  10762. }
  10763. class ArcCurve extends EllipseCurve {
  10764. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10765. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10766. this.isArcCurve = true;
  10767. this.type = 'ArcCurve';
  10768. }
  10769. }
  10770. /**
  10771. * Centripetal CatmullRom Curve - which is useful for avoiding
  10772. * cusps and self-intersections in non-uniform catmull rom curves.
  10773. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10774. *
  10775. * curve.type accepts centripetal(default), chordal and catmullrom
  10776. * curve.tension is used for catmullrom which defaults to 0.5
  10777. */
  10778. /*
  10779. Based on an optimized c++ solution in
  10780. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10781. - http://ideone.com/NoEbVM
  10782. This CubicPoly class could be used for reusing some variables and calculations,
  10783. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10784. which can be placed in CurveUtils.
  10785. */
  10786. function CubicPoly() {
  10787. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10788. /*
  10789. * Compute coefficients for a cubic polynomial
  10790. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10791. * such that
  10792. * p(0) = x0, p(1) = x1
  10793. * and
  10794. * p'(0) = t0, p'(1) = t1.
  10795. */
  10796. function init( x0, x1, t0, t1 ) {
  10797. c0 = x0;
  10798. c1 = t0;
  10799. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10800. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10801. }
  10802. return {
  10803. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10804. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10805. },
  10806. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10807. // compute tangents when parameterized in [t1,t2]
  10808. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10809. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10810. // rescale tangents for parametrization in [0,1]
  10811. t1 *= dt1;
  10812. t2 *= dt1;
  10813. init( x1, x2, t1, t2 );
  10814. },
  10815. calc: function ( t ) {
  10816. const t2 = t * t;
  10817. const t3 = t2 * t;
  10818. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10819. }
  10820. };
  10821. }
  10822. //
  10823. const tmp = /*@__PURE__*/ new Vector3();
  10824. const px = /*@__PURE__*/ new CubicPoly();
  10825. const py = /*@__PURE__*/ new CubicPoly();
  10826. const pz = /*@__PURE__*/ new CubicPoly();
  10827. class CatmullRomCurve3 extends Curve {
  10828. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10829. super();
  10830. this.isCatmullRomCurve3 = true;
  10831. this.type = 'CatmullRomCurve3';
  10832. this.points = points;
  10833. this.closed = closed;
  10834. this.curveType = curveType;
  10835. this.tension = tension;
  10836. }
  10837. getPoint( t, optionalTarget = new Vector3() ) {
  10838. const point = optionalTarget;
  10839. const points = this.points;
  10840. const l = points.length;
  10841. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10842. let intPoint = Math.floor( p );
  10843. let weight = p - intPoint;
  10844. if ( this.closed ) {
  10845. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10846. } else if ( weight === 0 && intPoint === l - 1 ) {
  10847. intPoint = l - 2;
  10848. weight = 1;
  10849. }
  10850. let p0, p3; // 4 points (p1 & p2 defined below)
  10851. if ( this.closed || intPoint > 0 ) {
  10852. p0 = points[ ( intPoint - 1 ) % l ];
  10853. } else {
  10854. // extrapolate first point
  10855. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10856. p0 = tmp;
  10857. }
  10858. const p1 = points[ intPoint % l ];
  10859. const p2 = points[ ( intPoint + 1 ) % l ];
  10860. if ( this.closed || intPoint + 2 < l ) {
  10861. p3 = points[ ( intPoint + 2 ) % l ];
  10862. } else {
  10863. // extrapolate last point
  10864. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10865. p3 = tmp;
  10866. }
  10867. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10868. // init Centripetal / Chordal Catmull-Rom
  10869. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10870. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10871. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10872. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10873. // safety check for repeated points
  10874. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10875. if ( dt0 < 1e-4 ) dt0 = dt1;
  10876. if ( dt2 < 1e-4 ) dt2 = dt1;
  10877. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10878. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10879. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10880. } else if ( this.curveType === 'catmullrom' ) {
  10881. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10882. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10883. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10884. }
  10885. point.set(
  10886. px.calc( weight ),
  10887. py.calc( weight ),
  10888. pz.calc( weight )
  10889. );
  10890. return point;
  10891. }
  10892. copy( source ) {
  10893. super.copy( source );
  10894. this.points = [];
  10895. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10896. const point = source.points[ i ];
  10897. this.points.push( point.clone() );
  10898. }
  10899. this.closed = source.closed;
  10900. this.curveType = source.curveType;
  10901. this.tension = source.tension;
  10902. return this;
  10903. }
  10904. toJSON() {
  10905. const data = super.toJSON();
  10906. data.points = [];
  10907. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10908. const point = this.points[ i ];
  10909. data.points.push( point.toArray() );
  10910. }
  10911. data.closed = this.closed;
  10912. data.curveType = this.curveType;
  10913. data.tension = this.tension;
  10914. return data;
  10915. }
  10916. fromJSON( json ) {
  10917. super.fromJSON( json );
  10918. this.points = [];
  10919. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10920. const point = json.points[ i ];
  10921. this.points.push( new Vector3().fromArray( point ) );
  10922. }
  10923. this.closed = json.closed;
  10924. this.curveType = json.curveType;
  10925. this.tension = json.tension;
  10926. return this;
  10927. }
  10928. }
  10929. /**
  10930. * Bezier Curves formulas obtained from
  10931. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10932. */
  10933. function CatmullRom( t, p0, p1, p2, p3 ) {
  10934. const v0 = ( p2 - p0 ) * 0.5;
  10935. const v1 = ( p3 - p1 ) * 0.5;
  10936. const t2 = t * t;
  10937. const t3 = t * t2;
  10938. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10939. }
  10940. //
  10941. function QuadraticBezierP0( t, p ) {
  10942. const k = 1 - t;
  10943. return k * k * p;
  10944. }
  10945. function QuadraticBezierP1( t, p ) {
  10946. return 2 * ( 1 - t ) * t * p;
  10947. }
  10948. function QuadraticBezierP2( t, p ) {
  10949. return t * t * p;
  10950. }
  10951. function QuadraticBezier( t, p0, p1, p2 ) {
  10952. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10953. QuadraticBezierP2( t, p2 );
  10954. }
  10955. //
  10956. function CubicBezierP0( t, p ) {
  10957. const k = 1 - t;
  10958. return k * k * k * p;
  10959. }
  10960. function CubicBezierP1( t, p ) {
  10961. const k = 1 - t;
  10962. return 3 * k * k * t * p;
  10963. }
  10964. function CubicBezierP2( t, p ) {
  10965. return 3 * ( 1 - t ) * t * t * p;
  10966. }
  10967. function CubicBezierP3( t, p ) {
  10968. return t * t * t * p;
  10969. }
  10970. function CubicBezier( t, p0, p1, p2, p3 ) {
  10971. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10972. CubicBezierP3( t, p3 );
  10973. }
  10974. class CubicBezierCurve extends Curve {
  10975. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10976. super();
  10977. this.isCubicBezierCurve = true;
  10978. this.type = 'CubicBezierCurve';
  10979. this.v0 = v0;
  10980. this.v1 = v1;
  10981. this.v2 = v2;
  10982. this.v3 = v3;
  10983. }
  10984. getPoint( t, optionalTarget = new Vector2() ) {
  10985. const point = optionalTarget;
  10986. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10987. point.set(
  10988. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10989. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10990. );
  10991. return point;
  10992. }
  10993. copy( source ) {
  10994. super.copy( source );
  10995. this.v0.copy( source.v0 );
  10996. this.v1.copy( source.v1 );
  10997. this.v2.copy( source.v2 );
  10998. this.v3.copy( source.v3 );
  10999. return this;
  11000. }
  11001. toJSON() {
  11002. const data = super.toJSON();
  11003. data.v0 = this.v0.toArray();
  11004. data.v1 = this.v1.toArray();
  11005. data.v2 = this.v2.toArray();
  11006. data.v3 = this.v3.toArray();
  11007. return data;
  11008. }
  11009. fromJSON( json ) {
  11010. super.fromJSON( json );
  11011. this.v0.fromArray( json.v0 );
  11012. this.v1.fromArray( json.v1 );
  11013. this.v2.fromArray( json.v2 );
  11014. this.v3.fromArray( json.v3 );
  11015. return this;
  11016. }
  11017. }
  11018. class CubicBezierCurve3 extends Curve {
  11019. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  11020. super();
  11021. this.isCubicBezierCurve3 = true;
  11022. this.type = 'CubicBezierCurve3';
  11023. this.v0 = v0;
  11024. this.v1 = v1;
  11025. this.v2 = v2;
  11026. this.v3 = v3;
  11027. }
  11028. getPoint( t, optionalTarget = new Vector3() ) {
  11029. const point = optionalTarget;
  11030. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  11031. point.set(
  11032. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  11033. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  11034. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  11035. );
  11036. return point;
  11037. }
  11038. copy( source ) {
  11039. super.copy( source );
  11040. this.v0.copy( source.v0 );
  11041. this.v1.copy( source.v1 );
  11042. this.v2.copy( source.v2 );
  11043. this.v3.copy( source.v3 );
  11044. return this;
  11045. }
  11046. toJSON() {
  11047. const data = super.toJSON();
  11048. data.v0 = this.v0.toArray();
  11049. data.v1 = this.v1.toArray();
  11050. data.v2 = this.v2.toArray();
  11051. data.v3 = this.v3.toArray();
  11052. return data;
  11053. }
  11054. fromJSON( json ) {
  11055. super.fromJSON( json );
  11056. this.v0.fromArray( json.v0 );
  11057. this.v1.fromArray( json.v1 );
  11058. this.v2.fromArray( json.v2 );
  11059. this.v3.fromArray( json.v3 );
  11060. return this;
  11061. }
  11062. }
  11063. class LineCurve extends Curve {
  11064. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  11065. super();
  11066. this.isLineCurve = true;
  11067. this.type = 'LineCurve';
  11068. this.v1 = v1;
  11069. this.v2 = v2;
  11070. }
  11071. getPoint( t, optionalTarget = new Vector2() ) {
  11072. const point = optionalTarget;
  11073. if ( t === 1 ) {
  11074. point.copy( this.v2 );
  11075. } else {
  11076. point.copy( this.v2 ).sub( this.v1 );
  11077. point.multiplyScalar( t ).add( this.v1 );
  11078. }
  11079. return point;
  11080. }
  11081. // Line curve is linear, so we can overwrite default getPointAt
  11082. getPointAt( u, optionalTarget ) {
  11083. return this.getPoint( u, optionalTarget );
  11084. }
  11085. getTangent( t, optionalTarget = new Vector2() ) {
  11086. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11087. }
  11088. getTangentAt( u, optionalTarget ) {
  11089. return this.getTangent( u, optionalTarget );
  11090. }
  11091. copy( source ) {
  11092. super.copy( source );
  11093. this.v1.copy( source.v1 );
  11094. this.v2.copy( source.v2 );
  11095. return this;
  11096. }
  11097. toJSON() {
  11098. const data = super.toJSON();
  11099. data.v1 = this.v1.toArray();
  11100. data.v2 = this.v2.toArray();
  11101. return data;
  11102. }
  11103. fromJSON( json ) {
  11104. super.fromJSON( json );
  11105. this.v1.fromArray( json.v1 );
  11106. this.v2.fromArray( json.v2 );
  11107. return this;
  11108. }
  11109. }
  11110. class LineCurve3 extends Curve {
  11111. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  11112. super();
  11113. this.isLineCurve3 = true;
  11114. this.type = 'LineCurve3';
  11115. this.v1 = v1;
  11116. this.v2 = v2;
  11117. }
  11118. getPoint( t, optionalTarget = new Vector3() ) {
  11119. const point = optionalTarget;
  11120. if ( t === 1 ) {
  11121. point.copy( this.v2 );
  11122. } else {
  11123. point.copy( this.v2 ).sub( this.v1 );
  11124. point.multiplyScalar( t ).add( this.v1 );
  11125. }
  11126. return point;
  11127. }
  11128. // Line curve is linear, so we can overwrite default getPointAt
  11129. getPointAt( u, optionalTarget ) {
  11130. return this.getPoint( u, optionalTarget );
  11131. }
  11132. getTangent( t, optionalTarget = new Vector3() ) {
  11133. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11134. }
  11135. getTangentAt( u, optionalTarget ) {
  11136. return this.getTangent( u, optionalTarget );
  11137. }
  11138. copy( source ) {
  11139. super.copy( source );
  11140. this.v1.copy( source.v1 );
  11141. this.v2.copy( source.v2 );
  11142. return this;
  11143. }
  11144. toJSON() {
  11145. const data = super.toJSON();
  11146. data.v1 = this.v1.toArray();
  11147. data.v2 = this.v2.toArray();
  11148. return data;
  11149. }
  11150. fromJSON( json ) {
  11151. super.fromJSON( json );
  11152. this.v1.fromArray( json.v1 );
  11153. this.v2.fromArray( json.v2 );
  11154. return this;
  11155. }
  11156. }
  11157. class QuadraticBezierCurve extends Curve {
  11158. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  11159. super();
  11160. this.isQuadraticBezierCurve = true;
  11161. this.type = 'QuadraticBezierCurve';
  11162. this.v0 = v0;
  11163. this.v1 = v1;
  11164. this.v2 = v2;
  11165. }
  11166. getPoint( t, optionalTarget = new Vector2() ) {
  11167. const point = optionalTarget;
  11168. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11169. point.set(
  11170. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11171. QuadraticBezier( t, v0.y, v1.y, v2.y )
  11172. );
  11173. return point;
  11174. }
  11175. copy( source ) {
  11176. super.copy( source );
  11177. this.v0.copy( source.v0 );
  11178. this.v1.copy( source.v1 );
  11179. this.v2.copy( source.v2 );
  11180. return this;
  11181. }
  11182. toJSON() {
  11183. const data = super.toJSON();
  11184. data.v0 = this.v0.toArray();
  11185. data.v1 = this.v1.toArray();
  11186. data.v2 = this.v2.toArray();
  11187. return data;
  11188. }
  11189. fromJSON( json ) {
  11190. super.fromJSON( json );
  11191. this.v0.fromArray( json.v0 );
  11192. this.v1.fromArray( json.v1 );
  11193. this.v2.fromArray( json.v2 );
  11194. return this;
  11195. }
  11196. }
  11197. class QuadraticBezierCurve3 extends Curve {
  11198. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  11199. super();
  11200. this.isQuadraticBezierCurve3 = true;
  11201. this.type = 'QuadraticBezierCurve3';
  11202. this.v0 = v0;
  11203. this.v1 = v1;
  11204. this.v2 = v2;
  11205. }
  11206. getPoint( t, optionalTarget = new Vector3() ) {
  11207. const point = optionalTarget;
  11208. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11209. point.set(
  11210. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11211. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  11212. QuadraticBezier( t, v0.z, v1.z, v2.z )
  11213. );
  11214. return point;
  11215. }
  11216. copy( source ) {
  11217. super.copy( source );
  11218. this.v0.copy( source.v0 );
  11219. this.v1.copy( source.v1 );
  11220. this.v2.copy( source.v2 );
  11221. return this;
  11222. }
  11223. toJSON() {
  11224. const data = super.toJSON();
  11225. data.v0 = this.v0.toArray();
  11226. data.v1 = this.v1.toArray();
  11227. data.v2 = this.v2.toArray();
  11228. return data;
  11229. }
  11230. fromJSON( json ) {
  11231. super.fromJSON( json );
  11232. this.v0.fromArray( json.v0 );
  11233. this.v1.fromArray( json.v1 );
  11234. this.v2.fromArray( json.v2 );
  11235. return this;
  11236. }
  11237. }
  11238. class SplineCurve extends Curve {
  11239. constructor( points = [] ) {
  11240. super();
  11241. this.isSplineCurve = true;
  11242. this.type = 'SplineCurve';
  11243. this.points = points;
  11244. }
  11245. getPoint( t, optionalTarget = new Vector2() ) {
  11246. const point = optionalTarget;
  11247. const points = this.points;
  11248. const p = ( points.length - 1 ) * t;
  11249. const intPoint = Math.floor( p );
  11250. const weight = p - intPoint;
  11251. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  11252. const p1 = points[ intPoint ];
  11253. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  11254. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  11255. point.set(
  11256. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  11257. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  11258. );
  11259. return point;
  11260. }
  11261. copy( source ) {
  11262. super.copy( source );
  11263. this.points = [];
  11264. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  11265. const point = source.points[ i ];
  11266. this.points.push( point.clone() );
  11267. }
  11268. return this;
  11269. }
  11270. toJSON() {
  11271. const data = super.toJSON();
  11272. data.points = [];
  11273. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11274. const point = this.points[ i ];
  11275. data.points.push( point.toArray() );
  11276. }
  11277. return data;
  11278. }
  11279. fromJSON( json ) {
  11280. super.fromJSON( json );
  11281. this.points = [];
  11282. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11283. const point = json.points[ i ];
  11284. this.points.push( new Vector2().fromArray( point ) );
  11285. }
  11286. return this;
  11287. }
  11288. }
  11289. var Curves = /*#__PURE__*/Object.freeze({
  11290. __proto__: null,
  11291. ArcCurve: ArcCurve,
  11292. CatmullRomCurve3: CatmullRomCurve3,
  11293. CubicBezierCurve: CubicBezierCurve,
  11294. CubicBezierCurve3: CubicBezierCurve3,
  11295. EllipseCurve: EllipseCurve,
  11296. LineCurve: LineCurve,
  11297. LineCurve3: LineCurve3,
  11298. QuadraticBezierCurve: QuadraticBezierCurve,
  11299. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11300. SplineCurve: SplineCurve
  11301. });
  11302. /**************************************************************
  11303. * Curved Path - a curve path is simply a array of connected
  11304. * curves, but retains the api of a curve
  11305. **************************************************************/
  11306. class CurvePath extends Curve {
  11307. constructor() {
  11308. super();
  11309. this.type = 'CurvePath';
  11310. this.curves = [];
  11311. this.autoClose = false; // Automatically closes the path
  11312. }
  11313. add( curve ) {
  11314. this.curves.push( curve );
  11315. }
  11316. closePath() {
  11317. // Add a line curve if start and end of lines are not connected
  11318. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11319. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11320. if ( ! startPoint.equals( endPoint ) ) {
  11321. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11322. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11323. }
  11324. return this;
  11325. }
  11326. // To get accurate point with reference to
  11327. // entire path distance at time t,
  11328. // following has to be done:
  11329. // 1. Length of each sub path have to be known
  11330. // 2. Locate and identify type of curve
  11331. // 3. Get t for the curve
  11332. // 4. Return curve.getPointAt(t')
  11333. getPoint( t, optionalTarget ) {
  11334. const d = t * this.getLength();
  11335. const curveLengths = this.getCurveLengths();
  11336. let i = 0;
  11337. // To think about boundaries points.
  11338. while ( i < curveLengths.length ) {
  11339. if ( curveLengths[ i ] >= d ) {
  11340. const diff = curveLengths[ i ] - d;
  11341. const curve = this.curves[ i ];
  11342. const segmentLength = curve.getLength();
  11343. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11344. return curve.getPointAt( u, optionalTarget );
  11345. }
  11346. i ++;
  11347. }
  11348. return null;
  11349. // loop where sum != 0, sum > d , sum+1 <d
  11350. }
  11351. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11352. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11353. // getPoint() depends on getLength
  11354. getLength() {
  11355. const lens = this.getCurveLengths();
  11356. return lens[ lens.length - 1 ];
  11357. }
  11358. // cacheLengths must be recalculated.
  11359. updateArcLengths() {
  11360. this.needsUpdate = true;
  11361. this.cacheLengths = null;
  11362. this.getCurveLengths();
  11363. }
  11364. // Compute lengths and cache them
  11365. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11366. getCurveLengths() {
  11367. // We use cache values if curves and cache array are same length
  11368. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11369. return this.cacheLengths;
  11370. }
  11371. // Get length of sub-curve
  11372. // Push sums into cached array
  11373. const lengths = [];
  11374. let sums = 0;
  11375. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11376. sums += this.curves[ i ].getLength();
  11377. lengths.push( sums );
  11378. }
  11379. this.cacheLengths = lengths;
  11380. return lengths;
  11381. }
  11382. getSpacedPoints( divisions = 40 ) {
  11383. const points = [];
  11384. for ( let i = 0; i <= divisions; i ++ ) {
  11385. points.push( this.getPoint( i / divisions ) );
  11386. }
  11387. if ( this.autoClose ) {
  11388. points.push( points[ 0 ] );
  11389. }
  11390. return points;
  11391. }
  11392. getPoints( divisions = 12 ) {
  11393. const points = [];
  11394. let last;
  11395. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11396. const curve = curves[ i ];
  11397. const resolution = curve.isEllipseCurve ? divisions * 2
  11398. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11399. : curve.isSplineCurve ? divisions * curve.points.length
  11400. : divisions;
  11401. const pts = curve.getPoints( resolution );
  11402. for ( let j = 0; j < pts.length; j ++ ) {
  11403. const point = pts[ j ];
  11404. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11405. points.push( point );
  11406. last = point;
  11407. }
  11408. }
  11409. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11410. points.push( points[ 0 ] );
  11411. }
  11412. return points;
  11413. }
  11414. copy( source ) {
  11415. super.copy( source );
  11416. this.curves = [];
  11417. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11418. const curve = source.curves[ i ];
  11419. this.curves.push( curve.clone() );
  11420. }
  11421. this.autoClose = source.autoClose;
  11422. return this;
  11423. }
  11424. toJSON() {
  11425. const data = super.toJSON();
  11426. data.autoClose = this.autoClose;
  11427. data.curves = [];
  11428. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11429. const curve = this.curves[ i ];
  11430. data.curves.push( curve.toJSON() );
  11431. }
  11432. return data;
  11433. }
  11434. fromJSON( json ) {
  11435. super.fromJSON( json );
  11436. this.autoClose = json.autoClose;
  11437. this.curves = [];
  11438. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11439. const curve = json.curves[ i ];
  11440. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11441. }
  11442. return this;
  11443. }
  11444. }
  11445. class Path extends CurvePath {
  11446. constructor( points ) {
  11447. super();
  11448. this.type = 'Path';
  11449. this.currentPoint = new Vector2();
  11450. if ( points ) {
  11451. this.setFromPoints( points );
  11452. }
  11453. }
  11454. setFromPoints( points ) {
  11455. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11456. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11457. this.lineTo( points[ i ].x, points[ i ].y );
  11458. }
  11459. return this;
  11460. }
  11461. moveTo( x, y ) {
  11462. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11463. return this;
  11464. }
  11465. lineTo( x, y ) {
  11466. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11467. this.curves.push( curve );
  11468. this.currentPoint.set( x, y );
  11469. return this;
  11470. }
  11471. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11472. const curve = new QuadraticBezierCurve(
  11473. this.currentPoint.clone(),
  11474. new Vector2( aCPx, aCPy ),
  11475. new Vector2( aX, aY )
  11476. );
  11477. this.curves.push( curve );
  11478. this.currentPoint.set( aX, aY );
  11479. return this;
  11480. }
  11481. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11482. const curve = new CubicBezierCurve(
  11483. this.currentPoint.clone(),
  11484. new Vector2( aCP1x, aCP1y ),
  11485. new Vector2( aCP2x, aCP2y ),
  11486. new Vector2( aX, aY )
  11487. );
  11488. this.curves.push( curve );
  11489. this.currentPoint.set( aX, aY );
  11490. return this;
  11491. }
  11492. splineThru( pts /*Array of Vector*/ ) {
  11493. const npts = [ this.currentPoint.clone() ].concat( pts );
  11494. const curve = new SplineCurve( npts );
  11495. this.curves.push( curve );
  11496. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11497. return this;
  11498. }
  11499. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11500. const x0 = this.currentPoint.x;
  11501. const y0 = this.currentPoint.y;
  11502. this.absarc( aX + x0, aY + y0, aRadius,
  11503. aStartAngle, aEndAngle, aClockwise );
  11504. return this;
  11505. }
  11506. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11507. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11508. return this;
  11509. }
  11510. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11511. const x0 = this.currentPoint.x;
  11512. const y0 = this.currentPoint.y;
  11513. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11514. return this;
  11515. }
  11516. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11517. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11518. if ( this.curves.length > 0 ) {
  11519. // if a previous curve is present, attempt to join
  11520. const firstPoint = curve.getPoint( 0 );
  11521. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11522. this.lineTo( firstPoint.x, firstPoint.y );
  11523. }
  11524. }
  11525. this.curves.push( curve );
  11526. const lastPoint = curve.getPoint( 1 );
  11527. this.currentPoint.copy( lastPoint );
  11528. return this;
  11529. }
  11530. copy( source ) {
  11531. super.copy( source );
  11532. this.currentPoint.copy( source.currentPoint );
  11533. return this;
  11534. }
  11535. toJSON() {
  11536. const data = super.toJSON();
  11537. data.currentPoint = this.currentPoint.toArray();
  11538. return data;
  11539. }
  11540. fromJSON( json ) {
  11541. super.fromJSON( json );
  11542. this.currentPoint.fromArray( json.currentPoint );
  11543. return this;
  11544. }
  11545. }
  11546. class LatheGeometry extends BufferGeometry {
  11547. 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 ) {
  11548. super();
  11549. this.type = 'LatheGeometry';
  11550. this.parameters = {
  11551. points: points,
  11552. segments: segments,
  11553. phiStart: phiStart,
  11554. phiLength: phiLength
  11555. };
  11556. segments = Math.floor( segments );
  11557. // clamp phiLength so it's in range of [ 0, 2PI ]
  11558. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  11559. // buffers
  11560. const indices = [];
  11561. const vertices = [];
  11562. const uvs = [];
  11563. const initNormals = [];
  11564. const normals = [];
  11565. // helper variables
  11566. const inverseSegments = 1.0 / segments;
  11567. const vertex = new Vector3();
  11568. const uv = new Vector2();
  11569. const normal = new Vector3();
  11570. const curNormal = new Vector3();
  11571. const prevNormal = new Vector3();
  11572. let dx = 0;
  11573. let dy = 0;
  11574. // pre-compute normals for initial "meridian"
  11575. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11576. switch ( j ) {
  11577. case 0: // special handling for 1st vertex on path
  11578. dx = points[ j + 1 ].x - points[ j ].x;
  11579. dy = points[ j + 1 ].y - points[ j ].y;
  11580. normal.x = dy * 1.0;
  11581. normal.y = - dx;
  11582. normal.z = dy * 0.0;
  11583. prevNormal.copy( normal );
  11584. normal.normalize();
  11585. initNormals.push( normal.x, normal.y, normal.z );
  11586. break;
  11587. case ( points.length - 1 ): // special handling for last Vertex on path
  11588. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11589. break;
  11590. default: // default handling for all vertices in between
  11591. dx = points[ j + 1 ].x - points[ j ].x;
  11592. dy = points[ j + 1 ].y - points[ j ].y;
  11593. normal.x = dy * 1.0;
  11594. normal.y = - dx;
  11595. normal.z = dy * 0.0;
  11596. curNormal.copy( normal );
  11597. normal.x += prevNormal.x;
  11598. normal.y += prevNormal.y;
  11599. normal.z += prevNormal.z;
  11600. normal.normalize();
  11601. initNormals.push( normal.x, normal.y, normal.z );
  11602. prevNormal.copy( curNormal );
  11603. }
  11604. }
  11605. // generate vertices, uvs and normals
  11606. for ( let i = 0; i <= segments; i ++ ) {
  11607. const phi = phiStart + i * inverseSegments * phiLength;
  11608. const sin = Math.sin( phi );
  11609. const cos = Math.cos( phi );
  11610. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11611. // vertex
  11612. vertex.x = points[ j ].x * sin;
  11613. vertex.y = points[ j ].y;
  11614. vertex.z = points[ j ].x * cos;
  11615. vertices.push( vertex.x, vertex.y, vertex.z );
  11616. // uv
  11617. uv.x = i / segments;
  11618. uv.y = j / ( points.length - 1 );
  11619. uvs.push( uv.x, uv.y );
  11620. // normal
  11621. const x = initNormals[ 3 * j + 0 ] * sin;
  11622. const y = initNormals[ 3 * j + 1 ];
  11623. const z = initNormals[ 3 * j + 0 ] * cos;
  11624. normals.push( x, y, z );
  11625. }
  11626. }
  11627. // indices
  11628. for ( let i = 0; i < segments; i ++ ) {
  11629. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11630. const base = j + i * points.length;
  11631. const a = base;
  11632. const b = base + points.length;
  11633. const c = base + points.length + 1;
  11634. const d = base + 1;
  11635. // faces
  11636. indices.push( a, b, d );
  11637. indices.push( c, d, b );
  11638. }
  11639. }
  11640. // build geometry
  11641. this.setIndex( indices );
  11642. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11643. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11644. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11645. }
  11646. copy( source ) {
  11647. super.copy( source );
  11648. this.parameters = Object.assign( {}, source.parameters );
  11649. return this;
  11650. }
  11651. static fromJSON( data ) {
  11652. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11653. }
  11654. }
  11655. class CapsuleGeometry extends LatheGeometry {
  11656. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11657. const path = new Path();
  11658. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11659. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11660. super( path.getPoints( capSegments ), radialSegments );
  11661. this.type = 'CapsuleGeometry';
  11662. this.parameters = {
  11663. radius: radius,
  11664. length: length,
  11665. capSegments: capSegments,
  11666. radialSegments: radialSegments,
  11667. };
  11668. }
  11669. static fromJSON( data ) {
  11670. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11671. }
  11672. }
  11673. class CircleGeometry extends BufferGeometry {
  11674. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11675. super();
  11676. this.type = 'CircleGeometry';
  11677. this.parameters = {
  11678. radius: radius,
  11679. segments: segments,
  11680. thetaStart: thetaStart,
  11681. thetaLength: thetaLength
  11682. };
  11683. segments = Math.max( 3, segments );
  11684. // buffers
  11685. const indices = [];
  11686. const vertices = [];
  11687. const normals = [];
  11688. const uvs = [];
  11689. // helper variables
  11690. const vertex = new Vector3();
  11691. const uv = new Vector2();
  11692. // center point
  11693. vertices.push( 0, 0, 0 );
  11694. normals.push( 0, 0, 1 );
  11695. uvs.push( 0.5, 0.5 );
  11696. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11697. const segment = thetaStart + s / segments * thetaLength;
  11698. // vertex
  11699. vertex.x = radius * Math.cos( segment );
  11700. vertex.y = radius * Math.sin( segment );
  11701. vertices.push( vertex.x, vertex.y, vertex.z );
  11702. // normal
  11703. normals.push( 0, 0, 1 );
  11704. // uvs
  11705. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11706. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11707. uvs.push( uv.x, uv.y );
  11708. }
  11709. // indices
  11710. for ( let i = 1; i <= segments; i ++ ) {
  11711. indices.push( i, i + 1, 0 );
  11712. }
  11713. // build geometry
  11714. this.setIndex( indices );
  11715. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11716. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11717. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11718. }
  11719. copy( source ) {
  11720. super.copy( source );
  11721. this.parameters = Object.assign( {}, source.parameters );
  11722. return this;
  11723. }
  11724. static fromJSON( data ) {
  11725. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11726. }
  11727. }
  11728. class CylinderGeometry extends BufferGeometry {
  11729. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11730. super();
  11731. this.type = 'CylinderGeometry';
  11732. this.parameters = {
  11733. radiusTop: radiusTop,
  11734. radiusBottom: radiusBottom,
  11735. height: height,
  11736. radialSegments: radialSegments,
  11737. heightSegments: heightSegments,
  11738. openEnded: openEnded,
  11739. thetaStart: thetaStart,
  11740. thetaLength: thetaLength
  11741. };
  11742. const scope = this;
  11743. radialSegments = Math.floor( radialSegments );
  11744. heightSegments = Math.floor( heightSegments );
  11745. // buffers
  11746. const indices = [];
  11747. const vertices = [];
  11748. const normals = [];
  11749. const uvs = [];
  11750. // helper variables
  11751. let index = 0;
  11752. const indexArray = [];
  11753. const halfHeight = height / 2;
  11754. let groupStart = 0;
  11755. // generate geometry
  11756. generateTorso();
  11757. if ( openEnded === false ) {
  11758. if ( radiusTop > 0 ) generateCap( true );
  11759. if ( radiusBottom > 0 ) generateCap( false );
  11760. }
  11761. // build geometry
  11762. this.setIndex( indices );
  11763. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11764. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11765. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11766. function generateTorso() {
  11767. const normal = new Vector3();
  11768. const vertex = new Vector3();
  11769. let groupCount = 0;
  11770. // this will be used to calculate the normal
  11771. const slope = ( radiusBottom - radiusTop ) / height;
  11772. // generate vertices, normals and uvs
  11773. for ( let y = 0; y <= heightSegments; y ++ ) {
  11774. const indexRow = [];
  11775. const v = y / heightSegments;
  11776. // calculate the radius of the current row
  11777. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11778. for ( let x = 0; x <= radialSegments; x ++ ) {
  11779. const u = x / radialSegments;
  11780. const theta = u * thetaLength + thetaStart;
  11781. const sinTheta = Math.sin( theta );
  11782. const cosTheta = Math.cos( theta );
  11783. // vertex
  11784. vertex.x = radius * sinTheta;
  11785. vertex.y = - v * height + halfHeight;
  11786. vertex.z = radius * cosTheta;
  11787. vertices.push( vertex.x, vertex.y, vertex.z );
  11788. // normal
  11789. normal.set( sinTheta, slope, cosTheta ).normalize();
  11790. normals.push( normal.x, normal.y, normal.z );
  11791. // uv
  11792. uvs.push( u, 1 - v );
  11793. // save index of vertex in respective row
  11794. indexRow.push( index ++ );
  11795. }
  11796. // now save vertices of the row in our index array
  11797. indexArray.push( indexRow );
  11798. }
  11799. // generate indices
  11800. for ( let x = 0; x < radialSegments; x ++ ) {
  11801. for ( let y = 0; y < heightSegments; y ++ ) {
  11802. // we use the index array to access the correct indices
  11803. const a = indexArray[ y ][ x ];
  11804. const b = indexArray[ y + 1 ][ x ];
  11805. const c = indexArray[ y + 1 ][ x + 1 ];
  11806. const d = indexArray[ y ][ x + 1 ];
  11807. // faces
  11808. if ( radiusTop > 0 || y !== 0 ) {
  11809. indices.push( a, b, d );
  11810. groupCount += 3;
  11811. }
  11812. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  11813. indices.push( b, c, d );
  11814. groupCount += 3;
  11815. }
  11816. }
  11817. }
  11818. // add a group to the geometry. this will ensure multi material support
  11819. scope.addGroup( groupStart, groupCount, 0 );
  11820. // calculate new start value for groups
  11821. groupStart += groupCount;
  11822. }
  11823. function generateCap( top ) {
  11824. // save the index of the first center vertex
  11825. const centerIndexStart = index;
  11826. const uv = new Vector2();
  11827. const vertex = new Vector3();
  11828. let groupCount = 0;
  11829. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11830. const sign = ( top === true ) ? 1 : - 1;
  11831. // first we generate the center vertex data of the cap.
  11832. // because the geometry needs one set of uvs per face,
  11833. // we must generate a center vertex per face/segment
  11834. for ( let x = 1; x <= radialSegments; x ++ ) {
  11835. // vertex
  11836. vertices.push( 0, halfHeight * sign, 0 );
  11837. // normal
  11838. normals.push( 0, sign, 0 );
  11839. // uv
  11840. uvs.push( 0.5, 0.5 );
  11841. // increase index
  11842. index ++;
  11843. }
  11844. // save the index of the last center vertex
  11845. const centerIndexEnd = index;
  11846. // now we generate the surrounding vertices, normals and uvs
  11847. for ( let x = 0; x <= radialSegments; x ++ ) {
  11848. const u = x / radialSegments;
  11849. const theta = u * thetaLength + thetaStart;
  11850. const cosTheta = Math.cos( theta );
  11851. const sinTheta = Math.sin( theta );
  11852. // vertex
  11853. vertex.x = radius * sinTheta;
  11854. vertex.y = halfHeight * sign;
  11855. vertex.z = radius * cosTheta;
  11856. vertices.push( vertex.x, vertex.y, vertex.z );
  11857. // normal
  11858. normals.push( 0, sign, 0 );
  11859. // uv
  11860. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11861. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11862. uvs.push( uv.x, uv.y );
  11863. // increase index
  11864. index ++;
  11865. }
  11866. // generate indices
  11867. for ( let x = 0; x < radialSegments; x ++ ) {
  11868. const c = centerIndexStart + x;
  11869. const i = centerIndexEnd + x;
  11870. if ( top === true ) {
  11871. // face top
  11872. indices.push( i, i + 1, c );
  11873. } else {
  11874. // face bottom
  11875. indices.push( i + 1, i, c );
  11876. }
  11877. groupCount += 3;
  11878. }
  11879. // add a group to the geometry. this will ensure multi material support
  11880. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11881. // calculate new start value for groups
  11882. groupStart += groupCount;
  11883. }
  11884. }
  11885. copy( source ) {
  11886. super.copy( source );
  11887. this.parameters = Object.assign( {}, source.parameters );
  11888. return this;
  11889. }
  11890. static fromJSON( data ) {
  11891. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11892. }
  11893. }
  11894. class ConeGeometry extends CylinderGeometry {
  11895. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11896. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11897. this.type = 'ConeGeometry';
  11898. this.parameters = {
  11899. radius: radius,
  11900. height: height,
  11901. radialSegments: radialSegments,
  11902. heightSegments: heightSegments,
  11903. openEnded: openEnded,
  11904. thetaStart: thetaStart,
  11905. thetaLength: thetaLength
  11906. };
  11907. }
  11908. static fromJSON( data ) {
  11909. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11910. }
  11911. }
  11912. class PolyhedronGeometry extends BufferGeometry {
  11913. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11914. super();
  11915. this.type = 'PolyhedronGeometry';
  11916. this.parameters = {
  11917. vertices: vertices,
  11918. indices: indices,
  11919. radius: radius,
  11920. detail: detail
  11921. };
  11922. // default buffer data
  11923. const vertexBuffer = [];
  11924. const uvBuffer = [];
  11925. // the subdivision creates the vertex buffer data
  11926. subdivide( detail );
  11927. // all vertices should lie on a conceptual sphere with a given radius
  11928. applyRadius( radius );
  11929. // finally, create the uv data
  11930. generateUVs();
  11931. // build non-indexed geometry
  11932. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11933. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11934. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11935. if ( detail === 0 ) {
  11936. this.computeVertexNormals(); // flat normals
  11937. } else {
  11938. this.normalizeNormals(); // smooth normals
  11939. }
  11940. // helper functions
  11941. function subdivide( detail ) {
  11942. const a = new Vector3();
  11943. const b = new Vector3();
  11944. const c = new Vector3();
  11945. // iterate over all faces and apply a subdivision with the given detail value
  11946. for ( let i = 0; i < indices.length; i += 3 ) {
  11947. // get the vertices of the face
  11948. getVertexByIndex( indices[ i + 0 ], a );
  11949. getVertexByIndex( indices[ i + 1 ], b );
  11950. getVertexByIndex( indices[ i + 2 ], c );
  11951. // perform subdivision
  11952. subdivideFace( a, b, c, detail );
  11953. }
  11954. }
  11955. function subdivideFace( a, b, c, detail ) {
  11956. const cols = detail + 1;
  11957. // we use this multidimensional array as a data structure for creating the subdivision
  11958. const v = [];
  11959. // construct all of the vertices for this subdivision
  11960. for ( let i = 0; i <= cols; i ++ ) {
  11961. v[ i ] = [];
  11962. const aj = a.clone().lerp( c, i / cols );
  11963. const bj = b.clone().lerp( c, i / cols );
  11964. const rows = cols - i;
  11965. for ( let j = 0; j <= rows; j ++ ) {
  11966. if ( j === 0 && i === cols ) {
  11967. v[ i ][ j ] = aj;
  11968. } else {
  11969. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11970. }
  11971. }
  11972. }
  11973. // construct all of the faces
  11974. for ( let i = 0; i < cols; i ++ ) {
  11975. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11976. const k = Math.floor( j / 2 );
  11977. if ( j % 2 === 0 ) {
  11978. pushVertex( v[ i ][ k + 1 ] );
  11979. pushVertex( v[ i + 1 ][ k ] );
  11980. pushVertex( v[ i ][ k ] );
  11981. } else {
  11982. pushVertex( v[ i ][ k + 1 ] );
  11983. pushVertex( v[ i + 1 ][ k + 1 ] );
  11984. pushVertex( v[ i + 1 ][ k ] );
  11985. }
  11986. }
  11987. }
  11988. }
  11989. function applyRadius( radius ) {
  11990. const vertex = new Vector3();
  11991. // iterate over the entire buffer and apply the radius to each vertex
  11992. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11993. vertex.x = vertexBuffer[ i + 0 ];
  11994. vertex.y = vertexBuffer[ i + 1 ];
  11995. vertex.z = vertexBuffer[ i + 2 ];
  11996. vertex.normalize().multiplyScalar( radius );
  11997. vertexBuffer[ i + 0 ] = vertex.x;
  11998. vertexBuffer[ i + 1 ] = vertex.y;
  11999. vertexBuffer[ i + 2 ] = vertex.z;
  12000. }
  12001. }
  12002. function generateUVs() {
  12003. const vertex = new Vector3();
  12004. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  12005. vertex.x = vertexBuffer[ i + 0 ];
  12006. vertex.y = vertexBuffer[ i + 1 ];
  12007. vertex.z = vertexBuffer[ i + 2 ];
  12008. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  12009. const v = inclination( vertex ) / Math.PI + 0.5;
  12010. uvBuffer.push( u, 1 - v );
  12011. }
  12012. correctUVs();
  12013. correctSeam();
  12014. }
  12015. function correctSeam() {
  12016. // handle case when face straddles the seam, see #3269
  12017. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  12018. // uv data of a single face
  12019. const x0 = uvBuffer[ i + 0 ];
  12020. const x1 = uvBuffer[ i + 2 ];
  12021. const x2 = uvBuffer[ i + 4 ];
  12022. const max = Math.max( x0, x1, x2 );
  12023. const min = Math.min( x0, x1, x2 );
  12024. // 0.9 is somewhat arbitrary
  12025. if ( max > 0.9 && min < 0.1 ) {
  12026. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  12027. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  12028. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  12029. }
  12030. }
  12031. }
  12032. function pushVertex( vertex ) {
  12033. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  12034. }
  12035. function getVertexByIndex( index, vertex ) {
  12036. const stride = index * 3;
  12037. vertex.x = vertices[ stride + 0 ];
  12038. vertex.y = vertices[ stride + 1 ];
  12039. vertex.z = vertices[ stride + 2 ];
  12040. }
  12041. function correctUVs() {
  12042. const a = new Vector3();
  12043. const b = new Vector3();
  12044. const c = new Vector3();
  12045. const centroid = new Vector3();
  12046. const uvA = new Vector2();
  12047. const uvB = new Vector2();
  12048. const uvC = new Vector2();
  12049. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  12050. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  12051. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  12052. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  12053. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  12054. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  12055. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  12056. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  12057. const azi = azimuth( centroid );
  12058. correctUV( uvA, j + 0, a, azi );
  12059. correctUV( uvB, j + 2, b, azi );
  12060. correctUV( uvC, j + 4, c, azi );
  12061. }
  12062. }
  12063. function correctUV( uv, stride, vector, azimuth ) {
  12064. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  12065. uvBuffer[ stride ] = uv.x - 1;
  12066. }
  12067. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  12068. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  12069. }
  12070. }
  12071. // Angle around the Y axis, counter-clockwise when looking from above.
  12072. function azimuth( vector ) {
  12073. return Math.atan2( vector.z, - vector.x );
  12074. }
  12075. // Angle above the XZ plane.
  12076. function inclination( vector ) {
  12077. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  12078. }
  12079. }
  12080. copy( source ) {
  12081. super.copy( source );
  12082. this.parameters = Object.assign( {}, source.parameters );
  12083. return this;
  12084. }
  12085. static fromJSON( data ) {
  12086. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  12087. }
  12088. }
  12089. class DodecahedronGeometry extends PolyhedronGeometry {
  12090. constructor( radius = 1, detail = 0 ) {
  12091. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  12092. const r = 1 / t;
  12093. const vertices = [
  12094. // (±1, ±1, ±1)
  12095. - 1, - 1, - 1, - 1, - 1, 1,
  12096. - 1, 1, - 1, - 1, 1, 1,
  12097. 1, - 1, - 1, 1, - 1, 1,
  12098. 1, 1, - 1, 1, 1, 1,
  12099. // (0, ±1/φ, ±φ)
  12100. 0, - r, - t, 0, - r, t,
  12101. 0, r, - t, 0, r, t,
  12102. // (±1/φ, ±φ, 0)
  12103. - r, - t, 0, - r, t, 0,
  12104. r, - t, 0, r, t, 0,
  12105. // (±φ, 0, ±1/φ)
  12106. - t, 0, - r, t, 0, - r,
  12107. - t, 0, r, t, 0, r
  12108. ];
  12109. const indices = [
  12110. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  12111. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  12112. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  12113. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  12114. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  12115. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  12116. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  12117. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  12118. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  12119. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  12120. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  12121. 1, 12, 14, 1, 14, 5, 1, 5, 9
  12122. ];
  12123. super( vertices, indices, radius, detail );
  12124. this.type = 'DodecahedronGeometry';
  12125. this.parameters = {
  12126. radius: radius,
  12127. detail: detail
  12128. };
  12129. }
  12130. static fromJSON( data ) {
  12131. return new DodecahedronGeometry( data.radius, data.detail );
  12132. }
  12133. }
  12134. const _v0$1 = /*@__PURE__*/ new Vector3();
  12135. const _v1$1 = /*@__PURE__*/ new Vector3();
  12136. const _normal = /*@__PURE__*/ new Vector3();
  12137. const _triangle = /*@__PURE__*/ new Triangle();
  12138. class EdgesGeometry extends BufferGeometry {
  12139. constructor( geometry = null, thresholdAngle = 1 ) {
  12140. super();
  12141. this.type = 'EdgesGeometry';
  12142. this.parameters = {
  12143. geometry: geometry,
  12144. thresholdAngle: thresholdAngle
  12145. };
  12146. if ( geometry !== null ) {
  12147. const precisionPoints = 4;
  12148. const precision = Math.pow( 10, precisionPoints );
  12149. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  12150. const indexAttr = geometry.getIndex();
  12151. const positionAttr = geometry.getAttribute( 'position' );
  12152. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  12153. const indexArr = [ 0, 0, 0 ];
  12154. const vertKeys = [ 'a', 'b', 'c' ];
  12155. const hashes = new Array( 3 );
  12156. const edgeData = {};
  12157. const vertices = [];
  12158. for ( let i = 0; i < indexCount; i += 3 ) {
  12159. if ( indexAttr ) {
  12160. indexArr[ 0 ] = indexAttr.getX( i );
  12161. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  12162. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  12163. } else {
  12164. indexArr[ 0 ] = i;
  12165. indexArr[ 1 ] = i + 1;
  12166. indexArr[ 2 ] = i + 2;
  12167. }
  12168. const { a, b, c } = _triangle;
  12169. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  12170. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  12171. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  12172. _triangle.getNormal( _normal );
  12173. // create hashes for the edge from the vertices
  12174. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  12175. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  12176. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  12177. // skip degenerate triangles
  12178. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  12179. continue;
  12180. }
  12181. // iterate over every edge
  12182. for ( let j = 0; j < 3; j ++ ) {
  12183. // get the first and next vertex making up the edge
  12184. const jNext = ( j + 1 ) % 3;
  12185. const vecHash0 = hashes[ j ];
  12186. const vecHash1 = hashes[ jNext ];
  12187. const v0 = _triangle[ vertKeys[ j ] ];
  12188. const v1 = _triangle[ vertKeys[ jNext ] ];
  12189. const hash = `${ vecHash0 }_${ vecHash1 }`;
  12190. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  12191. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  12192. // if we found a sibling edge add it into the vertex array if
  12193. // it meets the angle threshold and delete the edge from the map.
  12194. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  12195. vertices.push( v0.x, v0.y, v0.z );
  12196. vertices.push( v1.x, v1.y, v1.z );
  12197. }
  12198. edgeData[ reverseHash ] = null;
  12199. } else if ( ! ( hash in edgeData ) ) {
  12200. // if we've already got an edge here then skip adding a new one
  12201. edgeData[ hash ] = {
  12202. index0: indexArr[ j ],
  12203. index1: indexArr[ jNext ],
  12204. normal: _normal.clone(),
  12205. };
  12206. }
  12207. }
  12208. }
  12209. // iterate over all remaining, unmatched edges and add them to the vertex array
  12210. for ( const key in edgeData ) {
  12211. if ( edgeData[ key ] ) {
  12212. const { index0, index1 } = edgeData[ key ];
  12213. _v0$1.fromBufferAttribute( positionAttr, index0 );
  12214. _v1$1.fromBufferAttribute( positionAttr, index1 );
  12215. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  12216. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  12217. }
  12218. }
  12219. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12220. }
  12221. }
  12222. copy( source ) {
  12223. super.copy( source );
  12224. this.parameters = Object.assign( {}, source.parameters );
  12225. return this;
  12226. }
  12227. }
  12228. class Shape extends Path {
  12229. constructor( points ) {
  12230. super( points );
  12231. this.uuid = generateUUID();
  12232. this.type = 'Shape';
  12233. this.holes = [];
  12234. }
  12235. getPointsHoles( divisions ) {
  12236. const holesPts = [];
  12237. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12238. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  12239. }
  12240. return holesPts;
  12241. }
  12242. // get points of shape and holes (keypoints based on segments parameter)
  12243. extractPoints( divisions ) {
  12244. return {
  12245. shape: this.getPoints( divisions ),
  12246. holes: this.getPointsHoles( divisions )
  12247. };
  12248. }
  12249. copy( source ) {
  12250. super.copy( source );
  12251. this.holes = [];
  12252. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  12253. const hole = source.holes[ i ];
  12254. this.holes.push( hole.clone() );
  12255. }
  12256. return this;
  12257. }
  12258. toJSON() {
  12259. const data = super.toJSON();
  12260. data.uuid = this.uuid;
  12261. data.holes = [];
  12262. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12263. const hole = this.holes[ i ];
  12264. data.holes.push( hole.toJSON() );
  12265. }
  12266. return data;
  12267. }
  12268. fromJSON( json ) {
  12269. super.fromJSON( json );
  12270. this.uuid = json.uuid;
  12271. this.holes = [];
  12272. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12273. const hole = json.holes[ i ];
  12274. this.holes.push( new Path().fromJSON( hole ) );
  12275. }
  12276. return this;
  12277. }
  12278. }
  12279. /**
  12280. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12281. */
  12282. const Earcut = {
  12283. triangulate: function ( data, holeIndices, dim = 2 ) {
  12284. const hasHoles = holeIndices && holeIndices.length;
  12285. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12286. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12287. const triangles = [];
  12288. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12289. let minX, minY, maxX, maxY, x, y, invSize;
  12290. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12291. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12292. if ( data.length > 80 * dim ) {
  12293. minX = maxX = data[ 0 ];
  12294. minY = maxY = data[ 1 ];
  12295. for ( let i = dim; i < outerLen; i += dim ) {
  12296. x = data[ i ];
  12297. y = data[ i + 1 ];
  12298. if ( x < minX ) minX = x;
  12299. if ( y < minY ) minY = y;
  12300. if ( x > maxX ) maxX = x;
  12301. if ( y > maxY ) maxY = y;
  12302. }
  12303. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12304. invSize = Math.max( maxX - minX, maxY - minY );
  12305. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12306. }
  12307. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12308. return triangles;
  12309. }
  12310. };
  12311. // create a circular doubly linked list from polygon points in the specified winding order
  12312. function linkedList( data, start, end, dim, clockwise ) {
  12313. let i, last;
  12314. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12315. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12316. } else {
  12317. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12318. }
  12319. if ( last && equals( last, last.next ) ) {
  12320. removeNode( last );
  12321. last = last.next;
  12322. }
  12323. return last;
  12324. }
  12325. // eliminate colinear or duplicate points
  12326. function filterPoints( start, end ) {
  12327. if ( ! start ) return start;
  12328. if ( ! end ) end = start;
  12329. let p = start,
  12330. again;
  12331. do {
  12332. again = false;
  12333. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12334. removeNode( p );
  12335. p = end = p.prev;
  12336. if ( p === p.next ) break;
  12337. again = true;
  12338. } else {
  12339. p = p.next;
  12340. }
  12341. } while ( again || p !== end );
  12342. return end;
  12343. }
  12344. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12345. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12346. if ( ! ear ) return;
  12347. // interlink polygon nodes in z-order
  12348. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12349. let stop = ear,
  12350. prev, next;
  12351. // iterate through ears, slicing them one by one
  12352. while ( ear.prev !== ear.next ) {
  12353. prev = ear.prev;
  12354. next = ear.next;
  12355. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12356. // cut off the triangle
  12357. triangles.push( prev.i / dim | 0 );
  12358. triangles.push( ear.i / dim | 0 );
  12359. triangles.push( next.i / dim | 0 );
  12360. removeNode( ear );
  12361. // skipping the next vertex leads to less sliver triangles
  12362. ear = next.next;
  12363. stop = next.next;
  12364. continue;
  12365. }
  12366. ear = next;
  12367. // if we looped through the whole remaining polygon and can't find any more ears
  12368. if ( ear === stop ) {
  12369. // try filtering points and slicing again
  12370. if ( ! pass ) {
  12371. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12372. // if this didn't work, try curing all small self-intersections locally
  12373. } else if ( pass === 1 ) {
  12374. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12375. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12376. // as a last resort, try splitting the remaining polygon into two
  12377. } else if ( pass === 2 ) {
  12378. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12379. }
  12380. break;
  12381. }
  12382. }
  12383. }
  12384. // check whether a polygon node forms a valid ear with adjacent nodes
  12385. function isEar( ear ) {
  12386. const a = ear.prev,
  12387. b = ear,
  12388. c = ear.next;
  12389. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12390. // now make sure we don't have other points inside the potential ear
  12391. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12392. // triangle bbox; min & max are calculated like this for speed
  12393. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12394. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12395. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12396. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12397. let p = c.next;
  12398. while ( p !== a ) {
  12399. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12400. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12401. area( p.prev, p, p.next ) >= 0 ) return false;
  12402. p = p.next;
  12403. }
  12404. return true;
  12405. }
  12406. function isEarHashed( ear, minX, minY, invSize ) {
  12407. const a = ear.prev,
  12408. b = ear,
  12409. c = ear.next;
  12410. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12411. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12412. // triangle bbox; min & max are calculated like this for speed
  12413. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12414. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12415. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12416. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12417. // z-order range for the current triangle bbox;
  12418. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12419. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12420. let p = ear.prevZ,
  12421. n = ear.nextZ;
  12422. // look for points inside the triangle in both directions
  12423. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12424. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12425. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12426. p = p.prevZ;
  12427. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12428. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12429. n = n.nextZ;
  12430. }
  12431. // look for remaining points in decreasing z-order
  12432. while ( p && p.z >= minZ ) {
  12433. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12434. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12435. p = p.prevZ;
  12436. }
  12437. // look for remaining points in increasing z-order
  12438. while ( n && n.z <= maxZ ) {
  12439. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12440. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12441. n = n.nextZ;
  12442. }
  12443. return true;
  12444. }
  12445. // go through all polygon nodes and cure small local self-intersections
  12446. function cureLocalIntersections( start, triangles, dim ) {
  12447. let p = start;
  12448. do {
  12449. const a = p.prev,
  12450. b = p.next.next;
  12451. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12452. triangles.push( a.i / dim | 0 );
  12453. triangles.push( p.i / dim | 0 );
  12454. triangles.push( b.i / dim | 0 );
  12455. // remove two nodes involved
  12456. removeNode( p );
  12457. removeNode( p.next );
  12458. p = start = b;
  12459. }
  12460. p = p.next;
  12461. } while ( p !== start );
  12462. return filterPoints( p );
  12463. }
  12464. // try splitting polygon into two and triangulate them independently
  12465. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12466. // look for a valid diagonal that divides the polygon into two
  12467. let a = start;
  12468. do {
  12469. let b = a.next.next;
  12470. while ( b !== a.prev ) {
  12471. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12472. // split the polygon in two by the diagonal
  12473. let c = splitPolygon( a, b );
  12474. // filter colinear points around the cuts
  12475. a = filterPoints( a, a.next );
  12476. c = filterPoints( c, c.next );
  12477. // run earcut on each half
  12478. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12479. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12480. return;
  12481. }
  12482. b = b.next;
  12483. }
  12484. a = a.next;
  12485. } while ( a !== start );
  12486. }
  12487. // link every hole into the outer loop, producing a single-ring polygon without holes
  12488. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12489. const queue = [];
  12490. let i, len, start, end, list;
  12491. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12492. start = holeIndices[ i ] * dim;
  12493. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12494. list = linkedList( data, start, end, dim, false );
  12495. if ( list === list.next ) list.steiner = true;
  12496. queue.push( getLeftmost( list ) );
  12497. }
  12498. queue.sort( compareX );
  12499. // process holes from left to right
  12500. for ( i = 0; i < queue.length; i ++ ) {
  12501. outerNode = eliminateHole( queue[ i ], outerNode );
  12502. }
  12503. return outerNode;
  12504. }
  12505. function compareX( a, b ) {
  12506. return a.x - b.x;
  12507. }
  12508. // find a bridge between vertices that connects hole with an outer ring and link it
  12509. function eliminateHole( hole, outerNode ) {
  12510. const bridge = findHoleBridge( hole, outerNode );
  12511. if ( ! bridge ) {
  12512. return outerNode;
  12513. }
  12514. const bridgeReverse = splitPolygon( bridge, hole );
  12515. // filter collinear points around the cuts
  12516. filterPoints( bridgeReverse, bridgeReverse.next );
  12517. return filterPoints( bridge, bridge.next );
  12518. }
  12519. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12520. function findHoleBridge( hole, outerNode ) {
  12521. let p = outerNode,
  12522. qx = - Infinity,
  12523. m;
  12524. const hx = hole.x, hy = hole.y;
  12525. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12526. // segment's endpoint with lesser x will be potential connection point
  12527. do {
  12528. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12529. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12530. if ( x <= hx && x > qx ) {
  12531. qx = x;
  12532. m = p.x < p.next.x ? p : p.next;
  12533. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12534. }
  12535. }
  12536. p = p.next;
  12537. } while ( p !== outerNode );
  12538. if ( ! m ) return null;
  12539. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12540. // if there are no points found, we have a valid connection;
  12541. // otherwise choose the point of the minimum angle with the ray as connection point
  12542. const stop = m,
  12543. mx = m.x,
  12544. my = m.y;
  12545. let tanMin = Infinity, tan;
  12546. p = m;
  12547. do {
  12548. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12549. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12550. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12551. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12552. m = p;
  12553. tanMin = tan;
  12554. }
  12555. }
  12556. p = p.next;
  12557. } while ( p !== stop );
  12558. return m;
  12559. }
  12560. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12561. function sectorContainsSector( m, p ) {
  12562. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12563. }
  12564. // interlink polygon nodes in z-order
  12565. function indexCurve( start, minX, minY, invSize ) {
  12566. let p = start;
  12567. do {
  12568. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12569. p.prevZ = p.prev;
  12570. p.nextZ = p.next;
  12571. p = p.next;
  12572. } while ( p !== start );
  12573. p.prevZ.nextZ = null;
  12574. p.prevZ = null;
  12575. sortLinked( p );
  12576. }
  12577. // Simon Tatham's linked list merge sort algorithm
  12578. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12579. function sortLinked( list ) {
  12580. let i, p, q, e, tail, numMerges, pSize, qSize,
  12581. inSize = 1;
  12582. do {
  12583. p = list;
  12584. list = null;
  12585. tail = null;
  12586. numMerges = 0;
  12587. while ( p ) {
  12588. numMerges ++;
  12589. q = p;
  12590. pSize = 0;
  12591. for ( i = 0; i < inSize; i ++ ) {
  12592. pSize ++;
  12593. q = q.nextZ;
  12594. if ( ! q ) break;
  12595. }
  12596. qSize = inSize;
  12597. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12598. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12599. e = p;
  12600. p = p.nextZ;
  12601. pSize --;
  12602. } else {
  12603. e = q;
  12604. q = q.nextZ;
  12605. qSize --;
  12606. }
  12607. if ( tail ) tail.nextZ = e;
  12608. else list = e;
  12609. e.prevZ = tail;
  12610. tail = e;
  12611. }
  12612. p = q;
  12613. }
  12614. tail.nextZ = null;
  12615. inSize *= 2;
  12616. } while ( numMerges > 1 );
  12617. return list;
  12618. }
  12619. // z-order of a point given coords and inverse of the longer side of data bbox
  12620. function zOrder( x, y, minX, minY, invSize ) {
  12621. // coords are transformed into non-negative 15-bit integer range
  12622. x = ( x - minX ) * invSize | 0;
  12623. y = ( y - minY ) * invSize | 0;
  12624. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12625. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12626. x = ( x | ( x << 2 ) ) & 0x33333333;
  12627. x = ( x | ( x << 1 ) ) & 0x55555555;
  12628. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12629. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12630. y = ( y | ( y << 2 ) ) & 0x33333333;
  12631. y = ( y | ( y << 1 ) ) & 0x55555555;
  12632. return x | ( y << 1 );
  12633. }
  12634. // find the leftmost node of a polygon ring
  12635. function getLeftmost( start ) {
  12636. let p = start,
  12637. leftmost = start;
  12638. do {
  12639. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12640. p = p.next;
  12641. } while ( p !== start );
  12642. return leftmost;
  12643. }
  12644. // check if a point lies within a convex triangle
  12645. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12646. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12647. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12648. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12649. }
  12650. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12651. function isValidDiagonal( a, b ) {
  12652. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12653. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12654. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12655. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12656. }
  12657. // signed area of a triangle
  12658. function area( p, q, r ) {
  12659. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12660. }
  12661. // check if two points are equal
  12662. function equals( p1, p2 ) {
  12663. return p1.x === p2.x && p1.y === p2.y;
  12664. }
  12665. // check if two segments intersect
  12666. function intersects( p1, q1, p2, q2 ) {
  12667. const o1 = sign( area( p1, q1, p2 ) );
  12668. const o2 = sign( area( p1, q1, q2 ) );
  12669. const o3 = sign( area( p2, q2, p1 ) );
  12670. const o4 = sign( area( p2, q2, q1 ) );
  12671. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12672. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12673. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12674. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12675. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12676. return false;
  12677. }
  12678. // for collinear points p, q, r, check if point q lies on segment pr
  12679. function onSegment( p, q, r ) {
  12680. 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 );
  12681. }
  12682. function sign( num ) {
  12683. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12684. }
  12685. // check if a polygon diagonal intersects any polygon segments
  12686. function intersectsPolygon( a, b ) {
  12687. let p = a;
  12688. do {
  12689. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12690. intersects( p, p.next, a, b ) ) return true;
  12691. p = p.next;
  12692. } while ( p !== a );
  12693. return false;
  12694. }
  12695. // check if a polygon diagonal is locally inside the polygon
  12696. function locallyInside( a, b ) {
  12697. return area( a.prev, a, a.next ) < 0 ?
  12698. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12699. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12700. }
  12701. // check if the middle point of a polygon diagonal is inside the polygon
  12702. function middleInside( a, b ) {
  12703. let p = a,
  12704. inside = false;
  12705. const px = ( a.x + b.x ) / 2,
  12706. py = ( a.y + b.y ) / 2;
  12707. do {
  12708. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12709. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12710. inside = ! inside;
  12711. p = p.next;
  12712. } while ( p !== a );
  12713. return inside;
  12714. }
  12715. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12716. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12717. function splitPolygon( a, b ) {
  12718. const a2 = new Node( a.i, a.x, a.y ),
  12719. b2 = new Node( b.i, b.x, b.y ),
  12720. an = a.next,
  12721. bp = b.prev;
  12722. a.next = b;
  12723. b.prev = a;
  12724. a2.next = an;
  12725. an.prev = a2;
  12726. b2.next = a2;
  12727. a2.prev = b2;
  12728. bp.next = b2;
  12729. b2.prev = bp;
  12730. return b2;
  12731. }
  12732. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12733. function insertNode( i, x, y, last ) {
  12734. const p = new Node( i, x, y );
  12735. if ( ! last ) {
  12736. p.prev = p;
  12737. p.next = p;
  12738. } else {
  12739. p.next = last.next;
  12740. p.prev = last;
  12741. last.next.prev = p;
  12742. last.next = p;
  12743. }
  12744. return p;
  12745. }
  12746. function removeNode( p ) {
  12747. p.next.prev = p.prev;
  12748. p.prev.next = p.next;
  12749. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12750. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12751. }
  12752. function Node( i, x, y ) {
  12753. // vertex index in coordinates array
  12754. this.i = i;
  12755. // vertex coordinates
  12756. this.x = x;
  12757. this.y = y;
  12758. // previous and next vertex nodes in a polygon ring
  12759. this.prev = null;
  12760. this.next = null;
  12761. // z-order curve value
  12762. this.z = 0;
  12763. // previous and next nodes in z-order
  12764. this.prevZ = null;
  12765. this.nextZ = null;
  12766. // indicates whether this is a steiner point
  12767. this.steiner = false;
  12768. }
  12769. function signedArea( data, start, end, dim ) {
  12770. let sum = 0;
  12771. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12772. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12773. j = i;
  12774. }
  12775. return sum;
  12776. }
  12777. class ShapeUtils {
  12778. // calculate area of the contour polygon
  12779. static area( contour ) {
  12780. const n = contour.length;
  12781. let a = 0.0;
  12782. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12783. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12784. }
  12785. return a * 0.5;
  12786. }
  12787. static isClockWise( pts ) {
  12788. return ShapeUtils.area( pts ) < 0;
  12789. }
  12790. static triangulateShape( contour, holes ) {
  12791. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12792. const holeIndices = []; // array of hole indices
  12793. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12794. removeDupEndPts( contour );
  12795. addContour( vertices, contour );
  12796. //
  12797. let holeIndex = contour.length;
  12798. holes.forEach( removeDupEndPts );
  12799. for ( let i = 0; i < holes.length; i ++ ) {
  12800. holeIndices.push( holeIndex );
  12801. holeIndex += holes[ i ].length;
  12802. addContour( vertices, holes[ i ] );
  12803. }
  12804. //
  12805. const triangles = Earcut.triangulate( vertices, holeIndices );
  12806. //
  12807. for ( let i = 0; i < triangles.length; i += 3 ) {
  12808. faces.push( triangles.slice( i, i + 3 ) );
  12809. }
  12810. return faces;
  12811. }
  12812. }
  12813. function removeDupEndPts( points ) {
  12814. const l = points.length;
  12815. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12816. points.pop();
  12817. }
  12818. }
  12819. function addContour( vertices, contour ) {
  12820. for ( let i = 0; i < contour.length; i ++ ) {
  12821. vertices.push( contour[ i ].x );
  12822. vertices.push( contour[ i ].y );
  12823. }
  12824. }
  12825. /**
  12826. * Creates extruded geometry from a path shape.
  12827. *
  12828. * parameters = {
  12829. *
  12830. * curveSegments: <int>, // number of points on the curves
  12831. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12832. * depth: <float>, // Depth to extrude the shape
  12833. *
  12834. * bevelEnabled: <bool>, // turn on bevel
  12835. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12836. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12837. * bevelOffset: <float>, // how far from shape outline does bevel start
  12838. * bevelSegments: <int>, // number of bevel layers
  12839. *
  12840. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12841. *
  12842. * UVGenerator: <Object> // object that provides UV generator functions
  12843. *
  12844. * }
  12845. */
  12846. class ExtrudeGeometry extends BufferGeometry {
  12847. 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 = {} ) {
  12848. super();
  12849. this.type = 'ExtrudeGeometry';
  12850. this.parameters = {
  12851. shapes: shapes,
  12852. options: options
  12853. };
  12854. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12855. const scope = this;
  12856. const verticesArray = [];
  12857. const uvArray = [];
  12858. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12859. const shape = shapes[ i ];
  12860. addShape( shape );
  12861. }
  12862. // build geometry
  12863. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12864. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12865. this.computeVertexNormals();
  12866. // functions
  12867. function addShape( shape ) {
  12868. const placeholder = [];
  12869. // options
  12870. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12871. const steps = options.steps !== undefined ? options.steps : 1;
  12872. const depth = options.depth !== undefined ? options.depth : 1;
  12873. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12874. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12875. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12876. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12877. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12878. const extrudePath = options.extrudePath;
  12879. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12880. //
  12881. let extrudePts, extrudeByPath = false;
  12882. let splineTube, binormal, normal, position2;
  12883. if ( extrudePath ) {
  12884. extrudePts = extrudePath.getSpacedPoints( steps );
  12885. extrudeByPath = true;
  12886. bevelEnabled = false; // bevels not supported for path extrusion
  12887. // SETUP TNB variables
  12888. // TODO1 - have a .isClosed in spline?
  12889. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12890. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12891. binormal = new Vector3();
  12892. normal = new Vector3();
  12893. position2 = new Vector3();
  12894. }
  12895. // Safeguards if bevels are not enabled
  12896. if ( ! bevelEnabled ) {
  12897. bevelSegments = 0;
  12898. bevelThickness = 0;
  12899. bevelSize = 0;
  12900. bevelOffset = 0;
  12901. }
  12902. // Variables initialization
  12903. const shapePoints = shape.extractPoints( curveSegments );
  12904. let vertices = shapePoints.shape;
  12905. const holes = shapePoints.holes;
  12906. const reverse = ! ShapeUtils.isClockWise( vertices );
  12907. if ( reverse ) {
  12908. vertices = vertices.reverse();
  12909. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12910. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12911. const ahole = holes[ h ];
  12912. if ( ShapeUtils.isClockWise( ahole ) ) {
  12913. holes[ h ] = ahole.reverse();
  12914. }
  12915. }
  12916. }
  12917. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12918. /* Vertices */
  12919. const contour = vertices; // vertices has all points but contour has only points of circumference
  12920. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12921. const ahole = holes[ h ];
  12922. vertices = vertices.concat( ahole );
  12923. }
  12924. function scalePt2( pt, vec, size ) {
  12925. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12926. return pt.clone().addScaledVector( vec, size );
  12927. }
  12928. const vlen = vertices.length, flen = faces.length;
  12929. // Find directions for point movement
  12930. function getBevelVec( inPt, inPrev, inNext ) {
  12931. // computes for inPt the corresponding point inPt' on a new contour
  12932. // shifted by 1 unit (length of normalized vector) to the left
  12933. // if we walk along contour clockwise, this new contour is outside the old one
  12934. //
  12935. // inPt' is the intersection of the two lines parallel to the two
  12936. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12937. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12938. // good reading for geometry algorithms (here: line-line intersection)
  12939. // http://geomalgorithms.com/a05-_intersect-1.html
  12940. const v_prev_x = inPt.x - inPrev.x,
  12941. v_prev_y = inPt.y - inPrev.y;
  12942. const v_next_x = inNext.x - inPt.x,
  12943. v_next_y = inNext.y - inPt.y;
  12944. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12945. // check for collinear edges
  12946. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12947. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12948. // not collinear
  12949. // length of vectors for normalizing
  12950. const v_prev_len = Math.sqrt( v_prev_lensq );
  12951. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12952. // shift adjacent points by unit vectors to the left
  12953. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12954. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12955. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12956. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12957. // scaling factor for v_prev to intersection point
  12958. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12959. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12960. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12961. // vector from inPt to intersection point
  12962. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12963. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12964. // Don't normalize!, otherwise sharp corners become ugly
  12965. // but prevent crazy spikes
  12966. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12967. if ( v_trans_lensq <= 2 ) {
  12968. return new Vector2( v_trans_x, v_trans_y );
  12969. } else {
  12970. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12971. }
  12972. } else {
  12973. // handle special case of collinear edges
  12974. let direction_eq = false; // assumes: opposite
  12975. if ( v_prev_x > Number.EPSILON ) {
  12976. if ( v_next_x > Number.EPSILON ) {
  12977. direction_eq = true;
  12978. }
  12979. } else {
  12980. if ( v_prev_x < - Number.EPSILON ) {
  12981. if ( v_next_x < - Number.EPSILON ) {
  12982. direction_eq = true;
  12983. }
  12984. } else {
  12985. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12986. direction_eq = true;
  12987. }
  12988. }
  12989. }
  12990. if ( direction_eq ) {
  12991. // console.log("Warning: lines are a straight sequence");
  12992. v_trans_x = - v_prev_y;
  12993. v_trans_y = v_prev_x;
  12994. shrink_by = Math.sqrt( v_prev_lensq );
  12995. } else {
  12996. // console.log("Warning: lines are a straight spike");
  12997. v_trans_x = v_prev_x;
  12998. v_trans_y = v_prev_y;
  12999. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  13000. }
  13001. }
  13002. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  13003. }
  13004. const contourMovements = [];
  13005. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  13006. if ( j === il ) j = 0;
  13007. if ( k === il ) k = 0;
  13008. // (j)---(i)---(k)
  13009. // console.log('i,j,k', i, j , k)
  13010. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  13011. }
  13012. const holesMovements = [];
  13013. let oneHoleMovements, verticesMovements = contourMovements.concat();
  13014. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13015. const ahole = holes[ h ];
  13016. oneHoleMovements = [];
  13017. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  13018. if ( j === il ) j = 0;
  13019. if ( k === il ) k = 0;
  13020. // (j)---(i)---(k)
  13021. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  13022. }
  13023. holesMovements.push( oneHoleMovements );
  13024. verticesMovements = verticesMovements.concat( oneHoleMovements );
  13025. }
  13026. // Loop bevelSegments, 1 for the front, 1 for the back
  13027. for ( let b = 0; b < bevelSegments; b ++ ) {
  13028. //for ( b = bevelSegments; b > 0; b -- ) {
  13029. const t = b / bevelSegments;
  13030. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  13031. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  13032. // contract shape
  13033. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  13034. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  13035. v( vert.x, vert.y, - z );
  13036. }
  13037. // expand holes
  13038. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13039. const ahole = holes[ h ];
  13040. oneHoleMovements = holesMovements[ h ];
  13041. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13042. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13043. v( vert.x, vert.y, - z );
  13044. }
  13045. }
  13046. }
  13047. const bs = bevelSize + bevelOffset;
  13048. // Back facing vertices
  13049. for ( let i = 0; i < vlen; i ++ ) {
  13050. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13051. if ( ! extrudeByPath ) {
  13052. v( vert.x, vert.y, 0 );
  13053. } else {
  13054. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  13055. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  13056. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  13057. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  13058. v( position2.x, position2.y, position2.z );
  13059. }
  13060. }
  13061. // Add stepped vertices...
  13062. // Including front facing vertices
  13063. for ( let s = 1; s <= steps; s ++ ) {
  13064. for ( let i = 0; i < vlen; i ++ ) {
  13065. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13066. if ( ! extrudeByPath ) {
  13067. v( vert.x, vert.y, depth / steps * s );
  13068. } else {
  13069. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  13070. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  13071. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  13072. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  13073. v( position2.x, position2.y, position2.z );
  13074. }
  13075. }
  13076. }
  13077. // Add bevel segments planes
  13078. //for ( b = 1; b <= bevelSegments; b ++ ) {
  13079. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  13080. const t = b / bevelSegments;
  13081. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  13082. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  13083. // contract shape
  13084. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  13085. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  13086. v( vert.x, vert.y, depth + z );
  13087. }
  13088. // expand holes
  13089. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13090. const ahole = holes[ h ];
  13091. oneHoleMovements = holesMovements[ h ];
  13092. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13093. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13094. if ( ! extrudeByPath ) {
  13095. v( vert.x, vert.y, depth + z );
  13096. } else {
  13097. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  13098. }
  13099. }
  13100. }
  13101. }
  13102. /* Faces */
  13103. // Top and bottom faces
  13104. buildLidFaces();
  13105. // Sides faces
  13106. buildSideFaces();
  13107. ///// Internal functions
  13108. function buildLidFaces() {
  13109. const start = verticesArray.length / 3;
  13110. if ( bevelEnabled ) {
  13111. let layer = 0; // steps + 1
  13112. let offset = vlen * layer;
  13113. // Bottom faces
  13114. for ( let i = 0; i < flen; i ++ ) {
  13115. const face = faces[ i ];
  13116. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  13117. }
  13118. layer = steps + bevelSegments * 2;
  13119. offset = vlen * layer;
  13120. // Top faces
  13121. for ( let i = 0; i < flen; i ++ ) {
  13122. const face = faces[ i ];
  13123. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  13124. }
  13125. } else {
  13126. // Bottom faces
  13127. for ( let i = 0; i < flen; i ++ ) {
  13128. const face = faces[ i ];
  13129. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  13130. }
  13131. // Top faces
  13132. for ( let i = 0; i < flen; i ++ ) {
  13133. const face = faces[ i ];
  13134. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  13135. }
  13136. }
  13137. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  13138. }
  13139. // Create faces for the z-sides of the shape
  13140. function buildSideFaces() {
  13141. const start = verticesArray.length / 3;
  13142. let layeroffset = 0;
  13143. sidewalls( contour, layeroffset );
  13144. layeroffset += contour.length;
  13145. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13146. const ahole = holes[ h ];
  13147. sidewalls( ahole, layeroffset );
  13148. //, true
  13149. layeroffset += ahole.length;
  13150. }
  13151. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  13152. }
  13153. function sidewalls( contour, layeroffset ) {
  13154. let i = contour.length;
  13155. while ( -- i >= 0 ) {
  13156. const j = i;
  13157. let k = i - 1;
  13158. if ( k < 0 ) k = contour.length - 1;
  13159. //console.log('b', i,j, i-1, k,vertices.length);
  13160. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  13161. const slen1 = vlen * s;
  13162. const slen2 = vlen * ( s + 1 );
  13163. const a = layeroffset + j + slen1,
  13164. b = layeroffset + k + slen1,
  13165. c = layeroffset + k + slen2,
  13166. d = layeroffset + j + slen2;
  13167. f4( a, b, c, d );
  13168. }
  13169. }
  13170. }
  13171. function v( x, y, z ) {
  13172. placeholder.push( x );
  13173. placeholder.push( y );
  13174. placeholder.push( z );
  13175. }
  13176. function f3( a, b, c ) {
  13177. addVertex( a );
  13178. addVertex( b );
  13179. addVertex( c );
  13180. const nextIndex = verticesArray.length / 3;
  13181. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13182. addUV( uvs[ 0 ] );
  13183. addUV( uvs[ 1 ] );
  13184. addUV( uvs[ 2 ] );
  13185. }
  13186. function f4( a, b, c, d ) {
  13187. addVertex( a );
  13188. addVertex( b );
  13189. addVertex( d );
  13190. addVertex( b );
  13191. addVertex( c );
  13192. addVertex( d );
  13193. const nextIndex = verticesArray.length / 3;
  13194. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13195. addUV( uvs[ 0 ] );
  13196. addUV( uvs[ 1 ] );
  13197. addUV( uvs[ 3 ] );
  13198. addUV( uvs[ 1 ] );
  13199. addUV( uvs[ 2 ] );
  13200. addUV( uvs[ 3 ] );
  13201. }
  13202. function addVertex( index ) {
  13203. verticesArray.push( placeholder[ index * 3 + 0 ] );
  13204. verticesArray.push( placeholder[ index * 3 + 1 ] );
  13205. verticesArray.push( placeholder[ index * 3 + 2 ] );
  13206. }
  13207. function addUV( vector2 ) {
  13208. uvArray.push( vector2.x );
  13209. uvArray.push( vector2.y );
  13210. }
  13211. }
  13212. }
  13213. copy( source ) {
  13214. super.copy( source );
  13215. this.parameters = Object.assign( {}, source.parameters );
  13216. return this;
  13217. }
  13218. toJSON() {
  13219. const data = super.toJSON();
  13220. const shapes = this.parameters.shapes;
  13221. const options = this.parameters.options;
  13222. return toJSON$1( shapes, options, data );
  13223. }
  13224. static fromJSON( data, shapes ) {
  13225. const geometryShapes = [];
  13226. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13227. const shape = shapes[ data.shapes[ j ] ];
  13228. geometryShapes.push( shape );
  13229. }
  13230. const extrudePath = data.options.extrudePath;
  13231. if ( extrudePath !== undefined ) {
  13232. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  13233. }
  13234. return new ExtrudeGeometry( geometryShapes, data.options );
  13235. }
  13236. }
  13237. const WorldUVGenerator = {
  13238. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  13239. const a_x = vertices[ indexA * 3 ];
  13240. const a_y = vertices[ indexA * 3 + 1 ];
  13241. const b_x = vertices[ indexB * 3 ];
  13242. const b_y = vertices[ indexB * 3 + 1 ];
  13243. const c_x = vertices[ indexC * 3 ];
  13244. const c_y = vertices[ indexC * 3 + 1 ];
  13245. return [
  13246. new Vector2( a_x, a_y ),
  13247. new Vector2( b_x, b_y ),
  13248. new Vector2( c_x, c_y )
  13249. ];
  13250. },
  13251. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  13252. const a_x = vertices[ indexA * 3 ];
  13253. const a_y = vertices[ indexA * 3 + 1 ];
  13254. const a_z = vertices[ indexA * 3 + 2 ];
  13255. const b_x = vertices[ indexB * 3 ];
  13256. const b_y = vertices[ indexB * 3 + 1 ];
  13257. const b_z = vertices[ indexB * 3 + 2 ];
  13258. const c_x = vertices[ indexC * 3 ];
  13259. const c_y = vertices[ indexC * 3 + 1 ];
  13260. const c_z = vertices[ indexC * 3 + 2 ];
  13261. const d_x = vertices[ indexD * 3 ];
  13262. const d_y = vertices[ indexD * 3 + 1 ];
  13263. const d_z = vertices[ indexD * 3 + 2 ];
  13264. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  13265. return [
  13266. new Vector2( a_x, 1 - a_z ),
  13267. new Vector2( b_x, 1 - b_z ),
  13268. new Vector2( c_x, 1 - c_z ),
  13269. new Vector2( d_x, 1 - d_z )
  13270. ];
  13271. } else {
  13272. return [
  13273. new Vector2( a_y, 1 - a_z ),
  13274. new Vector2( b_y, 1 - b_z ),
  13275. new Vector2( c_y, 1 - c_z ),
  13276. new Vector2( d_y, 1 - d_z )
  13277. ];
  13278. }
  13279. }
  13280. };
  13281. function toJSON$1( shapes, options, data ) {
  13282. data.shapes = [];
  13283. if ( Array.isArray( shapes ) ) {
  13284. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13285. const shape = shapes[ i ];
  13286. data.shapes.push( shape.uuid );
  13287. }
  13288. } else {
  13289. data.shapes.push( shapes.uuid );
  13290. }
  13291. data.options = Object.assign( {}, options );
  13292. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13293. return data;
  13294. }
  13295. class IcosahedronGeometry extends PolyhedronGeometry {
  13296. constructor( radius = 1, detail = 0 ) {
  13297. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13298. const vertices = [
  13299. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13300. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13301. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13302. ];
  13303. const indices = [
  13304. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13305. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13306. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13307. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13308. ];
  13309. super( vertices, indices, radius, detail );
  13310. this.type = 'IcosahedronGeometry';
  13311. this.parameters = {
  13312. radius: radius,
  13313. detail: detail
  13314. };
  13315. }
  13316. static fromJSON( data ) {
  13317. return new IcosahedronGeometry( data.radius, data.detail );
  13318. }
  13319. }
  13320. class OctahedronGeometry extends PolyhedronGeometry {
  13321. constructor( radius = 1, detail = 0 ) {
  13322. const vertices = [
  13323. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13324. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13325. ];
  13326. const indices = [
  13327. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13328. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13329. 1, 3, 4, 1, 4, 2
  13330. ];
  13331. super( vertices, indices, radius, detail );
  13332. this.type = 'OctahedronGeometry';
  13333. this.parameters = {
  13334. radius: radius,
  13335. detail: detail
  13336. };
  13337. }
  13338. static fromJSON( data ) {
  13339. return new OctahedronGeometry( data.radius, data.detail );
  13340. }
  13341. }
  13342. class PlaneGeometry extends BufferGeometry {
  13343. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13344. super();
  13345. this.type = 'PlaneGeometry';
  13346. this.parameters = {
  13347. width: width,
  13348. height: height,
  13349. widthSegments: widthSegments,
  13350. heightSegments: heightSegments
  13351. };
  13352. const width_half = width / 2;
  13353. const height_half = height / 2;
  13354. const gridX = Math.floor( widthSegments );
  13355. const gridY = Math.floor( heightSegments );
  13356. const gridX1 = gridX + 1;
  13357. const gridY1 = gridY + 1;
  13358. const segment_width = width / gridX;
  13359. const segment_height = height / gridY;
  13360. //
  13361. const indices = [];
  13362. const vertices = [];
  13363. const normals = [];
  13364. const uvs = [];
  13365. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13366. const y = iy * segment_height - height_half;
  13367. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13368. const x = ix * segment_width - width_half;
  13369. vertices.push( x, - y, 0 );
  13370. normals.push( 0, 0, 1 );
  13371. uvs.push( ix / gridX );
  13372. uvs.push( 1 - ( iy / gridY ) );
  13373. }
  13374. }
  13375. for ( let iy = 0; iy < gridY; iy ++ ) {
  13376. for ( let ix = 0; ix < gridX; ix ++ ) {
  13377. const a = ix + gridX1 * iy;
  13378. const b = ix + gridX1 * ( iy + 1 );
  13379. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13380. const d = ( ix + 1 ) + gridX1 * iy;
  13381. indices.push( a, b, d );
  13382. indices.push( b, c, d );
  13383. }
  13384. }
  13385. this.setIndex( indices );
  13386. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13387. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13388. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13389. }
  13390. copy( source ) {
  13391. super.copy( source );
  13392. this.parameters = Object.assign( {}, source.parameters );
  13393. return this;
  13394. }
  13395. static fromJSON( data ) {
  13396. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13397. }
  13398. }
  13399. class RingGeometry extends BufferGeometry {
  13400. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13401. super();
  13402. this.type = 'RingGeometry';
  13403. this.parameters = {
  13404. innerRadius: innerRadius,
  13405. outerRadius: outerRadius,
  13406. thetaSegments: thetaSegments,
  13407. phiSegments: phiSegments,
  13408. thetaStart: thetaStart,
  13409. thetaLength: thetaLength
  13410. };
  13411. thetaSegments = Math.max( 3, thetaSegments );
  13412. phiSegments = Math.max( 1, phiSegments );
  13413. // buffers
  13414. const indices = [];
  13415. const vertices = [];
  13416. const normals = [];
  13417. const uvs = [];
  13418. // some helper variables
  13419. let radius = innerRadius;
  13420. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13421. const vertex = new Vector3();
  13422. const uv = new Vector2();
  13423. // generate vertices, normals and uvs
  13424. for ( let j = 0; j <= phiSegments; j ++ ) {
  13425. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13426. // values are generate from the inside of the ring to the outside
  13427. const segment = thetaStart + i / thetaSegments * thetaLength;
  13428. // vertex
  13429. vertex.x = radius * Math.cos( segment );
  13430. vertex.y = radius * Math.sin( segment );
  13431. vertices.push( vertex.x, vertex.y, vertex.z );
  13432. // normal
  13433. normals.push( 0, 0, 1 );
  13434. // uv
  13435. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13436. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13437. uvs.push( uv.x, uv.y );
  13438. }
  13439. // increase the radius for next row of vertices
  13440. radius += radiusStep;
  13441. }
  13442. // indices
  13443. for ( let j = 0; j < phiSegments; j ++ ) {
  13444. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13445. for ( let i = 0; i < thetaSegments; i ++ ) {
  13446. const segment = i + thetaSegmentLevel;
  13447. const a = segment;
  13448. const b = segment + thetaSegments + 1;
  13449. const c = segment + thetaSegments + 2;
  13450. const d = segment + 1;
  13451. // faces
  13452. indices.push( a, b, d );
  13453. indices.push( b, c, d );
  13454. }
  13455. }
  13456. // build geometry
  13457. this.setIndex( indices );
  13458. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13459. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13460. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13461. }
  13462. copy( source ) {
  13463. super.copy( source );
  13464. this.parameters = Object.assign( {}, source.parameters );
  13465. return this;
  13466. }
  13467. static fromJSON( data ) {
  13468. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13469. }
  13470. }
  13471. class ShapeGeometry extends BufferGeometry {
  13472. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13473. super();
  13474. this.type = 'ShapeGeometry';
  13475. this.parameters = {
  13476. shapes: shapes,
  13477. curveSegments: curveSegments
  13478. };
  13479. // buffers
  13480. const indices = [];
  13481. const vertices = [];
  13482. const normals = [];
  13483. const uvs = [];
  13484. // helper variables
  13485. let groupStart = 0;
  13486. let groupCount = 0;
  13487. // allow single and array values for "shapes" parameter
  13488. if ( Array.isArray( shapes ) === false ) {
  13489. addShape( shapes );
  13490. } else {
  13491. for ( let i = 0; i < shapes.length; i ++ ) {
  13492. addShape( shapes[ i ] );
  13493. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13494. groupStart += groupCount;
  13495. groupCount = 0;
  13496. }
  13497. }
  13498. // build geometry
  13499. this.setIndex( indices );
  13500. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13501. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13502. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13503. // helper functions
  13504. function addShape( shape ) {
  13505. const indexOffset = vertices.length / 3;
  13506. const points = shape.extractPoints( curveSegments );
  13507. let shapeVertices = points.shape;
  13508. const shapeHoles = points.holes;
  13509. // check direction of vertices
  13510. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13511. shapeVertices = shapeVertices.reverse();
  13512. }
  13513. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13514. const shapeHole = shapeHoles[ i ];
  13515. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13516. shapeHoles[ i ] = shapeHole.reverse();
  13517. }
  13518. }
  13519. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13520. // join vertices of inner and outer paths to a single array
  13521. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13522. const shapeHole = shapeHoles[ i ];
  13523. shapeVertices = shapeVertices.concat( shapeHole );
  13524. }
  13525. // vertices, normals, uvs
  13526. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13527. const vertex = shapeVertices[ i ];
  13528. vertices.push( vertex.x, vertex.y, 0 );
  13529. normals.push( 0, 0, 1 );
  13530. uvs.push( vertex.x, vertex.y ); // world uvs
  13531. }
  13532. // indices
  13533. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13534. const face = faces[ i ];
  13535. const a = face[ 0 ] + indexOffset;
  13536. const b = face[ 1 ] + indexOffset;
  13537. const c = face[ 2 ] + indexOffset;
  13538. indices.push( a, b, c );
  13539. groupCount += 3;
  13540. }
  13541. }
  13542. }
  13543. copy( source ) {
  13544. super.copy( source );
  13545. this.parameters = Object.assign( {}, source.parameters );
  13546. return this;
  13547. }
  13548. toJSON() {
  13549. const data = super.toJSON();
  13550. const shapes = this.parameters.shapes;
  13551. return toJSON( shapes, data );
  13552. }
  13553. static fromJSON( data, shapes ) {
  13554. const geometryShapes = [];
  13555. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13556. const shape = shapes[ data.shapes[ j ] ];
  13557. geometryShapes.push( shape );
  13558. }
  13559. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13560. }
  13561. }
  13562. function toJSON( shapes, data ) {
  13563. data.shapes = [];
  13564. if ( Array.isArray( shapes ) ) {
  13565. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13566. const shape = shapes[ i ];
  13567. data.shapes.push( shape.uuid );
  13568. }
  13569. } else {
  13570. data.shapes.push( shapes.uuid );
  13571. }
  13572. return data;
  13573. }
  13574. class SphereGeometry extends BufferGeometry {
  13575. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13576. super();
  13577. this.type = 'SphereGeometry';
  13578. this.parameters = {
  13579. radius: radius,
  13580. widthSegments: widthSegments,
  13581. heightSegments: heightSegments,
  13582. phiStart: phiStart,
  13583. phiLength: phiLength,
  13584. thetaStart: thetaStart,
  13585. thetaLength: thetaLength
  13586. };
  13587. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13588. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13589. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13590. let index = 0;
  13591. const grid = [];
  13592. const vertex = new Vector3();
  13593. const normal = new Vector3();
  13594. // buffers
  13595. const indices = [];
  13596. const vertices = [];
  13597. const normals = [];
  13598. const uvs = [];
  13599. // generate vertices, normals and uvs
  13600. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13601. const verticesRow = [];
  13602. const v = iy / heightSegments;
  13603. // special case for the poles
  13604. let uOffset = 0;
  13605. if ( iy === 0 && thetaStart === 0 ) {
  13606. uOffset = 0.5 / widthSegments;
  13607. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13608. uOffset = - 0.5 / widthSegments;
  13609. }
  13610. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13611. const u = ix / widthSegments;
  13612. // vertex
  13613. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13614. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13615. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13616. vertices.push( vertex.x, vertex.y, vertex.z );
  13617. // normal
  13618. normal.copy( vertex ).normalize();
  13619. normals.push( normal.x, normal.y, normal.z );
  13620. // uv
  13621. uvs.push( u + uOffset, 1 - v );
  13622. verticesRow.push( index ++ );
  13623. }
  13624. grid.push( verticesRow );
  13625. }
  13626. // indices
  13627. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13628. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13629. const a = grid[ iy ][ ix + 1 ];
  13630. const b = grid[ iy ][ ix ];
  13631. const c = grid[ iy + 1 ][ ix ];
  13632. const d = grid[ iy + 1 ][ ix + 1 ];
  13633. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13634. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13635. }
  13636. }
  13637. // build geometry
  13638. this.setIndex( indices );
  13639. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13640. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13641. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13642. }
  13643. copy( source ) {
  13644. super.copy( source );
  13645. this.parameters = Object.assign( {}, source.parameters );
  13646. return this;
  13647. }
  13648. static fromJSON( data ) {
  13649. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13650. }
  13651. }
  13652. class TetrahedronGeometry extends PolyhedronGeometry {
  13653. constructor( radius = 1, detail = 0 ) {
  13654. const vertices = [
  13655. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13656. ];
  13657. const indices = [
  13658. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13659. ];
  13660. super( vertices, indices, radius, detail );
  13661. this.type = 'TetrahedronGeometry';
  13662. this.parameters = {
  13663. radius: radius,
  13664. detail: detail
  13665. };
  13666. }
  13667. static fromJSON( data ) {
  13668. return new TetrahedronGeometry( data.radius, data.detail );
  13669. }
  13670. }
  13671. class TorusGeometry extends BufferGeometry {
  13672. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13673. super();
  13674. this.type = 'TorusGeometry';
  13675. this.parameters = {
  13676. radius: radius,
  13677. tube: tube,
  13678. radialSegments: radialSegments,
  13679. tubularSegments: tubularSegments,
  13680. arc: arc
  13681. };
  13682. radialSegments = Math.floor( radialSegments );
  13683. tubularSegments = Math.floor( tubularSegments );
  13684. // buffers
  13685. const indices = [];
  13686. const vertices = [];
  13687. const normals = [];
  13688. const uvs = [];
  13689. // helper variables
  13690. const center = new Vector3();
  13691. const vertex = new Vector3();
  13692. const normal = new Vector3();
  13693. // generate vertices, normals and uvs
  13694. for ( let j = 0; j <= radialSegments; j ++ ) {
  13695. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13696. const u = i / tubularSegments * arc;
  13697. const v = j / radialSegments * Math.PI * 2;
  13698. // vertex
  13699. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13700. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13701. vertex.z = tube * Math.sin( v );
  13702. vertices.push( vertex.x, vertex.y, vertex.z );
  13703. // normal
  13704. center.x = radius * Math.cos( u );
  13705. center.y = radius * Math.sin( u );
  13706. normal.subVectors( vertex, center ).normalize();
  13707. normals.push( normal.x, normal.y, normal.z );
  13708. // uv
  13709. uvs.push( i / tubularSegments );
  13710. uvs.push( j / radialSegments );
  13711. }
  13712. }
  13713. // generate indices
  13714. for ( let j = 1; j <= radialSegments; j ++ ) {
  13715. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13716. // indices
  13717. const a = ( tubularSegments + 1 ) * j + i - 1;
  13718. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13719. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13720. const d = ( tubularSegments + 1 ) * j + i;
  13721. // faces
  13722. indices.push( a, b, d );
  13723. indices.push( b, c, d );
  13724. }
  13725. }
  13726. // build geometry
  13727. this.setIndex( indices );
  13728. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13729. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13730. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13731. }
  13732. copy( source ) {
  13733. super.copy( source );
  13734. this.parameters = Object.assign( {}, source.parameters );
  13735. return this;
  13736. }
  13737. static fromJSON( data ) {
  13738. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13739. }
  13740. }
  13741. class TorusKnotGeometry extends BufferGeometry {
  13742. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13743. super();
  13744. this.type = 'TorusKnotGeometry';
  13745. this.parameters = {
  13746. radius: radius,
  13747. tube: tube,
  13748. tubularSegments: tubularSegments,
  13749. radialSegments: radialSegments,
  13750. p: p,
  13751. q: q
  13752. };
  13753. tubularSegments = Math.floor( tubularSegments );
  13754. radialSegments = Math.floor( radialSegments );
  13755. // buffers
  13756. const indices = [];
  13757. const vertices = [];
  13758. const normals = [];
  13759. const uvs = [];
  13760. // helper variables
  13761. const vertex = new Vector3();
  13762. const normal = new Vector3();
  13763. const P1 = new Vector3();
  13764. const P2 = new Vector3();
  13765. const B = new Vector3();
  13766. const T = new Vector3();
  13767. const N = new Vector3();
  13768. // generate vertices, normals and uvs
  13769. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13770. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13771. const u = i / tubularSegments * p * Math.PI * 2;
  13772. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13773. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13774. calculatePositionOnCurve( u, p, q, radius, P1 );
  13775. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13776. // calculate orthonormal basis
  13777. T.subVectors( P2, P1 );
  13778. N.addVectors( P2, P1 );
  13779. B.crossVectors( T, N );
  13780. N.crossVectors( B, T );
  13781. // normalize B, N. T can be ignored, we don't use it
  13782. B.normalize();
  13783. N.normalize();
  13784. for ( let j = 0; j <= radialSegments; ++ j ) {
  13785. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13786. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13787. const v = j / radialSegments * Math.PI * 2;
  13788. const cx = - tube * Math.cos( v );
  13789. const cy = tube * Math.sin( v );
  13790. // now calculate the final vertex position.
  13791. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13792. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13793. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13794. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13795. vertices.push( vertex.x, vertex.y, vertex.z );
  13796. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13797. normal.subVectors( vertex, P1 ).normalize();
  13798. normals.push( normal.x, normal.y, normal.z );
  13799. // uv
  13800. uvs.push( i / tubularSegments );
  13801. uvs.push( j / radialSegments );
  13802. }
  13803. }
  13804. // generate indices
  13805. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13806. for ( let i = 1; i <= radialSegments; i ++ ) {
  13807. // indices
  13808. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13809. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13810. const c = ( radialSegments + 1 ) * j + i;
  13811. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13812. // faces
  13813. indices.push( a, b, d );
  13814. indices.push( b, c, d );
  13815. }
  13816. }
  13817. // build geometry
  13818. this.setIndex( indices );
  13819. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13820. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13821. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13822. // this function calculates the current position on the torus curve
  13823. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13824. const cu = Math.cos( u );
  13825. const su = Math.sin( u );
  13826. const quOverP = q / p * u;
  13827. const cs = Math.cos( quOverP );
  13828. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13829. position.y = radius * ( 2 + cs ) * su * 0.5;
  13830. position.z = radius * Math.sin( quOverP ) * 0.5;
  13831. }
  13832. }
  13833. copy( source ) {
  13834. super.copy( source );
  13835. this.parameters = Object.assign( {}, source.parameters );
  13836. return this;
  13837. }
  13838. static fromJSON( data ) {
  13839. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13840. }
  13841. }
  13842. class TubeGeometry extends BufferGeometry {
  13843. 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 ) {
  13844. super();
  13845. this.type = 'TubeGeometry';
  13846. this.parameters = {
  13847. path: path,
  13848. tubularSegments: tubularSegments,
  13849. radius: radius,
  13850. radialSegments: radialSegments,
  13851. closed: closed
  13852. };
  13853. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13854. // expose internals
  13855. this.tangents = frames.tangents;
  13856. this.normals = frames.normals;
  13857. this.binormals = frames.binormals;
  13858. // helper variables
  13859. const vertex = new Vector3();
  13860. const normal = new Vector3();
  13861. const uv = new Vector2();
  13862. let P = new Vector3();
  13863. // buffer
  13864. const vertices = [];
  13865. const normals = [];
  13866. const uvs = [];
  13867. const indices = [];
  13868. // create buffer data
  13869. generateBufferData();
  13870. // build geometry
  13871. this.setIndex( indices );
  13872. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13873. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13874. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13875. // functions
  13876. function generateBufferData() {
  13877. for ( let i = 0; i < tubularSegments; i ++ ) {
  13878. generateSegment( i );
  13879. }
  13880. // if the geometry is not closed, generate the last row of vertices and normals
  13881. // at the regular position on the given path
  13882. //
  13883. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13884. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13885. // uvs are generated in a separate function.
  13886. // this makes it easy compute correct values for closed geometries
  13887. generateUVs();
  13888. // finally create faces
  13889. generateIndices();
  13890. }
  13891. function generateSegment( i ) {
  13892. // we use getPointAt to sample evenly distributed points from the given path
  13893. P = path.getPointAt( i / tubularSegments, P );
  13894. // retrieve corresponding normal and binormal
  13895. const N = frames.normals[ i ];
  13896. const B = frames.binormals[ i ];
  13897. // generate normals and vertices for the current segment
  13898. for ( let j = 0; j <= radialSegments; j ++ ) {
  13899. const v = j / radialSegments * Math.PI * 2;
  13900. const sin = Math.sin( v );
  13901. const cos = - Math.cos( v );
  13902. // normal
  13903. normal.x = ( cos * N.x + sin * B.x );
  13904. normal.y = ( cos * N.y + sin * B.y );
  13905. normal.z = ( cos * N.z + sin * B.z );
  13906. normal.normalize();
  13907. normals.push( normal.x, normal.y, normal.z );
  13908. // vertex
  13909. vertex.x = P.x + radius * normal.x;
  13910. vertex.y = P.y + radius * normal.y;
  13911. vertex.z = P.z + radius * normal.z;
  13912. vertices.push( vertex.x, vertex.y, vertex.z );
  13913. }
  13914. }
  13915. function generateIndices() {
  13916. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13917. for ( let i = 1; i <= radialSegments; i ++ ) {
  13918. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13919. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13920. const c = ( radialSegments + 1 ) * j + i;
  13921. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13922. // faces
  13923. indices.push( a, b, d );
  13924. indices.push( b, c, d );
  13925. }
  13926. }
  13927. }
  13928. function generateUVs() {
  13929. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13930. for ( let j = 0; j <= radialSegments; j ++ ) {
  13931. uv.x = i / tubularSegments;
  13932. uv.y = j / radialSegments;
  13933. uvs.push( uv.x, uv.y );
  13934. }
  13935. }
  13936. }
  13937. }
  13938. copy( source ) {
  13939. super.copy( source );
  13940. this.parameters = Object.assign( {}, source.parameters );
  13941. return this;
  13942. }
  13943. toJSON() {
  13944. const data = super.toJSON();
  13945. data.path = this.parameters.path.toJSON();
  13946. return data;
  13947. }
  13948. static fromJSON( data ) {
  13949. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13950. // User defined curves or instances of CurvePath will not be deserialized.
  13951. return new TubeGeometry(
  13952. new Curves[ data.path.type ]().fromJSON( data.path ),
  13953. data.tubularSegments,
  13954. data.radius,
  13955. data.radialSegments,
  13956. data.closed
  13957. );
  13958. }
  13959. }
  13960. class WireframeGeometry extends BufferGeometry {
  13961. constructor( geometry = null ) {
  13962. super();
  13963. this.type = 'WireframeGeometry';
  13964. this.parameters = {
  13965. geometry: geometry
  13966. };
  13967. if ( geometry !== null ) {
  13968. // buffer
  13969. const vertices = [];
  13970. const edges = new Set();
  13971. // helper variables
  13972. const start = new Vector3();
  13973. const end = new Vector3();
  13974. if ( geometry.index !== null ) {
  13975. // indexed BufferGeometry
  13976. const position = geometry.attributes.position;
  13977. const indices = geometry.index;
  13978. let groups = geometry.groups;
  13979. if ( groups.length === 0 ) {
  13980. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13981. }
  13982. // create a data structure that contains all edges without duplicates
  13983. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13984. const group = groups[ o ];
  13985. const groupStart = group.start;
  13986. const groupCount = group.count;
  13987. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13988. for ( let j = 0; j < 3; j ++ ) {
  13989. const index1 = indices.getX( i + j );
  13990. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13991. start.fromBufferAttribute( position, index1 );
  13992. end.fromBufferAttribute( position, index2 );
  13993. if ( isUniqueEdge( start, end, edges ) === true ) {
  13994. vertices.push( start.x, start.y, start.z );
  13995. vertices.push( end.x, end.y, end.z );
  13996. }
  13997. }
  13998. }
  13999. }
  14000. } else {
  14001. // non-indexed BufferGeometry
  14002. const position = geometry.attributes.position;
  14003. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  14004. for ( let j = 0; j < 3; j ++ ) {
  14005. // three edges per triangle, an edge is represented as (index1, index2)
  14006. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  14007. const index1 = 3 * i + j;
  14008. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  14009. start.fromBufferAttribute( position, index1 );
  14010. end.fromBufferAttribute( position, index2 );
  14011. if ( isUniqueEdge( start, end, edges ) === true ) {
  14012. vertices.push( start.x, start.y, start.z );
  14013. vertices.push( end.x, end.y, end.z );
  14014. }
  14015. }
  14016. }
  14017. }
  14018. // build geometry
  14019. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14020. }
  14021. }
  14022. copy( source ) {
  14023. super.copy( source );
  14024. this.parameters = Object.assign( {}, source.parameters );
  14025. return this;
  14026. }
  14027. }
  14028. function isUniqueEdge( start, end, edges ) {
  14029. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  14030. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  14031. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  14032. return false;
  14033. } else {
  14034. edges.add( hash1 );
  14035. edges.add( hash2 );
  14036. return true;
  14037. }
  14038. }
  14039. var Geometries = /*#__PURE__*/Object.freeze({
  14040. __proto__: null,
  14041. BoxGeometry: BoxGeometry,
  14042. CapsuleGeometry: CapsuleGeometry,
  14043. CircleGeometry: CircleGeometry,
  14044. ConeGeometry: ConeGeometry,
  14045. CylinderGeometry: CylinderGeometry,
  14046. DodecahedronGeometry: DodecahedronGeometry,
  14047. EdgesGeometry: EdgesGeometry,
  14048. ExtrudeGeometry: ExtrudeGeometry,
  14049. IcosahedronGeometry: IcosahedronGeometry,
  14050. LatheGeometry: LatheGeometry,
  14051. OctahedronGeometry: OctahedronGeometry,
  14052. PlaneGeometry: PlaneGeometry,
  14053. PolyhedronGeometry: PolyhedronGeometry,
  14054. RingGeometry: RingGeometry,
  14055. ShapeGeometry: ShapeGeometry,
  14056. SphereGeometry: SphereGeometry,
  14057. TetrahedronGeometry: TetrahedronGeometry,
  14058. TorusGeometry: TorusGeometry,
  14059. TorusKnotGeometry: TorusKnotGeometry,
  14060. TubeGeometry: TubeGeometry,
  14061. WireframeGeometry: WireframeGeometry
  14062. });
  14063. class ShadowMaterial extends Material {
  14064. constructor( parameters ) {
  14065. super();
  14066. this.isShadowMaterial = true;
  14067. this.type = 'ShadowMaterial';
  14068. this.color = new Color( 0x000000 );
  14069. this.transparent = true;
  14070. this.fog = true;
  14071. this.setValues( parameters );
  14072. }
  14073. copy( source ) {
  14074. super.copy( source );
  14075. this.color.copy( source.color );
  14076. this.fog = source.fog;
  14077. return this;
  14078. }
  14079. }
  14080. class RawShaderMaterial extends ShaderMaterial {
  14081. constructor( parameters ) {
  14082. super( parameters );
  14083. this.isRawShaderMaterial = true;
  14084. this.type = 'RawShaderMaterial';
  14085. }
  14086. }
  14087. class MeshStandardMaterial extends Material {
  14088. constructor( parameters ) {
  14089. super();
  14090. this.isMeshStandardMaterial = true;
  14091. this.type = 'MeshStandardMaterial';
  14092. this.defines = { 'STANDARD': '' };
  14093. this.color = new Color( 0xffffff ); // diffuse
  14094. this.roughness = 1.0;
  14095. this.metalness = 0.0;
  14096. this.map = null;
  14097. this.lightMap = null;
  14098. this.lightMapIntensity = 1.0;
  14099. this.aoMap = null;
  14100. this.aoMapIntensity = 1.0;
  14101. this.emissive = new Color( 0x000000 );
  14102. this.emissiveIntensity = 1.0;
  14103. this.emissiveMap = null;
  14104. this.bumpMap = null;
  14105. this.bumpScale = 1;
  14106. this.normalMap = null;
  14107. this.normalMapType = TangentSpaceNormalMap;
  14108. this.normalScale = new Vector2( 1, 1 );
  14109. this.displacementMap = null;
  14110. this.displacementScale = 1;
  14111. this.displacementBias = 0;
  14112. this.roughnessMap = null;
  14113. this.metalnessMap = null;
  14114. this.alphaMap = null;
  14115. this.envMap = null;
  14116. this.envMapRotation = new Euler();
  14117. this.envMapIntensity = 1.0;
  14118. this.wireframe = false;
  14119. this.wireframeLinewidth = 1;
  14120. this.wireframeLinecap = 'round';
  14121. this.wireframeLinejoin = 'round';
  14122. this.flatShading = false;
  14123. this.fog = true;
  14124. this.setValues( parameters );
  14125. }
  14126. copy( source ) {
  14127. super.copy( source );
  14128. this.defines = { 'STANDARD': '' };
  14129. this.color.copy( source.color );
  14130. this.roughness = source.roughness;
  14131. this.metalness = source.metalness;
  14132. this.map = source.map;
  14133. this.lightMap = source.lightMap;
  14134. this.lightMapIntensity = source.lightMapIntensity;
  14135. this.aoMap = source.aoMap;
  14136. this.aoMapIntensity = source.aoMapIntensity;
  14137. this.emissive.copy( source.emissive );
  14138. this.emissiveMap = source.emissiveMap;
  14139. this.emissiveIntensity = source.emissiveIntensity;
  14140. this.bumpMap = source.bumpMap;
  14141. this.bumpScale = source.bumpScale;
  14142. this.normalMap = source.normalMap;
  14143. this.normalMapType = source.normalMapType;
  14144. this.normalScale.copy( source.normalScale );
  14145. this.displacementMap = source.displacementMap;
  14146. this.displacementScale = source.displacementScale;
  14147. this.displacementBias = source.displacementBias;
  14148. this.roughnessMap = source.roughnessMap;
  14149. this.metalnessMap = source.metalnessMap;
  14150. this.alphaMap = source.alphaMap;
  14151. this.envMap = source.envMap;
  14152. this.envMapRotation.copy( source.envMapRotation );
  14153. this.envMapIntensity = source.envMapIntensity;
  14154. this.wireframe = source.wireframe;
  14155. this.wireframeLinewidth = source.wireframeLinewidth;
  14156. this.wireframeLinecap = source.wireframeLinecap;
  14157. this.wireframeLinejoin = source.wireframeLinejoin;
  14158. this.flatShading = source.flatShading;
  14159. this.fog = source.fog;
  14160. return this;
  14161. }
  14162. }
  14163. class MeshPhysicalMaterial extends MeshStandardMaterial {
  14164. constructor( parameters ) {
  14165. super();
  14166. this.isMeshPhysicalMaterial = true;
  14167. this.defines = {
  14168. 'STANDARD': '',
  14169. 'PHYSICAL': ''
  14170. };
  14171. this.type = 'MeshPhysicalMaterial';
  14172. this.anisotropyRotation = 0;
  14173. this.anisotropyMap = null;
  14174. this.clearcoatMap = null;
  14175. this.clearcoatRoughness = 0.0;
  14176. this.clearcoatRoughnessMap = null;
  14177. this.clearcoatNormalScale = new Vector2( 1, 1 );
  14178. this.clearcoatNormalMap = null;
  14179. this.ior = 1.5;
  14180. Object.defineProperty( this, 'reflectivity', {
  14181. get: function () {
  14182. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  14183. },
  14184. set: function ( reflectivity ) {
  14185. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  14186. }
  14187. } );
  14188. this.iridescenceMap = null;
  14189. this.iridescenceIOR = 1.3;
  14190. this.iridescenceThicknessRange = [ 100, 400 ];
  14191. this.iridescenceThicknessMap = null;
  14192. this.sheenColor = new Color( 0x000000 );
  14193. this.sheenColorMap = null;
  14194. this.sheenRoughness = 1.0;
  14195. this.sheenRoughnessMap = null;
  14196. this.transmissionMap = null;
  14197. this.thickness = 0;
  14198. this.thicknessMap = null;
  14199. this.attenuationDistance = Infinity;
  14200. this.attenuationColor = new Color( 1, 1, 1 );
  14201. this.specularIntensity = 1.0;
  14202. this.specularIntensityMap = null;
  14203. this.specularColor = new Color( 1, 1, 1 );
  14204. this.specularColorMap = null;
  14205. this._anisotropy = 0;
  14206. this._clearcoat = 0;
  14207. this._dispersion = 0;
  14208. this._iridescence = 0;
  14209. this._sheen = 0.0;
  14210. this._transmission = 0;
  14211. this.setValues( parameters );
  14212. }
  14213. get anisotropy() {
  14214. return this._anisotropy;
  14215. }
  14216. set anisotropy( value ) {
  14217. if ( this._anisotropy > 0 !== value > 0 ) {
  14218. this.version ++;
  14219. }
  14220. this._anisotropy = value;
  14221. }
  14222. get clearcoat() {
  14223. return this._clearcoat;
  14224. }
  14225. set clearcoat( value ) {
  14226. if ( this._clearcoat > 0 !== value > 0 ) {
  14227. this.version ++;
  14228. }
  14229. this._clearcoat = value;
  14230. }
  14231. get iridescence() {
  14232. return this._iridescence;
  14233. }
  14234. set iridescence( value ) {
  14235. if ( this._iridescence > 0 !== value > 0 ) {
  14236. this.version ++;
  14237. }
  14238. this._iridescence = value;
  14239. }
  14240. get dispersion() {
  14241. return this._dispersion;
  14242. }
  14243. set dispersion( value ) {
  14244. if ( this._dispersion > 0 !== value > 0 ) {
  14245. this.version ++;
  14246. }
  14247. this._dispersion = value;
  14248. }
  14249. get sheen() {
  14250. return this._sheen;
  14251. }
  14252. set sheen( value ) {
  14253. if ( this._sheen > 0 !== value > 0 ) {
  14254. this.version ++;
  14255. }
  14256. this._sheen = value;
  14257. }
  14258. get transmission() {
  14259. return this._transmission;
  14260. }
  14261. set transmission( value ) {
  14262. if ( this._transmission > 0 !== value > 0 ) {
  14263. this.version ++;
  14264. }
  14265. this._transmission = value;
  14266. }
  14267. copy( source ) {
  14268. super.copy( source );
  14269. this.defines = {
  14270. 'STANDARD': '',
  14271. 'PHYSICAL': ''
  14272. };
  14273. this.anisotropy = source.anisotropy;
  14274. this.anisotropyRotation = source.anisotropyRotation;
  14275. this.anisotropyMap = source.anisotropyMap;
  14276. this.clearcoat = source.clearcoat;
  14277. this.clearcoatMap = source.clearcoatMap;
  14278. this.clearcoatRoughness = source.clearcoatRoughness;
  14279. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14280. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14281. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14282. this.dispersion = source.dispersion;
  14283. this.ior = source.ior;
  14284. this.iridescence = source.iridescence;
  14285. this.iridescenceMap = source.iridescenceMap;
  14286. this.iridescenceIOR = source.iridescenceIOR;
  14287. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14288. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14289. this.sheen = source.sheen;
  14290. this.sheenColor.copy( source.sheenColor );
  14291. this.sheenColorMap = source.sheenColorMap;
  14292. this.sheenRoughness = source.sheenRoughness;
  14293. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14294. this.transmission = source.transmission;
  14295. this.transmissionMap = source.transmissionMap;
  14296. this.thickness = source.thickness;
  14297. this.thicknessMap = source.thicknessMap;
  14298. this.attenuationDistance = source.attenuationDistance;
  14299. this.attenuationColor.copy( source.attenuationColor );
  14300. this.specularIntensity = source.specularIntensity;
  14301. this.specularIntensityMap = source.specularIntensityMap;
  14302. this.specularColor.copy( source.specularColor );
  14303. this.specularColorMap = source.specularColorMap;
  14304. return this;
  14305. }
  14306. }
  14307. class MeshPhongMaterial extends Material {
  14308. constructor( parameters ) {
  14309. super();
  14310. this.isMeshPhongMaterial = true;
  14311. this.type = 'MeshPhongMaterial';
  14312. this.color = new Color( 0xffffff ); // diffuse
  14313. this.specular = new Color( 0x111111 );
  14314. this.shininess = 30;
  14315. this.map = null;
  14316. this.lightMap = null;
  14317. this.lightMapIntensity = 1.0;
  14318. this.aoMap = null;
  14319. this.aoMapIntensity = 1.0;
  14320. this.emissive = new Color( 0x000000 );
  14321. this.emissiveIntensity = 1.0;
  14322. this.emissiveMap = null;
  14323. this.bumpMap = null;
  14324. this.bumpScale = 1;
  14325. this.normalMap = null;
  14326. this.normalMapType = TangentSpaceNormalMap;
  14327. this.normalScale = new Vector2( 1, 1 );
  14328. this.displacementMap = null;
  14329. this.displacementScale = 1;
  14330. this.displacementBias = 0;
  14331. this.specularMap = null;
  14332. this.alphaMap = null;
  14333. this.envMap = null;
  14334. this.envMapRotation = new Euler();
  14335. this.combine = MultiplyOperation;
  14336. this.reflectivity = 1;
  14337. this.refractionRatio = 0.98;
  14338. this.wireframe = false;
  14339. this.wireframeLinewidth = 1;
  14340. this.wireframeLinecap = 'round';
  14341. this.wireframeLinejoin = 'round';
  14342. this.flatShading = false;
  14343. this.fog = true;
  14344. this.setValues( parameters );
  14345. }
  14346. copy( source ) {
  14347. super.copy( source );
  14348. this.color.copy( source.color );
  14349. this.specular.copy( source.specular );
  14350. this.shininess = source.shininess;
  14351. this.map = source.map;
  14352. this.lightMap = source.lightMap;
  14353. this.lightMapIntensity = source.lightMapIntensity;
  14354. this.aoMap = source.aoMap;
  14355. this.aoMapIntensity = source.aoMapIntensity;
  14356. this.emissive.copy( source.emissive );
  14357. this.emissiveMap = source.emissiveMap;
  14358. this.emissiveIntensity = source.emissiveIntensity;
  14359. this.bumpMap = source.bumpMap;
  14360. this.bumpScale = source.bumpScale;
  14361. this.normalMap = source.normalMap;
  14362. this.normalMapType = source.normalMapType;
  14363. this.normalScale.copy( source.normalScale );
  14364. this.displacementMap = source.displacementMap;
  14365. this.displacementScale = source.displacementScale;
  14366. this.displacementBias = source.displacementBias;
  14367. this.specularMap = source.specularMap;
  14368. this.alphaMap = source.alphaMap;
  14369. this.envMap = source.envMap;
  14370. this.envMapRotation.copy( source.envMapRotation );
  14371. this.combine = source.combine;
  14372. this.reflectivity = source.reflectivity;
  14373. this.refractionRatio = source.refractionRatio;
  14374. this.wireframe = source.wireframe;
  14375. this.wireframeLinewidth = source.wireframeLinewidth;
  14376. this.wireframeLinecap = source.wireframeLinecap;
  14377. this.wireframeLinejoin = source.wireframeLinejoin;
  14378. this.flatShading = source.flatShading;
  14379. this.fog = source.fog;
  14380. return this;
  14381. }
  14382. }
  14383. class MeshToonMaterial extends Material {
  14384. constructor( parameters ) {
  14385. super();
  14386. this.isMeshToonMaterial = true;
  14387. this.defines = { 'TOON': '' };
  14388. this.type = 'MeshToonMaterial';
  14389. this.color = new Color( 0xffffff );
  14390. this.map = null;
  14391. this.gradientMap = null;
  14392. this.lightMap = null;
  14393. this.lightMapIntensity = 1.0;
  14394. this.aoMap = null;
  14395. this.aoMapIntensity = 1.0;
  14396. this.emissive = new Color( 0x000000 );
  14397. this.emissiveIntensity = 1.0;
  14398. this.emissiveMap = null;
  14399. this.bumpMap = null;
  14400. this.bumpScale = 1;
  14401. this.normalMap = null;
  14402. this.normalMapType = TangentSpaceNormalMap;
  14403. this.normalScale = new Vector2( 1, 1 );
  14404. this.displacementMap = null;
  14405. this.displacementScale = 1;
  14406. this.displacementBias = 0;
  14407. this.alphaMap = null;
  14408. this.wireframe = false;
  14409. this.wireframeLinewidth = 1;
  14410. this.wireframeLinecap = 'round';
  14411. this.wireframeLinejoin = 'round';
  14412. this.fog = true;
  14413. this.setValues( parameters );
  14414. }
  14415. copy( source ) {
  14416. super.copy( source );
  14417. this.color.copy( source.color );
  14418. this.map = source.map;
  14419. this.gradientMap = source.gradientMap;
  14420. this.lightMap = source.lightMap;
  14421. this.lightMapIntensity = source.lightMapIntensity;
  14422. this.aoMap = source.aoMap;
  14423. this.aoMapIntensity = source.aoMapIntensity;
  14424. this.emissive.copy( source.emissive );
  14425. this.emissiveMap = source.emissiveMap;
  14426. this.emissiveIntensity = source.emissiveIntensity;
  14427. this.bumpMap = source.bumpMap;
  14428. this.bumpScale = source.bumpScale;
  14429. this.normalMap = source.normalMap;
  14430. this.normalMapType = source.normalMapType;
  14431. this.normalScale.copy( source.normalScale );
  14432. this.displacementMap = source.displacementMap;
  14433. this.displacementScale = source.displacementScale;
  14434. this.displacementBias = source.displacementBias;
  14435. this.alphaMap = source.alphaMap;
  14436. this.wireframe = source.wireframe;
  14437. this.wireframeLinewidth = source.wireframeLinewidth;
  14438. this.wireframeLinecap = source.wireframeLinecap;
  14439. this.wireframeLinejoin = source.wireframeLinejoin;
  14440. this.fog = source.fog;
  14441. return this;
  14442. }
  14443. }
  14444. class MeshNormalMaterial extends Material {
  14445. constructor( parameters ) {
  14446. super();
  14447. this.isMeshNormalMaterial = true;
  14448. this.type = 'MeshNormalMaterial';
  14449. this.bumpMap = null;
  14450. this.bumpScale = 1;
  14451. this.normalMap = null;
  14452. this.normalMapType = TangentSpaceNormalMap;
  14453. this.normalScale = new Vector2( 1, 1 );
  14454. this.displacementMap = null;
  14455. this.displacementScale = 1;
  14456. this.displacementBias = 0;
  14457. this.wireframe = false;
  14458. this.wireframeLinewidth = 1;
  14459. this.flatShading = false;
  14460. this.setValues( parameters );
  14461. }
  14462. copy( source ) {
  14463. super.copy( source );
  14464. this.bumpMap = source.bumpMap;
  14465. this.bumpScale = source.bumpScale;
  14466. this.normalMap = source.normalMap;
  14467. this.normalMapType = source.normalMapType;
  14468. this.normalScale.copy( source.normalScale );
  14469. this.displacementMap = source.displacementMap;
  14470. this.displacementScale = source.displacementScale;
  14471. this.displacementBias = source.displacementBias;
  14472. this.wireframe = source.wireframe;
  14473. this.wireframeLinewidth = source.wireframeLinewidth;
  14474. this.flatShading = source.flatShading;
  14475. return this;
  14476. }
  14477. }
  14478. class MeshLambertMaterial extends Material {
  14479. constructor( parameters ) {
  14480. super();
  14481. this.isMeshLambertMaterial = true;
  14482. this.type = 'MeshLambertMaterial';
  14483. this.color = new Color( 0xffffff ); // diffuse
  14484. this.map = null;
  14485. this.lightMap = null;
  14486. this.lightMapIntensity = 1.0;
  14487. this.aoMap = null;
  14488. this.aoMapIntensity = 1.0;
  14489. this.emissive = new Color( 0x000000 );
  14490. this.emissiveIntensity = 1.0;
  14491. this.emissiveMap = null;
  14492. this.bumpMap = null;
  14493. this.bumpScale = 1;
  14494. this.normalMap = null;
  14495. this.normalMapType = TangentSpaceNormalMap;
  14496. this.normalScale = new Vector2( 1, 1 );
  14497. this.displacementMap = null;
  14498. this.displacementScale = 1;
  14499. this.displacementBias = 0;
  14500. this.specularMap = null;
  14501. this.alphaMap = null;
  14502. this.envMap = null;
  14503. this.envMapRotation = new Euler();
  14504. this.combine = MultiplyOperation;
  14505. this.reflectivity = 1;
  14506. this.refractionRatio = 0.98;
  14507. this.wireframe = false;
  14508. this.wireframeLinewidth = 1;
  14509. this.wireframeLinecap = 'round';
  14510. this.wireframeLinejoin = 'round';
  14511. this.flatShading = false;
  14512. this.fog = true;
  14513. this.setValues( parameters );
  14514. }
  14515. copy( source ) {
  14516. super.copy( source );
  14517. this.color.copy( source.color );
  14518. this.map = source.map;
  14519. this.lightMap = source.lightMap;
  14520. this.lightMapIntensity = source.lightMapIntensity;
  14521. this.aoMap = source.aoMap;
  14522. this.aoMapIntensity = source.aoMapIntensity;
  14523. this.emissive.copy( source.emissive );
  14524. this.emissiveMap = source.emissiveMap;
  14525. this.emissiveIntensity = source.emissiveIntensity;
  14526. this.bumpMap = source.bumpMap;
  14527. this.bumpScale = source.bumpScale;
  14528. this.normalMap = source.normalMap;
  14529. this.normalMapType = source.normalMapType;
  14530. this.normalScale.copy( source.normalScale );
  14531. this.displacementMap = source.displacementMap;
  14532. this.displacementScale = source.displacementScale;
  14533. this.displacementBias = source.displacementBias;
  14534. this.specularMap = source.specularMap;
  14535. this.alphaMap = source.alphaMap;
  14536. this.envMap = source.envMap;
  14537. this.envMapRotation.copy( source.envMapRotation );
  14538. this.combine = source.combine;
  14539. this.reflectivity = source.reflectivity;
  14540. this.refractionRatio = source.refractionRatio;
  14541. this.wireframe = source.wireframe;
  14542. this.wireframeLinewidth = source.wireframeLinewidth;
  14543. this.wireframeLinecap = source.wireframeLinecap;
  14544. this.wireframeLinejoin = source.wireframeLinejoin;
  14545. this.flatShading = source.flatShading;
  14546. this.fog = source.fog;
  14547. return this;
  14548. }
  14549. }
  14550. class MeshDepthMaterial extends Material {
  14551. constructor( parameters ) {
  14552. super();
  14553. this.isMeshDepthMaterial = true;
  14554. this.type = 'MeshDepthMaterial';
  14555. this.depthPacking = BasicDepthPacking;
  14556. this.map = null;
  14557. this.alphaMap = null;
  14558. this.displacementMap = null;
  14559. this.displacementScale = 1;
  14560. this.displacementBias = 0;
  14561. this.wireframe = false;
  14562. this.wireframeLinewidth = 1;
  14563. this.setValues( parameters );
  14564. }
  14565. copy( source ) {
  14566. super.copy( source );
  14567. this.depthPacking = source.depthPacking;
  14568. this.map = source.map;
  14569. this.alphaMap = source.alphaMap;
  14570. this.displacementMap = source.displacementMap;
  14571. this.displacementScale = source.displacementScale;
  14572. this.displacementBias = source.displacementBias;
  14573. this.wireframe = source.wireframe;
  14574. this.wireframeLinewidth = source.wireframeLinewidth;
  14575. return this;
  14576. }
  14577. }
  14578. class MeshDistanceMaterial extends Material {
  14579. constructor( parameters ) {
  14580. super();
  14581. this.isMeshDistanceMaterial = true;
  14582. this.type = 'MeshDistanceMaterial';
  14583. this.map = null;
  14584. this.alphaMap = null;
  14585. this.displacementMap = null;
  14586. this.displacementScale = 1;
  14587. this.displacementBias = 0;
  14588. this.setValues( parameters );
  14589. }
  14590. copy( source ) {
  14591. super.copy( source );
  14592. this.map = source.map;
  14593. this.alphaMap = source.alphaMap;
  14594. this.displacementMap = source.displacementMap;
  14595. this.displacementScale = source.displacementScale;
  14596. this.displacementBias = source.displacementBias;
  14597. return this;
  14598. }
  14599. }
  14600. class MeshMatcapMaterial extends Material {
  14601. constructor( parameters ) {
  14602. super();
  14603. this.isMeshMatcapMaterial = true;
  14604. this.defines = { 'MATCAP': '' };
  14605. this.type = 'MeshMatcapMaterial';
  14606. this.color = new Color( 0xffffff ); // diffuse
  14607. this.matcap = null;
  14608. this.map = null;
  14609. this.bumpMap = null;
  14610. this.bumpScale = 1;
  14611. this.normalMap = null;
  14612. this.normalMapType = TangentSpaceNormalMap;
  14613. this.normalScale = new Vector2( 1, 1 );
  14614. this.displacementMap = null;
  14615. this.displacementScale = 1;
  14616. this.displacementBias = 0;
  14617. this.alphaMap = null;
  14618. this.flatShading = false;
  14619. this.fog = true;
  14620. this.setValues( parameters );
  14621. }
  14622. copy( source ) {
  14623. super.copy( source );
  14624. this.defines = { 'MATCAP': '' };
  14625. this.color.copy( source.color );
  14626. this.matcap = source.matcap;
  14627. this.map = source.map;
  14628. this.bumpMap = source.bumpMap;
  14629. this.bumpScale = source.bumpScale;
  14630. this.normalMap = source.normalMap;
  14631. this.normalMapType = source.normalMapType;
  14632. this.normalScale.copy( source.normalScale );
  14633. this.displacementMap = source.displacementMap;
  14634. this.displacementScale = source.displacementScale;
  14635. this.displacementBias = source.displacementBias;
  14636. this.alphaMap = source.alphaMap;
  14637. this.flatShading = source.flatShading;
  14638. this.fog = source.fog;
  14639. return this;
  14640. }
  14641. }
  14642. class LineDashedMaterial extends LineBasicMaterial {
  14643. constructor( parameters ) {
  14644. super();
  14645. this.isLineDashedMaterial = true;
  14646. this.type = 'LineDashedMaterial';
  14647. this.scale = 1;
  14648. this.dashSize = 3;
  14649. this.gapSize = 1;
  14650. this.setValues( parameters );
  14651. }
  14652. copy( source ) {
  14653. super.copy( source );
  14654. this.scale = source.scale;
  14655. this.dashSize = source.dashSize;
  14656. this.gapSize = source.gapSize;
  14657. return this;
  14658. }
  14659. }
  14660. // converts an array to a specific type
  14661. function convertArray( array, type, forceClone ) {
  14662. if ( ! array || // let 'undefined' and 'null' pass
  14663. ! forceClone && array.constructor === type ) return array;
  14664. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14665. return new type( array ); // create typed array
  14666. }
  14667. return Array.prototype.slice.call( array ); // create Array
  14668. }
  14669. function isTypedArray( object ) {
  14670. return ArrayBuffer.isView( object ) &&
  14671. ! ( object instanceof DataView );
  14672. }
  14673. // returns an array by which times and values can be sorted
  14674. function getKeyframeOrder( times ) {
  14675. function compareTime( i, j ) {
  14676. return times[ i ] - times[ j ];
  14677. }
  14678. const n = times.length;
  14679. const result = new Array( n );
  14680. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14681. result.sort( compareTime );
  14682. return result;
  14683. }
  14684. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14685. function sortedArray( values, stride, order ) {
  14686. const nValues = values.length;
  14687. const result = new values.constructor( nValues );
  14688. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14689. const srcOffset = order[ i ] * stride;
  14690. for ( let j = 0; j !== stride; ++ j ) {
  14691. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14692. }
  14693. }
  14694. return result;
  14695. }
  14696. // function for parsing AOS keyframe formats
  14697. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14698. let i = 1, key = jsonKeys[ 0 ];
  14699. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14700. key = jsonKeys[ i ++ ];
  14701. }
  14702. if ( key === undefined ) return; // no data
  14703. let value = key[ valuePropertyName ];
  14704. if ( value === undefined ) return; // no data
  14705. if ( Array.isArray( value ) ) {
  14706. do {
  14707. value = key[ valuePropertyName ];
  14708. if ( value !== undefined ) {
  14709. times.push( key.time );
  14710. values.push.apply( values, value ); // push all elements
  14711. }
  14712. key = jsonKeys[ i ++ ];
  14713. } while ( key !== undefined );
  14714. } else if ( value.toArray !== undefined ) {
  14715. // ...assume THREE.Math-ish
  14716. do {
  14717. value = key[ valuePropertyName ];
  14718. if ( value !== undefined ) {
  14719. times.push( key.time );
  14720. value.toArray( values, values.length );
  14721. }
  14722. key = jsonKeys[ i ++ ];
  14723. } while ( key !== undefined );
  14724. } else {
  14725. // otherwise push as-is
  14726. do {
  14727. value = key[ valuePropertyName ];
  14728. if ( value !== undefined ) {
  14729. times.push( key.time );
  14730. values.push( value );
  14731. }
  14732. key = jsonKeys[ i ++ ];
  14733. } while ( key !== undefined );
  14734. }
  14735. }
  14736. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14737. const clip = sourceClip.clone();
  14738. clip.name = name;
  14739. const tracks = [];
  14740. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14741. const track = clip.tracks[ i ];
  14742. const valueSize = track.getValueSize();
  14743. const times = [];
  14744. const values = [];
  14745. for ( let j = 0; j < track.times.length; ++ j ) {
  14746. const frame = track.times[ j ] * fps;
  14747. if ( frame < startFrame || frame >= endFrame ) continue;
  14748. times.push( track.times[ j ] );
  14749. for ( let k = 0; k < valueSize; ++ k ) {
  14750. values.push( track.values[ j * valueSize + k ] );
  14751. }
  14752. }
  14753. if ( times.length === 0 ) continue;
  14754. track.times = convertArray( times, track.times.constructor );
  14755. track.values = convertArray( values, track.values.constructor );
  14756. tracks.push( track );
  14757. }
  14758. clip.tracks = tracks;
  14759. // find minimum .times value across all tracks in the trimmed clip
  14760. let minStartTime = Infinity;
  14761. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14762. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14763. minStartTime = clip.tracks[ i ].times[ 0 ];
  14764. }
  14765. }
  14766. // shift all tracks such that clip begins at t=0
  14767. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14768. clip.tracks[ i ].shift( - 1 * minStartTime );
  14769. }
  14770. clip.resetDuration();
  14771. return clip;
  14772. }
  14773. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14774. if ( fps <= 0 ) fps = 30;
  14775. const numTracks = referenceClip.tracks.length;
  14776. const referenceTime = referenceFrame / fps;
  14777. // Make each track's values relative to the values at the reference frame
  14778. for ( let i = 0; i < numTracks; ++ i ) {
  14779. const referenceTrack = referenceClip.tracks[ i ];
  14780. const referenceTrackType = referenceTrack.ValueTypeName;
  14781. // Skip this track if it's non-numeric
  14782. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14783. // Find the track in the target clip whose name and type matches the reference track
  14784. const targetTrack = targetClip.tracks.find( function ( track ) {
  14785. return track.name === referenceTrack.name
  14786. && track.ValueTypeName === referenceTrackType;
  14787. } );
  14788. if ( targetTrack === undefined ) continue;
  14789. let referenceOffset = 0;
  14790. const referenceValueSize = referenceTrack.getValueSize();
  14791. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14792. referenceOffset = referenceValueSize / 3;
  14793. }
  14794. let targetOffset = 0;
  14795. const targetValueSize = targetTrack.getValueSize();
  14796. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14797. targetOffset = targetValueSize / 3;
  14798. }
  14799. const lastIndex = referenceTrack.times.length - 1;
  14800. let referenceValue;
  14801. // Find the value to subtract out of the track
  14802. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14803. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14804. const startIndex = referenceOffset;
  14805. const endIndex = referenceValueSize - referenceOffset;
  14806. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14807. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14808. // Reference frame is after the last keyframe, so just use the last keyframe
  14809. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14810. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14811. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14812. } else {
  14813. // Interpolate to the reference value
  14814. const interpolant = referenceTrack.createInterpolant();
  14815. const startIndex = referenceOffset;
  14816. const endIndex = referenceValueSize - referenceOffset;
  14817. interpolant.evaluate( referenceTime );
  14818. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14819. }
  14820. // Conjugate the quaternion
  14821. if ( referenceTrackType === 'quaternion' ) {
  14822. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14823. referenceQuat.toArray( referenceValue );
  14824. }
  14825. // Subtract the reference value from all of the track values
  14826. const numTimes = targetTrack.times.length;
  14827. for ( let j = 0; j < numTimes; ++ j ) {
  14828. const valueStart = j * targetValueSize + targetOffset;
  14829. if ( referenceTrackType === 'quaternion' ) {
  14830. // Multiply the conjugate for quaternion track types
  14831. Quaternion.multiplyQuaternionsFlat(
  14832. targetTrack.values,
  14833. valueStart,
  14834. referenceValue,
  14835. 0,
  14836. targetTrack.values,
  14837. valueStart
  14838. );
  14839. } else {
  14840. const valueEnd = targetValueSize - targetOffset * 2;
  14841. // Subtract each value for all other numeric track types
  14842. for ( let k = 0; k < valueEnd; ++ k ) {
  14843. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14844. }
  14845. }
  14846. }
  14847. }
  14848. targetClip.blendMode = AdditiveAnimationBlendMode;
  14849. return targetClip;
  14850. }
  14851. const AnimationUtils = {
  14852. convertArray: convertArray,
  14853. isTypedArray: isTypedArray,
  14854. getKeyframeOrder: getKeyframeOrder,
  14855. sortedArray: sortedArray,
  14856. flattenJSON: flattenJSON,
  14857. subclip: subclip,
  14858. makeClipAdditive: makeClipAdditive
  14859. };
  14860. /**
  14861. * Abstract base class of interpolants over parametric samples.
  14862. *
  14863. * The parameter domain is one dimensional, typically the time or a path
  14864. * along a curve defined by the data.
  14865. *
  14866. * The sample values can have any dimensionality and derived classes may
  14867. * apply special interpretations to the data.
  14868. *
  14869. * This class provides the interval seek in a Template Method, deferring
  14870. * the actual interpolation to derived classes.
  14871. *
  14872. * Time complexity is O(1) for linear access crossing at most two points
  14873. * and O(log N) for random access, where N is the number of positions.
  14874. *
  14875. * References:
  14876. *
  14877. * http://www.oodesign.com/template-method-pattern.html
  14878. *
  14879. */
  14880. class Interpolant {
  14881. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14882. this.parameterPositions = parameterPositions;
  14883. this._cachedIndex = 0;
  14884. this.resultBuffer = resultBuffer !== undefined ?
  14885. resultBuffer : new sampleValues.constructor( sampleSize );
  14886. this.sampleValues = sampleValues;
  14887. this.valueSize = sampleSize;
  14888. this.settings = null;
  14889. this.DefaultSettings_ = {};
  14890. }
  14891. evaluate( t ) {
  14892. const pp = this.parameterPositions;
  14893. let i1 = this._cachedIndex,
  14894. t1 = pp[ i1 ],
  14895. t0 = pp[ i1 - 1 ];
  14896. validate_interval: {
  14897. seek: {
  14898. let right;
  14899. linear_scan: {
  14900. //- See http://jsperf.com/comparison-to-undefined/3
  14901. //- slower code:
  14902. //-
  14903. //- if ( t >= t1 || t1 === undefined ) {
  14904. forward_scan: if ( ! ( t < t1 ) ) {
  14905. for ( let giveUpAt = i1 + 2; ; ) {
  14906. if ( t1 === undefined ) {
  14907. if ( t < t0 ) break forward_scan;
  14908. // after end
  14909. i1 = pp.length;
  14910. this._cachedIndex = i1;
  14911. return this.copySampleValue_( i1 - 1 );
  14912. }
  14913. if ( i1 === giveUpAt ) break; // this loop
  14914. t0 = t1;
  14915. t1 = pp[ ++ i1 ];
  14916. if ( t < t1 ) {
  14917. // we have arrived at the sought interval
  14918. break seek;
  14919. }
  14920. }
  14921. // prepare binary search on the right side of the index
  14922. right = pp.length;
  14923. break linear_scan;
  14924. }
  14925. //- slower code:
  14926. //- if ( t < t0 || t0 === undefined ) {
  14927. if ( ! ( t >= t0 ) ) {
  14928. // looping?
  14929. const t1global = pp[ 1 ];
  14930. if ( t < t1global ) {
  14931. i1 = 2; // + 1, using the scan for the details
  14932. t0 = t1global;
  14933. }
  14934. // linear reverse scan
  14935. for ( let giveUpAt = i1 - 2; ; ) {
  14936. if ( t0 === undefined ) {
  14937. // before start
  14938. this._cachedIndex = 0;
  14939. return this.copySampleValue_( 0 );
  14940. }
  14941. if ( i1 === giveUpAt ) break; // this loop
  14942. t1 = t0;
  14943. t0 = pp[ -- i1 - 1 ];
  14944. if ( t >= t0 ) {
  14945. // we have arrived at the sought interval
  14946. break seek;
  14947. }
  14948. }
  14949. // prepare binary search on the left side of the index
  14950. right = i1;
  14951. i1 = 0;
  14952. break linear_scan;
  14953. }
  14954. // the interval is valid
  14955. break validate_interval;
  14956. } // linear scan
  14957. // binary search
  14958. while ( i1 < right ) {
  14959. const mid = ( i1 + right ) >>> 1;
  14960. if ( t < pp[ mid ] ) {
  14961. right = mid;
  14962. } else {
  14963. i1 = mid + 1;
  14964. }
  14965. }
  14966. t1 = pp[ i1 ];
  14967. t0 = pp[ i1 - 1 ];
  14968. // check boundary cases, again
  14969. if ( t0 === undefined ) {
  14970. this._cachedIndex = 0;
  14971. return this.copySampleValue_( 0 );
  14972. }
  14973. if ( t1 === undefined ) {
  14974. i1 = pp.length;
  14975. this._cachedIndex = i1;
  14976. return this.copySampleValue_( i1 - 1 );
  14977. }
  14978. } // seek
  14979. this._cachedIndex = i1;
  14980. this.intervalChanged_( i1, t0, t1 );
  14981. } // validate_interval
  14982. return this.interpolate_( i1, t0, t, t1 );
  14983. }
  14984. getSettings_() {
  14985. return this.settings || this.DefaultSettings_;
  14986. }
  14987. copySampleValue_( index ) {
  14988. // copies a sample value to the result buffer
  14989. const result = this.resultBuffer,
  14990. values = this.sampleValues,
  14991. stride = this.valueSize,
  14992. offset = index * stride;
  14993. for ( let i = 0; i !== stride; ++ i ) {
  14994. result[ i ] = values[ offset + i ];
  14995. }
  14996. return result;
  14997. }
  14998. // Template methods for derived classes:
  14999. interpolate_( /* i1, t0, t, t1 */ ) {
  15000. throw new Error( 'call to abstract method' );
  15001. // implementations shall return this.resultBuffer
  15002. }
  15003. intervalChanged_( /* i1, t0, t1 */ ) {
  15004. // empty
  15005. }
  15006. }
  15007. /**
  15008. * Fast and simple cubic spline interpolant.
  15009. *
  15010. * It was derived from a Hermitian construction setting the first derivative
  15011. * at each sample position to the linear slope between neighboring positions
  15012. * over their parameter interval.
  15013. */
  15014. class CubicInterpolant extends Interpolant {
  15015. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15016. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15017. this._weightPrev = - 0;
  15018. this._offsetPrev = - 0;
  15019. this._weightNext = - 0;
  15020. this._offsetNext = - 0;
  15021. this.DefaultSettings_ = {
  15022. endingStart: ZeroCurvatureEnding,
  15023. endingEnd: ZeroCurvatureEnding
  15024. };
  15025. }
  15026. intervalChanged_( i1, t0, t1 ) {
  15027. const pp = this.parameterPositions;
  15028. let iPrev = i1 - 2,
  15029. iNext = i1 + 1,
  15030. tPrev = pp[ iPrev ],
  15031. tNext = pp[ iNext ];
  15032. if ( tPrev === undefined ) {
  15033. switch ( this.getSettings_().endingStart ) {
  15034. case ZeroSlopeEnding:
  15035. // f'(t0) = 0
  15036. iPrev = i1;
  15037. tPrev = 2 * t0 - t1;
  15038. break;
  15039. case WrapAroundEnding:
  15040. // use the other end of the curve
  15041. iPrev = pp.length - 2;
  15042. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  15043. break;
  15044. default: // ZeroCurvatureEnding
  15045. // f''(t0) = 0 a.k.a. Natural Spline
  15046. iPrev = i1;
  15047. tPrev = t1;
  15048. }
  15049. }
  15050. if ( tNext === undefined ) {
  15051. switch ( this.getSettings_().endingEnd ) {
  15052. case ZeroSlopeEnding:
  15053. // f'(tN) = 0
  15054. iNext = i1;
  15055. tNext = 2 * t1 - t0;
  15056. break;
  15057. case WrapAroundEnding:
  15058. // use the other end of the curve
  15059. iNext = 1;
  15060. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  15061. break;
  15062. default: // ZeroCurvatureEnding
  15063. // f''(tN) = 0, a.k.a. Natural Spline
  15064. iNext = i1 - 1;
  15065. tNext = t0;
  15066. }
  15067. }
  15068. const halfDt = ( t1 - t0 ) * 0.5,
  15069. stride = this.valueSize;
  15070. this._weightPrev = halfDt / ( t0 - tPrev );
  15071. this._weightNext = halfDt / ( tNext - t1 );
  15072. this._offsetPrev = iPrev * stride;
  15073. this._offsetNext = iNext * stride;
  15074. }
  15075. interpolate_( i1, t0, t, t1 ) {
  15076. const result = this.resultBuffer,
  15077. values = this.sampleValues,
  15078. stride = this.valueSize,
  15079. o1 = i1 * stride, o0 = o1 - stride,
  15080. oP = this._offsetPrev, oN = this._offsetNext,
  15081. wP = this._weightPrev, wN = this._weightNext,
  15082. p = ( t - t0 ) / ( t1 - t0 ),
  15083. pp = p * p,
  15084. ppp = pp * p;
  15085. // evaluate polynomials
  15086. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  15087. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  15088. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15089. const sN = wN * ppp - wN * pp;
  15090. // combine data linearly
  15091. for ( let i = 0; i !== stride; ++ i ) {
  15092. result[ i ] =
  15093. sP * values[ oP + i ] +
  15094. s0 * values[ o0 + i ] +
  15095. s1 * values[ o1 + i ] +
  15096. sN * values[ oN + i ];
  15097. }
  15098. return result;
  15099. }
  15100. }
  15101. class LinearInterpolant extends Interpolant {
  15102. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15103. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15104. }
  15105. interpolate_( i1, t0, t, t1 ) {
  15106. const result = this.resultBuffer,
  15107. values = this.sampleValues,
  15108. stride = this.valueSize,
  15109. offset1 = i1 * stride,
  15110. offset0 = offset1 - stride,
  15111. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15112. weight0 = 1 - weight1;
  15113. for ( let i = 0; i !== stride; ++ i ) {
  15114. result[ i ] =
  15115. values[ offset0 + i ] * weight0 +
  15116. values[ offset1 + i ] * weight1;
  15117. }
  15118. return result;
  15119. }
  15120. }
  15121. /**
  15122. *
  15123. * Interpolant that evaluates to the sample value at the position preceding
  15124. * the parameter.
  15125. */
  15126. class DiscreteInterpolant extends Interpolant {
  15127. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15128. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15129. }
  15130. interpolate_( i1 /*, t0, t, t1 */ ) {
  15131. return this.copySampleValue_( i1 - 1 );
  15132. }
  15133. }
  15134. class KeyframeTrack {
  15135. constructor( name, times, values, interpolation ) {
  15136. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  15137. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  15138. this.name = name;
  15139. this.times = convertArray( times, this.TimeBufferType );
  15140. this.values = convertArray( values, this.ValueBufferType );
  15141. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15142. }
  15143. // Serialization (in static context, because of constructor invocation
  15144. // and automatic invocation of .toJSON):
  15145. static toJSON( track ) {
  15146. const trackType = track.constructor;
  15147. let json;
  15148. // derived classes can define a static toJSON method
  15149. if ( trackType.toJSON !== this.toJSON ) {
  15150. json = trackType.toJSON( track );
  15151. } else {
  15152. // by default, we assume the data can be serialized as-is
  15153. json = {
  15154. 'name': track.name,
  15155. 'times': convertArray( track.times, Array ),
  15156. 'values': convertArray( track.values, Array )
  15157. };
  15158. const interpolation = track.getInterpolation();
  15159. if ( interpolation !== track.DefaultInterpolation ) {
  15160. json.interpolation = interpolation;
  15161. }
  15162. }
  15163. json.type = track.ValueTypeName; // mandatory
  15164. return json;
  15165. }
  15166. InterpolantFactoryMethodDiscrete( result ) {
  15167. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  15168. }
  15169. InterpolantFactoryMethodLinear( result ) {
  15170. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15171. }
  15172. InterpolantFactoryMethodSmooth( result ) {
  15173. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  15174. }
  15175. setInterpolation( interpolation ) {
  15176. let factoryMethod;
  15177. switch ( interpolation ) {
  15178. case InterpolateDiscrete:
  15179. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15180. break;
  15181. case InterpolateLinear:
  15182. factoryMethod = this.InterpolantFactoryMethodLinear;
  15183. break;
  15184. case InterpolateSmooth:
  15185. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15186. break;
  15187. }
  15188. if ( factoryMethod === undefined ) {
  15189. const message = 'unsupported interpolation for ' +
  15190. this.ValueTypeName + ' keyframe track named ' + this.name;
  15191. if ( this.createInterpolant === undefined ) {
  15192. // fall back to default, unless the default itself is messed up
  15193. if ( interpolation !== this.DefaultInterpolation ) {
  15194. this.setInterpolation( this.DefaultInterpolation );
  15195. } else {
  15196. throw new Error( message ); // fatal, in this case
  15197. }
  15198. }
  15199. console.warn( 'THREE.KeyframeTrack:', message );
  15200. return this;
  15201. }
  15202. this.createInterpolant = factoryMethod;
  15203. return this;
  15204. }
  15205. getInterpolation() {
  15206. switch ( this.createInterpolant ) {
  15207. case this.InterpolantFactoryMethodDiscrete:
  15208. return InterpolateDiscrete;
  15209. case this.InterpolantFactoryMethodLinear:
  15210. return InterpolateLinear;
  15211. case this.InterpolantFactoryMethodSmooth:
  15212. return InterpolateSmooth;
  15213. }
  15214. }
  15215. getValueSize() {
  15216. return this.values.length / this.times.length;
  15217. }
  15218. // move all keyframes either forwards or backwards in time
  15219. shift( timeOffset ) {
  15220. if ( timeOffset !== 0.0 ) {
  15221. const times = this.times;
  15222. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15223. times[ i ] += timeOffset;
  15224. }
  15225. }
  15226. return this;
  15227. }
  15228. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15229. scale( timeScale ) {
  15230. if ( timeScale !== 1.0 ) {
  15231. const times = this.times;
  15232. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15233. times[ i ] *= timeScale;
  15234. }
  15235. }
  15236. return this;
  15237. }
  15238. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15239. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15240. trim( startTime, endTime ) {
  15241. const times = this.times,
  15242. nKeys = times.length;
  15243. let from = 0,
  15244. to = nKeys - 1;
  15245. while ( from !== nKeys && times[ from ] < startTime ) {
  15246. ++ from;
  15247. }
  15248. while ( to !== - 1 && times[ to ] > endTime ) {
  15249. -- to;
  15250. }
  15251. ++ to; // inclusive -> exclusive bound
  15252. if ( from !== 0 || to !== nKeys ) {
  15253. // empty tracks are forbidden, so keep at least one keyframe
  15254. if ( from >= to ) {
  15255. to = Math.max( to, 1 );
  15256. from = to - 1;
  15257. }
  15258. const stride = this.getValueSize();
  15259. this.times = times.slice( from, to );
  15260. this.values = this.values.slice( from * stride, to * stride );
  15261. }
  15262. return this;
  15263. }
  15264. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15265. validate() {
  15266. let valid = true;
  15267. const valueSize = this.getValueSize();
  15268. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15269. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  15270. valid = false;
  15271. }
  15272. const times = this.times,
  15273. values = this.values,
  15274. nKeys = times.length;
  15275. if ( nKeys === 0 ) {
  15276. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15277. valid = false;
  15278. }
  15279. let prevTime = null;
  15280. for ( let i = 0; i !== nKeys; i ++ ) {
  15281. const currTime = times[ i ];
  15282. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15283. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15284. valid = false;
  15285. break;
  15286. }
  15287. if ( prevTime !== null && prevTime > currTime ) {
  15288. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15289. valid = false;
  15290. break;
  15291. }
  15292. prevTime = currTime;
  15293. }
  15294. if ( values !== undefined ) {
  15295. if ( isTypedArray( values ) ) {
  15296. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15297. const value = values[ i ];
  15298. if ( isNaN( value ) ) {
  15299. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15300. valid = false;
  15301. break;
  15302. }
  15303. }
  15304. }
  15305. }
  15306. return valid;
  15307. }
  15308. // removes equivalent sequential keys as common in morph target sequences
  15309. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15310. optimize() {
  15311. // times or values may be shared with other tracks, so overwriting is unsafe
  15312. const times = this.times.slice(),
  15313. values = this.values.slice(),
  15314. stride = this.getValueSize(),
  15315. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15316. lastIndex = times.length - 1;
  15317. let writeIndex = 1;
  15318. for ( let i = 1; i < lastIndex; ++ i ) {
  15319. let keep = false;
  15320. const time = times[ i ];
  15321. const timeNext = times[ i + 1 ];
  15322. // remove adjacent keyframes scheduled at the same time
  15323. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15324. if ( ! smoothInterpolation ) {
  15325. // remove unnecessary keyframes same as their neighbors
  15326. const offset = i * stride,
  15327. offsetP = offset - stride,
  15328. offsetN = offset + stride;
  15329. for ( let j = 0; j !== stride; ++ j ) {
  15330. const value = values[ offset + j ];
  15331. if ( value !== values[ offsetP + j ] ||
  15332. value !== values[ offsetN + j ] ) {
  15333. keep = true;
  15334. break;
  15335. }
  15336. }
  15337. } else {
  15338. keep = true;
  15339. }
  15340. }
  15341. // in-place compaction
  15342. if ( keep ) {
  15343. if ( i !== writeIndex ) {
  15344. times[ writeIndex ] = times[ i ];
  15345. const readOffset = i * stride,
  15346. writeOffset = writeIndex * stride;
  15347. for ( let j = 0; j !== stride; ++ j ) {
  15348. values[ writeOffset + j ] = values[ readOffset + j ];
  15349. }
  15350. }
  15351. ++ writeIndex;
  15352. }
  15353. }
  15354. // flush last keyframe (compaction looks ahead)
  15355. if ( lastIndex > 0 ) {
  15356. times[ writeIndex ] = times[ lastIndex ];
  15357. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15358. values[ writeOffset + j ] = values[ readOffset + j ];
  15359. }
  15360. ++ writeIndex;
  15361. }
  15362. if ( writeIndex !== times.length ) {
  15363. this.times = times.slice( 0, writeIndex );
  15364. this.values = values.slice( 0, writeIndex * stride );
  15365. } else {
  15366. this.times = times;
  15367. this.values = values;
  15368. }
  15369. return this;
  15370. }
  15371. clone() {
  15372. const times = this.times.slice();
  15373. const values = this.values.slice();
  15374. const TypedKeyframeTrack = this.constructor;
  15375. const track = new TypedKeyframeTrack( this.name, times, values );
  15376. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15377. track.createInterpolant = this.createInterpolant;
  15378. return track;
  15379. }
  15380. }
  15381. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15382. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15383. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15384. /**
  15385. * A Track of Boolean keyframe values.
  15386. */
  15387. class BooleanKeyframeTrack extends KeyframeTrack {
  15388. // No interpolation parameter because only InterpolateDiscrete is valid.
  15389. constructor( name, times, values ) {
  15390. super( name, times, values );
  15391. }
  15392. }
  15393. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15394. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15395. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15396. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15397. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15398. /**
  15399. * A Track of keyframe values that represent color.
  15400. */
  15401. class ColorKeyframeTrack extends KeyframeTrack {}
  15402. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15403. /**
  15404. * A Track of numeric keyframe values.
  15405. */
  15406. class NumberKeyframeTrack extends KeyframeTrack {}
  15407. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15408. /**
  15409. * Spherical linear unit quaternion interpolant.
  15410. */
  15411. class QuaternionLinearInterpolant extends Interpolant {
  15412. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15413. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15414. }
  15415. interpolate_( i1, t0, t, t1 ) {
  15416. const result = this.resultBuffer,
  15417. values = this.sampleValues,
  15418. stride = this.valueSize,
  15419. alpha = ( t - t0 ) / ( t1 - t0 );
  15420. let offset = i1 * stride;
  15421. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15422. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15423. }
  15424. return result;
  15425. }
  15426. }
  15427. /**
  15428. * A Track of quaternion keyframe values.
  15429. */
  15430. class QuaternionKeyframeTrack extends KeyframeTrack {
  15431. InterpolantFactoryMethodLinear( result ) {
  15432. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15433. }
  15434. }
  15435. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15436. // ValueBufferType is inherited
  15437. // DefaultInterpolation is inherited;
  15438. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15439. /**
  15440. * A Track that interpolates Strings
  15441. */
  15442. class StringKeyframeTrack extends KeyframeTrack {
  15443. // No interpolation parameter because only InterpolateDiscrete is valid.
  15444. constructor( name, times, values ) {
  15445. super( name, times, values );
  15446. }
  15447. }
  15448. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15449. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15450. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15451. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15452. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15453. /**
  15454. * A Track of vectored keyframe values.
  15455. */
  15456. class VectorKeyframeTrack extends KeyframeTrack {}
  15457. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15458. class AnimationClip {
  15459. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15460. this.name = name;
  15461. this.tracks = tracks;
  15462. this.duration = duration;
  15463. this.blendMode = blendMode;
  15464. this.uuid = generateUUID();
  15465. // this means it should figure out its duration by scanning the tracks
  15466. if ( this.duration < 0 ) {
  15467. this.resetDuration();
  15468. }
  15469. }
  15470. static parse( json ) {
  15471. const tracks = [],
  15472. jsonTracks = json.tracks,
  15473. frameTime = 1.0 / ( json.fps || 1.0 );
  15474. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15475. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15476. }
  15477. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15478. clip.uuid = json.uuid;
  15479. return clip;
  15480. }
  15481. static toJSON( clip ) {
  15482. const tracks = [],
  15483. clipTracks = clip.tracks;
  15484. const json = {
  15485. 'name': clip.name,
  15486. 'duration': clip.duration,
  15487. 'tracks': tracks,
  15488. 'uuid': clip.uuid,
  15489. 'blendMode': clip.blendMode
  15490. };
  15491. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15492. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15493. }
  15494. return json;
  15495. }
  15496. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15497. const numMorphTargets = morphTargetSequence.length;
  15498. const tracks = [];
  15499. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15500. let times = [];
  15501. let values = [];
  15502. times.push(
  15503. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15504. i,
  15505. ( i + 1 ) % numMorphTargets );
  15506. values.push( 0, 1, 0 );
  15507. const order = getKeyframeOrder( times );
  15508. times = sortedArray( times, 1, order );
  15509. values = sortedArray( values, 1, order );
  15510. // if there is a key at the first frame, duplicate it as the
  15511. // last frame as well for perfect loop.
  15512. if ( ! noLoop && times[ 0 ] === 0 ) {
  15513. times.push( numMorphTargets );
  15514. values.push( values[ 0 ] );
  15515. }
  15516. tracks.push(
  15517. new NumberKeyframeTrack(
  15518. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15519. times, values
  15520. ).scale( 1.0 / fps ) );
  15521. }
  15522. return new this( name, - 1, tracks );
  15523. }
  15524. static findByName( objectOrClipArray, name ) {
  15525. let clipArray = objectOrClipArray;
  15526. if ( ! Array.isArray( objectOrClipArray ) ) {
  15527. const o = objectOrClipArray;
  15528. clipArray = o.geometry && o.geometry.animations || o.animations;
  15529. }
  15530. for ( let i = 0; i < clipArray.length; i ++ ) {
  15531. if ( clipArray[ i ].name === name ) {
  15532. return clipArray[ i ];
  15533. }
  15534. }
  15535. return null;
  15536. }
  15537. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15538. const animationToMorphTargets = {};
  15539. // tested with https://regex101.com/ on trick sequences
  15540. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15541. const pattern = /^([\w-]*?)([\d]+)$/;
  15542. // sort morph target names into animation groups based
  15543. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15544. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15545. const morphTarget = morphTargets[ i ];
  15546. const parts = morphTarget.name.match( pattern );
  15547. if ( parts && parts.length > 1 ) {
  15548. const name = parts[ 1 ];
  15549. let animationMorphTargets = animationToMorphTargets[ name ];
  15550. if ( ! animationMorphTargets ) {
  15551. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15552. }
  15553. animationMorphTargets.push( morphTarget );
  15554. }
  15555. }
  15556. const clips = [];
  15557. for ( const name in animationToMorphTargets ) {
  15558. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15559. }
  15560. return clips;
  15561. }
  15562. // parse the animation.hierarchy format
  15563. static parseAnimation( animation, bones ) {
  15564. if ( ! animation ) {
  15565. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15566. return null;
  15567. }
  15568. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15569. // only return track if there are actually keys.
  15570. if ( animationKeys.length !== 0 ) {
  15571. const times = [];
  15572. const values = [];
  15573. flattenJSON( animationKeys, times, values, propertyName );
  15574. // empty keys are filtered out, so check again
  15575. if ( times.length !== 0 ) {
  15576. destTracks.push( new trackType( trackName, times, values ) );
  15577. }
  15578. }
  15579. };
  15580. const tracks = [];
  15581. const clipName = animation.name || 'default';
  15582. const fps = animation.fps || 30;
  15583. const blendMode = animation.blendMode;
  15584. // automatic length determination in AnimationClip.
  15585. let duration = animation.length || - 1;
  15586. const hierarchyTracks = animation.hierarchy || [];
  15587. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15588. const animationKeys = hierarchyTracks[ h ].keys;
  15589. // skip empty tracks
  15590. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15591. // process morph targets
  15592. if ( animationKeys[ 0 ].morphTargets ) {
  15593. // figure out all morph targets used in this track
  15594. const morphTargetNames = {};
  15595. let k;
  15596. for ( k = 0; k < animationKeys.length; k ++ ) {
  15597. if ( animationKeys[ k ].morphTargets ) {
  15598. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15599. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15600. }
  15601. }
  15602. }
  15603. // create a track for each morph target with all zero
  15604. // morphTargetInfluences except for the keys in which
  15605. // the morphTarget is named.
  15606. for ( const morphTargetName in morphTargetNames ) {
  15607. const times = [];
  15608. const values = [];
  15609. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15610. const animationKey = animationKeys[ k ];
  15611. times.push( animationKey.time );
  15612. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15613. }
  15614. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15615. }
  15616. duration = morphTargetNames.length * fps;
  15617. } else {
  15618. // ...assume skeletal animation
  15619. const boneName = '.bones[' + bones[ h ].name + ']';
  15620. addNonemptyTrack(
  15621. VectorKeyframeTrack, boneName + '.position',
  15622. animationKeys, 'pos', tracks );
  15623. addNonemptyTrack(
  15624. QuaternionKeyframeTrack, boneName + '.quaternion',
  15625. animationKeys, 'rot', tracks );
  15626. addNonemptyTrack(
  15627. VectorKeyframeTrack, boneName + '.scale',
  15628. animationKeys, 'scl', tracks );
  15629. }
  15630. }
  15631. if ( tracks.length === 0 ) {
  15632. return null;
  15633. }
  15634. const clip = new this( clipName, duration, tracks, blendMode );
  15635. return clip;
  15636. }
  15637. resetDuration() {
  15638. const tracks = this.tracks;
  15639. let duration = 0;
  15640. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15641. const track = this.tracks[ i ];
  15642. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15643. }
  15644. this.duration = duration;
  15645. return this;
  15646. }
  15647. trim() {
  15648. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15649. this.tracks[ i ].trim( 0, this.duration );
  15650. }
  15651. return this;
  15652. }
  15653. validate() {
  15654. let valid = true;
  15655. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15656. valid = valid && this.tracks[ i ].validate();
  15657. }
  15658. return valid;
  15659. }
  15660. optimize() {
  15661. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15662. this.tracks[ i ].optimize();
  15663. }
  15664. return this;
  15665. }
  15666. clone() {
  15667. const tracks = [];
  15668. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15669. tracks.push( this.tracks[ i ].clone() );
  15670. }
  15671. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15672. }
  15673. toJSON() {
  15674. return this.constructor.toJSON( this );
  15675. }
  15676. }
  15677. function getTrackTypeForValueTypeName( typeName ) {
  15678. switch ( typeName.toLowerCase() ) {
  15679. case 'scalar':
  15680. case 'double':
  15681. case 'float':
  15682. case 'number':
  15683. case 'integer':
  15684. return NumberKeyframeTrack;
  15685. case 'vector':
  15686. case 'vector2':
  15687. case 'vector3':
  15688. case 'vector4':
  15689. return VectorKeyframeTrack;
  15690. case 'color':
  15691. return ColorKeyframeTrack;
  15692. case 'quaternion':
  15693. return QuaternionKeyframeTrack;
  15694. case 'bool':
  15695. case 'boolean':
  15696. return BooleanKeyframeTrack;
  15697. case 'string':
  15698. return StringKeyframeTrack;
  15699. }
  15700. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15701. }
  15702. function parseKeyframeTrack( json ) {
  15703. if ( json.type === undefined ) {
  15704. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15705. }
  15706. const trackType = getTrackTypeForValueTypeName( json.type );
  15707. if ( json.times === undefined ) {
  15708. const times = [], values = [];
  15709. flattenJSON( json.keys, times, values, 'value' );
  15710. json.times = times;
  15711. json.values = values;
  15712. }
  15713. // derived classes can define a static parse method
  15714. if ( trackType.parse !== undefined ) {
  15715. return trackType.parse( json );
  15716. } else {
  15717. // by default, we assume a constructor compatible with the base
  15718. return new trackType( json.name, json.times, json.values, json.interpolation );
  15719. }
  15720. }
  15721. const Cache = {
  15722. enabled: false,
  15723. files: {},
  15724. add: function ( key, file ) {
  15725. if ( this.enabled === false ) return;
  15726. // console.log( 'THREE.Cache', 'Adding key:', key );
  15727. this.files[ key ] = file;
  15728. },
  15729. get: function ( key ) {
  15730. if ( this.enabled === false ) return;
  15731. // console.log( 'THREE.Cache', 'Checking key:', key );
  15732. return this.files[ key ];
  15733. },
  15734. remove: function ( key ) {
  15735. delete this.files[ key ];
  15736. },
  15737. clear: function () {
  15738. this.files = {};
  15739. }
  15740. };
  15741. class LoadingManager {
  15742. constructor( onLoad, onProgress, onError ) {
  15743. const scope = this;
  15744. let isLoading = false;
  15745. let itemsLoaded = 0;
  15746. let itemsTotal = 0;
  15747. let urlModifier = undefined;
  15748. const handlers = [];
  15749. // Refer to #5689 for the reason why we don't set .onStart
  15750. // in the constructor
  15751. this.onStart = undefined;
  15752. this.onLoad = onLoad;
  15753. this.onProgress = onProgress;
  15754. this.onError = onError;
  15755. this.itemStart = function ( url ) {
  15756. itemsTotal ++;
  15757. if ( isLoading === false ) {
  15758. if ( scope.onStart !== undefined ) {
  15759. scope.onStart( url, itemsLoaded, itemsTotal );
  15760. }
  15761. }
  15762. isLoading = true;
  15763. };
  15764. this.itemEnd = function ( url ) {
  15765. itemsLoaded ++;
  15766. if ( scope.onProgress !== undefined ) {
  15767. scope.onProgress( url, itemsLoaded, itemsTotal );
  15768. }
  15769. if ( itemsLoaded === itemsTotal ) {
  15770. isLoading = false;
  15771. if ( scope.onLoad !== undefined ) {
  15772. scope.onLoad();
  15773. }
  15774. }
  15775. };
  15776. this.itemError = function ( url ) {
  15777. if ( scope.onError !== undefined ) {
  15778. scope.onError( url );
  15779. }
  15780. };
  15781. this.resolveURL = function ( url ) {
  15782. if ( urlModifier ) {
  15783. return urlModifier( url );
  15784. }
  15785. return url;
  15786. };
  15787. this.setURLModifier = function ( transform ) {
  15788. urlModifier = transform;
  15789. return this;
  15790. };
  15791. this.addHandler = function ( regex, loader ) {
  15792. handlers.push( regex, loader );
  15793. return this;
  15794. };
  15795. this.removeHandler = function ( regex ) {
  15796. const index = handlers.indexOf( regex );
  15797. if ( index !== - 1 ) {
  15798. handlers.splice( index, 2 );
  15799. }
  15800. return this;
  15801. };
  15802. this.getHandler = function ( file ) {
  15803. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15804. const regex = handlers[ i ];
  15805. const loader = handlers[ i + 1 ];
  15806. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15807. if ( regex.test( file ) ) {
  15808. return loader;
  15809. }
  15810. }
  15811. return null;
  15812. };
  15813. }
  15814. }
  15815. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15816. class Loader {
  15817. constructor( manager ) {
  15818. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15819. this.crossOrigin = 'anonymous';
  15820. this.withCredentials = false;
  15821. this.path = '';
  15822. this.resourcePath = '';
  15823. this.requestHeader = {};
  15824. }
  15825. load( /* url, onLoad, onProgress, onError */ ) {}
  15826. loadAsync( url, onProgress ) {
  15827. const scope = this;
  15828. return new Promise( function ( resolve, reject ) {
  15829. scope.load( url, resolve, onProgress, reject );
  15830. } );
  15831. }
  15832. parse( /* data */ ) {}
  15833. setCrossOrigin( crossOrigin ) {
  15834. this.crossOrigin = crossOrigin;
  15835. return this;
  15836. }
  15837. setWithCredentials( value ) {
  15838. this.withCredentials = value;
  15839. return this;
  15840. }
  15841. setPath( path ) {
  15842. this.path = path;
  15843. return this;
  15844. }
  15845. setResourcePath( resourcePath ) {
  15846. this.resourcePath = resourcePath;
  15847. return this;
  15848. }
  15849. setRequestHeader( requestHeader ) {
  15850. this.requestHeader = requestHeader;
  15851. return this;
  15852. }
  15853. }
  15854. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15855. const loading = {};
  15856. class HttpError extends Error {
  15857. constructor( message, response ) {
  15858. super( message );
  15859. this.response = response;
  15860. }
  15861. }
  15862. class FileLoader extends Loader {
  15863. constructor( manager ) {
  15864. super( manager );
  15865. }
  15866. load( url, onLoad, onProgress, onError ) {
  15867. if ( url === undefined ) url = '';
  15868. if ( this.path !== undefined ) url = this.path + url;
  15869. url = this.manager.resolveURL( url );
  15870. const cached = Cache.get( url );
  15871. if ( cached !== undefined ) {
  15872. this.manager.itemStart( url );
  15873. setTimeout( () => {
  15874. if ( onLoad ) onLoad( cached );
  15875. this.manager.itemEnd( url );
  15876. }, 0 );
  15877. return cached;
  15878. }
  15879. // Check if request is duplicate
  15880. if ( loading[ url ] !== undefined ) {
  15881. loading[ url ].push( {
  15882. onLoad: onLoad,
  15883. onProgress: onProgress,
  15884. onError: onError
  15885. } );
  15886. return;
  15887. }
  15888. // Initialise array for duplicate requests
  15889. loading[ url ] = [];
  15890. loading[ url ].push( {
  15891. onLoad: onLoad,
  15892. onProgress: onProgress,
  15893. onError: onError,
  15894. } );
  15895. // create request
  15896. const req = new Request( url, {
  15897. headers: new Headers( this.requestHeader ),
  15898. credentials: this.withCredentials ? 'include' : 'same-origin',
  15899. // An abort controller could be added within a future PR
  15900. } );
  15901. // record states ( avoid data race )
  15902. const mimeType = this.mimeType;
  15903. const responseType = this.responseType;
  15904. // start the fetch
  15905. fetch( req )
  15906. .then( response => {
  15907. if ( response.status === 200 || response.status === 0 ) {
  15908. // Some browsers return HTTP Status 0 when using non-http protocol
  15909. // e.g. 'file://' or 'data://'. Handle as success.
  15910. if ( response.status === 0 ) {
  15911. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15912. }
  15913. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15914. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15915. return response;
  15916. }
  15917. const callbacks = loading[ url ];
  15918. const reader = response.body.getReader();
  15919. // Nginx needs X-File-Size check
  15920. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15921. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15922. const total = contentLength ? parseInt( contentLength ) : 0;
  15923. const lengthComputable = total !== 0;
  15924. let loaded = 0;
  15925. // periodically read data into the new stream tracking while download progress
  15926. const stream = new ReadableStream( {
  15927. start( controller ) {
  15928. readData();
  15929. function readData() {
  15930. reader.read().then( ( { done, value } ) => {
  15931. if ( done ) {
  15932. controller.close();
  15933. } else {
  15934. loaded += value.byteLength;
  15935. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15936. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15937. const callback = callbacks[ i ];
  15938. if ( callback.onProgress ) callback.onProgress( event );
  15939. }
  15940. controller.enqueue( value );
  15941. readData();
  15942. }
  15943. }, ( e ) => {
  15944. controller.error( e );
  15945. } );
  15946. }
  15947. }
  15948. } );
  15949. return new Response( stream );
  15950. } else {
  15951. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15952. }
  15953. } )
  15954. .then( response => {
  15955. switch ( responseType ) {
  15956. case 'arraybuffer':
  15957. return response.arrayBuffer();
  15958. case 'blob':
  15959. return response.blob();
  15960. case 'document':
  15961. return response.text()
  15962. .then( text => {
  15963. const parser = new DOMParser();
  15964. return parser.parseFromString( text, mimeType );
  15965. } );
  15966. case 'json':
  15967. return response.json();
  15968. default:
  15969. if ( mimeType === undefined ) {
  15970. return response.text();
  15971. } else {
  15972. // sniff encoding
  15973. const re = /charset="?([^;"\s]*)"?/i;
  15974. const exec = re.exec( mimeType );
  15975. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15976. const decoder = new TextDecoder( label );
  15977. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15978. }
  15979. }
  15980. } )
  15981. .then( data => {
  15982. // Add to cache only on HTTP success, so that we do not cache
  15983. // error response bodies as proper responses to requests.
  15984. Cache.add( url, data );
  15985. const callbacks = loading[ url ];
  15986. delete loading[ url ];
  15987. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15988. const callback = callbacks[ i ];
  15989. if ( callback.onLoad ) callback.onLoad( data );
  15990. }
  15991. } )
  15992. .catch( err => {
  15993. // Abort errors and other errors are handled the same
  15994. const callbacks = loading[ url ];
  15995. if ( callbacks === undefined ) {
  15996. // When onLoad was called and url was deleted in `loading`
  15997. this.manager.itemError( url );
  15998. throw err;
  15999. }
  16000. delete loading[ url ];
  16001. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  16002. const callback = callbacks[ i ];
  16003. if ( callback.onError ) callback.onError( err );
  16004. }
  16005. this.manager.itemError( url );
  16006. } )
  16007. .finally( () => {
  16008. this.manager.itemEnd( url );
  16009. } );
  16010. this.manager.itemStart( url );
  16011. }
  16012. setResponseType( value ) {
  16013. this.responseType = value;
  16014. return this;
  16015. }
  16016. setMimeType( value ) {
  16017. this.mimeType = value;
  16018. return this;
  16019. }
  16020. }
  16021. class AnimationLoader extends Loader {
  16022. constructor( manager ) {
  16023. super( manager );
  16024. }
  16025. load( url, onLoad, onProgress, onError ) {
  16026. const scope = this;
  16027. const loader = new FileLoader( this.manager );
  16028. loader.setPath( this.path );
  16029. loader.setRequestHeader( this.requestHeader );
  16030. loader.setWithCredentials( this.withCredentials );
  16031. loader.load( url, function ( text ) {
  16032. try {
  16033. onLoad( scope.parse( JSON.parse( text ) ) );
  16034. } catch ( e ) {
  16035. if ( onError ) {
  16036. onError( e );
  16037. } else {
  16038. console.error( e );
  16039. }
  16040. scope.manager.itemError( url );
  16041. }
  16042. }, onProgress, onError );
  16043. }
  16044. parse( json ) {
  16045. const animations = [];
  16046. for ( let i = 0; i < json.length; i ++ ) {
  16047. const clip = AnimationClip.parse( json[ i ] );
  16048. animations.push( clip );
  16049. }
  16050. return animations;
  16051. }
  16052. }
  16053. /**
  16054. * Abstract Base class to block based textures loader (dds, pvr, ...)
  16055. *
  16056. * Sub classes have to implement the parse() method which will be used in load().
  16057. */
  16058. class CompressedTextureLoader extends Loader {
  16059. constructor( manager ) {
  16060. super( manager );
  16061. }
  16062. load( url, onLoad, onProgress, onError ) {
  16063. const scope = this;
  16064. const images = [];
  16065. const texture = new CompressedTexture();
  16066. const loader = new FileLoader( this.manager );
  16067. loader.setPath( this.path );
  16068. loader.setResponseType( 'arraybuffer' );
  16069. loader.setRequestHeader( this.requestHeader );
  16070. loader.setWithCredentials( scope.withCredentials );
  16071. let loaded = 0;
  16072. function loadTexture( i ) {
  16073. loader.load( url[ i ], function ( buffer ) {
  16074. const texDatas = scope.parse( buffer, true );
  16075. images[ i ] = {
  16076. width: texDatas.width,
  16077. height: texDatas.height,
  16078. format: texDatas.format,
  16079. mipmaps: texDatas.mipmaps
  16080. };
  16081. loaded += 1;
  16082. if ( loaded === 6 ) {
  16083. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  16084. texture.image = images;
  16085. texture.format = texDatas.format;
  16086. texture.needsUpdate = true;
  16087. if ( onLoad ) onLoad( texture );
  16088. }
  16089. }, onProgress, onError );
  16090. }
  16091. if ( Array.isArray( url ) ) {
  16092. for ( let i = 0, il = url.length; i < il; ++ i ) {
  16093. loadTexture( i );
  16094. }
  16095. } else {
  16096. // compressed cubemap texture stored in a single DDS file
  16097. loader.load( url, function ( buffer ) {
  16098. const texDatas = scope.parse( buffer, true );
  16099. if ( texDatas.isCubemap ) {
  16100. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  16101. for ( let f = 0; f < faces; f ++ ) {
  16102. images[ f ] = { mipmaps: [] };
  16103. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  16104. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  16105. images[ f ].format = texDatas.format;
  16106. images[ f ].width = texDatas.width;
  16107. images[ f ].height = texDatas.height;
  16108. }
  16109. }
  16110. texture.image = images;
  16111. } else {
  16112. texture.image.width = texDatas.width;
  16113. texture.image.height = texDatas.height;
  16114. texture.mipmaps = texDatas.mipmaps;
  16115. }
  16116. if ( texDatas.mipmapCount === 1 ) {
  16117. texture.minFilter = LinearFilter;
  16118. }
  16119. texture.format = texDatas.format;
  16120. texture.needsUpdate = true;
  16121. if ( onLoad ) onLoad( texture );
  16122. }, onProgress, onError );
  16123. }
  16124. return texture;
  16125. }
  16126. }
  16127. class ImageLoader extends Loader {
  16128. constructor( manager ) {
  16129. super( manager );
  16130. }
  16131. load( url, onLoad, onProgress, onError ) {
  16132. if ( this.path !== undefined ) url = this.path + url;
  16133. url = this.manager.resolveURL( url );
  16134. const scope = this;
  16135. const cached = Cache.get( url );
  16136. if ( cached !== undefined ) {
  16137. scope.manager.itemStart( url );
  16138. setTimeout( function () {
  16139. if ( onLoad ) onLoad( cached );
  16140. scope.manager.itemEnd( url );
  16141. }, 0 );
  16142. return cached;
  16143. }
  16144. const image = createElementNS( 'img' );
  16145. function onImageLoad() {
  16146. removeEventListeners();
  16147. Cache.add( url, this );
  16148. if ( onLoad ) onLoad( this );
  16149. scope.manager.itemEnd( url );
  16150. }
  16151. function onImageError( event ) {
  16152. removeEventListeners();
  16153. if ( onError ) onError( event );
  16154. scope.manager.itemError( url );
  16155. scope.manager.itemEnd( url );
  16156. }
  16157. function removeEventListeners() {
  16158. image.removeEventListener( 'load', onImageLoad, false );
  16159. image.removeEventListener( 'error', onImageError, false );
  16160. }
  16161. image.addEventListener( 'load', onImageLoad, false );
  16162. image.addEventListener( 'error', onImageError, false );
  16163. if ( url.slice( 0, 5 ) !== 'data:' ) {
  16164. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  16165. }
  16166. scope.manager.itemStart( url );
  16167. image.src = url;
  16168. return image;
  16169. }
  16170. }
  16171. class CubeTextureLoader extends Loader {
  16172. constructor( manager ) {
  16173. super( manager );
  16174. }
  16175. load( urls, onLoad, onProgress, onError ) {
  16176. const texture = new CubeTexture();
  16177. texture.colorSpace = SRGBColorSpace;
  16178. const loader = new ImageLoader( this.manager );
  16179. loader.setCrossOrigin( this.crossOrigin );
  16180. loader.setPath( this.path );
  16181. let loaded = 0;
  16182. function loadTexture( i ) {
  16183. loader.load( urls[ i ], function ( image ) {
  16184. texture.images[ i ] = image;
  16185. loaded ++;
  16186. if ( loaded === 6 ) {
  16187. texture.needsUpdate = true;
  16188. if ( onLoad ) onLoad( texture );
  16189. }
  16190. }, undefined, onError );
  16191. }
  16192. for ( let i = 0; i < urls.length; ++ i ) {
  16193. loadTexture( i );
  16194. }
  16195. return texture;
  16196. }
  16197. }
  16198. /**
  16199. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  16200. *
  16201. * Sub classes have to implement the parse() method which will be used in load().
  16202. */
  16203. class DataTextureLoader extends Loader {
  16204. constructor( manager ) {
  16205. super( manager );
  16206. }
  16207. load( url, onLoad, onProgress, onError ) {
  16208. const scope = this;
  16209. const texture = new DataTexture();
  16210. const loader = new FileLoader( this.manager );
  16211. loader.setResponseType( 'arraybuffer' );
  16212. loader.setRequestHeader( this.requestHeader );
  16213. loader.setPath( this.path );
  16214. loader.setWithCredentials( scope.withCredentials );
  16215. loader.load( url, function ( buffer ) {
  16216. let texData;
  16217. try {
  16218. texData = scope.parse( buffer );
  16219. } catch ( error ) {
  16220. if ( onError !== undefined ) {
  16221. onError( error );
  16222. } else {
  16223. console.error( error );
  16224. return;
  16225. }
  16226. }
  16227. if ( texData.image !== undefined ) {
  16228. texture.image = texData.image;
  16229. } else if ( texData.data !== undefined ) {
  16230. texture.image.width = texData.width;
  16231. texture.image.height = texData.height;
  16232. texture.image.data = texData.data;
  16233. }
  16234. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  16235. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  16236. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  16237. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  16238. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  16239. if ( texData.colorSpace !== undefined ) {
  16240. texture.colorSpace = texData.colorSpace;
  16241. }
  16242. if ( texData.flipY !== undefined ) {
  16243. texture.flipY = texData.flipY;
  16244. }
  16245. if ( texData.format !== undefined ) {
  16246. texture.format = texData.format;
  16247. }
  16248. if ( texData.type !== undefined ) {
  16249. texture.type = texData.type;
  16250. }
  16251. if ( texData.mipmaps !== undefined ) {
  16252. texture.mipmaps = texData.mipmaps;
  16253. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  16254. }
  16255. if ( texData.mipmapCount === 1 ) {
  16256. texture.minFilter = LinearFilter;
  16257. }
  16258. if ( texData.generateMipmaps !== undefined ) {
  16259. texture.generateMipmaps = texData.generateMipmaps;
  16260. }
  16261. texture.needsUpdate = true;
  16262. if ( onLoad ) onLoad( texture, texData );
  16263. }, onProgress, onError );
  16264. return texture;
  16265. }
  16266. }
  16267. class TextureLoader extends Loader {
  16268. constructor( manager ) {
  16269. super( manager );
  16270. }
  16271. load( url, onLoad, onProgress, onError ) {
  16272. const texture = new Texture();
  16273. const loader = new ImageLoader( this.manager );
  16274. loader.setCrossOrigin( this.crossOrigin );
  16275. loader.setPath( this.path );
  16276. loader.load( url, function ( image ) {
  16277. texture.image = image;
  16278. texture.needsUpdate = true;
  16279. if ( onLoad !== undefined ) {
  16280. onLoad( texture );
  16281. }
  16282. }, onProgress, onError );
  16283. return texture;
  16284. }
  16285. }
  16286. class Light extends Object3D {
  16287. constructor( color, intensity = 1 ) {
  16288. super();
  16289. this.isLight = true;
  16290. this.type = 'Light';
  16291. this.color = new Color( color );
  16292. this.intensity = intensity;
  16293. }
  16294. dispose() {
  16295. // Empty here in base class; some subclasses override.
  16296. }
  16297. copy( source, recursive ) {
  16298. super.copy( source, recursive );
  16299. this.color.copy( source.color );
  16300. this.intensity = source.intensity;
  16301. return this;
  16302. }
  16303. toJSON( meta ) {
  16304. const data = super.toJSON( meta );
  16305. data.object.color = this.color.getHex();
  16306. data.object.intensity = this.intensity;
  16307. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16308. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16309. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16310. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16311. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16312. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16313. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16314. return data;
  16315. }
  16316. }
  16317. class HemisphereLight extends Light {
  16318. constructor( skyColor, groundColor, intensity ) {
  16319. super( skyColor, intensity );
  16320. this.isHemisphereLight = true;
  16321. this.type = 'HemisphereLight';
  16322. this.position.copy( Object3D.DEFAULT_UP );
  16323. this.updateMatrix();
  16324. this.groundColor = new Color( groundColor );
  16325. }
  16326. copy( source, recursive ) {
  16327. super.copy( source, recursive );
  16328. this.groundColor.copy( source.groundColor );
  16329. return this;
  16330. }
  16331. }
  16332. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16333. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16334. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16335. class LightShadow {
  16336. constructor( camera ) {
  16337. this.camera = camera;
  16338. this.intensity = 1;
  16339. this.bias = 0;
  16340. this.normalBias = 0;
  16341. this.radius = 1;
  16342. this.blurSamples = 8;
  16343. this.mapSize = new Vector2( 512, 512 );
  16344. this.map = null;
  16345. this.mapPass = null;
  16346. this.matrix = new Matrix4();
  16347. this.autoUpdate = true;
  16348. this.needsUpdate = false;
  16349. this._frustum = new Frustum();
  16350. this._frameExtents = new Vector2( 1, 1 );
  16351. this._viewportCount = 1;
  16352. this._viewports = [
  16353. new Vector4( 0, 0, 1, 1 )
  16354. ];
  16355. }
  16356. getViewportCount() {
  16357. return this._viewportCount;
  16358. }
  16359. getFrustum() {
  16360. return this._frustum;
  16361. }
  16362. updateMatrices( light ) {
  16363. const shadowCamera = this.camera;
  16364. const shadowMatrix = this.matrix;
  16365. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16366. shadowCamera.position.copy( _lightPositionWorld$1 );
  16367. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16368. shadowCamera.lookAt( _lookTarget$1 );
  16369. shadowCamera.updateMatrixWorld();
  16370. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16371. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16372. shadowMatrix.set(
  16373. 0.5, 0.0, 0.0, 0.5,
  16374. 0.0, 0.5, 0.0, 0.5,
  16375. 0.0, 0.0, 0.5, 0.5,
  16376. 0.0, 0.0, 0.0, 1.0
  16377. );
  16378. shadowMatrix.multiply( _projScreenMatrix$1 );
  16379. }
  16380. getViewport( viewportIndex ) {
  16381. return this._viewports[ viewportIndex ];
  16382. }
  16383. getFrameExtents() {
  16384. return this._frameExtents;
  16385. }
  16386. dispose() {
  16387. if ( this.map ) {
  16388. this.map.dispose();
  16389. }
  16390. if ( this.mapPass ) {
  16391. this.mapPass.dispose();
  16392. }
  16393. }
  16394. copy( source ) {
  16395. this.camera = source.camera.clone();
  16396. this.intensity = source.intensity;
  16397. this.bias = source.bias;
  16398. this.radius = source.radius;
  16399. this.mapSize.copy( source.mapSize );
  16400. return this;
  16401. }
  16402. clone() {
  16403. return new this.constructor().copy( this );
  16404. }
  16405. toJSON() {
  16406. const object = {};
  16407. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16408. if ( this.bias !== 0 ) object.bias = this.bias;
  16409. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16410. if ( this.radius !== 1 ) object.radius = this.radius;
  16411. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16412. object.camera = this.camera.toJSON( false ).object;
  16413. delete object.camera.matrix;
  16414. return object;
  16415. }
  16416. }
  16417. class SpotLightShadow extends LightShadow {
  16418. constructor() {
  16419. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16420. this.isSpotLightShadow = true;
  16421. this.focus = 1;
  16422. }
  16423. updateMatrices( light ) {
  16424. const camera = this.camera;
  16425. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16426. const aspect = this.mapSize.width / this.mapSize.height;
  16427. const far = light.distance || camera.far;
  16428. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16429. camera.fov = fov;
  16430. camera.aspect = aspect;
  16431. camera.far = far;
  16432. camera.updateProjectionMatrix();
  16433. }
  16434. super.updateMatrices( light );
  16435. }
  16436. copy( source ) {
  16437. super.copy( source );
  16438. this.focus = source.focus;
  16439. return this;
  16440. }
  16441. }
  16442. class SpotLight extends Light {
  16443. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16444. super( color, intensity );
  16445. this.isSpotLight = true;
  16446. this.type = 'SpotLight';
  16447. this.position.copy( Object3D.DEFAULT_UP );
  16448. this.updateMatrix();
  16449. this.target = new Object3D();
  16450. this.distance = distance;
  16451. this.angle = angle;
  16452. this.penumbra = penumbra;
  16453. this.decay = decay;
  16454. this.map = null;
  16455. this.shadow = new SpotLightShadow();
  16456. }
  16457. get power() {
  16458. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16459. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16460. return this.intensity * Math.PI;
  16461. }
  16462. set power( power ) {
  16463. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16464. this.intensity = power / Math.PI;
  16465. }
  16466. dispose() {
  16467. this.shadow.dispose();
  16468. }
  16469. copy( source, recursive ) {
  16470. super.copy( source, recursive );
  16471. this.distance = source.distance;
  16472. this.angle = source.angle;
  16473. this.penumbra = source.penumbra;
  16474. this.decay = source.decay;
  16475. this.target = source.target.clone();
  16476. this.shadow = source.shadow.clone();
  16477. return this;
  16478. }
  16479. }
  16480. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  16481. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16482. const _lookTarget = /*@__PURE__*/ new Vector3();
  16483. class PointLightShadow extends LightShadow {
  16484. constructor() {
  16485. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16486. this.isPointLightShadow = true;
  16487. this._frameExtents = new Vector2( 4, 2 );
  16488. this._viewportCount = 6;
  16489. this._viewports = [
  16490. // These viewports map a cube-map onto a 2D texture with the
  16491. // following orientation:
  16492. //
  16493. // xzXZ
  16494. // y Y
  16495. //
  16496. // X - Positive x direction
  16497. // x - Negative x direction
  16498. // Y - Positive y direction
  16499. // y - Negative y direction
  16500. // Z - Positive z direction
  16501. // z - Negative z direction
  16502. // positive X
  16503. new Vector4( 2, 1, 1, 1 ),
  16504. // negative X
  16505. new Vector4( 0, 1, 1, 1 ),
  16506. // positive Z
  16507. new Vector4( 3, 1, 1, 1 ),
  16508. // negative Z
  16509. new Vector4( 1, 1, 1, 1 ),
  16510. // positive Y
  16511. new Vector4( 3, 0, 1, 1 ),
  16512. // negative Y
  16513. new Vector4( 1, 0, 1, 1 )
  16514. ];
  16515. this._cubeDirections = [
  16516. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16517. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16518. ];
  16519. this._cubeUps = [
  16520. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16521. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16522. ];
  16523. }
  16524. updateMatrices( light, viewportIndex = 0 ) {
  16525. const camera = this.camera;
  16526. const shadowMatrix = this.matrix;
  16527. const far = light.distance || camera.far;
  16528. if ( far !== camera.far ) {
  16529. camera.far = far;
  16530. camera.updateProjectionMatrix();
  16531. }
  16532. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16533. camera.position.copy( _lightPositionWorld );
  16534. _lookTarget.copy( camera.position );
  16535. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16536. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16537. camera.lookAt( _lookTarget );
  16538. camera.updateMatrixWorld();
  16539. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16540. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16541. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  16542. }
  16543. }
  16544. class PointLight extends Light {
  16545. constructor( color, intensity, distance = 0, decay = 2 ) {
  16546. super( color, intensity );
  16547. this.isPointLight = true;
  16548. this.type = 'PointLight';
  16549. this.distance = distance;
  16550. this.decay = decay;
  16551. this.shadow = new PointLightShadow();
  16552. }
  16553. get power() {
  16554. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16555. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16556. return this.intensity * 4 * Math.PI;
  16557. }
  16558. set power( power ) {
  16559. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16560. this.intensity = power / ( 4 * Math.PI );
  16561. }
  16562. dispose() {
  16563. this.shadow.dispose();
  16564. }
  16565. copy( source, recursive ) {
  16566. super.copy( source, recursive );
  16567. this.distance = source.distance;
  16568. this.decay = source.decay;
  16569. this.shadow = source.shadow.clone();
  16570. return this;
  16571. }
  16572. }
  16573. class OrthographicCamera extends Camera {
  16574. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16575. super();
  16576. this.isOrthographicCamera = true;
  16577. this.type = 'OrthographicCamera';
  16578. this.zoom = 1;
  16579. this.view = null;
  16580. this.left = left;
  16581. this.right = right;
  16582. this.top = top;
  16583. this.bottom = bottom;
  16584. this.near = near;
  16585. this.far = far;
  16586. this.updateProjectionMatrix();
  16587. }
  16588. copy( source, recursive ) {
  16589. super.copy( source, recursive );
  16590. this.left = source.left;
  16591. this.right = source.right;
  16592. this.top = source.top;
  16593. this.bottom = source.bottom;
  16594. this.near = source.near;
  16595. this.far = source.far;
  16596. this.zoom = source.zoom;
  16597. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16598. return this;
  16599. }
  16600. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16601. if ( this.view === null ) {
  16602. this.view = {
  16603. enabled: true,
  16604. fullWidth: 1,
  16605. fullHeight: 1,
  16606. offsetX: 0,
  16607. offsetY: 0,
  16608. width: 1,
  16609. height: 1
  16610. };
  16611. }
  16612. this.view.enabled = true;
  16613. this.view.fullWidth = fullWidth;
  16614. this.view.fullHeight = fullHeight;
  16615. this.view.offsetX = x;
  16616. this.view.offsetY = y;
  16617. this.view.width = width;
  16618. this.view.height = height;
  16619. this.updateProjectionMatrix();
  16620. }
  16621. clearViewOffset() {
  16622. if ( this.view !== null ) {
  16623. this.view.enabled = false;
  16624. }
  16625. this.updateProjectionMatrix();
  16626. }
  16627. updateProjectionMatrix() {
  16628. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16629. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16630. const cx = ( this.right + this.left ) / 2;
  16631. const cy = ( this.top + this.bottom ) / 2;
  16632. let left = cx - dx;
  16633. let right = cx + dx;
  16634. let top = cy + dy;
  16635. let bottom = cy - dy;
  16636. if ( this.view !== null && this.view.enabled ) {
  16637. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16638. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16639. left += scaleW * this.view.offsetX;
  16640. right = left + scaleW * this.view.width;
  16641. top -= scaleH * this.view.offsetY;
  16642. bottom = top - scaleH * this.view.height;
  16643. }
  16644. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16645. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16646. }
  16647. toJSON( meta ) {
  16648. const data = super.toJSON( meta );
  16649. data.object.zoom = this.zoom;
  16650. data.object.left = this.left;
  16651. data.object.right = this.right;
  16652. data.object.top = this.top;
  16653. data.object.bottom = this.bottom;
  16654. data.object.near = this.near;
  16655. data.object.far = this.far;
  16656. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16657. return data;
  16658. }
  16659. }
  16660. class DirectionalLightShadow extends LightShadow {
  16661. constructor() {
  16662. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16663. this.isDirectionalLightShadow = true;
  16664. }
  16665. }
  16666. class DirectionalLight extends Light {
  16667. constructor( color, intensity ) {
  16668. super( color, intensity );
  16669. this.isDirectionalLight = true;
  16670. this.type = 'DirectionalLight';
  16671. this.position.copy( Object3D.DEFAULT_UP );
  16672. this.updateMatrix();
  16673. this.target = new Object3D();
  16674. this.shadow = new DirectionalLightShadow();
  16675. }
  16676. dispose() {
  16677. this.shadow.dispose();
  16678. }
  16679. copy( source ) {
  16680. super.copy( source );
  16681. this.target = source.target.clone();
  16682. this.shadow = source.shadow.clone();
  16683. return this;
  16684. }
  16685. }
  16686. class AmbientLight extends Light {
  16687. constructor( color, intensity ) {
  16688. super( color, intensity );
  16689. this.isAmbientLight = true;
  16690. this.type = 'AmbientLight';
  16691. }
  16692. }
  16693. class RectAreaLight extends Light {
  16694. constructor( color, intensity, width = 10, height = 10 ) {
  16695. super( color, intensity );
  16696. this.isRectAreaLight = true;
  16697. this.type = 'RectAreaLight';
  16698. this.width = width;
  16699. this.height = height;
  16700. }
  16701. get power() {
  16702. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16703. return this.intensity * this.width * this.height * Math.PI;
  16704. }
  16705. set power( power ) {
  16706. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16707. this.intensity = power / ( this.width * this.height * Math.PI );
  16708. }
  16709. copy( source ) {
  16710. super.copy( source );
  16711. this.width = source.width;
  16712. this.height = source.height;
  16713. return this;
  16714. }
  16715. toJSON( meta ) {
  16716. const data = super.toJSON( meta );
  16717. data.object.width = this.width;
  16718. data.object.height = this.height;
  16719. return data;
  16720. }
  16721. }
  16722. /**
  16723. * Primary reference:
  16724. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16725. *
  16726. * Secondary reference:
  16727. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16728. */
  16729. // 3-band SH defined by 9 coefficients
  16730. class SphericalHarmonics3 {
  16731. constructor() {
  16732. this.isSphericalHarmonics3 = true;
  16733. this.coefficients = [];
  16734. for ( let i = 0; i < 9; i ++ ) {
  16735. this.coefficients.push( new Vector3() );
  16736. }
  16737. }
  16738. set( coefficients ) {
  16739. for ( let i = 0; i < 9; i ++ ) {
  16740. this.coefficients[ i ].copy( coefficients[ i ] );
  16741. }
  16742. return this;
  16743. }
  16744. zero() {
  16745. for ( let i = 0; i < 9; i ++ ) {
  16746. this.coefficients[ i ].set( 0, 0, 0 );
  16747. }
  16748. return this;
  16749. }
  16750. // get the radiance in the direction of the normal
  16751. // target is a Vector3
  16752. getAt( normal, target ) {
  16753. // normal is assumed to be unit length
  16754. const x = normal.x, y = normal.y, z = normal.z;
  16755. const coeff = this.coefficients;
  16756. // band 0
  16757. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16758. // band 1
  16759. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16760. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16761. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16762. // band 2
  16763. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16764. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16765. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16766. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16767. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16768. return target;
  16769. }
  16770. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16771. // target is a Vector3
  16772. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16773. getIrradianceAt( normal, target ) {
  16774. // normal is assumed to be unit length
  16775. const x = normal.x, y = normal.y, z = normal.z;
  16776. const coeff = this.coefficients;
  16777. // band 0
  16778. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16779. // band 1
  16780. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16781. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16782. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16783. // band 2
  16784. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16785. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16786. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16787. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16788. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16789. return target;
  16790. }
  16791. add( sh ) {
  16792. for ( let i = 0; i < 9; i ++ ) {
  16793. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16794. }
  16795. return this;
  16796. }
  16797. addScaledSH( sh, s ) {
  16798. for ( let i = 0; i < 9; i ++ ) {
  16799. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16800. }
  16801. return this;
  16802. }
  16803. scale( s ) {
  16804. for ( let i = 0; i < 9; i ++ ) {
  16805. this.coefficients[ i ].multiplyScalar( s );
  16806. }
  16807. return this;
  16808. }
  16809. lerp( sh, alpha ) {
  16810. for ( let i = 0; i < 9; i ++ ) {
  16811. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16812. }
  16813. return this;
  16814. }
  16815. equals( sh ) {
  16816. for ( let i = 0; i < 9; i ++ ) {
  16817. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16818. return false;
  16819. }
  16820. }
  16821. return true;
  16822. }
  16823. copy( sh ) {
  16824. return this.set( sh.coefficients );
  16825. }
  16826. clone() {
  16827. return new this.constructor().copy( this );
  16828. }
  16829. fromArray( array, offset = 0 ) {
  16830. const coefficients = this.coefficients;
  16831. for ( let i = 0; i < 9; i ++ ) {
  16832. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16833. }
  16834. return this;
  16835. }
  16836. toArray( array = [], offset = 0 ) {
  16837. const coefficients = this.coefficients;
  16838. for ( let i = 0; i < 9; i ++ ) {
  16839. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16840. }
  16841. return array;
  16842. }
  16843. // evaluate the basis functions
  16844. // shBasis is an Array[ 9 ]
  16845. static getBasisAt( normal, shBasis ) {
  16846. // normal is assumed to be unit length
  16847. const x = normal.x, y = normal.y, z = normal.z;
  16848. // band 0
  16849. shBasis[ 0 ] = 0.282095;
  16850. // band 1
  16851. shBasis[ 1 ] = 0.488603 * y;
  16852. shBasis[ 2 ] = 0.488603 * z;
  16853. shBasis[ 3 ] = 0.488603 * x;
  16854. // band 2
  16855. shBasis[ 4 ] = 1.092548 * x * y;
  16856. shBasis[ 5 ] = 1.092548 * y * z;
  16857. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16858. shBasis[ 7 ] = 1.092548 * x * z;
  16859. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16860. }
  16861. }
  16862. class LightProbe extends Light {
  16863. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16864. super( undefined, intensity );
  16865. this.isLightProbe = true;
  16866. this.sh = sh;
  16867. }
  16868. copy( source ) {
  16869. super.copy( source );
  16870. this.sh.copy( source.sh );
  16871. return this;
  16872. }
  16873. fromJSON( json ) {
  16874. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16875. this.sh.fromArray( json.sh );
  16876. return this;
  16877. }
  16878. toJSON( meta ) {
  16879. const data = super.toJSON( meta );
  16880. data.object.sh = this.sh.toArray();
  16881. return data;
  16882. }
  16883. }
  16884. class MaterialLoader extends Loader {
  16885. constructor( manager ) {
  16886. super( manager );
  16887. this.textures = {};
  16888. }
  16889. load( url, onLoad, onProgress, onError ) {
  16890. const scope = this;
  16891. const loader = new FileLoader( scope.manager );
  16892. loader.setPath( scope.path );
  16893. loader.setRequestHeader( scope.requestHeader );
  16894. loader.setWithCredentials( scope.withCredentials );
  16895. loader.load( url, function ( text ) {
  16896. try {
  16897. onLoad( scope.parse( JSON.parse( text ) ) );
  16898. } catch ( e ) {
  16899. if ( onError ) {
  16900. onError( e );
  16901. } else {
  16902. console.error( e );
  16903. }
  16904. scope.manager.itemError( url );
  16905. }
  16906. }, onProgress, onError );
  16907. }
  16908. parse( json ) {
  16909. const textures = this.textures;
  16910. function getTexture( name ) {
  16911. if ( textures[ name ] === undefined ) {
  16912. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16913. }
  16914. return textures[ name ];
  16915. }
  16916. const material = this.createMaterialFromType( json.type );
  16917. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16918. if ( json.name !== undefined ) material.name = json.name;
  16919. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16920. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16921. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16922. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16923. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16924. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16925. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16926. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16927. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16928. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16929. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16930. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16931. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16932. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16933. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16934. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16935. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16936. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16937. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16938. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16939. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16940. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16941. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16942. if ( json.fog !== undefined ) material.fog = json.fog;
  16943. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16944. if ( json.blending !== undefined ) material.blending = json.blending;
  16945. if ( json.combine !== undefined ) material.combine = json.combine;
  16946. if ( json.side !== undefined ) material.side = json.side;
  16947. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16948. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16949. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16950. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16951. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16952. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16953. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16954. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16955. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16956. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16957. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16958. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16959. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16960. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16961. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16962. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16963. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16964. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16965. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16966. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16967. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16968. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16969. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16970. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16971. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16972. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16973. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16974. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16975. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16976. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16977. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16978. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16979. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16980. if ( json.scale !== undefined ) material.scale = json.scale;
  16981. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16982. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16983. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16984. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16985. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16986. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16987. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16988. if ( json.visible !== undefined ) material.visible = json.visible;
  16989. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16990. if ( json.userData !== undefined ) material.userData = json.userData;
  16991. if ( json.vertexColors !== undefined ) {
  16992. if ( typeof json.vertexColors === 'number' ) {
  16993. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16994. } else {
  16995. material.vertexColors = json.vertexColors;
  16996. }
  16997. }
  16998. // Shader Material
  16999. if ( json.uniforms !== undefined ) {
  17000. for ( const name in json.uniforms ) {
  17001. const uniform = json.uniforms[ name ];
  17002. material.uniforms[ name ] = {};
  17003. switch ( uniform.type ) {
  17004. case 't':
  17005. material.uniforms[ name ].value = getTexture( uniform.value );
  17006. break;
  17007. case 'c':
  17008. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  17009. break;
  17010. case 'v2':
  17011. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  17012. break;
  17013. case 'v3':
  17014. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  17015. break;
  17016. case 'v4':
  17017. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  17018. break;
  17019. case 'm3':
  17020. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  17021. break;
  17022. case 'm4':
  17023. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  17024. break;
  17025. default:
  17026. material.uniforms[ name ].value = uniform.value;
  17027. }
  17028. }
  17029. }
  17030. if ( json.defines !== undefined ) material.defines = json.defines;
  17031. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  17032. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  17033. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  17034. if ( json.extensions !== undefined ) {
  17035. for ( const key in json.extensions ) {
  17036. material.extensions[ key ] = json.extensions[ key ];
  17037. }
  17038. }
  17039. if ( json.lights !== undefined ) material.lights = json.lights;
  17040. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  17041. // for PointsMaterial
  17042. if ( json.size !== undefined ) material.size = json.size;
  17043. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  17044. // maps
  17045. if ( json.map !== undefined ) material.map = getTexture( json.map );
  17046. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  17047. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  17048. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  17049. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  17050. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  17051. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  17052. if ( json.normalScale !== undefined ) {
  17053. let normalScale = json.normalScale;
  17054. if ( Array.isArray( normalScale ) === false ) {
  17055. // Blender exporter used to export a scalar. See #7459
  17056. normalScale = [ normalScale, normalScale ];
  17057. }
  17058. material.normalScale = new Vector2().fromArray( normalScale );
  17059. }
  17060. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  17061. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  17062. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  17063. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  17064. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  17065. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  17066. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  17067. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  17068. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  17069. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  17070. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  17071. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  17072. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  17073. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  17074. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  17075. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  17076. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  17077. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  17078. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  17079. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  17080. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  17081. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  17082. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  17083. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  17084. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  17085. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  17086. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  17087. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  17088. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  17089. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  17090. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  17091. return material;
  17092. }
  17093. setTextures( value ) {
  17094. this.textures = value;
  17095. return this;
  17096. }
  17097. createMaterialFromType( type ) {
  17098. return MaterialLoader.createMaterialFromType( type );
  17099. }
  17100. static createMaterialFromType( type ) {
  17101. const materialLib = {
  17102. ShadowMaterial,
  17103. SpriteMaterial,
  17104. RawShaderMaterial,
  17105. ShaderMaterial,
  17106. PointsMaterial,
  17107. MeshPhysicalMaterial,
  17108. MeshStandardMaterial,
  17109. MeshPhongMaterial,
  17110. MeshToonMaterial,
  17111. MeshNormalMaterial,
  17112. MeshLambertMaterial,
  17113. MeshDepthMaterial,
  17114. MeshDistanceMaterial,
  17115. MeshBasicMaterial,
  17116. MeshMatcapMaterial,
  17117. LineDashedMaterial,
  17118. LineBasicMaterial,
  17119. Material
  17120. };
  17121. return new materialLib[ type ]();
  17122. }
  17123. }
  17124. class LoaderUtils {
  17125. static decodeText( array ) { // @deprecated, r165
  17126. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  17127. if ( typeof TextDecoder !== 'undefined' ) {
  17128. return new TextDecoder().decode( array );
  17129. }
  17130. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  17131. // throws a "maximum call stack size exceeded" error for large arrays.
  17132. let s = '';
  17133. for ( let i = 0, il = array.length; i < il; i ++ ) {
  17134. // Implicitly assumes little-endian.
  17135. s += String.fromCharCode( array[ i ] );
  17136. }
  17137. try {
  17138. // merges multi-byte utf-8 characters.
  17139. return decodeURIComponent( escape( s ) );
  17140. } catch ( e ) { // see #16358
  17141. return s;
  17142. }
  17143. }
  17144. static extractUrlBase( url ) {
  17145. const index = url.lastIndexOf( '/' );
  17146. if ( index === - 1 ) return './';
  17147. return url.slice( 0, index + 1 );
  17148. }
  17149. static resolveURL( url, path ) {
  17150. // Invalid URL
  17151. if ( typeof url !== 'string' || url === '' ) return '';
  17152. // Host Relative URL
  17153. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  17154. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  17155. }
  17156. // Absolute URL http://,https://,//
  17157. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  17158. // Data URI
  17159. if ( /^data:.*,.*$/i.test( url ) ) return url;
  17160. // Blob URL
  17161. if ( /^blob:.*$/i.test( url ) ) return url;
  17162. // Relative URL
  17163. return path + url;
  17164. }
  17165. }
  17166. class InstancedBufferGeometry extends BufferGeometry {
  17167. constructor() {
  17168. super();
  17169. this.isInstancedBufferGeometry = true;
  17170. this.type = 'InstancedBufferGeometry';
  17171. this.instanceCount = Infinity;
  17172. }
  17173. copy( source ) {
  17174. super.copy( source );
  17175. this.instanceCount = source.instanceCount;
  17176. return this;
  17177. }
  17178. toJSON() {
  17179. const data = super.toJSON();
  17180. data.instanceCount = this.instanceCount;
  17181. data.isInstancedBufferGeometry = true;
  17182. return data;
  17183. }
  17184. }
  17185. class BufferGeometryLoader extends Loader {
  17186. constructor( manager ) {
  17187. super( manager );
  17188. }
  17189. load( url, onLoad, onProgress, onError ) {
  17190. const scope = this;
  17191. const loader = new FileLoader( scope.manager );
  17192. loader.setPath( scope.path );
  17193. loader.setRequestHeader( scope.requestHeader );
  17194. loader.setWithCredentials( scope.withCredentials );
  17195. loader.load( url, function ( text ) {
  17196. try {
  17197. onLoad( scope.parse( JSON.parse( text ) ) );
  17198. } catch ( e ) {
  17199. if ( onError ) {
  17200. onError( e );
  17201. } else {
  17202. console.error( e );
  17203. }
  17204. scope.manager.itemError( url );
  17205. }
  17206. }, onProgress, onError );
  17207. }
  17208. parse( json ) {
  17209. const interleavedBufferMap = {};
  17210. const arrayBufferMap = {};
  17211. function getInterleavedBuffer( json, uuid ) {
  17212. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  17213. const interleavedBuffers = json.interleavedBuffers;
  17214. const interleavedBuffer = interleavedBuffers[ uuid ];
  17215. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  17216. const array = getTypedArray( interleavedBuffer.type, buffer );
  17217. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  17218. ib.uuid = interleavedBuffer.uuid;
  17219. interleavedBufferMap[ uuid ] = ib;
  17220. return ib;
  17221. }
  17222. function getArrayBuffer( json, uuid ) {
  17223. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  17224. const arrayBuffers = json.arrayBuffers;
  17225. const arrayBuffer = arrayBuffers[ uuid ];
  17226. const ab = new Uint32Array( arrayBuffer ).buffer;
  17227. arrayBufferMap[ uuid ] = ab;
  17228. return ab;
  17229. }
  17230. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  17231. const index = json.data.index;
  17232. if ( index !== undefined ) {
  17233. const typedArray = getTypedArray( index.type, index.array );
  17234. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  17235. }
  17236. const attributes = json.data.attributes;
  17237. for ( const key in attributes ) {
  17238. const attribute = attributes[ key ];
  17239. let bufferAttribute;
  17240. if ( attribute.isInterleavedBufferAttribute ) {
  17241. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17242. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17243. } else {
  17244. const typedArray = getTypedArray( attribute.type, attribute.array );
  17245. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  17246. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  17247. }
  17248. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17249. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  17250. geometry.setAttribute( key, bufferAttribute );
  17251. }
  17252. const morphAttributes = json.data.morphAttributes;
  17253. if ( morphAttributes ) {
  17254. for ( const key in morphAttributes ) {
  17255. const attributeArray = morphAttributes[ key ];
  17256. const array = [];
  17257. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  17258. const attribute = attributeArray[ i ];
  17259. let bufferAttribute;
  17260. if ( attribute.isInterleavedBufferAttribute ) {
  17261. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17262. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17263. } else {
  17264. const typedArray = getTypedArray( attribute.type, attribute.array );
  17265. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  17266. }
  17267. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17268. array.push( bufferAttribute );
  17269. }
  17270. geometry.morphAttributes[ key ] = array;
  17271. }
  17272. }
  17273. const morphTargetsRelative = json.data.morphTargetsRelative;
  17274. if ( morphTargetsRelative ) {
  17275. geometry.morphTargetsRelative = true;
  17276. }
  17277. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17278. if ( groups !== undefined ) {
  17279. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17280. const group = groups[ i ];
  17281. geometry.addGroup( group.start, group.count, group.materialIndex );
  17282. }
  17283. }
  17284. const boundingSphere = json.data.boundingSphere;
  17285. if ( boundingSphere !== undefined ) {
  17286. const center = new Vector3();
  17287. if ( boundingSphere.center !== undefined ) {
  17288. center.fromArray( boundingSphere.center );
  17289. }
  17290. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17291. }
  17292. if ( json.name ) geometry.name = json.name;
  17293. if ( json.userData ) geometry.userData = json.userData;
  17294. return geometry;
  17295. }
  17296. }
  17297. class ObjectLoader extends Loader {
  17298. constructor( manager ) {
  17299. super( manager );
  17300. }
  17301. load( url, onLoad, onProgress, onError ) {
  17302. const scope = this;
  17303. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17304. this.resourcePath = this.resourcePath || path;
  17305. const loader = new FileLoader( this.manager );
  17306. loader.setPath( this.path );
  17307. loader.setRequestHeader( this.requestHeader );
  17308. loader.setWithCredentials( this.withCredentials );
  17309. loader.load( url, function ( text ) {
  17310. let json = null;
  17311. try {
  17312. json = JSON.parse( text );
  17313. } catch ( error ) {
  17314. if ( onError !== undefined ) onError( error );
  17315. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17316. return;
  17317. }
  17318. const metadata = json.metadata;
  17319. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17320. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17321. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17322. return;
  17323. }
  17324. scope.parse( json, onLoad );
  17325. }, onProgress, onError );
  17326. }
  17327. async loadAsync( url, onProgress ) {
  17328. const scope = this;
  17329. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17330. this.resourcePath = this.resourcePath || path;
  17331. const loader = new FileLoader( this.manager );
  17332. loader.setPath( this.path );
  17333. loader.setRequestHeader( this.requestHeader );
  17334. loader.setWithCredentials( this.withCredentials );
  17335. const text = await loader.loadAsync( url, onProgress );
  17336. const json = JSON.parse( text );
  17337. const metadata = json.metadata;
  17338. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17339. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17340. }
  17341. return await scope.parseAsync( json );
  17342. }
  17343. parse( json, onLoad ) {
  17344. const animations = this.parseAnimations( json.animations );
  17345. const shapes = this.parseShapes( json.shapes );
  17346. const geometries = this.parseGeometries( json.geometries, shapes );
  17347. const images = this.parseImages( json.images, function () {
  17348. if ( onLoad !== undefined ) onLoad( object );
  17349. } );
  17350. const textures = this.parseTextures( json.textures, images );
  17351. const materials = this.parseMaterials( json.materials, textures );
  17352. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17353. const skeletons = this.parseSkeletons( json.skeletons, object );
  17354. this.bindSkeletons( object, skeletons );
  17355. this.bindLightTargets( object );
  17356. //
  17357. if ( onLoad !== undefined ) {
  17358. let hasImages = false;
  17359. for ( const uuid in images ) {
  17360. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17361. hasImages = true;
  17362. break;
  17363. }
  17364. }
  17365. if ( hasImages === false ) onLoad( object );
  17366. }
  17367. return object;
  17368. }
  17369. async parseAsync( json ) {
  17370. const animations = this.parseAnimations( json.animations );
  17371. const shapes = this.parseShapes( json.shapes );
  17372. const geometries = this.parseGeometries( json.geometries, shapes );
  17373. const images = await this.parseImagesAsync( json.images );
  17374. const textures = this.parseTextures( json.textures, images );
  17375. const materials = this.parseMaterials( json.materials, textures );
  17376. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17377. const skeletons = this.parseSkeletons( json.skeletons, object );
  17378. this.bindSkeletons( object, skeletons );
  17379. this.bindLightTargets( object );
  17380. return object;
  17381. }
  17382. parseShapes( json ) {
  17383. const shapes = {};
  17384. if ( json !== undefined ) {
  17385. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17386. const shape = new Shape().fromJSON( json[ i ] );
  17387. shapes[ shape.uuid ] = shape;
  17388. }
  17389. }
  17390. return shapes;
  17391. }
  17392. parseSkeletons( json, object ) {
  17393. const skeletons = {};
  17394. const bones = {};
  17395. // generate bone lookup table
  17396. object.traverse( function ( child ) {
  17397. if ( child.isBone ) bones[ child.uuid ] = child;
  17398. } );
  17399. // create skeletons
  17400. if ( json !== undefined ) {
  17401. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17402. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17403. skeletons[ skeleton.uuid ] = skeleton;
  17404. }
  17405. }
  17406. return skeletons;
  17407. }
  17408. parseGeometries( json, shapes ) {
  17409. const geometries = {};
  17410. if ( json !== undefined ) {
  17411. const bufferGeometryLoader = new BufferGeometryLoader();
  17412. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17413. let geometry;
  17414. const data = json[ i ];
  17415. switch ( data.type ) {
  17416. case 'BufferGeometry':
  17417. case 'InstancedBufferGeometry':
  17418. geometry = bufferGeometryLoader.parse( data );
  17419. break;
  17420. default:
  17421. if ( data.type in Geometries ) {
  17422. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  17423. } else {
  17424. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17425. }
  17426. }
  17427. geometry.uuid = data.uuid;
  17428. if ( data.name !== undefined ) geometry.name = data.name;
  17429. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17430. geometries[ data.uuid ] = geometry;
  17431. }
  17432. }
  17433. return geometries;
  17434. }
  17435. parseMaterials( json, textures ) {
  17436. const cache = {}; // MultiMaterial
  17437. const materials = {};
  17438. if ( json !== undefined ) {
  17439. const loader = new MaterialLoader();
  17440. loader.setTextures( textures );
  17441. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17442. const data = json[ i ];
  17443. if ( cache[ data.uuid ] === undefined ) {
  17444. cache[ data.uuid ] = loader.parse( data );
  17445. }
  17446. materials[ data.uuid ] = cache[ data.uuid ];
  17447. }
  17448. }
  17449. return materials;
  17450. }
  17451. parseAnimations( json ) {
  17452. const animations = {};
  17453. if ( json !== undefined ) {
  17454. for ( let i = 0; i < json.length; i ++ ) {
  17455. const data = json[ i ];
  17456. const clip = AnimationClip.parse( data );
  17457. animations[ clip.uuid ] = clip;
  17458. }
  17459. }
  17460. return animations;
  17461. }
  17462. parseImages( json, onLoad ) {
  17463. const scope = this;
  17464. const images = {};
  17465. let loader;
  17466. function loadImage( url ) {
  17467. scope.manager.itemStart( url );
  17468. return loader.load( url, function () {
  17469. scope.manager.itemEnd( url );
  17470. }, undefined, function () {
  17471. scope.manager.itemError( url );
  17472. scope.manager.itemEnd( url );
  17473. } );
  17474. }
  17475. function deserializeImage( image ) {
  17476. if ( typeof image === 'string' ) {
  17477. const url = image;
  17478. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17479. return loadImage( path );
  17480. } else {
  17481. if ( image.data ) {
  17482. return {
  17483. data: getTypedArray( image.type, image.data ),
  17484. width: image.width,
  17485. height: image.height
  17486. };
  17487. } else {
  17488. return null;
  17489. }
  17490. }
  17491. }
  17492. if ( json !== undefined && json.length > 0 ) {
  17493. const manager = new LoadingManager( onLoad );
  17494. loader = new ImageLoader( manager );
  17495. loader.setCrossOrigin( this.crossOrigin );
  17496. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17497. const image = json[ i ];
  17498. const url = image.url;
  17499. if ( Array.isArray( url ) ) {
  17500. // load array of images e.g CubeTexture
  17501. const imageArray = [];
  17502. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17503. const currentUrl = url[ j ];
  17504. const deserializedImage = deserializeImage( currentUrl );
  17505. if ( deserializedImage !== null ) {
  17506. if ( deserializedImage instanceof HTMLImageElement ) {
  17507. imageArray.push( deserializedImage );
  17508. } else {
  17509. // special case: handle array of data textures for cube textures
  17510. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17511. }
  17512. }
  17513. }
  17514. images[ image.uuid ] = new Source( imageArray );
  17515. } else {
  17516. // load single image
  17517. const deserializedImage = deserializeImage( image.url );
  17518. images[ image.uuid ] = new Source( deserializedImage );
  17519. }
  17520. }
  17521. }
  17522. return images;
  17523. }
  17524. async parseImagesAsync( json ) {
  17525. const scope = this;
  17526. const images = {};
  17527. let loader;
  17528. async function deserializeImage( image ) {
  17529. if ( typeof image === 'string' ) {
  17530. const url = image;
  17531. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17532. return await loader.loadAsync( path );
  17533. } else {
  17534. if ( image.data ) {
  17535. return {
  17536. data: getTypedArray( image.type, image.data ),
  17537. width: image.width,
  17538. height: image.height
  17539. };
  17540. } else {
  17541. return null;
  17542. }
  17543. }
  17544. }
  17545. if ( json !== undefined && json.length > 0 ) {
  17546. loader = new ImageLoader( this.manager );
  17547. loader.setCrossOrigin( this.crossOrigin );
  17548. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17549. const image = json[ i ];
  17550. const url = image.url;
  17551. if ( Array.isArray( url ) ) {
  17552. // load array of images e.g CubeTexture
  17553. const imageArray = [];
  17554. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17555. const currentUrl = url[ j ];
  17556. const deserializedImage = await deserializeImage( currentUrl );
  17557. if ( deserializedImage !== null ) {
  17558. if ( deserializedImage instanceof HTMLImageElement ) {
  17559. imageArray.push( deserializedImage );
  17560. } else {
  17561. // special case: handle array of data textures for cube textures
  17562. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17563. }
  17564. }
  17565. }
  17566. images[ image.uuid ] = new Source( imageArray );
  17567. } else {
  17568. // load single image
  17569. const deserializedImage = await deserializeImage( image.url );
  17570. images[ image.uuid ] = new Source( deserializedImage );
  17571. }
  17572. }
  17573. }
  17574. return images;
  17575. }
  17576. parseTextures( json, images ) {
  17577. function parseConstant( value, type ) {
  17578. if ( typeof value === 'number' ) return value;
  17579. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17580. return type[ value ];
  17581. }
  17582. const textures = {};
  17583. if ( json !== undefined ) {
  17584. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17585. const data = json[ i ];
  17586. if ( data.image === undefined ) {
  17587. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17588. }
  17589. if ( images[ data.image ] === undefined ) {
  17590. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17591. }
  17592. const source = images[ data.image ];
  17593. const image = source.data;
  17594. let texture;
  17595. if ( Array.isArray( image ) ) {
  17596. texture = new CubeTexture();
  17597. if ( image.length === 6 ) texture.needsUpdate = true;
  17598. } else {
  17599. if ( image && image.data ) {
  17600. texture = new DataTexture();
  17601. } else {
  17602. texture = new Texture();
  17603. }
  17604. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17605. }
  17606. texture.source = source;
  17607. texture.uuid = data.uuid;
  17608. if ( data.name !== undefined ) texture.name = data.name;
  17609. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17610. if ( data.channel !== undefined ) texture.channel = data.channel;
  17611. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17612. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17613. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17614. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17615. if ( data.wrap !== undefined ) {
  17616. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17617. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17618. }
  17619. if ( data.format !== undefined ) texture.format = data.format;
  17620. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17621. if ( data.type !== undefined ) texture.type = data.type;
  17622. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17623. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17624. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17625. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17626. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17627. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17628. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17629. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17630. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17631. if ( data.userData !== undefined ) texture.userData = data.userData;
  17632. textures[ data.uuid ] = texture;
  17633. }
  17634. }
  17635. return textures;
  17636. }
  17637. parseObject( data, geometries, materials, textures, animations ) {
  17638. let object;
  17639. function getGeometry( name ) {
  17640. if ( geometries[ name ] === undefined ) {
  17641. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17642. }
  17643. return geometries[ name ];
  17644. }
  17645. function getMaterial( name ) {
  17646. if ( name === undefined ) return undefined;
  17647. if ( Array.isArray( name ) ) {
  17648. const array = [];
  17649. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17650. const uuid = name[ i ];
  17651. if ( materials[ uuid ] === undefined ) {
  17652. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17653. }
  17654. array.push( materials[ uuid ] );
  17655. }
  17656. return array;
  17657. }
  17658. if ( materials[ name ] === undefined ) {
  17659. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17660. }
  17661. return materials[ name ];
  17662. }
  17663. function getTexture( uuid ) {
  17664. if ( textures[ uuid ] === undefined ) {
  17665. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17666. }
  17667. return textures[ uuid ];
  17668. }
  17669. let geometry, material;
  17670. switch ( data.type ) {
  17671. case 'Scene':
  17672. object = new Scene();
  17673. if ( data.background !== undefined ) {
  17674. if ( Number.isInteger( data.background ) ) {
  17675. object.background = new Color( data.background );
  17676. } else {
  17677. object.background = getTexture( data.background );
  17678. }
  17679. }
  17680. if ( data.environment !== undefined ) {
  17681. object.environment = getTexture( data.environment );
  17682. }
  17683. if ( data.fog !== undefined ) {
  17684. if ( data.fog.type === 'Fog' ) {
  17685. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17686. } else if ( data.fog.type === 'FogExp2' ) {
  17687. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17688. }
  17689. if ( data.fog.name !== '' ) {
  17690. object.fog.name = data.fog.name;
  17691. }
  17692. }
  17693. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17694. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17695. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17696. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17697. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17698. break;
  17699. case 'PerspectiveCamera':
  17700. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17701. if ( data.focus !== undefined ) object.focus = data.focus;
  17702. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17703. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17704. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17705. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17706. break;
  17707. case 'OrthographicCamera':
  17708. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17709. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17710. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17711. break;
  17712. case 'AmbientLight':
  17713. object = new AmbientLight( data.color, data.intensity );
  17714. break;
  17715. case 'DirectionalLight':
  17716. object = new DirectionalLight( data.color, data.intensity );
  17717. object.target = data.target || '';
  17718. break;
  17719. case 'PointLight':
  17720. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17721. break;
  17722. case 'RectAreaLight':
  17723. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17724. break;
  17725. case 'SpotLight':
  17726. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17727. object.target = data.target || '';
  17728. break;
  17729. case 'HemisphereLight':
  17730. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17731. break;
  17732. case 'LightProbe':
  17733. object = new LightProbe().fromJSON( data );
  17734. break;
  17735. case 'SkinnedMesh':
  17736. geometry = getGeometry( data.geometry );
  17737. material = getMaterial( data.material );
  17738. object = new SkinnedMesh( geometry, material );
  17739. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17740. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17741. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17742. break;
  17743. case 'Mesh':
  17744. geometry = getGeometry( data.geometry );
  17745. material = getMaterial( data.material );
  17746. object = new Mesh( geometry, material );
  17747. break;
  17748. case 'InstancedMesh':
  17749. geometry = getGeometry( data.geometry );
  17750. material = getMaterial( data.material );
  17751. const count = data.count;
  17752. const instanceMatrix = data.instanceMatrix;
  17753. const instanceColor = data.instanceColor;
  17754. object = new InstancedMesh( geometry, material, count );
  17755. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17756. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17757. break;
  17758. case 'BatchedMesh':
  17759. geometry = getGeometry( data.geometry );
  17760. material = getMaterial( data.material );
  17761. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17762. object.geometry = geometry;
  17763. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17764. object.sortObjects = data.sortObjects;
  17765. object._drawRanges = data.drawRanges;
  17766. object._reservedRanges = data.reservedRanges;
  17767. object._visibility = data.visibility;
  17768. object._active = data.active;
  17769. object._bounds = data.bounds.map( bound => {
  17770. const box = new Box3();
  17771. box.min.fromArray( bound.boxMin );
  17772. box.max.fromArray( bound.boxMax );
  17773. const sphere = new Sphere();
  17774. sphere.radius = bound.sphereRadius;
  17775. sphere.center.fromArray( bound.sphereCenter );
  17776. return {
  17777. boxInitialized: bound.boxInitialized,
  17778. box: box,
  17779. sphereInitialized: bound.sphereInitialized,
  17780. sphere: sphere
  17781. };
  17782. } );
  17783. object._maxInstanceCount = data.maxInstanceCount;
  17784. object._maxVertexCount = data.maxVertexCount;
  17785. object._maxIndexCount = data.maxIndexCount;
  17786. object._geometryInitialized = data.geometryInitialized;
  17787. object._geometryCount = data.geometryCount;
  17788. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17789. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17790. break;
  17791. case 'LOD':
  17792. object = new LOD();
  17793. break;
  17794. case 'Line':
  17795. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17796. break;
  17797. case 'LineLoop':
  17798. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17799. break;
  17800. case 'LineSegments':
  17801. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17802. break;
  17803. case 'PointCloud':
  17804. case 'Points':
  17805. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17806. break;
  17807. case 'Sprite':
  17808. object = new Sprite( getMaterial( data.material ) );
  17809. break;
  17810. case 'Group':
  17811. object = new Group();
  17812. break;
  17813. case 'Bone':
  17814. object = new Bone();
  17815. break;
  17816. default:
  17817. object = new Object3D();
  17818. }
  17819. object.uuid = data.uuid;
  17820. if ( data.name !== undefined ) object.name = data.name;
  17821. if ( data.matrix !== undefined ) {
  17822. object.matrix.fromArray( data.matrix );
  17823. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17824. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17825. } else {
  17826. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17827. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17828. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17829. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17830. }
  17831. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17832. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17833. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17834. if ( data.shadow ) {
  17835. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17836. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17837. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17838. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17839. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17840. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17841. }
  17842. if ( data.visible !== undefined ) object.visible = data.visible;
  17843. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17844. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17845. if ( data.userData !== undefined ) object.userData = data.userData;
  17846. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17847. if ( data.children !== undefined ) {
  17848. const children = data.children;
  17849. for ( let i = 0; i < children.length; i ++ ) {
  17850. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17851. }
  17852. }
  17853. if ( data.animations !== undefined ) {
  17854. const objectAnimations = data.animations;
  17855. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17856. const uuid = objectAnimations[ i ];
  17857. object.animations.push( animations[ uuid ] );
  17858. }
  17859. }
  17860. if ( data.type === 'LOD' ) {
  17861. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17862. const levels = data.levels;
  17863. for ( let l = 0; l < levels.length; l ++ ) {
  17864. const level = levels[ l ];
  17865. const child = object.getObjectByProperty( 'uuid', level.object );
  17866. if ( child !== undefined ) {
  17867. object.addLevel( child, level.distance, level.hysteresis );
  17868. }
  17869. }
  17870. }
  17871. return object;
  17872. }
  17873. bindSkeletons( object, skeletons ) {
  17874. if ( Object.keys( skeletons ).length === 0 ) return;
  17875. object.traverse( function ( child ) {
  17876. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17877. const skeleton = skeletons[ child.skeleton ];
  17878. if ( skeleton === undefined ) {
  17879. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17880. } else {
  17881. child.bind( skeleton, child.bindMatrix );
  17882. }
  17883. }
  17884. } );
  17885. }
  17886. bindLightTargets( object ) {
  17887. object.traverse( function ( child ) {
  17888. if ( child.isDirectionalLight || child.isSpotLight ) {
  17889. const uuid = child.target;
  17890. const target = object.getObjectByProperty( 'uuid', uuid );
  17891. if ( target !== undefined ) {
  17892. child.target = target;
  17893. } else {
  17894. child.target = new Object3D();
  17895. }
  17896. }
  17897. } );
  17898. }
  17899. }
  17900. const TEXTURE_MAPPING = {
  17901. UVMapping: UVMapping,
  17902. CubeReflectionMapping: CubeReflectionMapping,
  17903. CubeRefractionMapping: CubeRefractionMapping,
  17904. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17905. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17906. CubeUVReflectionMapping: CubeUVReflectionMapping
  17907. };
  17908. const TEXTURE_WRAPPING = {
  17909. RepeatWrapping: RepeatWrapping,
  17910. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17911. MirroredRepeatWrapping: MirroredRepeatWrapping
  17912. };
  17913. const TEXTURE_FILTER = {
  17914. NearestFilter: NearestFilter,
  17915. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17916. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17917. LinearFilter: LinearFilter,
  17918. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17919. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17920. };
  17921. class ImageBitmapLoader extends Loader {
  17922. constructor( manager ) {
  17923. super( manager );
  17924. this.isImageBitmapLoader = true;
  17925. if ( typeof createImageBitmap === 'undefined' ) {
  17926. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17927. }
  17928. if ( typeof fetch === 'undefined' ) {
  17929. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17930. }
  17931. this.options = { premultiplyAlpha: 'none' };
  17932. }
  17933. setOptions( options ) {
  17934. this.options = options;
  17935. return this;
  17936. }
  17937. load( url, onLoad, onProgress, onError ) {
  17938. if ( url === undefined ) url = '';
  17939. if ( this.path !== undefined ) url = this.path + url;
  17940. url = this.manager.resolveURL( url );
  17941. const scope = this;
  17942. const cached = Cache.get( url );
  17943. if ( cached !== undefined ) {
  17944. scope.manager.itemStart( url );
  17945. // If cached is a promise, wait for it to resolve
  17946. if ( cached.then ) {
  17947. cached.then( imageBitmap => {
  17948. if ( onLoad ) onLoad( imageBitmap );
  17949. scope.manager.itemEnd( url );
  17950. } ).catch( e => {
  17951. if ( onError ) onError( e );
  17952. } );
  17953. return;
  17954. }
  17955. // If cached is not a promise (i.e., it's already an imageBitmap)
  17956. setTimeout( function () {
  17957. if ( onLoad ) onLoad( cached );
  17958. scope.manager.itemEnd( url );
  17959. }, 0 );
  17960. return cached;
  17961. }
  17962. const fetchOptions = {};
  17963. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17964. fetchOptions.headers = this.requestHeader;
  17965. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17966. return res.blob();
  17967. } ).then( function ( blob ) {
  17968. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17969. } ).then( function ( imageBitmap ) {
  17970. Cache.add( url, imageBitmap );
  17971. if ( onLoad ) onLoad( imageBitmap );
  17972. scope.manager.itemEnd( url );
  17973. return imageBitmap;
  17974. } ).catch( function ( e ) {
  17975. if ( onError ) onError( e );
  17976. Cache.remove( url );
  17977. scope.manager.itemError( url );
  17978. scope.manager.itemEnd( url );
  17979. } );
  17980. Cache.add( url, promise );
  17981. scope.manager.itemStart( url );
  17982. }
  17983. }
  17984. let _context;
  17985. class AudioContext {
  17986. static getContext() {
  17987. if ( _context === undefined ) {
  17988. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17989. }
  17990. return _context;
  17991. }
  17992. static setContext( value ) {
  17993. _context = value;
  17994. }
  17995. }
  17996. class AudioLoader extends Loader {
  17997. constructor( manager ) {
  17998. super( manager );
  17999. }
  18000. load( url, onLoad, onProgress, onError ) {
  18001. const scope = this;
  18002. const loader = new FileLoader( this.manager );
  18003. loader.setResponseType( 'arraybuffer' );
  18004. loader.setPath( this.path );
  18005. loader.setRequestHeader( this.requestHeader );
  18006. loader.setWithCredentials( this.withCredentials );
  18007. loader.load( url, function ( buffer ) {
  18008. try {
  18009. // Create a copy of the buffer. The `decodeAudioData` method
  18010. // detaches the buffer when complete, preventing reuse.
  18011. const bufferCopy = buffer.slice( 0 );
  18012. const context = AudioContext.getContext();
  18013. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  18014. onLoad( audioBuffer );
  18015. } ).catch( handleError );
  18016. } catch ( e ) {
  18017. handleError( e );
  18018. }
  18019. }, onProgress, onError );
  18020. function handleError( e ) {
  18021. if ( onError ) {
  18022. onError( e );
  18023. } else {
  18024. console.error( e );
  18025. }
  18026. scope.manager.itemError( url );
  18027. }
  18028. }
  18029. }
  18030. const _eyeRight = /*@__PURE__*/ new Matrix4();
  18031. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  18032. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  18033. class StereoCamera {
  18034. constructor() {
  18035. this.type = 'StereoCamera';
  18036. this.aspect = 1;
  18037. this.eyeSep = 0.064;
  18038. this.cameraL = new PerspectiveCamera();
  18039. this.cameraL.layers.enable( 1 );
  18040. this.cameraL.matrixAutoUpdate = false;
  18041. this.cameraR = new PerspectiveCamera();
  18042. this.cameraR.layers.enable( 2 );
  18043. this.cameraR.matrixAutoUpdate = false;
  18044. this._cache = {
  18045. focus: null,
  18046. fov: null,
  18047. aspect: null,
  18048. near: null,
  18049. far: null,
  18050. zoom: null,
  18051. eyeSep: null
  18052. };
  18053. }
  18054. update( camera ) {
  18055. const cache = this._cache;
  18056. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  18057. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  18058. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  18059. if ( needsUpdate ) {
  18060. cache.focus = camera.focus;
  18061. cache.fov = camera.fov;
  18062. cache.aspect = camera.aspect * this.aspect;
  18063. cache.near = camera.near;
  18064. cache.far = camera.far;
  18065. cache.zoom = camera.zoom;
  18066. cache.eyeSep = this.eyeSep;
  18067. // Off-axis stereoscopic effect based on
  18068. // http://paulbourke.net/stereographics/stereorender/
  18069. _projectionMatrix.copy( camera.projectionMatrix );
  18070. const eyeSepHalf = cache.eyeSep / 2;
  18071. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  18072. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  18073. let xmin, xmax;
  18074. // translate xOffset
  18075. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  18076. _eyeRight.elements[ 12 ] = eyeSepHalf;
  18077. // for left eye
  18078. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  18079. xmax = ymax * cache.aspect + eyeSepOnProjection;
  18080. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18081. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18082. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  18083. // for right eye
  18084. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  18085. xmax = ymax * cache.aspect - eyeSepOnProjection;
  18086. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18087. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18088. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  18089. }
  18090. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  18091. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  18092. }
  18093. }
  18094. class ArrayCamera extends PerspectiveCamera {
  18095. constructor( array = [] ) {
  18096. super();
  18097. this.isArrayCamera = true;
  18098. this.cameras = array;
  18099. }
  18100. }
  18101. class Clock {
  18102. constructor( autoStart = true ) {
  18103. this.autoStart = autoStart;
  18104. this.startTime = 0;
  18105. this.oldTime = 0;
  18106. this.elapsedTime = 0;
  18107. this.running = false;
  18108. }
  18109. start() {
  18110. this.startTime = now();
  18111. this.oldTime = this.startTime;
  18112. this.elapsedTime = 0;
  18113. this.running = true;
  18114. }
  18115. stop() {
  18116. this.getElapsedTime();
  18117. this.running = false;
  18118. this.autoStart = false;
  18119. }
  18120. getElapsedTime() {
  18121. this.getDelta();
  18122. return this.elapsedTime;
  18123. }
  18124. getDelta() {
  18125. let diff = 0;
  18126. if ( this.autoStart && ! this.running ) {
  18127. this.start();
  18128. return 0;
  18129. }
  18130. if ( this.running ) {
  18131. const newTime = now();
  18132. diff = ( newTime - this.oldTime ) / 1000;
  18133. this.oldTime = newTime;
  18134. this.elapsedTime += diff;
  18135. }
  18136. return diff;
  18137. }
  18138. }
  18139. function now() {
  18140. return performance.now();
  18141. }
  18142. const _position$1 = /*@__PURE__*/ new Vector3();
  18143. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  18144. const _scale$1 = /*@__PURE__*/ new Vector3();
  18145. const _orientation$1 = /*@__PURE__*/ new Vector3();
  18146. class AudioListener extends Object3D {
  18147. constructor() {
  18148. super();
  18149. this.type = 'AudioListener';
  18150. this.context = AudioContext.getContext();
  18151. this.gain = this.context.createGain();
  18152. this.gain.connect( this.context.destination );
  18153. this.filter = null;
  18154. this.timeDelta = 0;
  18155. // private
  18156. this._clock = new Clock();
  18157. }
  18158. getInput() {
  18159. return this.gain;
  18160. }
  18161. removeFilter() {
  18162. if ( this.filter !== null ) {
  18163. this.gain.disconnect( this.filter );
  18164. this.filter.disconnect( this.context.destination );
  18165. this.gain.connect( this.context.destination );
  18166. this.filter = null;
  18167. }
  18168. return this;
  18169. }
  18170. getFilter() {
  18171. return this.filter;
  18172. }
  18173. setFilter( value ) {
  18174. if ( this.filter !== null ) {
  18175. this.gain.disconnect( this.filter );
  18176. this.filter.disconnect( this.context.destination );
  18177. } else {
  18178. this.gain.disconnect( this.context.destination );
  18179. }
  18180. this.filter = value;
  18181. this.gain.connect( this.filter );
  18182. this.filter.connect( this.context.destination );
  18183. return this;
  18184. }
  18185. getMasterVolume() {
  18186. return this.gain.gain.value;
  18187. }
  18188. setMasterVolume( value ) {
  18189. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18190. return this;
  18191. }
  18192. updateMatrixWorld( force ) {
  18193. super.updateMatrixWorld( force );
  18194. const listener = this.context.listener;
  18195. const up = this.up;
  18196. this.timeDelta = this._clock.getDelta();
  18197. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  18198. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  18199. if ( listener.positionX ) {
  18200. // code path for Chrome (see #14393)
  18201. const endTime = this.context.currentTime + this.timeDelta;
  18202. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  18203. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  18204. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  18205. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  18206. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  18207. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  18208. listener.upX.linearRampToValueAtTime( up.x, endTime );
  18209. listener.upY.linearRampToValueAtTime( up.y, endTime );
  18210. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  18211. } else {
  18212. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  18213. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  18214. }
  18215. }
  18216. }
  18217. class Audio extends Object3D {
  18218. constructor( listener ) {
  18219. super();
  18220. this.type = 'Audio';
  18221. this.listener = listener;
  18222. this.context = listener.context;
  18223. this.gain = this.context.createGain();
  18224. this.gain.connect( listener.getInput() );
  18225. this.autoplay = false;
  18226. this.buffer = null;
  18227. this.detune = 0;
  18228. this.loop = false;
  18229. this.loopStart = 0;
  18230. this.loopEnd = 0;
  18231. this.offset = 0;
  18232. this.duration = undefined;
  18233. this.playbackRate = 1;
  18234. this.isPlaying = false;
  18235. this.hasPlaybackControl = true;
  18236. this.source = null;
  18237. this.sourceType = 'empty';
  18238. this._startedAt = 0;
  18239. this._progress = 0;
  18240. this._connected = false;
  18241. this.filters = [];
  18242. }
  18243. getOutput() {
  18244. return this.gain;
  18245. }
  18246. setNodeSource( audioNode ) {
  18247. this.hasPlaybackControl = false;
  18248. this.sourceType = 'audioNode';
  18249. this.source = audioNode;
  18250. this.connect();
  18251. return this;
  18252. }
  18253. setMediaElementSource( mediaElement ) {
  18254. this.hasPlaybackControl = false;
  18255. this.sourceType = 'mediaNode';
  18256. this.source = this.context.createMediaElementSource( mediaElement );
  18257. this.connect();
  18258. return this;
  18259. }
  18260. setMediaStreamSource( mediaStream ) {
  18261. this.hasPlaybackControl = false;
  18262. this.sourceType = 'mediaStreamNode';
  18263. this.source = this.context.createMediaStreamSource( mediaStream );
  18264. this.connect();
  18265. return this;
  18266. }
  18267. setBuffer( audioBuffer ) {
  18268. this.buffer = audioBuffer;
  18269. this.sourceType = 'buffer';
  18270. if ( this.autoplay ) this.play();
  18271. return this;
  18272. }
  18273. play( delay = 0 ) {
  18274. if ( this.isPlaying === true ) {
  18275. console.warn( 'THREE.Audio: Audio is already playing.' );
  18276. return;
  18277. }
  18278. if ( this.hasPlaybackControl === false ) {
  18279. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18280. return;
  18281. }
  18282. this._startedAt = this.context.currentTime + delay;
  18283. const source = this.context.createBufferSource();
  18284. source.buffer = this.buffer;
  18285. source.loop = this.loop;
  18286. source.loopStart = this.loopStart;
  18287. source.loopEnd = this.loopEnd;
  18288. source.onended = this.onEnded.bind( this );
  18289. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18290. this.isPlaying = true;
  18291. this.source = source;
  18292. this.setDetune( this.detune );
  18293. this.setPlaybackRate( this.playbackRate );
  18294. return this.connect();
  18295. }
  18296. pause() {
  18297. if ( this.hasPlaybackControl === false ) {
  18298. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18299. return;
  18300. }
  18301. if ( this.isPlaying === true ) {
  18302. // update current progress
  18303. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18304. if ( this.loop === true ) {
  18305. // ensure _progress does not exceed duration with looped audios
  18306. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18307. }
  18308. this.source.stop();
  18309. this.source.onended = null;
  18310. this.isPlaying = false;
  18311. }
  18312. return this;
  18313. }
  18314. stop( delay = 0 ) {
  18315. if ( this.hasPlaybackControl === false ) {
  18316. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18317. return;
  18318. }
  18319. this._progress = 0;
  18320. if ( this.source !== null ) {
  18321. this.source.stop( this.context.currentTime + delay );
  18322. this.source.onended = null;
  18323. }
  18324. this.isPlaying = false;
  18325. return this;
  18326. }
  18327. connect() {
  18328. if ( this.filters.length > 0 ) {
  18329. this.source.connect( this.filters[ 0 ] );
  18330. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18331. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18332. }
  18333. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18334. } else {
  18335. this.source.connect( this.getOutput() );
  18336. }
  18337. this._connected = true;
  18338. return this;
  18339. }
  18340. disconnect() {
  18341. if ( this._connected === false ) {
  18342. return;
  18343. }
  18344. if ( this.filters.length > 0 ) {
  18345. this.source.disconnect( this.filters[ 0 ] );
  18346. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18347. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18348. }
  18349. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18350. } else {
  18351. this.source.disconnect( this.getOutput() );
  18352. }
  18353. this._connected = false;
  18354. return this;
  18355. }
  18356. getFilters() {
  18357. return this.filters;
  18358. }
  18359. setFilters( value ) {
  18360. if ( ! value ) value = [];
  18361. if ( this._connected === true ) {
  18362. this.disconnect();
  18363. this.filters = value.slice();
  18364. this.connect();
  18365. } else {
  18366. this.filters = value.slice();
  18367. }
  18368. return this;
  18369. }
  18370. setDetune( value ) {
  18371. this.detune = value;
  18372. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18373. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18374. }
  18375. return this;
  18376. }
  18377. getDetune() {
  18378. return this.detune;
  18379. }
  18380. getFilter() {
  18381. return this.getFilters()[ 0 ];
  18382. }
  18383. setFilter( filter ) {
  18384. return this.setFilters( filter ? [ filter ] : [] );
  18385. }
  18386. setPlaybackRate( value ) {
  18387. if ( this.hasPlaybackControl === false ) {
  18388. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18389. return;
  18390. }
  18391. this.playbackRate = value;
  18392. if ( this.isPlaying === true ) {
  18393. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18394. }
  18395. return this;
  18396. }
  18397. getPlaybackRate() {
  18398. return this.playbackRate;
  18399. }
  18400. onEnded() {
  18401. this.isPlaying = false;
  18402. this._progress = 0;
  18403. }
  18404. getLoop() {
  18405. if ( this.hasPlaybackControl === false ) {
  18406. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18407. return false;
  18408. }
  18409. return this.loop;
  18410. }
  18411. setLoop( value ) {
  18412. if ( this.hasPlaybackControl === false ) {
  18413. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18414. return;
  18415. }
  18416. this.loop = value;
  18417. if ( this.isPlaying === true ) {
  18418. this.source.loop = this.loop;
  18419. }
  18420. return this;
  18421. }
  18422. setLoopStart( value ) {
  18423. this.loopStart = value;
  18424. return this;
  18425. }
  18426. setLoopEnd( value ) {
  18427. this.loopEnd = value;
  18428. return this;
  18429. }
  18430. getVolume() {
  18431. return this.gain.gain.value;
  18432. }
  18433. setVolume( value ) {
  18434. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18435. return this;
  18436. }
  18437. copy( source, recursive ) {
  18438. super.copy( source, recursive );
  18439. if ( source.sourceType !== 'buffer' ) {
  18440. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  18441. return this;
  18442. }
  18443. this.autoplay = source.autoplay;
  18444. this.buffer = source.buffer;
  18445. this.detune = source.detune;
  18446. this.loop = source.loop;
  18447. this.loopStart = source.loopStart;
  18448. this.loopEnd = source.loopEnd;
  18449. this.offset = source.offset;
  18450. this.duration = source.duration;
  18451. this.playbackRate = source.playbackRate;
  18452. this.hasPlaybackControl = source.hasPlaybackControl;
  18453. this.sourceType = source.sourceType;
  18454. this.filters = source.filters.slice();
  18455. return this;
  18456. }
  18457. clone( recursive ) {
  18458. return new this.constructor( this.listener ).copy( this, recursive );
  18459. }
  18460. }
  18461. const _position = /*@__PURE__*/ new Vector3();
  18462. const _quaternion = /*@__PURE__*/ new Quaternion();
  18463. const _scale = /*@__PURE__*/ new Vector3();
  18464. const _orientation = /*@__PURE__*/ new Vector3();
  18465. class PositionalAudio extends Audio {
  18466. constructor( listener ) {
  18467. super( listener );
  18468. this.panner = this.context.createPanner();
  18469. this.panner.panningModel = 'HRTF';
  18470. this.panner.connect( this.gain );
  18471. }
  18472. connect() {
  18473. super.connect();
  18474. this.panner.connect( this.gain );
  18475. }
  18476. disconnect() {
  18477. super.disconnect();
  18478. this.panner.disconnect( this.gain );
  18479. }
  18480. getOutput() {
  18481. return this.panner;
  18482. }
  18483. getRefDistance() {
  18484. return this.panner.refDistance;
  18485. }
  18486. setRefDistance( value ) {
  18487. this.panner.refDistance = value;
  18488. return this;
  18489. }
  18490. getRolloffFactor() {
  18491. return this.panner.rolloffFactor;
  18492. }
  18493. setRolloffFactor( value ) {
  18494. this.panner.rolloffFactor = value;
  18495. return this;
  18496. }
  18497. getDistanceModel() {
  18498. return this.panner.distanceModel;
  18499. }
  18500. setDistanceModel( value ) {
  18501. this.panner.distanceModel = value;
  18502. return this;
  18503. }
  18504. getMaxDistance() {
  18505. return this.panner.maxDistance;
  18506. }
  18507. setMaxDistance( value ) {
  18508. this.panner.maxDistance = value;
  18509. return this;
  18510. }
  18511. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18512. this.panner.coneInnerAngle = coneInnerAngle;
  18513. this.panner.coneOuterAngle = coneOuterAngle;
  18514. this.panner.coneOuterGain = coneOuterGain;
  18515. return this;
  18516. }
  18517. updateMatrixWorld( force ) {
  18518. super.updateMatrixWorld( force );
  18519. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18520. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18521. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18522. const panner = this.panner;
  18523. if ( panner.positionX ) {
  18524. // code path for Chrome and Firefox (see #14393)
  18525. const endTime = this.context.currentTime + this.listener.timeDelta;
  18526. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18527. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18528. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18529. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18530. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18531. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18532. } else {
  18533. panner.setPosition( _position.x, _position.y, _position.z );
  18534. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18535. }
  18536. }
  18537. }
  18538. class AudioAnalyser {
  18539. constructor( audio, fftSize = 2048 ) {
  18540. this.analyser = audio.context.createAnalyser();
  18541. this.analyser.fftSize = fftSize;
  18542. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18543. audio.getOutput().connect( this.analyser );
  18544. }
  18545. getFrequencyData() {
  18546. this.analyser.getByteFrequencyData( this.data );
  18547. return this.data;
  18548. }
  18549. getAverageFrequency() {
  18550. let value = 0;
  18551. const data = this.getFrequencyData();
  18552. for ( let i = 0; i < data.length; i ++ ) {
  18553. value += data[ i ];
  18554. }
  18555. return value / data.length;
  18556. }
  18557. }
  18558. class PropertyMixer {
  18559. constructor( binding, typeName, valueSize ) {
  18560. this.binding = binding;
  18561. this.valueSize = valueSize;
  18562. let mixFunction,
  18563. mixFunctionAdditive,
  18564. setIdentity;
  18565. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18566. //
  18567. // interpolators can use .buffer as their .result
  18568. // the data then goes to 'incoming'
  18569. //
  18570. // 'accu0' and 'accu1' are used frame-interleaved for
  18571. // the cumulative result and are compared to detect
  18572. // changes
  18573. //
  18574. // 'orig' stores the original state of the property
  18575. //
  18576. // 'add' is used for additive cumulative results
  18577. //
  18578. // 'work' is optional and is only present for quaternion types. It is used
  18579. // to store intermediate quaternion multiplication results
  18580. switch ( typeName ) {
  18581. case 'quaternion':
  18582. mixFunction = this._slerp;
  18583. mixFunctionAdditive = this._slerpAdditive;
  18584. setIdentity = this._setAdditiveIdentityQuaternion;
  18585. this.buffer = new Float64Array( valueSize * 6 );
  18586. this._workIndex = 5;
  18587. break;
  18588. case 'string':
  18589. case 'bool':
  18590. mixFunction = this._select;
  18591. // Use the regular mix function and for additive on these types,
  18592. // additive is not relevant for non-numeric types
  18593. mixFunctionAdditive = this._select;
  18594. setIdentity = this._setAdditiveIdentityOther;
  18595. this.buffer = new Array( valueSize * 5 );
  18596. break;
  18597. default:
  18598. mixFunction = this._lerp;
  18599. mixFunctionAdditive = this._lerpAdditive;
  18600. setIdentity = this._setAdditiveIdentityNumeric;
  18601. this.buffer = new Float64Array( valueSize * 5 );
  18602. }
  18603. this._mixBufferRegion = mixFunction;
  18604. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18605. this._setIdentity = setIdentity;
  18606. this._origIndex = 3;
  18607. this._addIndex = 4;
  18608. this.cumulativeWeight = 0;
  18609. this.cumulativeWeightAdditive = 0;
  18610. this.useCount = 0;
  18611. this.referenceCount = 0;
  18612. }
  18613. // accumulate data in the 'incoming' region into 'accu<i>'
  18614. accumulate( accuIndex, weight ) {
  18615. // note: happily accumulating nothing when weight = 0, the caller knows
  18616. // the weight and shouldn't have made the call in the first place
  18617. const buffer = this.buffer,
  18618. stride = this.valueSize,
  18619. offset = accuIndex * stride + stride;
  18620. let currentWeight = this.cumulativeWeight;
  18621. if ( currentWeight === 0 ) {
  18622. // accuN := incoming * weight
  18623. for ( let i = 0; i !== stride; ++ i ) {
  18624. buffer[ offset + i ] = buffer[ i ];
  18625. }
  18626. currentWeight = weight;
  18627. } else {
  18628. // accuN := accuN + incoming * weight
  18629. currentWeight += weight;
  18630. const mix = weight / currentWeight;
  18631. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18632. }
  18633. this.cumulativeWeight = currentWeight;
  18634. }
  18635. // accumulate data in the 'incoming' region into 'add'
  18636. accumulateAdditive( weight ) {
  18637. const buffer = this.buffer,
  18638. stride = this.valueSize,
  18639. offset = stride * this._addIndex;
  18640. if ( this.cumulativeWeightAdditive === 0 ) {
  18641. // add = identity
  18642. this._setIdentity();
  18643. }
  18644. // add := add + incoming * weight
  18645. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18646. this.cumulativeWeightAdditive += weight;
  18647. }
  18648. // apply the state of 'accu<i>' to the binding when accus differ
  18649. apply( accuIndex ) {
  18650. const stride = this.valueSize,
  18651. buffer = this.buffer,
  18652. offset = accuIndex * stride + stride,
  18653. weight = this.cumulativeWeight,
  18654. weightAdditive = this.cumulativeWeightAdditive,
  18655. binding = this.binding;
  18656. this.cumulativeWeight = 0;
  18657. this.cumulativeWeightAdditive = 0;
  18658. if ( weight < 1 ) {
  18659. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18660. const originalValueOffset = stride * this._origIndex;
  18661. this._mixBufferRegion(
  18662. buffer, offset, originalValueOffset, 1 - weight, stride );
  18663. }
  18664. if ( weightAdditive > 0 ) {
  18665. // accuN := accuN + additive accuN
  18666. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18667. }
  18668. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18669. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18670. // value has changed -> update scene graph
  18671. binding.setValue( buffer, offset );
  18672. break;
  18673. }
  18674. }
  18675. }
  18676. // remember the state of the bound property and copy it to both accus
  18677. saveOriginalState() {
  18678. const binding = this.binding;
  18679. const buffer = this.buffer,
  18680. stride = this.valueSize,
  18681. originalValueOffset = stride * this._origIndex;
  18682. binding.getValue( buffer, originalValueOffset );
  18683. // accu[0..1] := orig -- initially detect changes against the original
  18684. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18685. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18686. }
  18687. // Add to identity for additive
  18688. this._setIdentity();
  18689. this.cumulativeWeight = 0;
  18690. this.cumulativeWeightAdditive = 0;
  18691. }
  18692. // apply the state previously taken via 'saveOriginalState' to the binding
  18693. restoreOriginalState() {
  18694. const originalValueOffset = this.valueSize * 3;
  18695. this.binding.setValue( this.buffer, originalValueOffset );
  18696. }
  18697. _setAdditiveIdentityNumeric() {
  18698. const startIndex = this._addIndex * this.valueSize;
  18699. const endIndex = startIndex + this.valueSize;
  18700. for ( let i = startIndex; i < endIndex; i ++ ) {
  18701. this.buffer[ i ] = 0;
  18702. }
  18703. }
  18704. _setAdditiveIdentityQuaternion() {
  18705. this._setAdditiveIdentityNumeric();
  18706. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18707. }
  18708. _setAdditiveIdentityOther() {
  18709. const startIndex = this._origIndex * this.valueSize;
  18710. const targetIndex = this._addIndex * this.valueSize;
  18711. for ( let i = 0; i < this.valueSize; i ++ ) {
  18712. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18713. }
  18714. }
  18715. // mix functions
  18716. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18717. if ( t >= 0.5 ) {
  18718. for ( let i = 0; i !== stride; ++ i ) {
  18719. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18720. }
  18721. }
  18722. }
  18723. _slerp( buffer, dstOffset, srcOffset, t ) {
  18724. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18725. }
  18726. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18727. const workOffset = this._workIndex * stride;
  18728. // Store result in intermediate buffer offset
  18729. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18730. // Slerp to the intermediate result
  18731. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18732. }
  18733. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18734. const s = 1 - t;
  18735. for ( let i = 0; i !== stride; ++ i ) {
  18736. const j = dstOffset + i;
  18737. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18738. }
  18739. }
  18740. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18741. for ( let i = 0; i !== stride; ++ i ) {
  18742. const j = dstOffset + i;
  18743. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18744. }
  18745. }
  18746. }
  18747. // Characters [].:/ are reserved for track binding syntax.
  18748. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18749. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18750. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18751. // only latin characters, and the unicode \p{L} is not yet supported. So
  18752. // instead, we exclude reserved characters and match everything else.
  18753. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18754. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18755. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18756. // be matched to parse the rest of the track name.
  18757. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18758. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18759. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18760. // Object on target node, and accessor. May not contain reserved
  18761. // characters. Accessor may contain any character except closing bracket.
  18762. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18763. // Property and accessor. May not contain reserved characters. Accessor may
  18764. // contain any non-bracket characters.
  18765. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18766. const _trackRe = new RegExp( ''
  18767. + '^'
  18768. + _directoryRe
  18769. + _nodeRe
  18770. + _objectRe
  18771. + _propertyRe
  18772. + '$'
  18773. );
  18774. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18775. class Composite {
  18776. constructor( targetGroup, path, optionalParsedPath ) {
  18777. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18778. this._targetGroup = targetGroup;
  18779. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18780. }
  18781. getValue( array, offset ) {
  18782. this.bind(); // bind all binding
  18783. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18784. binding = this._bindings[ firstValidIndex ];
  18785. // and only call .getValue on the first
  18786. if ( binding !== undefined ) binding.getValue( array, offset );
  18787. }
  18788. setValue( array, offset ) {
  18789. const bindings = this._bindings;
  18790. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18791. bindings[ i ].setValue( array, offset );
  18792. }
  18793. }
  18794. bind() {
  18795. const bindings = this._bindings;
  18796. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18797. bindings[ i ].bind();
  18798. }
  18799. }
  18800. unbind() {
  18801. const bindings = this._bindings;
  18802. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18803. bindings[ i ].unbind();
  18804. }
  18805. }
  18806. }
  18807. // Note: This class uses a State pattern on a per-method basis:
  18808. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18809. // prototype version of these methods with one that represents
  18810. // the bound state. When the property is not found, the methods
  18811. // become no-ops.
  18812. class PropertyBinding {
  18813. constructor( rootNode, path, parsedPath ) {
  18814. this.path = path;
  18815. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18816. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18817. this.rootNode = rootNode;
  18818. // initial state of these methods that calls 'bind'
  18819. this.getValue = this._getValue_unbound;
  18820. this.setValue = this._setValue_unbound;
  18821. }
  18822. static create( root, path, parsedPath ) {
  18823. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18824. return new PropertyBinding( root, path, parsedPath );
  18825. } else {
  18826. return new PropertyBinding.Composite( root, path, parsedPath );
  18827. }
  18828. }
  18829. /**
  18830. * Replaces spaces with underscores and removes unsupported characters from
  18831. * node names, to ensure compatibility with parseTrackName().
  18832. *
  18833. * @param {string} name Node name to be sanitized.
  18834. * @return {string}
  18835. */
  18836. static sanitizeNodeName( name ) {
  18837. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18838. }
  18839. static parseTrackName( trackName ) {
  18840. const matches = _trackRe.exec( trackName );
  18841. if ( matches === null ) {
  18842. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18843. }
  18844. const results = {
  18845. // directoryName: matches[ 1 ], // (tschw) currently unused
  18846. nodeName: matches[ 2 ],
  18847. objectName: matches[ 3 ],
  18848. objectIndex: matches[ 4 ],
  18849. propertyName: matches[ 5 ], // required
  18850. propertyIndex: matches[ 6 ]
  18851. };
  18852. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18853. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18854. const objectName = results.nodeName.substring( lastDot + 1 );
  18855. // Object names must be checked against an allowlist. Otherwise, there
  18856. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18857. // 'bar' could be the objectName, or part of a nodeName (which can
  18858. // include '.' characters).
  18859. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18860. results.nodeName = results.nodeName.substring( 0, lastDot );
  18861. results.objectName = objectName;
  18862. }
  18863. }
  18864. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18865. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18866. }
  18867. return results;
  18868. }
  18869. static findNode( root, nodeName ) {
  18870. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18871. return root;
  18872. }
  18873. // search into skeleton bones.
  18874. if ( root.skeleton ) {
  18875. const bone = root.skeleton.getBoneByName( nodeName );
  18876. if ( bone !== undefined ) {
  18877. return bone;
  18878. }
  18879. }
  18880. // search into node subtree.
  18881. if ( root.children ) {
  18882. const searchNodeSubtree = function ( children ) {
  18883. for ( let i = 0; i < children.length; i ++ ) {
  18884. const childNode = children[ i ];
  18885. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18886. return childNode;
  18887. }
  18888. const result = searchNodeSubtree( childNode.children );
  18889. if ( result ) return result;
  18890. }
  18891. return null;
  18892. };
  18893. const subTreeNode = searchNodeSubtree( root.children );
  18894. if ( subTreeNode ) {
  18895. return subTreeNode;
  18896. }
  18897. }
  18898. return null;
  18899. }
  18900. // these are used to "bind" a nonexistent property
  18901. _getValue_unavailable() {}
  18902. _setValue_unavailable() {}
  18903. // Getters
  18904. _getValue_direct( buffer, offset ) {
  18905. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18906. }
  18907. _getValue_array( buffer, offset ) {
  18908. const source = this.resolvedProperty;
  18909. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18910. buffer[ offset ++ ] = source[ i ];
  18911. }
  18912. }
  18913. _getValue_arrayElement( buffer, offset ) {
  18914. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18915. }
  18916. _getValue_toArray( buffer, offset ) {
  18917. this.resolvedProperty.toArray( buffer, offset );
  18918. }
  18919. // Direct
  18920. _setValue_direct( buffer, offset ) {
  18921. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18922. }
  18923. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18924. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18925. this.targetObject.needsUpdate = true;
  18926. }
  18927. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18928. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18929. this.targetObject.matrixWorldNeedsUpdate = true;
  18930. }
  18931. // EntireArray
  18932. _setValue_array( buffer, offset ) {
  18933. const dest = this.resolvedProperty;
  18934. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18935. dest[ i ] = buffer[ offset ++ ];
  18936. }
  18937. }
  18938. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18939. const dest = this.resolvedProperty;
  18940. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18941. dest[ i ] = buffer[ offset ++ ];
  18942. }
  18943. this.targetObject.needsUpdate = true;
  18944. }
  18945. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18946. const dest = this.resolvedProperty;
  18947. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18948. dest[ i ] = buffer[ offset ++ ];
  18949. }
  18950. this.targetObject.matrixWorldNeedsUpdate = true;
  18951. }
  18952. // ArrayElement
  18953. _setValue_arrayElement( buffer, offset ) {
  18954. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18955. }
  18956. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18957. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18958. this.targetObject.needsUpdate = true;
  18959. }
  18960. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18961. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18962. this.targetObject.matrixWorldNeedsUpdate = true;
  18963. }
  18964. // HasToFromArray
  18965. _setValue_fromArray( buffer, offset ) {
  18966. this.resolvedProperty.fromArray( buffer, offset );
  18967. }
  18968. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18969. this.resolvedProperty.fromArray( buffer, offset );
  18970. this.targetObject.needsUpdate = true;
  18971. }
  18972. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18973. this.resolvedProperty.fromArray( buffer, offset );
  18974. this.targetObject.matrixWorldNeedsUpdate = true;
  18975. }
  18976. _getValue_unbound( targetArray, offset ) {
  18977. this.bind();
  18978. this.getValue( targetArray, offset );
  18979. }
  18980. _setValue_unbound( sourceArray, offset ) {
  18981. this.bind();
  18982. this.setValue( sourceArray, offset );
  18983. }
  18984. // create getter / setter pair for a property in the scene graph
  18985. bind() {
  18986. let targetObject = this.node;
  18987. const parsedPath = this.parsedPath;
  18988. const objectName = parsedPath.objectName;
  18989. const propertyName = parsedPath.propertyName;
  18990. let propertyIndex = parsedPath.propertyIndex;
  18991. if ( ! targetObject ) {
  18992. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18993. this.node = targetObject;
  18994. }
  18995. // set fail state so we can just 'return' on error
  18996. this.getValue = this._getValue_unavailable;
  18997. this.setValue = this._setValue_unavailable;
  18998. // ensure there is a value node
  18999. if ( ! targetObject ) {
  19000. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  19001. return;
  19002. }
  19003. if ( objectName ) {
  19004. let objectIndex = parsedPath.objectIndex;
  19005. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  19006. switch ( objectName ) {
  19007. case 'materials':
  19008. if ( ! targetObject.material ) {
  19009. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  19010. return;
  19011. }
  19012. if ( ! targetObject.material.materials ) {
  19013. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  19014. return;
  19015. }
  19016. targetObject = targetObject.material.materials;
  19017. break;
  19018. case 'bones':
  19019. if ( ! targetObject.skeleton ) {
  19020. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  19021. return;
  19022. }
  19023. // potential future optimization: skip this if propertyIndex is already an integer
  19024. // and convert the integer string to a true integer.
  19025. targetObject = targetObject.skeleton.bones;
  19026. // support resolving morphTarget names into indices.
  19027. for ( let i = 0; i < targetObject.length; i ++ ) {
  19028. if ( targetObject[ i ].name === objectIndex ) {
  19029. objectIndex = i;
  19030. break;
  19031. }
  19032. }
  19033. break;
  19034. case 'map':
  19035. if ( 'map' in targetObject ) {
  19036. targetObject = targetObject.map;
  19037. break;
  19038. }
  19039. if ( ! targetObject.material ) {
  19040. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  19041. return;
  19042. }
  19043. if ( ! targetObject.material.map ) {
  19044. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  19045. return;
  19046. }
  19047. targetObject = targetObject.material.map;
  19048. break;
  19049. default:
  19050. if ( targetObject[ objectName ] === undefined ) {
  19051. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  19052. return;
  19053. }
  19054. targetObject = targetObject[ objectName ];
  19055. }
  19056. if ( objectIndex !== undefined ) {
  19057. if ( targetObject[ objectIndex ] === undefined ) {
  19058. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  19059. return;
  19060. }
  19061. targetObject = targetObject[ objectIndex ];
  19062. }
  19063. }
  19064. // resolve property
  19065. const nodeProperty = targetObject[ propertyName ];
  19066. if ( nodeProperty === undefined ) {
  19067. const nodeName = parsedPath.nodeName;
  19068. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  19069. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  19070. return;
  19071. }
  19072. // determine versioning scheme
  19073. let versioning = this.Versioning.None;
  19074. this.targetObject = targetObject;
  19075. if ( targetObject.isMaterial === true ) {
  19076. versioning = this.Versioning.NeedsUpdate;
  19077. } else if ( targetObject.isObject3D === true ) {
  19078. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  19079. }
  19080. // determine how the property gets bound
  19081. let bindingType = this.BindingType.Direct;
  19082. if ( propertyIndex !== undefined ) {
  19083. // access a sub element of the property array (only primitives are supported right now)
  19084. if ( propertyName === 'morphTargetInfluences' ) {
  19085. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  19086. // support resolving morphTarget names into indices.
  19087. if ( ! targetObject.geometry ) {
  19088. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  19089. return;
  19090. }
  19091. if ( ! targetObject.geometry.morphAttributes ) {
  19092. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  19093. return;
  19094. }
  19095. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  19096. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  19097. }
  19098. }
  19099. bindingType = this.BindingType.ArrayElement;
  19100. this.resolvedProperty = nodeProperty;
  19101. this.propertyIndex = propertyIndex;
  19102. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19103. // must use copy for Object3D.Euler/Quaternion
  19104. bindingType = this.BindingType.HasFromToArray;
  19105. this.resolvedProperty = nodeProperty;
  19106. } else if ( Array.isArray( nodeProperty ) ) {
  19107. bindingType = this.BindingType.EntireArray;
  19108. this.resolvedProperty = nodeProperty;
  19109. } else {
  19110. this.propertyName = propertyName;
  19111. }
  19112. // select getter / setter
  19113. this.getValue = this.GetterByBindingType[ bindingType ];
  19114. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19115. }
  19116. unbind() {
  19117. this.node = null;
  19118. // back to the prototype version of getValue / setValue
  19119. // note: avoiding to mutate the shape of 'this' via 'delete'
  19120. this.getValue = this._getValue_unbound;
  19121. this.setValue = this._setValue_unbound;
  19122. }
  19123. }
  19124. PropertyBinding.Composite = Composite;
  19125. PropertyBinding.prototype.BindingType = {
  19126. Direct: 0,
  19127. EntireArray: 1,
  19128. ArrayElement: 2,
  19129. HasFromToArray: 3
  19130. };
  19131. PropertyBinding.prototype.Versioning = {
  19132. None: 0,
  19133. NeedsUpdate: 1,
  19134. MatrixWorldNeedsUpdate: 2
  19135. };
  19136. PropertyBinding.prototype.GetterByBindingType = [
  19137. PropertyBinding.prototype._getValue_direct,
  19138. PropertyBinding.prototype._getValue_array,
  19139. PropertyBinding.prototype._getValue_arrayElement,
  19140. PropertyBinding.prototype._getValue_toArray,
  19141. ];
  19142. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  19143. [
  19144. // Direct
  19145. PropertyBinding.prototype._setValue_direct,
  19146. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  19147. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  19148. ], [
  19149. // EntireArray
  19150. PropertyBinding.prototype._setValue_array,
  19151. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  19152. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  19153. ], [
  19154. // ArrayElement
  19155. PropertyBinding.prototype._setValue_arrayElement,
  19156. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  19157. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  19158. ], [
  19159. // HasToFromArray
  19160. PropertyBinding.prototype._setValue_fromArray,
  19161. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  19162. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  19163. ]
  19164. ];
  19165. /**
  19166. *
  19167. * A group of objects that receives a shared animation state.
  19168. *
  19169. * Usage:
  19170. *
  19171. * - Add objects you would otherwise pass as 'root' to the
  19172. * constructor or the .clipAction method of AnimationMixer.
  19173. *
  19174. * - Instead pass this object as 'root'.
  19175. *
  19176. * - You can also add and remove objects later when the mixer
  19177. * is running.
  19178. *
  19179. * Note:
  19180. *
  19181. * Objects of this class appear as one object to the mixer,
  19182. * so cache control of the individual objects must be done
  19183. * on the group.
  19184. *
  19185. * Limitation:
  19186. *
  19187. * - The animated properties must be compatible among the
  19188. * all objects in the group.
  19189. *
  19190. * - A single property can either be controlled through a
  19191. * target group or directly, but not both.
  19192. */
  19193. class AnimationObjectGroup {
  19194. constructor() {
  19195. this.isAnimationObjectGroup = true;
  19196. this.uuid = generateUUID();
  19197. // cached objects followed by the active ones
  19198. this._objects = Array.prototype.slice.call( arguments );
  19199. this.nCachedObjects_ = 0; // threshold
  19200. // note: read by PropertyBinding.Composite
  19201. const indices = {};
  19202. this._indicesByUUID = indices; // for bookkeeping
  19203. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19204. indices[ arguments[ i ].uuid ] = i;
  19205. }
  19206. this._paths = []; // inside: string
  19207. this._parsedPaths = []; // inside: { we don't care, here }
  19208. this._bindings = []; // inside: Array< PropertyBinding >
  19209. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  19210. const scope = this;
  19211. this.stats = {
  19212. objects: {
  19213. get total() {
  19214. return scope._objects.length;
  19215. },
  19216. get inUse() {
  19217. return this.total - scope.nCachedObjects_;
  19218. }
  19219. },
  19220. get bindingsPerObject() {
  19221. return scope._bindings.length;
  19222. }
  19223. };
  19224. }
  19225. add() {
  19226. const objects = this._objects,
  19227. indicesByUUID = this._indicesByUUID,
  19228. paths = this._paths,
  19229. parsedPaths = this._parsedPaths,
  19230. bindings = this._bindings,
  19231. nBindings = bindings.length;
  19232. let knownObject = undefined,
  19233. nObjects = objects.length,
  19234. nCachedObjects = this.nCachedObjects_;
  19235. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19236. const object = arguments[ i ],
  19237. uuid = object.uuid;
  19238. let index = indicesByUUID[ uuid ];
  19239. if ( index === undefined ) {
  19240. // unknown object -> add it to the ACTIVE region
  19241. index = nObjects ++;
  19242. indicesByUUID[ uuid ] = index;
  19243. objects.push( object );
  19244. // accounting is done, now do the same for all bindings
  19245. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19246. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  19247. }
  19248. } else if ( index < nCachedObjects ) {
  19249. knownObject = objects[ index ];
  19250. // move existing object to the ACTIVE region
  19251. const firstActiveIndex = -- nCachedObjects,
  19252. lastCachedObject = objects[ firstActiveIndex ];
  19253. indicesByUUID[ lastCachedObject.uuid ] = index;
  19254. objects[ index ] = lastCachedObject;
  19255. indicesByUUID[ uuid ] = firstActiveIndex;
  19256. objects[ firstActiveIndex ] = object;
  19257. // accounting is done, now do the same for all bindings
  19258. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19259. const bindingsForPath = bindings[ j ],
  19260. lastCached = bindingsForPath[ firstActiveIndex ];
  19261. let binding = bindingsForPath[ index ];
  19262. bindingsForPath[ index ] = lastCached;
  19263. if ( binding === undefined ) {
  19264. // since we do not bother to create new bindings
  19265. // for objects that are cached, the binding may
  19266. // or may not exist
  19267. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  19268. }
  19269. bindingsForPath[ firstActiveIndex ] = binding;
  19270. }
  19271. } else if ( objects[ index ] !== knownObject ) {
  19272. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  19273. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  19274. } // else the object is already where we want it to be
  19275. } // for arguments
  19276. this.nCachedObjects_ = nCachedObjects;
  19277. }
  19278. remove() {
  19279. const objects = this._objects,
  19280. indicesByUUID = this._indicesByUUID,
  19281. bindings = this._bindings,
  19282. nBindings = bindings.length;
  19283. let nCachedObjects = this.nCachedObjects_;
  19284. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19285. const object = arguments[ i ],
  19286. uuid = object.uuid,
  19287. index = indicesByUUID[ uuid ];
  19288. if ( index !== undefined && index >= nCachedObjects ) {
  19289. // move existing object into the CACHED region
  19290. const lastCachedIndex = nCachedObjects ++,
  19291. firstActiveObject = objects[ lastCachedIndex ];
  19292. indicesByUUID[ firstActiveObject.uuid ] = index;
  19293. objects[ index ] = firstActiveObject;
  19294. indicesByUUID[ uuid ] = lastCachedIndex;
  19295. objects[ lastCachedIndex ] = object;
  19296. // accounting is done, now do the same for all bindings
  19297. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19298. const bindingsForPath = bindings[ j ],
  19299. firstActive = bindingsForPath[ lastCachedIndex ],
  19300. binding = bindingsForPath[ index ];
  19301. bindingsForPath[ index ] = firstActive;
  19302. bindingsForPath[ lastCachedIndex ] = binding;
  19303. }
  19304. }
  19305. } // for arguments
  19306. this.nCachedObjects_ = nCachedObjects;
  19307. }
  19308. // remove & forget
  19309. uncache() {
  19310. const objects = this._objects,
  19311. indicesByUUID = this._indicesByUUID,
  19312. bindings = this._bindings,
  19313. nBindings = bindings.length;
  19314. let nCachedObjects = this.nCachedObjects_,
  19315. nObjects = objects.length;
  19316. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19317. const object = arguments[ i ],
  19318. uuid = object.uuid,
  19319. index = indicesByUUID[ uuid ];
  19320. if ( index !== undefined ) {
  19321. delete indicesByUUID[ uuid ];
  19322. if ( index < nCachedObjects ) {
  19323. // object is cached, shrink the CACHED region
  19324. const firstActiveIndex = -- nCachedObjects,
  19325. lastCachedObject = objects[ firstActiveIndex ],
  19326. lastIndex = -- nObjects,
  19327. lastObject = objects[ lastIndex ];
  19328. // last cached object takes this object's place
  19329. indicesByUUID[ lastCachedObject.uuid ] = index;
  19330. objects[ index ] = lastCachedObject;
  19331. // last object goes to the activated slot and pop
  19332. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19333. objects[ firstActiveIndex ] = lastObject;
  19334. objects.pop();
  19335. // accounting is done, now do the same for all bindings
  19336. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19337. const bindingsForPath = bindings[ j ],
  19338. lastCached = bindingsForPath[ firstActiveIndex ],
  19339. last = bindingsForPath[ lastIndex ];
  19340. bindingsForPath[ index ] = lastCached;
  19341. bindingsForPath[ firstActiveIndex ] = last;
  19342. bindingsForPath.pop();
  19343. }
  19344. } else {
  19345. // object is active, just swap with the last and pop
  19346. const lastIndex = -- nObjects,
  19347. lastObject = objects[ lastIndex ];
  19348. if ( lastIndex > 0 ) {
  19349. indicesByUUID[ lastObject.uuid ] = index;
  19350. }
  19351. objects[ index ] = lastObject;
  19352. objects.pop();
  19353. // accounting is done, now do the same for all bindings
  19354. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19355. const bindingsForPath = bindings[ j ];
  19356. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19357. bindingsForPath.pop();
  19358. }
  19359. } // cached or active
  19360. } // if object is known
  19361. } // for arguments
  19362. this.nCachedObjects_ = nCachedObjects;
  19363. }
  19364. // Internal interface used by befriended PropertyBinding.Composite:
  19365. subscribe_( path, parsedPath ) {
  19366. // returns an array of bindings for the given path that is changed
  19367. // according to the contained objects in the group
  19368. const indicesByPath = this._bindingsIndicesByPath;
  19369. let index = indicesByPath[ path ];
  19370. const bindings = this._bindings;
  19371. if ( index !== undefined ) return bindings[ index ];
  19372. const paths = this._paths,
  19373. parsedPaths = this._parsedPaths,
  19374. objects = this._objects,
  19375. nObjects = objects.length,
  19376. nCachedObjects = this.nCachedObjects_,
  19377. bindingsForPath = new Array( nObjects );
  19378. index = bindings.length;
  19379. indicesByPath[ path ] = index;
  19380. paths.push( path );
  19381. parsedPaths.push( parsedPath );
  19382. bindings.push( bindingsForPath );
  19383. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19384. const object = objects[ i ];
  19385. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19386. }
  19387. return bindingsForPath;
  19388. }
  19389. unsubscribe_( path ) {
  19390. // tells the group to forget about a property path and no longer
  19391. // update the array previously obtained with 'subscribe_'
  19392. const indicesByPath = this._bindingsIndicesByPath,
  19393. index = indicesByPath[ path ];
  19394. if ( index !== undefined ) {
  19395. const paths = this._paths,
  19396. parsedPaths = this._parsedPaths,
  19397. bindings = this._bindings,
  19398. lastBindingsIndex = bindings.length - 1,
  19399. lastBindings = bindings[ lastBindingsIndex ],
  19400. lastBindingsPath = path[ lastBindingsIndex ];
  19401. indicesByPath[ lastBindingsPath ] = index;
  19402. bindings[ index ] = lastBindings;
  19403. bindings.pop();
  19404. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19405. parsedPaths.pop();
  19406. paths[ index ] = paths[ lastBindingsIndex ];
  19407. paths.pop();
  19408. }
  19409. }
  19410. }
  19411. class AnimationAction {
  19412. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19413. this._mixer = mixer;
  19414. this._clip = clip;
  19415. this._localRoot = localRoot;
  19416. this.blendMode = blendMode;
  19417. const tracks = clip.tracks,
  19418. nTracks = tracks.length,
  19419. interpolants = new Array( nTracks );
  19420. const interpolantSettings = {
  19421. endingStart: ZeroCurvatureEnding,
  19422. endingEnd: ZeroCurvatureEnding
  19423. };
  19424. for ( let i = 0; i !== nTracks; ++ i ) {
  19425. const interpolant = tracks[ i ].createInterpolant( null );
  19426. interpolants[ i ] = interpolant;
  19427. interpolant.settings = interpolantSettings;
  19428. }
  19429. this._interpolantSettings = interpolantSettings;
  19430. this._interpolants = interpolants; // bound by the mixer
  19431. // inside: PropertyMixer (managed by the mixer)
  19432. this._propertyBindings = new Array( nTracks );
  19433. this._cacheIndex = null; // for the memory manager
  19434. this._byClipCacheIndex = null; // for the memory manager
  19435. this._timeScaleInterpolant = null;
  19436. this._weightInterpolant = null;
  19437. this.loop = LoopRepeat;
  19438. this._loopCount = - 1;
  19439. // global mixer time when the action is to be started
  19440. // it's set back to 'null' upon start of the action
  19441. this._startTime = null;
  19442. // scaled local time of the action
  19443. // gets clamped or wrapped to 0..clip.duration according to loop
  19444. this.time = 0;
  19445. this.timeScale = 1;
  19446. this._effectiveTimeScale = 1;
  19447. this.weight = 1;
  19448. this._effectiveWeight = 1;
  19449. this.repetitions = Infinity; // no. of repetitions when looping
  19450. this.paused = false; // true -> zero effective time scale
  19451. this.enabled = true; // false -> zero effective weight
  19452. this.clampWhenFinished = false;// keep feeding the last frame?
  19453. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19454. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19455. }
  19456. // State & Scheduling
  19457. play() {
  19458. this._mixer._activateAction( this );
  19459. return this;
  19460. }
  19461. stop() {
  19462. this._mixer._deactivateAction( this );
  19463. return this.reset();
  19464. }
  19465. reset() {
  19466. this.paused = false;
  19467. this.enabled = true;
  19468. this.time = 0; // restart clip
  19469. this._loopCount = - 1;// forget previous loops
  19470. this._startTime = null;// forget scheduling
  19471. return this.stopFading().stopWarping();
  19472. }
  19473. isRunning() {
  19474. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19475. this._startTime === null && this._mixer._isActiveAction( this );
  19476. }
  19477. // return true when play has been called
  19478. isScheduled() {
  19479. return this._mixer._isActiveAction( this );
  19480. }
  19481. startAt( time ) {
  19482. this._startTime = time;
  19483. return this;
  19484. }
  19485. setLoop( mode, repetitions ) {
  19486. this.loop = mode;
  19487. this.repetitions = repetitions;
  19488. return this;
  19489. }
  19490. // Weight
  19491. // set the weight stopping any scheduled fading
  19492. // although .enabled = false yields an effective weight of zero, this
  19493. // method does *not* change .enabled, because it would be confusing
  19494. setEffectiveWeight( weight ) {
  19495. this.weight = weight;
  19496. // note: same logic as when updated at runtime
  19497. this._effectiveWeight = this.enabled ? weight : 0;
  19498. return this.stopFading();
  19499. }
  19500. // return the weight considering fading and .enabled
  19501. getEffectiveWeight() {
  19502. return this._effectiveWeight;
  19503. }
  19504. fadeIn( duration ) {
  19505. return this._scheduleFading( duration, 0, 1 );
  19506. }
  19507. fadeOut( duration ) {
  19508. return this._scheduleFading( duration, 1, 0 );
  19509. }
  19510. crossFadeFrom( fadeOutAction, duration, warp ) {
  19511. fadeOutAction.fadeOut( duration );
  19512. this.fadeIn( duration );
  19513. if ( warp ) {
  19514. const fadeInDuration = this._clip.duration,
  19515. fadeOutDuration = fadeOutAction._clip.duration,
  19516. startEndRatio = fadeOutDuration / fadeInDuration,
  19517. endStartRatio = fadeInDuration / fadeOutDuration;
  19518. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19519. this.warp( endStartRatio, 1.0, duration );
  19520. }
  19521. return this;
  19522. }
  19523. crossFadeTo( fadeInAction, duration, warp ) {
  19524. return fadeInAction.crossFadeFrom( this, duration, warp );
  19525. }
  19526. stopFading() {
  19527. const weightInterpolant = this._weightInterpolant;
  19528. if ( weightInterpolant !== null ) {
  19529. this._weightInterpolant = null;
  19530. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19531. }
  19532. return this;
  19533. }
  19534. // Time Scale Control
  19535. // set the time scale stopping any scheduled warping
  19536. // although .paused = true yields an effective time scale of zero, this
  19537. // method does *not* change .paused, because it would be confusing
  19538. setEffectiveTimeScale( timeScale ) {
  19539. this.timeScale = timeScale;
  19540. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19541. return this.stopWarping();
  19542. }
  19543. // return the time scale considering warping and .paused
  19544. getEffectiveTimeScale() {
  19545. return this._effectiveTimeScale;
  19546. }
  19547. setDuration( duration ) {
  19548. this.timeScale = this._clip.duration / duration;
  19549. return this.stopWarping();
  19550. }
  19551. syncWith( action ) {
  19552. this.time = action.time;
  19553. this.timeScale = action.timeScale;
  19554. return this.stopWarping();
  19555. }
  19556. halt( duration ) {
  19557. return this.warp( this._effectiveTimeScale, 0, duration );
  19558. }
  19559. warp( startTimeScale, endTimeScale, duration ) {
  19560. const mixer = this._mixer,
  19561. now = mixer.time,
  19562. timeScale = this.timeScale;
  19563. let interpolant = this._timeScaleInterpolant;
  19564. if ( interpolant === null ) {
  19565. interpolant = mixer._lendControlInterpolant();
  19566. this._timeScaleInterpolant = interpolant;
  19567. }
  19568. const times = interpolant.parameterPositions,
  19569. values = interpolant.sampleValues;
  19570. times[ 0 ] = now;
  19571. times[ 1 ] = now + duration;
  19572. values[ 0 ] = startTimeScale / timeScale;
  19573. values[ 1 ] = endTimeScale / timeScale;
  19574. return this;
  19575. }
  19576. stopWarping() {
  19577. const timeScaleInterpolant = this._timeScaleInterpolant;
  19578. if ( timeScaleInterpolant !== null ) {
  19579. this._timeScaleInterpolant = null;
  19580. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19581. }
  19582. return this;
  19583. }
  19584. // Object Accessors
  19585. getMixer() {
  19586. return this._mixer;
  19587. }
  19588. getClip() {
  19589. return this._clip;
  19590. }
  19591. getRoot() {
  19592. return this._localRoot || this._mixer._root;
  19593. }
  19594. // Interna
  19595. _update( time, deltaTime, timeDirection, accuIndex ) {
  19596. // called by the mixer
  19597. if ( ! this.enabled ) {
  19598. // call ._updateWeight() to update ._effectiveWeight
  19599. this._updateWeight( time );
  19600. return;
  19601. }
  19602. const startTime = this._startTime;
  19603. if ( startTime !== null ) {
  19604. // check for scheduled start of action
  19605. const timeRunning = ( time - startTime ) * timeDirection;
  19606. if ( timeRunning < 0 || timeDirection === 0 ) {
  19607. deltaTime = 0;
  19608. } else {
  19609. this._startTime = null; // unschedule
  19610. deltaTime = timeDirection * timeRunning;
  19611. }
  19612. }
  19613. // apply time scale and advance time
  19614. deltaTime *= this._updateTimeScale( time );
  19615. const clipTime = this._updateTime( deltaTime );
  19616. // note: _updateTime may disable the action resulting in
  19617. // an effective weight of 0
  19618. const weight = this._updateWeight( time );
  19619. if ( weight > 0 ) {
  19620. const interpolants = this._interpolants;
  19621. const propertyMixers = this._propertyBindings;
  19622. switch ( this.blendMode ) {
  19623. case AdditiveAnimationBlendMode:
  19624. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19625. interpolants[ j ].evaluate( clipTime );
  19626. propertyMixers[ j ].accumulateAdditive( weight );
  19627. }
  19628. break;
  19629. case NormalAnimationBlendMode:
  19630. default:
  19631. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19632. interpolants[ j ].evaluate( clipTime );
  19633. propertyMixers[ j ].accumulate( accuIndex, weight );
  19634. }
  19635. }
  19636. }
  19637. }
  19638. _updateWeight( time ) {
  19639. let weight = 0;
  19640. if ( this.enabled ) {
  19641. weight = this.weight;
  19642. const interpolant = this._weightInterpolant;
  19643. if ( interpolant !== null ) {
  19644. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19645. weight *= interpolantValue;
  19646. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19647. this.stopFading();
  19648. if ( interpolantValue === 0 ) {
  19649. // faded out, disable
  19650. this.enabled = false;
  19651. }
  19652. }
  19653. }
  19654. }
  19655. this._effectiveWeight = weight;
  19656. return weight;
  19657. }
  19658. _updateTimeScale( time ) {
  19659. let timeScale = 0;
  19660. if ( ! this.paused ) {
  19661. timeScale = this.timeScale;
  19662. const interpolant = this._timeScaleInterpolant;
  19663. if ( interpolant !== null ) {
  19664. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19665. timeScale *= interpolantValue;
  19666. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19667. this.stopWarping();
  19668. if ( timeScale === 0 ) {
  19669. // motion has halted, pause
  19670. this.paused = true;
  19671. } else {
  19672. // warp done - apply final time scale
  19673. this.timeScale = timeScale;
  19674. }
  19675. }
  19676. }
  19677. }
  19678. this._effectiveTimeScale = timeScale;
  19679. return timeScale;
  19680. }
  19681. _updateTime( deltaTime ) {
  19682. const duration = this._clip.duration;
  19683. const loop = this.loop;
  19684. let time = this.time + deltaTime;
  19685. let loopCount = this._loopCount;
  19686. const pingPong = ( loop === LoopPingPong );
  19687. if ( deltaTime === 0 ) {
  19688. if ( loopCount === - 1 ) return time;
  19689. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19690. }
  19691. if ( loop === LoopOnce ) {
  19692. if ( loopCount === - 1 ) {
  19693. // just started
  19694. this._loopCount = 0;
  19695. this._setEndings( true, true, false );
  19696. }
  19697. handle_stop: {
  19698. if ( time >= duration ) {
  19699. time = duration;
  19700. } else if ( time < 0 ) {
  19701. time = 0;
  19702. } else {
  19703. this.time = time;
  19704. break handle_stop;
  19705. }
  19706. if ( this.clampWhenFinished ) this.paused = true;
  19707. else this.enabled = false;
  19708. this.time = time;
  19709. this._mixer.dispatchEvent( {
  19710. type: 'finished', action: this,
  19711. direction: deltaTime < 0 ? - 1 : 1
  19712. } );
  19713. }
  19714. } else { // repetitive Repeat or PingPong
  19715. if ( loopCount === - 1 ) {
  19716. // just started
  19717. if ( deltaTime >= 0 ) {
  19718. loopCount = 0;
  19719. this._setEndings( true, this.repetitions === 0, pingPong );
  19720. } else {
  19721. // when looping in reverse direction, the initial
  19722. // transition through zero counts as a repetition,
  19723. // so leave loopCount at -1
  19724. this._setEndings( this.repetitions === 0, true, pingPong );
  19725. }
  19726. }
  19727. if ( time >= duration || time < 0 ) {
  19728. // wrap around
  19729. const loopDelta = Math.floor( time / duration ); // signed
  19730. time -= duration * loopDelta;
  19731. loopCount += Math.abs( loopDelta );
  19732. const pending = this.repetitions - loopCount;
  19733. if ( pending <= 0 ) {
  19734. // have to stop (switch state, clamp time, fire event)
  19735. if ( this.clampWhenFinished ) this.paused = true;
  19736. else this.enabled = false;
  19737. time = deltaTime > 0 ? duration : 0;
  19738. this.time = time;
  19739. this._mixer.dispatchEvent( {
  19740. type: 'finished', action: this,
  19741. direction: deltaTime > 0 ? 1 : - 1
  19742. } );
  19743. } else {
  19744. // keep running
  19745. if ( pending === 1 ) {
  19746. // entering the last round
  19747. const atStart = deltaTime < 0;
  19748. this._setEndings( atStart, ! atStart, pingPong );
  19749. } else {
  19750. this._setEndings( false, false, pingPong );
  19751. }
  19752. this._loopCount = loopCount;
  19753. this.time = time;
  19754. this._mixer.dispatchEvent( {
  19755. type: 'loop', action: this, loopDelta: loopDelta
  19756. } );
  19757. }
  19758. } else {
  19759. this.time = time;
  19760. }
  19761. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19762. // invert time for the "pong round"
  19763. return duration - time;
  19764. }
  19765. }
  19766. return time;
  19767. }
  19768. _setEndings( atStart, atEnd, pingPong ) {
  19769. const settings = this._interpolantSettings;
  19770. if ( pingPong ) {
  19771. settings.endingStart = ZeroSlopeEnding;
  19772. settings.endingEnd = ZeroSlopeEnding;
  19773. } else {
  19774. // assuming for LoopOnce atStart == atEnd == true
  19775. if ( atStart ) {
  19776. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19777. } else {
  19778. settings.endingStart = WrapAroundEnding;
  19779. }
  19780. if ( atEnd ) {
  19781. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19782. } else {
  19783. settings.endingEnd = WrapAroundEnding;
  19784. }
  19785. }
  19786. }
  19787. _scheduleFading( duration, weightNow, weightThen ) {
  19788. const mixer = this._mixer, now = mixer.time;
  19789. let interpolant = this._weightInterpolant;
  19790. if ( interpolant === null ) {
  19791. interpolant = mixer._lendControlInterpolant();
  19792. this._weightInterpolant = interpolant;
  19793. }
  19794. const times = interpolant.parameterPositions,
  19795. values = interpolant.sampleValues;
  19796. times[ 0 ] = now;
  19797. values[ 0 ] = weightNow;
  19798. times[ 1 ] = now + duration;
  19799. values[ 1 ] = weightThen;
  19800. return this;
  19801. }
  19802. }
  19803. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19804. class AnimationMixer extends EventDispatcher {
  19805. constructor( root ) {
  19806. super();
  19807. this._root = root;
  19808. this._initMemoryManager();
  19809. this._accuIndex = 0;
  19810. this.time = 0;
  19811. this.timeScale = 1.0;
  19812. }
  19813. _bindAction( action, prototypeAction ) {
  19814. const root = action._localRoot || this._root,
  19815. tracks = action._clip.tracks,
  19816. nTracks = tracks.length,
  19817. bindings = action._propertyBindings,
  19818. interpolants = action._interpolants,
  19819. rootUuid = root.uuid,
  19820. bindingsByRoot = this._bindingsByRootAndName;
  19821. let bindingsByName = bindingsByRoot[ rootUuid ];
  19822. if ( bindingsByName === undefined ) {
  19823. bindingsByName = {};
  19824. bindingsByRoot[ rootUuid ] = bindingsByName;
  19825. }
  19826. for ( let i = 0; i !== nTracks; ++ i ) {
  19827. const track = tracks[ i ],
  19828. trackName = track.name;
  19829. let binding = bindingsByName[ trackName ];
  19830. if ( binding !== undefined ) {
  19831. ++ binding.referenceCount;
  19832. bindings[ i ] = binding;
  19833. } else {
  19834. binding = bindings[ i ];
  19835. if ( binding !== undefined ) {
  19836. // existing binding, make sure the cache knows
  19837. if ( binding._cacheIndex === null ) {
  19838. ++ binding.referenceCount;
  19839. this._addInactiveBinding( binding, rootUuid, trackName );
  19840. }
  19841. continue;
  19842. }
  19843. const path = prototypeAction && prototypeAction.
  19844. _propertyBindings[ i ].binding.parsedPath;
  19845. binding = new PropertyMixer(
  19846. PropertyBinding.create( root, trackName, path ),
  19847. track.ValueTypeName, track.getValueSize() );
  19848. ++ binding.referenceCount;
  19849. this._addInactiveBinding( binding, rootUuid, trackName );
  19850. bindings[ i ] = binding;
  19851. }
  19852. interpolants[ i ].resultBuffer = binding.buffer;
  19853. }
  19854. }
  19855. _activateAction( action ) {
  19856. if ( ! this._isActiveAction( action ) ) {
  19857. if ( action._cacheIndex === null ) {
  19858. // this action has been forgotten by the cache, but the user
  19859. // appears to be still using it -> rebind
  19860. const rootUuid = ( action._localRoot || this._root ).uuid,
  19861. clipUuid = action._clip.uuid,
  19862. actionsForClip = this._actionsByClip[ clipUuid ];
  19863. this._bindAction( action,
  19864. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19865. this._addInactiveAction( action, clipUuid, rootUuid );
  19866. }
  19867. const bindings = action._propertyBindings;
  19868. // increment reference counts / sort out state
  19869. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19870. const binding = bindings[ i ];
  19871. if ( binding.useCount ++ === 0 ) {
  19872. this._lendBinding( binding );
  19873. binding.saveOriginalState();
  19874. }
  19875. }
  19876. this._lendAction( action );
  19877. }
  19878. }
  19879. _deactivateAction( action ) {
  19880. if ( this._isActiveAction( action ) ) {
  19881. const bindings = action._propertyBindings;
  19882. // decrement reference counts / sort out state
  19883. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19884. const binding = bindings[ i ];
  19885. if ( -- binding.useCount === 0 ) {
  19886. binding.restoreOriginalState();
  19887. this._takeBackBinding( binding );
  19888. }
  19889. }
  19890. this._takeBackAction( action );
  19891. }
  19892. }
  19893. // Memory manager
  19894. _initMemoryManager() {
  19895. this._actions = []; // 'nActiveActions' followed by inactive ones
  19896. this._nActiveActions = 0;
  19897. this._actionsByClip = {};
  19898. // inside:
  19899. // {
  19900. // knownActions: Array< AnimationAction > - used as prototypes
  19901. // actionByRoot: AnimationAction - lookup
  19902. // }
  19903. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19904. this._nActiveBindings = 0;
  19905. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19906. this._controlInterpolants = []; // same game as above
  19907. this._nActiveControlInterpolants = 0;
  19908. const scope = this;
  19909. this.stats = {
  19910. actions: {
  19911. get total() {
  19912. return scope._actions.length;
  19913. },
  19914. get inUse() {
  19915. return scope._nActiveActions;
  19916. }
  19917. },
  19918. bindings: {
  19919. get total() {
  19920. return scope._bindings.length;
  19921. },
  19922. get inUse() {
  19923. return scope._nActiveBindings;
  19924. }
  19925. },
  19926. controlInterpolants: {
  19927. get total() {
  19928. return scope._controlInterpolants.length;
  19929. },
  19930. get inUse() {
  19931. return scope._nActiveControlInterpolants;
  19932. }
  19933. }
  19934. };
  19935. }
  19936. // Memory management for AnimationAction objects
  19937. _isActiveAction( action ) {
  19938. const index = action._cacheIndex;
  19939. return index !== null && index < this._nActiveActions;
  19940. }
  19941. _addInactiveAction( action, clipUuid, rootUuid ) {
  19942. const actions = this._actions,
  19943. actionsByClip = this._actionsByClip;
  19944. let actionsForClip = actionsByClip[ clipUuid ];
  19945. if ( actionsForClip === undefined ) {
  19946. actionsForClip = {
  19947. knownActions: [ action ],
  19948. actionByRoot: {}
  19949. };
  19950. action._byClipCacheIndex = 0;
  19951. actionsByClip[ clipUuid ] = actionsForClip;
  19952. } else {
  19953. const knownActions = actionsForClip.knownActions;
  19954. action._byClipCacheIndex = knownActions.length;
  19955. knownActions.push( action );
  19956. }
  19957. action._cacheIndex = actions.length;
  19958. actions.push( action );
  19959. actionsForClip.actionByRoot[ rootUuid ] = action;
  19960. }
  19961. _removeInactiveAction( action ) {
  19962. const actions = this._actions,
  19963. lastInactiveAction = actions[ actions.length - 1 ],
  19964. cacheIndex = action._cacheIndex;
  19965. lastInactiveAction._cacheIndex = cacheIndex;
  19966. actions[ cacheIndex ] = lastInactiveAction;
  19967. actions.pop();
  19968. action._cacheIndex = null;
  19969. const clipUuid = action._clip.uuid,
  19970. actionsByClip = this._actionsByClip,
  19971. actionsForClip = actionsByClip[ clipUuid ],
  19972. knownActionsForClip = actionsForClip.knownActions,
  19973. lastKnownAction =
  19974. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19975. byClipCacheIndex = action._byClipCacheIndex;
  19976. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19977. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19978. knownActionsForClip.pop();
  19979. action._byClipCacheIndex = null;
  19980. const actionByRoot = actionsForClip.actionByRoot,
  19981. rootUuid = ( action._localRoot || this._root ).uuid;
  19982. delete actionByRoot[ rootUuid ];
  19983. if ( knownActionsForClip.length === 0 ) {
  19984. delete actionsByClip[ clipUuid ];
  19985. }
  19986. this._removeInactiveBindingsForAction( action );
  19987. }
  19988. _removeInactiveBindingsForAction( action ) {
  19989. const bindings = action._propertyBindings;
  19990. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19991. const binding = bindings[ i ];
  19992. if ( -- binding.referenceCount === 0 ) {
  19993. this._removeInactiveBinding( binding );
  19994. }
  19995. }
  19996. }
  19997. _lendAction( action ) {
  19998. // [ active actions | inactive actions ]
  19999. // [ active actions >| inactive actions ]
  20000. // s a
  20001. // <-swap->
  20002. // a s
  20003. const actions = this._actions,
  20004. prevIndex = action._cacheIndex,
  20005. lastActiveIndex = this._nActiveActions ++,
  20006. firstInactiveAction = actions[ lastActiveIndex ];
  20007. action._cacheIndex = lastActiveIndex;
  20008. actions[ lastActiveIndex ] = action;
  20009. firstInactiveAction._cacheIndex = prevIndex;
  20010. actions[ prevIndex ] = firstInactiveAction;
  20011. }
  20012. _takeBackAction( action ) {
  20013. // [ active actions | inactive actions ]
  20014. // [ active actions |< inactive actions ]
  20015. // a s
  20016. // <-swap->
  20017. // s a
  20018. const actions = this._actions,
  20019. prevIndex = action._cacheIndex,
  20020. firstInactiveIndex = -- this._nActiveActions,
  20021. lastActiveAction = actions[ firstInactiveIndex ];
  20022. action._cacheIndex = firstInactiveIndex;
  20023. actions[ firstInactiveIndex ] = action;
  20024. lastActiveAction._cacheIndex = prevIndex;
  20025. actions[ prevIndex ] = lastActiveAction;
  20026. }
  20027. // Memory management for PropertyMixer objects
  20028. _addInactiveBinding( binding, rootUuid, trackName ) {
  20029. const bindingsByRoot = this._bindingsByRootAndName,
  20030. bindings = this._bindings;
  20031. let bindingByName = bindingsByRoot[ rootUuid ];
  20032. if ( bindingByName === undefined ) {
  20033. bindingByName = {};
  20034. bindingsByRoot[ rootUuid ] = bindingByName;
  20035. }
  20036. bindingByName[ trackName ] = binding;
  20037. binding._cacheIndex = bindings.length;
  20038. bindings.push( binding );
  20039. }
  20040. _removeInactiveBinding( binding ) {
  20041. const bindings = this._bindings,
  20042. propBinding = binding.binding,
  20043. rootUuid = propBinding.rootNode.uuid,
  20044. trackName = propBinding.path,
  20045. bindingsByRoot = this._bindingsByRootAndName,
  20046. bindingByName = bindingsByRoot[ rootUuid ],
  20047. lastInactiveBinding = bindings[ bindings.length - 1 ],
  20048. cacheIndex = binding._cacheIndex;
  20049. lastInactiveBinding._cacheIndex = cacheIndex;
  20050. bindings[ cacheIndex ] = lastInactiveBinding;
  20051. bindings.pop();
  20052. delete bindingByName[ trackName ];
  20053. if ( Object.keys( bindingByName ).length === 0 ) {
  20054. delete bindingsByRoot[ rootUuid ];
  20055. }
  20056. }
  20057. _lendBinding( binding ) {
  20058. const bindings = this._bindings,
  20059. prevIndex = binding._cacheIndex,
  20060. lastActiveIndex = this._nActiveBindings ++,
  20061. firstInactiveBinding = bindings[ lastActiveIndex ];
  20062. binding._cacheIndex = lastActiveIndex;
  20063. bindings[ lastActiveIndex ] = binding;
  20064. firstInactiveBinding._cacheIndex = prevIndex;
  20065. bindings[ prevIndex ] = firstInactiveBinding;
  20066. }
  20067. _takeBackBinding( binding ) {
  20068. const bindings = this._bindings,
  20069. prevIndex = binding._cacheIndex,
  20070. firstInactiveIndex = -- this._nActiveBindings,
  20071. lastActiveBinding = bindings[ firstInactiveIndex ];
  20072. binding._cacheIndex = firstInactiveIndex;
  20073. bindings[ firstInactiveIndex ] = binding;
  20074. lastActiveBinding._cacheIndex = prevIndex;
  20075. bindings[ prevIndex ] = lastActiveBinding;
  20076. }
  20077. // Memory management of Interpolants for weight and time scale
  20078. _lendControlInterpolant() {
  20079. const interpolants = this._controlInterpolants,
  20080. lastActiveIndex = this._nActiveControlInterpolants ++;
  20081. let interpolant = interpolants[ lastActiveIndex ];
  20082. if ( interpolant === undefined ) {
  20083. interpolant = new LinearInterpolant(
  20084. new Float32Array( 2 ), new Float32Array( 2 ),
  20085. 1, _controlInterpolantsResultBuffer );
  20086. interpolant.__cacheIndex = lastActiveIndex;
  20087. interpolants[ lastActiveIndex ] = interpolant;
  20088. }
  20089. return interpolant;
  20090. }
  20091. _takeBackControlInterpolant( interpolant ) {
  20092. const interpolants = this._controlInterpolants,
  20093. prevIndex = interpolant.__cacheIndex,
  20094. firstInactiveIndex = -- this._nActiveControlInterpolants,
  20095. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  20096. interpolant.__cacheIndex = firstInactiveIndex;
  20097. interpolants[ firstInactiveIndex ] = interpolant;
  20098. lastActiveInterpolant.__cacheIndex = prevIndex;
  20099. interpolants[ prevIndex ] = lastActiveInterpolant;
  20100. }
  20101. // return an action for a clip optionally using a custom root target
  20102. // object (this method allocates a lot of dynamic memory in case a
  20103. // previously unknown clip/root combination is specified)
  20104. clipAction( clip, optionalRoot, blendMode ) {
  20105. const root = optionalRoot || this._root,
  20106. rootUuid = root.uuid;
  20107. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  20108. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  20109. const actionsForClip = this._actionsByClip[ clipUuid ];
  20110. let prototypeAction = null;
  20111. if ( blendMode === undefined ) {
  20112. if ( clipObject !== null ) {
  20113. blendMode = clipObject.blendMode;
  20114. } else {
  20115. blendMode = NormalAnimationBlendMode;
  20116. }
  20117. }
  20118. if ( actionsForClip !== undefined ) {
  20119. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  20120. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  20121. return existingAction;
  20122. }
  20123. // we know the clip, so we don't have to parse all
  20124. // the bindings again but can just copy
  20125. prototypeAction = actionsForClip.knownActions[ 0 ];
  20126. // also, take the clip from the prototype action
  20127. if ( clipObject === null )
  20128. clipObject = prototypeAction._clip;
  20129. }
  20130. // clip must be known when specified via string
  20131. if ( clipObject === null ) return null;
  20132. // allocate all resources required to run it
  20133. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  20134. this._bindAction( newAction, prototypeAction );
  20135. // and make the action known to the memory manager
  20136. this._addInactiveAction( newAction, clipUuid, rootUuid );
  20137. return newAction;
  20138. }
  20139. // get an existing action
  20140. existingAction( clip, optionalRoot ) {
  20141. const root = optionalRoot || this._root,
  20142. rootUuid = root.uuid,
  20143. clipObject = typeof clip === 'string' ?
  20144. AnimationClip.findByName( root, clip ) : clip,
  20145. clipUuid = clipObject ? clipObject.uuid : clip,
  20146. actionsForClip = this._actionsByClip[ clipUuid ];
  20147. if ( actionsForClip !== undefined ) {
  20148. return actionsForClip.actionByRoot[ rootUuid ] || null;
  20149. }
  20150. return null;
  20151. }
  20152. // deactivates all previously scheduled actions
  20153. stopAllAction() {
  20154. const actions = this._actions,
  20155. nActions = this._nActiveActions;
  20156. for ( let i = nActions - 1; i >= 0; -- i ) {
  20157. actions[ i ].stop();
  20158. }
  20159. return this;
  20160. }
  20161. // advance the time and update apply the animation
  20162. update( deltaTime ) {
  20163. deltaTime *= this.timeScale;
  20164. const actions = this._actions,
  20165. nActions = this._nActiveActions,
  20166. time = this.time += deltaTime,
  20167. timeDirection = Math.sign( deltaTime ),
  20168. accuIndex = this._accuIndex ^= 1;
  20169. // run active actions
  20170. for ( let i = 0; i !== nActions; ++ i ) {
  20171. const action = actions[ i ];
  20172. action._update( time, deltaTime, timeDirection, accuIndex );
  20173. }
  20174. // update scene graph
  20175. const bindings = this._bindings,
  20176. nBindings = this._nActiveBindings;
  20177. for ( let i = 0; i !== nBindings; ++ i ) {
  20178. bindings[ i ].apply( accuIndex );
  20179. }
  20180. return this;
  20181. }
  20182. // Allows you to seek to a specific time in an animation.
  20183. setTime( timeInSeconds ) {
  20184. this.time = 0; // Zero out time attribute for AnimationMixer object;
  20185. for ( let i = 0; i < this._actions.length; i ++ ) {
  20186. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  20187. }
  20188. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  20189. }
  20190. // return this mixer's root target object
  20191. getRoot() {
  20192. return this._root;
  20193. }
  20194. // free all resources specific to a particular clip
  20195. uncacheClip( clip ) {
  20196. const actions = this._actions,
  20197. clipUuid = clip.uuid,
  20198. actionsByClip = this._actionsByClip,
  20199. actionsForClip = actionsByClip[ clipUuid ];
  20200. if ( actionsForClip !== undefined ) {
  20201. // note: just calling _removeInactiveAction would mess up the
  20202. // iteration state and also require updating the state we can
  20203. // just throw away
  20204. const actionsToRemove = actionsForClip.knownActions;
  20205. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  20206. const action = actionsToRemove[ i ];
  20207. this._deactivateAction( action );
  20208. const cacheIndex = action._cacheIndex,
  20209. lastInactiveAction = actions[ actions.length - 1 ];
  20210. action._cacheIndex = null;
  20211. action._byClipCacheIndex = null;
  20212. lastInactiveAction._cacheIndex = cacheIndex;
  20213. actions[ cacheIndex ] = lastInactiveAction;
  20214. actions.pop();
  20215. this._removeInactiveBindingsForAction( action );
  20216. }
  20217. delete actionsByClip[ clipUuid ];
  20218. }
  20219. }
  20220. // free all resources specific to a particular root target object
  20221. uncacheRoot( root ) {
  20222. const rootUuid = root.uuid,
  20223. actionsByClip = this._actionsByClip;
  20224. for ( const clipUuid in actionsByClip ) {
  20225. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  20226. action = actionByRoot[ rootUuid ];
  20227. if ( action !== undefined ) {
  20228. this._deactivateAction( action );
  20229. this._removeInactiveAction( action );
  20230. }
  20231. }
  20232. const bindingsByRoot = this._bindingsByRootAndName,
  20233. bindingByName = bindingsByRoot[ rootUuid ];
  20234. if ( bindingByName !== undefined ) {
  20235. for ( const trackName in bindingByName ) {
  20236. const binding = bindingByName[ trackName ];
  20237. binding.restoreOriginalState();
  20238. this._removeInactiveBinding( binding );
  20239. }
  20240. }
  20241. }
  20242. // remove a targeted clip from the cache
  20243. uncacheAction( clip, optionalRoot ) {
  20244. const action = this.existingAction( clip, optionalRoot );
  20245. if ( action !== null ) {
  20246. this._deactivateAction( action );
  20247. this._removeInactiveAction( action );
  20248. }
  20249. }
  20250. }
  20251. class Uniform {
  20252. constructor( value ) {
  20253. this.value = value;
  20254. }
  20255. clone() {
  20256. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  20257. }
  20258. }
  20259. let _id$1 = 0;
  20260. class UniformsGroup extends EventDispatcher {
  20261. constructor() {
  20262. super();
  20263. this.isUniformsGroup = true;
  20264. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  20265. this.name = '';
  20266. this.usage = StaticDrawUsage;
  20267. this.uniforms = [];
  20268. }
  20269. add( uniform ) {
  20270. this.uniforms.push( uniform );
  20271. return this;
  20272. }
  20273. remove( uniform ) {
  20274. const index = this.uniforms.indexOf( uniform );
  20275. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  20276. return this;
  20277. }
  20278. setName( name ) {
  20279. this.name = name;
  20280. return this;
  20281. }
  20282. setUsage( value ) {
  20283. this.usage = value;
  20284. return this;
  20285. }
  20286. dispose() {
  20287. this.dispatchEvent( { type: 'dispose' } );
  20288. return this;
  20289. }
  20290. copy( source ) {
  20291. this.name = source.name;
  20292. this.usage = source.usage;
  20293. const uniformsSource = source.uniforms;
  20294. this.uniforms.length = 0;
  20295. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  20296. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  20297. for ( let j = 0; j < uniforms.length; j ++ ) {
  20298. this.uniforms.push( uniforms[ j ].clone() );
  20299. }
  20300. }
  20301. return this;
  20302. }
  20303. clone() {
  20304. return new this.constructor().copy( this );
  20305. }
  20306. }
  20307. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20308. constructor( array, stride, meshPerAttribute = 1 ) {
  20309. super( array, stride );
  20310. this.isInstancedInterleavedBuffer = true;
  20311. this.meshPerAttribute = meshPerAttribute;
  20312. }
  20313. copy( source ) {
  20314. super.copy( source );
  20315. this.meshPerAttribute = source.meshPerAttribute;
  20316. return this;
  20317. }
  20318. clone( data ) {
  20319. const ib = super.clone( data );
  20320. ib.meshPerAttribute = this.meshPerAttribute;
  20321. return ib;
  20322. }
  20323. toJSON( data ) {
  20324. const json = super.toJSON( data );
  20325. json.isInstancedInterleavedBuffer = true;
  20326. json.meshPerAttribute = this.meshPerAttribute;
  20327. return json;
  20328. }
  20329. }
  20330. class GLBufferAttribute {
  20331. constructor( buffer, type, itemSize, elementSize, count ) {
  20332. this.isGLBufferAttribute = true;
  20333. this.name = '';
  20334. this.buffer = buffer;
  20335. this.type = type;
  20336. this.itemSize = itemSize;
  20337. this.elementSize = elementSize;
  20338. this.count = count;
  20339. this.version = 0;
  20340. }
  20341. set needsUpdate( value ) {
  20342. if ( value === true ) this.version ++;
  20343. }
  20344. setBuffer( buffer ) {
  20345. this.buffer = buffer;
  20346. return this;
  20347. }
  20348. setType( type, elementSize ) {
  20349. this.type = type;
  20350. this.elementSize = elementSize;
  20351. return this;
  20352. }
  20353. setItemSize( itemSize ) {
  20354. this.itemSize = itemSize;
  20355. return this;
  20356. }
  20357. setCount( count ) {
  20358. this.count = count;
  20359. return this;
  20360. }
  20361. }
  20362. const _matrix = /*@__PURE__*/ new Matrix4();
  20363. class Raycaster {
  20364. constructor( origin, direction, near = 0, far = Infinity ) {
  20365. this.ray = new Ray( origin, direction );
  20366. // direction is assumed to be normalized (for accurate distance calculations)
  20367. this.near = near;
  20368. this.far = far;
  20369. this.camera = null;
  20370. this.layers = new Layers();
  20371. this.params = {
  20372. Mesh: {},
  20373. Line: { threshold: 1 },
  20374. LOD: {},
  20375. Points: { threshold: 1 },
  20376. Sprite: {}
  20377. };
  20378. }
  20379. set( origin, direction ) {
  20380. // direction is assumed to be normalized (for accurate distance calculations)
  20381. this.ray.set( origin, direction );
  20382. }
  20383. setFromCamera( coords, camera ) {
  20384. if ( camera.isPerspectiveCamera ) {
  20385. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20386. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20387. this.camera = camera;
  20388. } else if ( camera.isOrthographicCamera ) {
  20389. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20390. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20391. this.camera = camera;
  20392. } else {
  20393. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20394. }
  20395. }
  20396. setFromXRController( controller ) {
  20397. _matrix.identity().extractRotation( controller.matrixWorld );
  20398. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20399. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20400. return this;
  20401. }
  20402. intersectObject( object, recursive = true, intersects = [] ) {
  20403. intersect( object, this, intersects, recursive );
  20404. intersects.sort( ascSort );
  20405. return intersects;
  20406. }
  20407. intersectObjects( objects, recursive = true, intersects = [] ) {
  20408. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20409. intersect( objects[ i ], this, intersects, recursive );
  20410. }
  20411. intersects.sort( ascSort );
  20412. return intersects;
  20413. }
  20414. }
  20415. function ascSort( a, b ) {
  20416. return a.distance - b.distance;
  20417. }
  20418. function intersect( object, raycaster, intersects, recursive ) {
  20419. let propagate = true;
  20420. if ( object.layers.test( raycaster.layers ) ) {
  20421. const result = object.raycast( raycaster, intersects );
  20422. if ( result === false ) propagate = false;
  20423. }
  20424. if ( propagate === true && recursive === true ) {
  20425. const children = object.children;
  20426. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20427. intersect( children[ i ], raycaster, intersects, true );
  20428. }
  20429. }
  20430. }
  20431. /**
  20432. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20433. *
  20434. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20435. * theta (the azimuthal angle) is measured from the positive z-axis.
  20436. */
  20437. class Spherical {
  20438. constructor( radius = 1, phi = 0, theta = 0 ) {
  20439. this.radius = radius;
  20440. this.phi = phi; // polar angle
  20441. this.theta = theta; // azimuthal angle
  20442. return this;
  20443. }
  20444. set( radius, phi, theta ) {
  20445. this.radius = radius;
  20446. this.phi = phi;
  20447. this.theta = theta;
  20448. return this;
  20449. }
  20450. copy( other ) {
  20451. this.radius = other.radius;
  20452. this.phi = other.phi;
  20453. this.theta = other.theta;
  20454. return this;
  20455. }
  20456. // restrict phi to be between EPS and PI-EPS
  20457. makeSafe() {
  20458. const EPS = 0.000001;
  20459. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  20460. return this;
  20461. }
  20462. setFromVector3( v ) {
  20463. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20464. }
  20465. setFromCartesianCoords( x, y, z ) {
  20466. this.radius = Math.sqrt( x * x + y * y + z * z );
  20467. if ( this.radius === 0 ) {
  20468. this.theta = 0;
  20469. this.phi = 0;
  20470. } else {
  20471. this.theta = Math.atan2( x, z );
  20472. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  20473. }
  20474. return this;
  20475. }
  20476. clone() {
  20477. return new this.constructor().copy( this );
  20478. }
  20479. }
  20480. /**
  20481. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20482. */
  20483. class Cylindrical {
  20484. constructor( radius = 1, theta = 0, y = 0 ) {
  20485. this.radius = radius; // distance from the origin to a point in the x-z plane
  20486. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20487. this.y = y; // height above the x-z plane
  20488. return this;
  20489. }
  20490. set( radius, theta, y ) {
  20491. this.radius = radius;
  20492. this.theta = theta;
  20493. this.y = y;
  20494. return this;
  20495. }
  20496. copy( other ) {
  20497. this.radius = other.radius;
  20498. this.theta = other.theta;
  20499. this.y = other.y;
  20500. return this;
  20501. }
  20502. setFromVector3( v ) {
  20503. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20504. }
  20505. setFromCartesianCoords( x, y, z ) {
  20506. this.radius = Math.sqrt( x * x + z * z );
  20507. this.theta = Math.atan2( x, z );
  20508. this.y = y;
  20509. return this;
  20510. }
  20511. clone() {
  20512. return new this.constructor().copy( this );
  20513. }
  20514. }
  20515. class Matrix2 {
  20516. constructor( n11, n12, n21, n22 ) {
  20517. Matrix2.prototype.isMatrix2 = true;
  20518. this.elements = [
  20519. 1, 0,
  20520. 0, 1,
  20521. ];
  20522. if ( n11 !== undefined ) {
  20523. this.set( n11, n12, n21, n22 );
  20524. }
  20525. }
  20526. identity() {
  20527. this.set(
  20528. 1, 0,
  20529. 0, 1,
  20530. );
  20531. return this;
  20532. }
  20533. fromArray( array, offset = 0 ) {
  20534. for ( let i = 0; i < 4; i ++ ) {
  20535. this.elements[ i ] = array[ i + offset ];
  20536. }
  20537. return this;
  20538. }
  20539. set( n11, n12, n21, n22 ) {
  20540. const te = this.elements;
  20541. te[ 0 ] = n11; te[ 2 ] = n12;
  20542. te[ 1 ] = n21; te[ 3 ] = n22;
  20543. return this;
  20544. }
  20545. }
  20546. const _vector$4 = /*@__PURE__*/ new Vector2();
  20547. class Box2 {
  20548. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20549. this.isBox2 = true;
  20550. this.min = min;
  20551. this.max = max;
  20552. }
  20553. set( min, max ) {
  20554. this.min.copy( min );
  20555. this.max.copy( max );
  20556. return this;
  20557. }
  20558. setFromPoints( points ) {
  20559. this.makeEmpty();
  20560. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20561. this.expandByPoint( points[ i ] );
  20562. }
  20563. return this;
  20564. }
  20565. setFromCenterAndSize( center, size ) {
  20566. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20567. this.min.copy( center ).sub( halfSize );
  20568. this.max.copy( center ).add( halfSize );
  20569. return this;
  20570. }
  20571. clone() {
  20572. return new this.constructor().copy( this );
  20573. }
  20574. copy( box ) {
  20575. this.min.copy( box.min );
  20576. this.max.copy( box.max );
  20577. return this;
  20578. }
  20579. makeEmpty() {
  20580. this.min.x = this.min.y = + Infinity;
  20581. this.max.x = this.max.y = - Infinity;
  20582. return this;
  20583. }
  20584. isEmpty() {
  20585. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20586. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20587. }
  20588. getCenter( target ) {
  20589. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20590. }
  20591. getSize( target ) {
  20592. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20593. }
  20594. expandByPoint( point ) {
  20595. this.min.min( point );
  20596. this.max.max( point );
  20597. return this;
  20598. }
  20599. expandByVector( vector ) {
  20600. this.min.sub( vector );
  20601. this.max.add( vector );
  20602. return this;
  20603. }
  20604. expandByScalar( scalar ) {
  20605. this.min.addScalar( - scalar );
  20606. this.max.addScalar( scalar );
  20607. return this;
  20608. }
  20609. containsPoint( point ) {
  20610. return point.x >= this.min.x && point.x <= this.max.x &&
  20611. point.y >= this.min.y && point.y <= this.max.y;
  20612. }
  20613. containsBox( box ) {
  20614. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20615. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20616. }
  20617. getParameter( point, target ) {
  20618. // This can potentially have a divide by zero if the box
  20619. // has a size dimension of 0.
  20620. return target.set(
  20621. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20622. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20623. );
  20624. }
  20625. intersectsBox( box ) {
  20626. // using 4 splitting planes to rule out intersections
  20627. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20628. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20629. }
  20630. clampPoint( point, target ) {
  20631. return target.copy( point ).clamp( this.min, this.max );
  20632. }
  20633. distanceToPoint( point ) {
  20634. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20635. }
  20636. intersect( box ) {
  20637. this.min.max( box.min );
  20638. this.max.min( box.max );
  20639. if ( this.isEmpty() ) this.makeEmpty();
  20640. return this;
  20641. }
  20642. union( box ) {
  20643. this.min.min( box.min );
  20644. this.max.max( box.max );
  20645. return this;
  20646. }
  20647. translate( offset ) {
  20648. this.min.add( offset );
  20649. this.max.add( offset );
  20650. return this;
  20651. }
  20652. equals( box ) {
  20653. return box.min.equals( this.min ) && box.max.equals( this.max );
  20654. }
  20655. }
  20656. const _startP = /*@__PURE__*/ new Vector3();
  20657. const _startEnd = /*@__PURE__*/ new Vector3();
  20658. class Line3 {
  20659. constructor( start = new Vector3(), end = new Vector3() ) {
  20660. this.start = start;
  20661. this.end = end;
  20662. }
  20663. set( start, end ) {
  20664. this.start.copy( start );
  20665. this.end.copy( end );
  20666. return this;
  20667. }
  20668. copy( line ) {
  20669. this.start.copy( line.start );
  20670. this.end.copy( line.end );
  20671. return this;
  20672. }
  20673. getCenter( target ) {
  20674. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20675. }
  20676. delta( target ) {
  20677. return target.subVectors( this.end, this.start );
  20678. }
  20679. distanceSq() {
  20680. return this.start.distanceToSquared( this.end );
  20681. }
  20682. distance() {
  20683. return this.start.distanceTo( this.end );
  20684. }
  20685. at( t, target ) {
  20686. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20687. }
  20688. closestPointToPointParameter( point, clampToLine ) {
  20689. _startP.subVectors( point, this.start );
  20690. _startEnd.subVectors( this.end, this.start );
  20691. const startEnd2 = _startEnd.dot( _startEnd );
  20692. const startEnd_startP = _startEnd.dot( _startP );
  20693. let t = startEnd_startP / startEnd2;
  20694. if ( clampToLine ) {
  20695. t = clamp( t, 0, 1 );
  20696. }
  20697. return t;
  20698. }
  20699. closestPointToPoint( point, clampToLine, target ) {
  20700. const t = this.closestPointToPointParameter( point, clampToLine );
  20701. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20702. }
  20703. applyMatrix4( matrix ) {
  20704. this.start.applyMatrix4( matrix );
  20705. this.end.applyMatrix4( matrix );
  20706. return this;
  20707. }
  20708. equals( line ) {
  20709. return line.start.equals( this.start ) && line.end.equals( this.end );
  20710. }
  20711. clone() {
  20712. return new this.constructor().copy( this );
  20713. }
  20714. }
  20715. const _vector$3 = /*@__PURE__*/ new Vector3();
  20716. class SpotLightHelper extends Object3D {
  20717. constructor( light, color ) {
  20718. super();
  20719. this.light = light;
  20720. this.matrixAutoUpdate = false;
  20721. this.color = color;
  20722. this.type = 'SpotLightHelper';
  20723. const geometry = new BufferGeometry();
  20724. const positions = [
  20725. 0, 0, 0, 0, 0, 1,
  20726. 0, 0, 0, 1, 0, 1,
  20727. 0, 0, 0, - 1, 0, 1,
  20728. 0, 0, 0, 0, 1, 1,
  20729. 0, 0, 0, 0, - 1, 1
  20730. ];
  20731. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20732. const p1 = ( i / l ) * Math.PI * 2;
  20733. const p2 = ( j / l ) * Math.PI * 2;
  20734. positions.push(
  20735. Math.cos( p1 ), Math.sin( p1 ), 1,
  20736. Math.cos( p2 ), Math.sin( p2 ), 1
  20737. );
  20738. }
  20739. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20740. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20741. this.cone = new LineSegments( geometry, material );
  20742. this.add( this.cone );
  20743. this.update();
  20744. }
  20745. dispose() {
  20746. this.cone.geometry.dispose();
  20747. this.cone.material.dispose();
  20748. }
  20749. update() {
  20750. this.light.updateWorldMatrix( true, false );
  20751. this.light.target.updateWorldMatrix( true, false );
  20752. // update the local matrix based on the parent and light target transforms
  20753. if ( this.parent ) {
  20754. this.parent.updateWorldMatrix( true );
  20755. this.matrix
  20756. .copy( this.parent.matrixWorld )
  20757. .invert()
  20758. .multiply( this.light.matrixWorld );
  20759. } else {
  20760. this.matrix.copy( this.light.matrixWorld );
  20761. }
  20762. this.matrixWorld.copy( this.light.matrixWorld );
  20763. const coneLength = this.light.distance ? this.light.distance : 1000;
  20764. const coneWidth = coneLength * Math.tan( this.light.angle );
  20765. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20766. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20767. this.cone.lookAt( _vector$3 );
  20768. if ( this.color !== undefined ) {
  20769. this.cone.material.color.set( this.color );
  20770. } else {
  20771. this.cone.material.color.copy( this.light.color );
  20772. }
  20773. }
  20774. }
  20775. const _vector$2 = /*@__PURE__*/ new Vector3();
  20776. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20777. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20778. class SkeletonHelper extends LineSegments {
  20779. constructor( object ) {
  20780. const bones = getBoneList( object );
  20781. const geometry = new BufferGeometry();
  20782. const vertices = [];
  20783. const colors = [];
  20784. const color1 = new Color( 0, 0, 1 );
  20785. const color2 = new Color( 0, 1, 0 );
  20786. for ( let i = 0; i < bones.length; i ++ ) {
  20787. const bone = bones[ i ];
  20788. if ( bone.parent && bone.parent.isBone ) {
  20789. vertices.push( 0, 0, 0 );
  20790. vertices.push( 0, 0, 0 );
  20791. colors.push( color1.r, color1.g, color1.b );
  20792. colors.push( color2.r, color2.g, color2.b );
  20793. }
  20794. }
  20795. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20796. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20797. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20798. super( geometry, material );
  20799. this.isSkeletonHelper = true;
  20800. this.type = 'SkeletonHelper';
  20801. this.root = object;
  20802. this.bones = bones;
  20803. this.matrix = object.matrixWorld;
  20804. this.matrixAutoUpdate = false;
  20805. }
  20806. updateMatrixWorld( force ) {
  20807. const bones = this.bones;
  20808. const geometry = this.geometry;
  20809. const position = geometry.getAttribute( 'position' );
  20810. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20811. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20812. const bone = bones[ i ];
  20813. if ( bone.parent && bone.parent.isBone ) {
  20814. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20815. _vector$2.setFromMatrixPosition( _boneMatrix );
  20816. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20817. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20818. _vector$2.setFromMatrixPosition( _boneMatrix );
  20819. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20820. j += 2;
  20821. }
  20822. }
  20823. geometry.getAttribute( 'position' ).needsUpdate = true;
  20824. super.updateMatrixWorld( force );
  20825. }
  20826. dispose() {
  20827. this.geometry.dispose();
  20828. this.material.dispose();
  20829. }
  20830. }
  20831. function getBoneList( object ) {
  20832. const boneList = [];
  20833. if ( object.isBone === true ) {
  20834. boneList.push( object );
  20835. }
  20836. for ( let i = 0; i < object.children.length; i ++ ) {
  20837. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20838. }
  20839. return boneList;
  20840. }
  20841. class PointLightHelper extends Mesh {
  20842. constructor( light, sphereSize, color ) {
  20843. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20844. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20845. super( geometry, material );
  20846. this.light = light;
  20847. this.color = color;
  20848. this.type = 'PointLightHelper';
  20849. this.matrix = this.light.matrixWorld;
  20850. this.matrixAutoUpdate = false;
  20851. this.update();
  20852. /*
  20853. // TODO: delete this comment?
  20854. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20855. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20856. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20857. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20858. const d = light.distance;
  20859. if ( d === 0.0 ) {
  20860. this.lightDistance.visible = false;
  20861. } else {
  20862. this.lightDistance.scale.set( d, d, d );
  20863. }
  20864. this.add( this.lightDistance );
  20865. */
  20866. }
  20867. dispose() {
  20868. this.geometry.dispose();
  20869. this.material.dispose();
  20870. }
  20871. update() {
  20872. this.light.updateWorldMatrix( true, false );
  20873. if ( this.color !== undefined ) {
  20874. this.material.color.set( this.color );
  20875. } else {
  20876. this.material.color.copy( this.light.color );
  20877. }
  20878. /*
  20879. const d = this.light.distance;
  20880. if ( d === 0.0 ) {
  20881. this.lightDistance.visible = false;
  20882. } else {
  20883. this.lightDistance.visible = true;
  20884. this.lightDistance.scale.set( d, d, d );
  20885. }
  20886. */
  20887. }
  20888. }
  20889. const _vector$1 = /*@__PURE__*/ new Vector3();
  20890. const _color1 = /*@__PURE__*/ new Color();
  20891. const _color2 = /*@__PURE__*/ new Color();
  20892. class HemisphereLightHelper extends Object3D {
  20893. constructor( light, size, color ) {
  20894. super();
  20895. this.light = light;
  20896. this.matrix = light.matrixWorld;
  20897. this.matrixAutoUpdate = false;
  20898. this.color = color;
  20899. this.type = 'HemisphereLightHelper';
  20900. const geometry = new OctahedronGeometry( size );
  20901. geometry.rotateY( Math.PI * 0.5 );
  20902. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20903. if ( this.color === undefined ) this.material.vertexColors = true;
  20904. const position = geometry.getAttribute( 'position' );
  20905. const colors = new Float32Array( position.count * 3 );
  20906. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20907. this.add( new Mesh( geometry, this.material ) );
  20908. this.update();
  20909. }
  20910. dispose() {
  20911. this.children[ 0 ].geometry.dispose();
  20912. this.children[ 0 ].material.dispose();
  20913. }
  20914. update() {
  20915. const mesh = this.children[ 0 ];
  20916. if ( this.color !== undefined ) {
  20917. this.material.color.set( this.color );
  20918. } else {
  20919. const colors = mesh.geometry.getAttribute( 'color' );
  20920. _color1.copy( this.light.color );
  20921. _color2.copy( this.light.groundColor );
  20922. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20923. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20924. colors.setXYZ( i, color.r, color.g, color.b );
  20925. }
  20926. colors.needsUpdate = true;
  20927. }
  20928. this.light.updateWorldMatrix( true, false );
  20929. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20930. }
  20931. }
  20932. class GridHelper extends LineSegments {
  20933. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20934. color1 = new Color( color1 );
  20935. color2 = new Color( color2 );
  20936. const center = divisions / 2;
  20937. const step = size / divisions;
  20938. const halfSize = size / 2;
  20939. const vertices = [], colors = [];
  20940. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20941. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20942. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20943. const color = i === center ? color1 : color2;
  20944. color.toArray( colors, j ); j += 3;
  20945. color.toArray( colors, j ); j += 3;
  20946. color.toArray( colors, j ); j += 3;
  20947. color.toArray( colors, j ); j += 3;
  20948. }
  20949. const geometry = new BufferGeometry();
  20950. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20951. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20952. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20953. super( geometry, material );
  20954. this.type = 'GridHelper';
  20955. }
  20956. dispose() {
  20957. this.geometry.dispose();
  20958. this.material.dispose();
  20959. }
  20960. }
  20961. class PolarGridHelper extends LineSegments {
  20962. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20963. color1 = new Color( color1 );
  20964. color2 = new Color( color2 );
  20965. const vertices = [];
  20966. const colors = [];
  20967. // create the sectors
  20968. if ( sectors > 1 ) {
  20969. for ( let i = 0; i < sectors; i ++ ) {
  20970. const v = ( i / sectors ) * ( Math.PI * 2 );
  20971. const x = Math.sin( v ) * radius;
  20972. const z = Math.cos( v ) * radius;
  20973. vertices.push( 0, 0, 0 );
  20974. vertices.push( x, 0, z );
  20975. const color = ( i & 1 ) ? color1 : color2;
  20976. colors.push( color.r, color.g, color.b );
  20977. colors.push( color.r, color.g, color.b );
  20978. }
  20979. }
  20980. // create the rings
  20981. for ( let i = 0; i < rings; i ++ ) {
  20982. const color = ( i & 1 ) ? color1 : color2;
  20983. const r = radius - ( radius / rings * i );
  20984. for ( let j = 0; j < divisions; j ++ ) {
  20985. // first vertex
  20986. let v = ( j / divisions ) * ( Math.PI * 2 );
  20987. let x = Math.sin( v ) * r;
  20988. let z = Math.cos( v ) * r;
  20989. vertices.push( x, 0, z );
  20990. colors.push( color.r, color.g, color.b );
  20991. // second vertex
  20992. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20993. x = Math.sin( v ) * r;
  20994. z = Math.cos( v ) * r;
  20995. vertices.push( x, 0, z );
  20996. colors.push( color.r, color.g, color.b );
  20997. }
  20998. }
  20999. const geometry = new BufferGeometry();
  21000. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21001. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21002. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21003. super( geometry, material );
  21004. this.type = 'PolarGridHelper';
  21005. }
  21006. dispose() {
  21007. this.geometry.dispose();
  21008. this.material.dispose();
  21009. }
  21010. }
  21011. const _v1 = /*@__PURE__*/ new Vector3();
  21012. const _v2 = /*@__PURE__*/ new Vector3();
  21013. const _v3 = /*@__PURE__*/ new Vector3();
  21014. class DirectionalLightHelper extends Object3D {
  21015. constructor( light, size, color ) {
  21016. super();
  21017. this.light = light;
  21018. this.matrix = light.matrixWorld;
  21019. this.matrixAutoUpdate = false;
  21020. this.color = color;
  21021. this.type = 'DirectionalLightHelper';
  21022. if ( size === undefined ) size = 1;
  21023. let geometry = new BufferGeometry();
  21024. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  21025. - size, size, 0,
  21026. size, size, 0,
  21027. size, - size, 0,
  21028. - size, - size, 0,
  21029. - size, size, 0
  21030. ], 3 ) );
  21031. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  21032. this.lightPlane = new Line( geometry, material );
  21033. this.add( this.lightPlane );
  21034. geometry = new BufferGeometry();
  21035. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  21036. this.targetLine = new Line( geometry, material );
  21037. this.add( this.targetLine );
  21038. this.update();
  21039. }
  21040. dispose() {
  21041. this.lightPlane.geometry.dispose();
  21042. this.lightPlane.material.dispose();
  21043. this.targetLine.geometry.dispose();
  21044. this.targetLine.material.dispose();
  21045. }
  21046. update() {
  21047. this.light.updateWorldMatrix( true, false );
  21048. this.light.target.updateWorldMatrix( true, false );
  21049. _v1.setFromMatrixPosition( this.light.matrixWorld );
  21050. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  21051. _v3.subVectors( _v2, _v1 );
  21052. this.lightPlane.lookAt( _v2 );
  21053. if ( this.color !== undefined ) {
  21054. this.lightPlane.material.color.set( this.color );
  21055. this.targetLine.material.color.set( this.color );
  21056. } else {
  21057. this.lightPlane.material.color.copy( this.light.color );
  21058. this.targetLine.material.color.copy( this.light.color );
  21059. }
  21060. this.targetLine.lookAt( _v2 );
  21061. this.targetLine.scale.z = _v3.length();
  21062. }
  21063. }
  21064. const _vector = /*@__PURE__*/ new Vector3();
  21065. const _camera = /*@__PURE__*/ new Camera();
  21066. /**
  21067. * - shows frustum, line of sight and up of the camera
  21068. * - suitable for fast updates
  21069. * - based on frustum visualization in lightgl.js shadowmap example
  21070. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  21071. */
  21072. class CameraHelper extends LineSegments {
  21073. constructor( camera ) {
  21074. const geometry = new BufferGeometry();
  21075. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  21076. const vertices = [];
  21077. const colors = [];
  21078. const pointMap = {};
  21079. // near
  21080. addLine( 'n1', 'n2' );
  21081. addLine( 'n2', 'n4' );
  21082. addLine( 'n4', 'n3' );
  21083. addLine( 'n3', 'n1' );
  21084. // far
  21085. addLine( 'f1', 'f2' );
  21086. addLine( 'f2', 'f4' );
  21087. addLine( 'f4', 'f3' );
  21088. addLine( 'f3', 'f1' );
  21089. // sides
  21090. addLine( 'n1', 'f1' );
  21091. addLine( 'n2', 'f2' );
  21092. addLine( 'n3', 'f3' );
  21093. addLine( 'n4', 'f4' );
  21094. // cone
  21095. addLine( 'p', 'n1' );
  21096. addLine( 'p', 'n2' );
  21097. addLine( 'p', 'n3' );
  21098. addLine( 'p', 'n4' );
  21099. // up
  21100. addLine( 'u1', 'u2' );
  21101. addLine( 'u2', 'u3' );
  21102. addLine( 'u3', 'u1' );
  21103. // target
  21104. addLine( 'c', 't' );
  21105. addLine( 'p', 'c' );
  21106. // cross
  21107. addLine( 'cn1', 'cn2' );
  21108. addLine( 'cn3', 'cn4' );
  21109. addLine( 'cf1', 'cf2' );
  21110. addLine( 'cf3', 'cf4' );
  21111. function addLine( a, b ) {
  21112. addPoint( a );
  21113. addPoint( b );
  21114. }
  21115. function addPoint( id ) {
  21116. vertices.push( 0, 0, 0 );
  21117. colors.push( 0, 0, 0 );
  21118. if ( pointMap[ id ] === undefined ) {
  21119. pointMap[ id ] = [];
  21120. }
  21121. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  21122. }
  21123. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21124. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21125. super( geometry, material );
  21126. this.type = 'CameraHelper';
  21127. this.camera = camera;
  21128. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  21129. this.matrix = camera.matrixWorld;
  21130. this.matrixAutoUpdate = false;
  21131. this.pointMap = pointMap;
  21132. this.update();
  21133. // colors
  21134. const colorFrustum = new Color( 0xffaa00 );
  21135. const colorCone = new Color( 0xff0000 );
  21136. const colorUp = new Color( 0x00aaff );
  21137. const colorTarget = new Color( 0xffffff );
  21138. const colorCross = new Color( 0x333333 );
  21139. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  21140. }
  21141. setColors( frustum, cone, up, target, cross ) {
  21142. const geometry = this.geometry;
  21143. const colorAttribute = geometry.getAttribute( 'color' );
  21144. // near
  21145. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  21146. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  21147. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  21148. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  21149. // far
  21150. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  21151. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  21152. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  21153. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  21154. // sides
  21155. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  21156. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  21157. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  21158. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  21159. // cone
  21160. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  21161. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  21162. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  21163. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  21164. // up
  21165. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  21166. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  21167. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  21168. // target
  21169. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  21170. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  21171. // cross
  21172. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  21173. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  21174. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  21175. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  21176. colorAttribute.needsUpdate = true;
  21177. }
  21178. update() {
  21179. const geometry = this.geometry;
  21180. const pointMap = this.pointMap;
  21181. const w = 1, h = 1;
  21182. // we need just camera projection matrix inverse
  21183. // world matrix must be identity
  21184. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  21185. // center / target
  21186. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  21187. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  21188. // near
  21189. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  21190. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  21191. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  21192. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  21193. // far
  21194. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  21195. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  21196. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  21197. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  21198. // up
  21199. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  21200. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  21201. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  21202. // cross
  21203. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  21204. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  21205. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  21206. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  21207. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  21208. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  21209. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  21210. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  21211. geometry.getAttribute( 'position' ).needsUpdate = true;
  21212. }
  21213. dispose() {
  21214. this.geometry.dispose();
  21215. this.material.dispose();
  21216. }
  21217. }
  21218. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  21219. _vector.set( x, y, z ).unproject( camera );
  21220. const points = pointMap[ point ];
  21221. if ( points !== undefined ) {
  21222. const position = geometry.getAttribute( 'position' );
  21223. for ( let i = 0, l = points.length; i < l; i ++ ) {
  21224. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  21225. }
  21226. }
  21227. }
  21228. const _box = /*@__PURE__*/ new Box3();
  21229. class BoxHelper extends LineSegments {
  21230. constructor( object, color = 0xffff00 ) {
  21231. 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 ] );
  21232. const positions = new Float32Array( 8 * 3 );
  21233. const geometry = new BufferGeometry();
  21234. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21235. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  21236. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21237. this.object = object;
  21238. this.type = 'BoxHelper';
  21239. this.matrixAutoUpdate = false;
  21240. this.update();
  21241. }
  21242. update( object ) {
  21243. if ( object !== undefined ) {
  21244. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  21245. }
  21246. if ( this.object !== undefined ) {
  21247. _box.setFromObject( this.object );
  21248. }
  21249. if ( _box.isEmpty() ) return;
  21250. const min = _box.min;
  21251. const max = _box.max;
  21252. /*
  21253. 5____4
  21254. 1/___0/|
  21255. | 6__|_7
  21256. 2/___3/
  21257. 0: max.x, max.y, max.z
  21258. 1: min.x, max.y, max.z
  21259. 2: min.x, min.y, max.z
  21260. 3: max.x, min.y, max.z
  21261. 4: max.x, max.y, min.z
  21262. 5: min.x, max.y, min.z
  21263. 6: min.x, min.y, min.z
  21264. 7: max.x, min.y, min.z
  21265. */
  21266. const position = this.geometry.attributes.position;
  21267. const array = position.array;
  21268. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  21269. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  21270. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  21271. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  21272. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  21273. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  21274. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  21275. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  21276. position.needsUpdate = true;
  21277. this.geometry.computeBoundingSphere();
  21278. }
  21279. setFromObject( object ) {
  21280. this.object = object;
  21281. this.update();
  21282. return this;
  21283. }
  21284. copy( source, recursive ) {
  21285. super.copy( source, recursive );
  21286. this.object = source.object;
  21287. return this;
  21288. }
  21289. dispose() {
  21290. this.geometry.dispose();
  21291. this.material.dispose();
  21292. }
  21293. }
  21294. class Box3Helper extends LineSegments {
  21295. constructor( box, color = 0xffff00 ) {
  21296. 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 ] );
  21297. 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 ];
  21298. const geometry = new BufferGeometry();
  21299. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21300. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21301. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21302. this.box = box;
  21303. this.type = 'Box3Helper';
  21304. this.geometry.computeBoundingSphere();
  21305. }
  21306. updateMatrixWorld( force ) {
  21307. const box = this.box;
  21308. if ( box.isEmpty() ) return;
  21309. box.getCenter( this.position );
  21310. box.getSize( this.scale );
  21311. this.scale.multiplyScalar( 0.5 );
  21312. super.updateMatrixWorld( force );
  21313. }
  21314. dispose() {
  21315. this.geometry.dispose();
  21316. this.material.dispose();
  21317. }
  21318. }
  21319. class PlaneHelper extends Line {
  21320. constructor( plane, size = 1, hex = 0xffff00 ) {
  21321. const color = hex;
  21322. 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 ];
  21323. const geometry = new BufferGeometry();
  21324. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21325. geometry.computeBoundingSphere();
  21326. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21327. this.type = 'PlaneHelper';
  21328. this.plane = plane;
  21329. this.size = size;
  21330. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21331. const geometry2 = new BufferGeometry();
  21332. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21333. geometry2.computeBoundingSphere();
  21334. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21335. }
  21336. updateMatrixWorld( force ) {
  21337. this.position.set( 0, 0, 0 );
  21338. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21339. this.lookAt( this.plane.normal );
  21340. this.translateZ( - this.plane.constant );
  21341. super.updateMatrixWorld( force );
  21342. }
  21343. dispose() {
  21344. this.geometry.dispose();
  21345. this.material.dispose();
  21346. this.children[ 0 ].geometry.dispose();
  21347. this.children[ 0 ].material.dispose();
  21348. }
  21349. }
  21350. const _axis = /*@__PURE__*/ new Vector3();
  21351. let _lineGeometry, _coneGeometry;
  21352. class ArrowHelper extends Object3D {
  21353. // dir is assumed to be normalized
  21354. 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 ) {
  21355. super();
  21356. this.type = 'ArrowHelper';
  21357. if ( _lineGeometry === undefined ) {
  21358. _lineGeometry = new BufferGeometry();
  21359. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21360. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21361. _coneGeometry.translate( 0, - 0.5, 0 );
  21362. }
  21363. this.position.copy( origin );
  21364. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21365. this.line.matrixAutoUpdate = false;
  21366. this.add( this.line );
  21367. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21368. this.cone.matrixAutoUpdate = false;
  21369. this.add( this.cone );
  21370. this.setDirection( dir );
  21371. this.setLength( length, headLength, headWidth );
  21372. }
  21373. setDirection( dir ) {
  21374. // dir is assumed to be normalized
  21375. if ( dir.y > 0.99999 ) {
  21376. this.quaternion.set( 0, 0, 0, 1 );
  21377. } else if ( dir.y < - 0.99999 ) {
  21378. this.quaternion.set( 1, 0, 0, 0 );
  21379. } else {
  21380. _axis.set( dir.z, 0, - dir.x ).normalize();
  21381. const radians = Math.acos( dir.y );
  21382. this.quaternion.setFromAxisAngle( _axis, radians );
  21383. }
  21384. }
  21385. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21386. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21387. this.line.updateMatrix();
  21388. this.cone.scale.set( headWidth, headLength, headWidth );
  21389. this.cone.position.y = length;
  21390. this.cone.updateMatrix();
  21391. }
  21392. setColor( color ) {
  21393. this.line.material.color.set( color );
  21394. this.cone.material.color.set( color );
  21395. }
  21396. copy( source ) {
  21397. super.copy( source, false );
  21398. this.line.copy( source.line );
  21399. this.cone.copy( source.cone );
  21400. return this;
  21401. }
  21402. dispose() {
  21403. this.line.geometry.dispose();
  21404. this.line.material.dispose();
  21405. this.cone.geometry.dispose();
  21406. this.cone.material.dispose();
  21407. }
  21408. }
  21409. class AxesHelper extends LineSegments {
  21410. constructor( size = 1 ) {
  21411. const vertices = [
  21412. 0, 0, 0, size, 0, 0,
  21413. 0, 0, 0, 0, size, 0,
  21414. 0, 0, 0, 0, 0, size
  21415. ];
  21416. const colors = [
  21417. 1, 0, 0, 1, 0.6, 0,
  21418. 0, 1, 0, 0.6, 1, 0,
  21419. 0, 0, 1, 0, 0.6, 1
  21420. ];
  21421. const geometry = new BufferGeometry();
  21422. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21423. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21424. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21425. super( geometry, material );
  21426. this.type = 'AxesHelper';
  21427. }
  21428. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21429. const color = new Color();
  21430. const array = this.geometry.attributes.color.array;
  21431. color.set( xAxisColor );
  21432. color.toArray( array, 0 );
  21433. color.toArray( array, 3 );
  21434. color.set( yAxisColor );
  21435. color.toArray( array, 6 );
  21436. color.toArray( array, 9 );
  21437. color.set( zAxisColor );
  21438. color.toArray( array, 12 );
  21439. color.toArray( array, 15 );
  21440. this.geometry.attributes.color.needsUpdate = true;
  21441. return this;
  21442. }
  21443. dispose() {
  21444. this.geometry.dispose();
  21445. this.material.dispose();
  21446. }
  21447. }
  21448. class ShapePath {
  21449. constructor() {
  21450. this.type = 'ShapePath';
  21451. this.color = new Color();
  21452. this.subPaths = [];
  21453. this.currentPath = null;
  21454. }
  21455. moveTo( x, y ) {
  21456. this.currentPath = new Path();
  21457. this.subPaths.push( this.currentPath );
  21458. this.currentPath.moveTo( x, y );
  21459. return this;
  21460. }
  21461. lineTo( x, y ) {
  21462. this.currentPath.lineTo( x, y );
  21463. return this;
  21464. }
  21465. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21466. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21467. return this;
  21468. }
  21469. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21470. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21471. return this;
  21472. }
  21473. splineThru( pts ) {
  21474. this.currentPath.splineThru( pts );
  21475. return this;
  21476. }
  21477. toShapes( isCCW ) {
  21478. function toShapesNoHoles( inSubpaths ) {
  21479. const shapes = [];
  21480. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21481. const tmpPath = inSubpaths[ i ];
  21482. const tmpShape = new Shape();
  21483. tmpShape.curves = tmpPath.curves;
  21484. shapes.push( tmpShape );
  21485. }
  21486. return shapes;
  21487. }
  21488. function isPointInsidePolygon( inPt, inPolygon ) {
  21489. const polyLen = inPolygon.length;
  21490. // inPt on polygon contour => immediate success or
  21491. // toggling of inside/outside at every single! intersection point of an edge
  21492. // with the horizontal line through inPt, left of inPt
  21493. // not counting lowerY endpoints of edges and whole edges on that line
  21494. let inside = false;
  21495. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21496. let edgeLowPt = inPolygon[ p ];
  21497. let edgeHighPt = inPolygon[ q ];
  21498. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21499. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21500. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21501. // not parallel
  21502. if ( edgeDy < 0 ) {
  21503. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21504. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21505. }
  21506. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21507. if ( inPt.y === edgeLowPt.y ) {
  21508. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21509. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21510. } else {
  21511. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21512. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21513. if ( perpEdge < 0 ) continue;
  21514. inside = ! inside; // true intersection left of inPt
  21515. }
  21516. } else {
  21517. // parallel or collinear
  21518. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21519. // edge lies on the same horizontal line as inPt
  21520. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21521. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21522. // continue;
  21523. }
  21524. }
  21525. return inside;
  21526. }
  21527. const isClockWise = ShapeUtils.isClockWise;
  21528. const subPaths = this.subPaths;
  21529. if ( subPaths.length === 0 ) return [];
  21530. let solid, tmpPath, tmpShape;
  21531. const shapes = [];
  21532. if ( subPaths.length === 1 ) {
  21533. tmpPath = subPaths[ 0 ];
  21534. tmpShape = new Shape();
  21535. tmpShape.curves = tmpPath.curves;
  21536. shapes.push( tmpShape );
  21537. return shapes;
  21538. }
  21539. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21540. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21541. // console.log("Holes first", holesFirst);
  21542. const betterShapeHoles = [];
  21543. const newShapes = [];
  21544. let newShapeHoles = [];
  21545. let mainIdx = 0;
  21546. let tmpPoints;
  21547. newShapes[ mainIdx ] = undefined;
  21548. newShapeHoles[ mainIdx ] = [];
  21549. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21550. tmpPath = subPaths[ i ];
  21551. tmpPoints = tmpPath.getPoints();
  21552. solid = isClockWise( tmpPoints );
  21553. solid = isCCW ? ! solid : solid;
  21554. if ( solid ) {
  21555. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21556. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21557. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21558. if ( holesFirst ) mainIdx ++;
  21559. newShapeHoles[ mainIdx ] = [];
  21560. //console.log('cw', i);
  21561. } else {
  21562. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21563. //console.log('ccw', i);
  21564. }
  21565. }
  21566. // only Holes? -> probably all Shapes with wrong orientation
  21567. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21568. if ( newShapes.length > 1 ) {
  21569. let ambiguous = false;
  21570. let toChange = 0;
  21571. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21572. betterShapeHoles[ sIdx ] = [];
  21573. }
  21574. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21575. const sho = newShapeHoles[ sIdx ];
  21576. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21577. const ho = sho[ hIdx ];
  21578. let hole_unassigned = true;
  21579. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21580. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21581. if ( sIdx !== s2Idx ) toChange ++;
  21582. if ( hole_unassigned ) {
  21583. hole_unassigned = false;
  21584. betterShapeHoles[ s2Idx ].push( ho );
  21585. } else {
  21586. ambiguous = true;
  21587. }
  21588. }
  21589. }
  21590. if ( hole_unassigned ) {
  21591. betterShapeHoles[ sIdx ].push( ho );
  21592. }
  21593. }
  21594. }
  21595. if ( toChange > 0 && ambiguous === false ) {
  21596. newShapeHoles = betterShapeHoles;
  21597. }
  21598. }
  21599. let tmpHoles;
  21600. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21601. tmpShape = newShapes[ i ].s;
  21602. shapes.push( tmpShape );
  21603. tmpHoles = newShapeHoles[ i ];
  21604. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21605. tmpShape.holes.push( tmpHoles[ j ].h );
  21606. }
  21607. }
  21608. //console.log("shape", shapes);
  21609. return shapes;
  21610. }
  21611. }
  21612. class Controls extends EventDispatcher {
  21613. constructor( object, domElement = null ) {
  21614. super();
  21615. this.object = object;
  21616. this.domElement = domElement;
  21617. this.enabled = true;
  21618. this.state = - 1;
  21619. this.keys = {};
  21620. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  21621. this.touches = { ONE: null, TWO: null };
  21622. }
  21623. connect() {}
  21624. disconnect() {}
  21625. dispose() {}
  21626. update( /* delta */ ) {}
  21627. }
  21628. function contain( texture, aspect ) {
  21629. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  21630. if ( imageAspect > aspect ) {
  21631. texture.repeat.x = 1;
  21632. texture.repeat.y = imageAspect / aspect;
  21633. texture.offset.x = 0;
  21634. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  21635. } else {
  21636. texture.repeat.x = aspect / imageAspect;
  21637. texture.repeat.y = 1;
  21638. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  21639. texture.offset.y = 0;
  21640. }
  21641. return texture;
  21642. }
  21643. function cover( texture, aspect ) {
  21644. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  21645. if ( imageAspect > aspect ) {
  21646. texture.repeat.x = aspect / imageAspect;
  21647. texture.repeat.y = 1;
  21648. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  21649. texture.offset.y = 0;
  21650. } else {
  21651. texture.repeat.x = 1;
  21652. texture.repeat.y = imageAspect / aspect;
  21653. texture.offset.x = 0;
  21654. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  21655. }
  21656. return texture;
  21657. }
  21658. function fill( texture ) {
  21659. texture.repeat.x = 1;
  21660. texture.repeat.y = 1;
  21661. texture.offset.x = 0;
  21662. texture.offset.y = 0;
  21663. return texture;
  21664. }
  21665. /**
  21666. * Given the width, height, format, and type of a texture. Determines how many
  21667. * bytes must be used to represent the texture.
  21668. */
  21669. function getByteLength( width, height, format, type ) {
  21670. const typeByteLength = getTextureTypeByteLength( type );
  21671. switch ( format ) {
  21672. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  21673. case AlphaFormat:
  21674. return width * height;
  21675. case LuminanceFormat:
  21676. return width * height;
  21677. case LuminanceAlphaFormat:
  21678. return width * height * 2;
  21679. case RedFormat:
  21680. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  21681. case RedIntegerFormat:
  21682. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  21683. case RGFormat:
  21684. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  21685. case RGIntegerFormat:
  21686. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  21687. case RGBFormat:
  21688. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  21689. case RGBAFormat:
  21690. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  21691. case RGBAIntegerFormat:
  21692. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  21693. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  21694. case RGB_S3TC_DXT1_Format:
  21695. case RGBA_S3TC_DXT1_Format:
  21696. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  21697. case RGBA_S3TC_DXT3_Format:
  21698. case RGBA_S3TC_DXT5_Format:
  21699. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  21700. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  21701. case RGB_PVRTC_2BPPV1_Format:
  21702. case RGBA_PVRTC_2BPPV1_Format:
  21703. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  21704. case RGB_PVRTC_4BPPV1_Format:
  21705. case RGBA_PVRTC_4BPPV1_Format:
  21706. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  21707. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  21708. case RGB_ETC1_Format:
  21709. case RGB_ETC2_Format:
  21710. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  21711. case RGBA_ETC2_EAC_Format:
  21712. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  21713. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  21714. case RGBA_ASTC_4x4_Format:
  21715. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  21716. case RGBA_ASTC_5x4_Format:
  21717. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  21718. case RGBA_ASTC_5x5_Format:
  21719. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  21720. case RGBA_ASTC_6x5_Format:
  21721. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  21722. case RGBA_ASTC_6x6_Format:
  21723. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  21724. case RGBA_ASTC_8x5_Format:
  21725. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  21726. case RGBA_ASTC_8x6_Format:
  21727. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  21728. case RGBA_ASTC_8x8_Format:
  21729. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  21730. case RGBA_ASTC_10x5_Format:
  21731. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  21732. case RGBA_ASTC_10x6_Format:
  21733. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  21734. case RGBA_ASTC_10x8_Format:
  21735. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  21736. case RGBA_ASTC_10x10_Format:
  21737. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  21738. case RGBA_ASTC_12x10_Format:
  21739. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  21740. case RGBA_ASTC_12x12_Format:
  21741. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  21742. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  21743. case RGBA_BPTC_Format:
  21744. case RGB_BPTC_SIGNED_Format:
  21745. case RGB_BPTC_UNSIGNED_Format:
  21746. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  21747. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  21748. case RED_RGTC1_Format:
  21749. case SIGNED_RED_RGTC1_Format:
  21750. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  21751. case RED_GREEN_RGTC2_Format:
  21752. case SIGNED_RED_GREEN_RGTC2_Format:
  21753. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  21754. }
  21755. throw new Error(
  21756. `Unable to determine texture byte length for ${format} format.`,
  21757. );
  21758. }
  21759. function getTextureTypeByteLength( type ) {
  21760. switch ( type ) {
  21761. case UnsignedByteType:
  21762. case ByteType:
  21763. return { byteLength: 1, components: 1 };
  21764. case UnsignedShortType:
  21765. case ShortType:
  21766. case HalfFloatType:
  21767. return { byteLength: 2, components: 1 };
  21768. case UnsignedShort4444Type:
  21769. case UnsignedShort5551Type:
  21770. return { byteLength: 2, components: 4 };
  21771. case UnsignedIntType:
  21772. case IntType:
  21773. case FloatType:
  21774. return { byteLength: 4, components: 1 };
  21775. case UnsignedInt5999Type:
  21776. return { byteLength: 4, components: 3 };
  21777. }
  21778. throw new Error( `Unknown texture type ${type}.` );
  21779. }
  21780. const TextureUtils = {
  21781. contain,
  21782. cover,
  21783. fill,
  21784. getByteLength
  21785. };
  21786. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  21787. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  21788. revision: REVISION,
  21789. } } ) );
  21790. }
  21791. if ( typeof window !== 'undefined' ) {
  21792. if ( window.__THREE__ ) {
  21793. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  21794. } else {
  21795. window.__THREE__ = REVISION;
  21796. }
  21797. }
  21798. function WebGLAnimation() {
  21799. let context = null;
  21800. let isAnimating = false;
  21801. let animationLoop = null;
  21802. let requestId = null;
  21803. function onAnimationFrame( time, frame ) {
  21804. animationLoop( time, frame );
  21805. requestId = context.requestAnimationFrame( onAnimationFrame );
  21806. }
  21807. return {
  21808. start: function () {
  21809. if ( isAnimating === true ) return;
  21810. if ( animationLoop === null ) return;
  21811. requestId = context.requestAnimationFrame( onAnimationFrame );
  21812. isAnimating = true;
  21813. },
  21814. stop: function () {
  21815. context.cancelAnimationFrame( requestId );
  21816. isAnimating = false;
  21817. },
  21818. setAnimationLoop: function ( callback ) {
  21819. animationLoop = callback;
  21820. },
  21821. setContext: function ( value ) {
  21822. context = value;
  21823. }
  21824. };
  21825. }
  21826. function WebGLAttributes( gl ) {
  21827. const buffers = new WeakMap();
  21828. function createBuffer( attribute, bufferType ) {
  21829. const array = attribute.array;
  21830. const usage = attribute.usage;
  21831. const size = array.byteLength;
  21832. const buffer = gl.createBuffer();
  21833. gl.bindBuffer( bufferType, buffer );
  21834. gl.bufferData( bufferType, array, usage );
  21835. attribute.onUploadCallback();
  21836. let type;
  21837. if ( array instanceof Float32Array ) {
  21838. type = gl.FLOAT;
  21839. } else if ( array instanceof Uint16Array ) {
  21840. if ( attribute.isFloat16BufferAttribute ) {
  21841. type = gl.HALF_FLOAT;
  21842. } else {
  21843. type = gl.UNSIGNED_SHORT;
  21844. }
  21845. } else if ( array instanceof Int16Array ) {
  21846. type = gl.SHORT;
  21847. } else if ( array instanceof Uint32Array ) {
  21848. type = gl.UNSIGNED_INT;
  21849. } else if ( array instanceof Int32Array ) {
  21850. type = gl.INT;
  21851. } else if ( array instanceof Int8Array ) {
  21852. type = gl.BYTE;
  21853. } else if ( array instanceof Uint8Array ) {
  21854. type = gl.UNSIGNED_BYTE;
  21855. } else if ( array instanceof Uint8ClampedArray ) {
  21856. type = gl.UNSIGNED_BYTE;
  21857. } else {
  21858. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  21859. }
  21860. return {
  21861. buffer: buffer,
  21862. type: type,
  21863. bytesPerElement: array.BYTES_PER_ELEMENT,
  21864. version: attribute.version,
  21865. size: size
  21866. };
  21867. }
  21868. function updateBuffer( buffer, attribute, bufferType ) {
  21869. const array = attribute.array;
  21870. const updateRanges = attribute.updateRanges;
  21871. gl.bindBuffer( bufferType, buffer );
  21872. if ( updateRanges.length === 0 ) {
  21873. // Not using update ranges
  21874. gl.bufferSubData( bufferType, 0, array );
  21875. } else {
  21876. // Before applying update ranges, we merge any adjacent / overlapping
  21877. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  21878. // to performance improvements for applications which make heavy use of
  21879. // update ranges. Likely due to GPU command overhead.
  21880. //
  21881. // Note that to reduce garbage collection between frames, we merge the
  21882. // update ranges in-place. This is safe because this method will clear the
  21883. // update ranges once updated.
  21884. updateRanges.sort( ( a, b ) => a.start - b.start );
  21885. // To merge the update ranges in-place, we work from left to right in the
  21886. // existing updateRanges array, merging ranges. This may result in a final
  21887. // array which is smaller than the original. This index tracks the last
  21888. // index representing a merged range, any data after this index can be
  21889. // trimmed once the merge algorithm is completed.
  21890. let mergeIndex = 0;
  21891. for ( let i = 1; i < updateRanges.length; i ++ ) {
  21892. const previousRange = updateRanges[ mergeIndex ];
  21893. const range = updateRanges[ i ];
  21894. // We add one here to merge adjacent ranges. This is safe because ranges
  21895. // operate over positive integers.
  21896. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  21897. previousRange.count = Math.max(
  21898. previousRange.count,
  21899. range.start + range.count - previousRange.start
  21900. );
  21901. } else {
  21902. ++ mergeIndex;
  21903. updateRanges[ mergeIndex ] = range;
  21904. }
  21905. }
  21906. // Trim the array to only contain the merged ranges.
  21907. updateRanges.length = mergeIndex + 1;
  21908. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  21909. const range = updateRanges[ i ];
  21910. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  21911. array, range.start, range.count );
  21912. }
  21913. attribute.clearUpdateRanges();
  21914. }
  21915. attribute.onUploadCallback();
  21916. }
  21917. //
  21918. function get( attribute ) {
  21919. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21920. return buffers.get( attribute );
  21921. }
  21922. function remove( attribute ) {
  21923. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21924. const data = buffers.get( attribute );
  21925. if ( data ) {
  21926. gl.deleteBuffer( data.buffer );
  21927. buffers.delete( attribute );
  21928. }
  21929. }
  21930. function update( attribute, bufferType ) {
  21931. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21932. if ( attribute.isGLBufferAttribute ) {
  21933. const cached = buffers.get( attribute );
  21934. if ( ! cached || cached.version < attribute.version ) {
  21935. buffers.set( attribute, {
  21936. buffer: attribute.buffer,
  21937. type: attribute.type,
  21938. bytesPerElement: attribute.elementSize,
  21939. version: attribute.version
  21940. } );
  21941. }
  21942. return;
  21943. }
  21944. const data = buffers.get( attribute );
  21945. if ( data === undefined ) {
  21946. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  21947. } else if ( data.version < attribute.version ) {
  21948. if ( data.size !== attribute.array.byteLength ) {
  21949. 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.' );
  21950. }
  21951. updateBuffer( data.buffer, attribute, bufferType );
  21952. data.version = attribute.version;
  21953. }
  21954. }
  21955. return {
  21956. get: get,
  21957. remove: remove,
  21958. update: update
  21959. };
  21960. }
  21961. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  21962. 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";
  21963. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  21964. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  21965. 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";
  21966. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  21967. 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";
  21968. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  21969. 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";
  21970. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  21971. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  21972. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  21973. 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";
  21974. 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";
  21975. 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";
  21976. 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";
  21977. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  21978. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  21979. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  21980. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  21981. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  21982. 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";
  21983. 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";
  21984. 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";
  21985. 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";
  21986. 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";
  21987. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  21988. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  21989. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  21990. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  21991. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  21992. var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\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}";
  21993. 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";
  21994. 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";
  21995. 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";
  21996. 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";
  21997. 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";
  21998. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  21999. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  22000. 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";
  22001. 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";
  22002. 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}";
  22003. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  22004. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  22005. 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";
  22006. 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";
  22007. 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";
  22008. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  22009. 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";
  22010. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  22011. 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";
  22012. 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";
  22013. 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}";
  22014. 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";
  22015. 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";
  22016. 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";
  22017. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  22018. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  22019. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  22020. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  22021. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  22022. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  22023. 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";
  22024. 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";
  22025. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  22026. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  22027. 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";
  22028. 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";
  22029. 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";
  22030. 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";
  22031. 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";
  22032. 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;";
  22033. 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";
  22034. 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";
  22035. 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";
  22036. 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";
  22037. 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";
  22038. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  22039. 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";
  22040. 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";
  22041. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  22042. 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 );";
  22043. 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}";
  22044. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  22045. 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;";
  22046. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  22047. 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";
  22048. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  22049. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  22050. 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";
  22051. 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";
  22052. 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";
  22053. 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}";
  22054. 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";
  22055. 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";
  22056. 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";
  22057. 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";
  22058. 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";
  22059. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  22060. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  22061. 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; }";
  22062. 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";
  22063. 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";
  22064. 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";
  22065. 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";
  22066. 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";
  22067. 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";
  22068. 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}";
  22069. 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}";
  22070. 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}";
  22071. 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}";
  22072. 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}";
  22073. 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}";
  22074. 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}";
  22075. 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}";
  22076. 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}";
  22077. 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}";
  22078. 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}";
  22079. 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}";
  22080. 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}";
  22081. 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}";
  22082. 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}";
  22083. 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}";
  22084. 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}";
  22085. 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}";
  22086. 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}";
  22087. 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}";
  22088. 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}";
  22089. 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}";
  22090. 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}";
  22091. 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}";
  22092. 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}";
  22093. 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}";
  22094. 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}";
  22095. 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}";
  22096. 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}";
  22097. 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}";
  22098. 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}";
  22099. 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}";
  22100. 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[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\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}";
  22101. 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}";
  22102. const ShaderChunk = {
  22103. alphahash_fragment: alphahash_fragment,
  22104. alphahash_pars_fragment: alphahash_pars_fragment,
  22105. alphamap_fragment: alphamap_fragment,
  22106. alphamap_pars_fragment: alphamap_pars_fragment,
  22107. alphatest_fragment: alphatest_fragment,
  22108. alphatest_pars_fragment: alphatest_pars_fragment,
  22109. aomap_fragment: aomap_fragment,
  22110. aomap_pars_fragment: aomap_pars_fragment,
  22111. batching_pars_vertex: batching_pars_vertex,
  22112. batching_vertex: batching_vertex,
  22113. begin_vertex: begin_vertex,
  22114. beginnormal_vertex: beginnormal_vertex,
  22115. bsdfs: bsdfs,
  22116. iridescence_fragment: iridescence_fragment,
  22117. bumpmap_pars_fragment: bumpmap_pars_fragment,
  22118. clipping_planes_fragment: clipping_planes_fragment,
  22119. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  22120. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  22121. clipping_planes_vertex: clipping_planes_vertex,
  22122. color_fragment: color_fragment,
  22123. color_pars_fragment: color_pars_fragment,
  22124. color_pars_vertex: color_pars_vertex,
  22125. color_vertex: color_vertex,
  22126. common: common,
  22127. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  22128. defaultnormal_vertex: defaultnormal_vertex,
  22129. displacementmap_pars_vertex: displacementmap_pars_vertex,
  22130. displacementmap_vertex: displacementmap_vertex,
  22131. emissivemap_fragment: emissivemap_fragment,
  22132. emissivemap_pars_fragment: emissivemap_pars_fragment,
  22133. colorspace_fragment: colorspace_fragment,
  22134. colorspace_pars_fragment: colorspace_pars_fragment,
  22135. envmap_fragment: envmap_fragment,
  22136. envmap_common_pars_fragment: envmap_common_pars_fragment,
  22137. envmap_pars_fragment: envmap_pars_fragment,
  22138. envmap_pars_vertex: envmap_pars_vertex,
  22139. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  22140. envmap_vertex: envmap_vertex,
  22141. fog_vertex: fog_vertex,
  22142. fog_pars_vertex: fog_pars_vertex,
  22143. fog_fragment: fog_fragment,
  22144. fog_pars_fragment: fog_pars_fragment,
  22145. gradientmap_pars_fragment: gradientmap_pars_fragment,
  22146. lightmap_pars_fragment: lightmap_pars_fragment,
  22147. lights_lambert_fragment: lights_lambert_fragment,
  22148. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  22149. lights_pars_begin: lights_pars_begin,
  22150. lights_toon_fragment: lights_toon_fragment,
  22151. lights_toon_pars_fragment: lights_toon_pars_fragment,
  22152. lights_phong_fragment: lights_phong_fragment,
  22153. lights_phong_pars_fragment: lights_phong_pars_fragment,
  22154. lights_physical_fragment: lights_physical_fragment,
  22155. lights_physical_pars_fragment: lights_physical_pars_fragment,
  22156. lights_fragment_begin: lights_fragment_begin,
  22157. lights_fragment_maps: lights_fragment_maps,
  22158. lights_fragment_end: lights_fragment_end,
  22159. logdepthbuf_fragment: logdepthbuf_fragment,
  22160. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  22161. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  22162. logdepthbuf_vertex: logdepthbuf_vertex,
  22163. map_fragment: map_fragment,
  22164. map_pars_fragment: map_pars_fragment,
  22165. map_particle_fragment: map_particle_fragment,
  22166. map_particle_pars_fragment: map_particle_pars_fragment,
  22167. metalnessmap_fragment: metalnessmap_fragment,
  22168. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  22169. morphinstance_vertex: morphinstance_vertex,
  22170. morphcolor_vertex: morphcolor_vertex,
  22171. morphnormal_vertex: morphnormal_vertex,
  22172. morphtarget_pars_vertex: morphtarget_pars_vertex,
  22173. morphtarget_vertex: morphtarget_vertex,
  22174. normal_fragment_begin: normal_fragment_begin,
  22175. normal_fragment_maps: normal_fragment_maps,
  22176. normal_pars_fragment: normal_pars_fragment,
  22177. normal_pars_vertex: normal_pars_vertex,
  22178. normal_vertex: normal_vertex,
  22179. normalmap_pars_fragment: normalmap_pars_fragment,
  22180. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  22181. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  22182. clearcoat_pars_fragment: clearcoat_pars_fragment,
  22183. iridescence_pars_fragment: iridescence_pars_fragment,
  22184. opaque_fragment: opaque_fragment,
  22185. packing: packing,
  22186. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  22187. project_vertex: project_vertex,
  22188. dithering_fragment: dithering_fragment,
  22189. dithering_pars_fragment: dithering_pars_fragment,
  22190. roughnessmap_fragment: roughnessmap_fragment,
  22191. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  22192. shadowmap_pars_fragment: shadowmap_pars_fragment,
  22193. shadowmap_pars_vertex: shadowmap_pars_vertex,
  22194. shadowmap_vertex: shadowmap_vertex,
  22195. shadowmask_pars_fragment: shadowmask_pars_fragment,
  22196. skinbase_vertex: skinbase_vertex,
  22197. skinning_pars_vertex: skinning_pars_vertex,
  22198. skinning_vertex: skinning_vertex,
  22199. skinnormal_vertex: skinnormal_vertex,
  22200. specularmap_fragment: specularmap_fragment,
  22201. specularmap_pars_fragment: specularmap_pars_fragment,
  22202. tonemapping_fragment: tonemapping_fragment,
  22203. tonemapping_pars_fragment: tonemapping_pars_fragment,
  22204. transmission_fragment: transmission_fragment,
  22205. transmission_pars_fragment: transmission_pars_fragment,
  22206. uv_pars_fragment: uv_pars_fragment,
  22207. uv_pars_vertex: uv_pars_vertex,
  22208. uv_vertex: uv_vertex,
  22209. worldpos_vertex: worldpos_vertex,
  22210. background_vert: vertex$h,
  22211. background_frag: fragment$h,
  22212. backgroundCube_vert: vertex$g,
  22213. backgroundCube_frag: fragment$g,
  22214. cube_vert: vertex$f,
  22215. cube_frag: fragment$f,
  22216. depth_vert: vertex$e,
  22217. depth_frag: fragment$e,
  22218. distanceRGBA_vert: vertex$d,
  22219. distanceRGBA_frag: fragment$d,
  22220. equirect_vert: vertex$c,
  22221. equirect_frag: fragment$c,
  22222. linedashed_vert: vertex$b,
  22223. linedashed_frag: fragment$b,
  22224. meshbasic_vert: vertex$a,
  22225. meshbasic_frag: fragment$a,
  22226. meshlambert_vert: vertex$9,
  22227. meshlambert_frag: fragment$9,
  22228. meshmatcap_vert: vertex$8,
  22229. meshmatcap_frag: fragment$8,
  22230. meshnormal_vert: vertex$7,
  22231. meshnormal_frag: fragment$7,
  22232. meshphong_vert: vertex$6,
  22233. meshphong_frag: fragment$6,
  22234. meshphysical_vert: vertex$5,
  22235. meshphysical_frag: fragment$5,
  22236. meshtoon_vert: vertex$4,
  22237. meshtoon_frag: fragment$4,
  22238. points_vert: vertex$3,
  22239. points_frag: fragment$3,
  22240. shadow_vert: vertex$2,
  22241. shadow_frag: fragment$2,
  22242. sprite_vert: vertex$1,
  22243. sprite_frag: fragment$1
  22244. };
  22245. /**
  22246. * Uniforms library for shared webgl shaders
  22247. */
  22248. const UniformsLib = {
  22249. common: {
  22250. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  22251. opacity: { value: 1.0 },
  22252. map: { value: null },
  22253. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22254. alphaMap: { value: null },
  22255. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22256. alphaTest: { value: 0 }
  22257. },
  22258. specularmap: {
  22259. specularMap: { value: null },
  22260. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  22261. },
  22262. envmap: {
  22263. envMap: { value: null },
  22264. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  22265. flipEnvMap: { value: - 1 },
  22266. reflectivity: { value: 1.0 }, // basic, lambert, phong
  22267. ior: { value: 1.5 }, // physical
  22268. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  22269. },
  22270. aomap: {
  22271. aoMap: { value: null },
  22272. aoMapIntensity: { value: 1 },
  22273. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  22274. },
  22275. lightmap: {
  22276. lightMap: { value: null },
  22277. lightMapIntensity: { value: 1 },
  22278. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  22279. },
  22280. bumpmap: {
  22281. bumpMap: { value: null },
  22282. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22283. bumpScale: { value: 1 }
  22284. },
  22285. normalmap: {
  22286. normalMap: { value: null },
  22287. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22288. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  22289. },
  22290. displacementmap: {
  22291. displacementMap: { value: null },
  22292. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22293. displacementScale: { value: 1 },
  22294. displacementBias: { value: 0 }
  22295. },
  22296. emissivemap: {
  22297. emissiveMap: { value: null },
  22298. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  22299. },
  22300. metalnessmap: {
  22301. metalnessMap: { value: null },
  22302. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  22303. },
  22304. roughnessmap: {
  22305. roughnessMap: { value: null },
  22306. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  22307. },
  22308. gradientmap: {
  22309. gradientMap: { value: null }
  22310. },
  22311. fog: {
  22312. fogDensity: { value: 0.00025 },
  22313. fogNear: { value: 1 },
  22314. fogFar: { value: 2000 },
  22315. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  22316. },
  22317. lights: {
  22318. ambientLightColor: { value: [] },
  22319. lightProbe: { value: [] },
  22320. directionalLights: { value: [], properties: {
  22321. direction: {},
  22322. color: {}
  22323. } },
  22324. directionalLightShadows: { value: [], properties: {
  22325. shadowIntensity: 1,
  22326. shadowBias: {},
  22327. shadowNormalBias: {},
  22328. shadowRadius: {},
  22329. shadowMapSize: {}
  22330. } },
  22331. directionalShadowMap: { value: [] },
  22332. directionalShadowMatrix: { value: [] },
  22333. spotLights: { value: [], properties: {
  22334. color: {},
  22335. position: {},
  22336. direction: {},
  22337. distance: {},
  22338. coneCos: {},
  22339. penumbraCos: {},
  22340. decay: {}
  22341. } },
  22342. spotLightShadows: { value: [], properties: {
  22343. shadowIntensity: 1,
  22344. shadowBias: {},
  22345. shadowNormalBias: {},
  22346. shadowRadius: {},
  22347. shadowMapSize: {}
  22348. } },
  22349. spotLightMap: { value: [] },
  22350. spotShadowMap: { value: [] },
  22351. spotLightMatrix: { value: [] },
  22352. pointLights: { value: [], properties: {
  22353. color: {},
  22354. position: {},
  22355. decay: {},
  22356. distance: {}
  22357. } },
  22358. pointLightShadows: { value: [], properties: {
  22359. shadowIntensity: 1,
  22360. shadowBias: {},
  22361. shadowNormalBias: {},
  22362. shadowRadius: {},
  22363. shadowMapSize: {},
  22364. shadowCameraNear: {},
  22365. shadowCameraFar: {}
  22366. } },
  22367. pointShadowMap: { value: [] },
  22368. pointShadowMatrix: { value: [] },
  22369. hemisphereLights: { value: [], properties: {
  22370. direction: {},
  22371. skyColor: {},
  22372. groundColor: {}
  22373. } },
  22374. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  22375. rectAreaLights: { value: [], properties: {
  22376. color: {},
  22377. position: {},
  22378. width: {},
  22379. height: {}
  22380. } },
  22381. ltc_1: { value: null },
  22382. ltc_2: { value: null }
  22383. },
  22384. points: {
  22385. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  22386. opacity: { value: 1.0 },
  22387. size: { value: 1.0 },
  22388. scale: { value: 1.0 },
  22389. map: { value: null },
  22390. alphaMap: { value: null },
  22391. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22392. alphaTest: { value: 0 },
  22393. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  22394. },
  22395. sprite: {
  22396. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  22397. opacity: { value: 1.0 },
  22398. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  22399. rotation: { value: 0.0 },
  22400. map: { value: null },
  22401. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22402. alphaMap: { value: null },
  22403. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22404. alphaTest: { value: 0 }
  22405. }
  22406. };
  22407. const ShaderLib = {
  22408. basic: {
  22409. uniforms: /*@__PURE__*/ mergeUniforms( [
  22410. UniformsLib.common,
  22411. UniformsLib.specularmap,
  22412. UniformsLib.envmap,
  22413. UniformsLib.aomap,
  22414. UniformsLib.lightmap,
  22415. UniformsLib.fog
  22416. ] ),
  22417. vertexShader: ShaderChunk.meshbasic_vert,
  22418. fragmentShader: ShaderChunk.meshbasic_frag
  22419. },
  22420. lambert: {
  22421. uniforms: /*@__PURE__*/ mergeUniforms( [
  22422. UniformsLib.common,
  22423. UniformsLib.specularmap,
  22424. UniformsLib.envmap,
  22425. UniformsLib.aomap,
  22426. UniformsLib.lightmap,
  22427. UniformsLib.emissivemap,
  22428. UniformsLib.bumpmap,
  22429. UniformsLib.normalmap,
  22430. UniformsLib.displacementmap,
  22431. UniformsLib.fog,
  22432. UniformsLib.lights,
  22433. {
  22434. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  22435. }
  22436. ] ),
  22437. vertexShader: ShaderChunk.meshlambert_vert,
  22438. fragmentShader: ShaderChunk.meshlambert_frag
  22439. },
  22440. phong: {
  22441. uniforms: /*@__PURE__*/ mergeUniforms( [
  22442. UniformsLib.common,
  22443. UniformsLib.specularmap,
  22444. UniformsLib.envmap,
  22445. UniformsLib.aomap,
  22446. UniformsLib.lightmap,
  22447. UniformsLib.emissivemap,
  22448. UniformsLib.bumpmap,
  22449. UniformsLib.normalmap,
  22450. UniformsLib.displacementmap,
  22451. UniformsLib.fog,
  22452. UniformsLib.lights,
  22453. {
  22454. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  22455. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  22456. shininess: { value: 30 }
  22457. }
  22458. ] ),
  22459. vertexShader: ShaderChunk.meshphong_vert,
  22460. fragmentShader: ShaderChunk.meshphong_frag
  22461. },
  22462. standard: {
  22463. uniforms: /*@__PURE__*/ mergeUniforms( [
  22464. UniformsLib.common,
  22465. UniformsLib.envmap,
  22466. UniformsLib.aomap,
  22467. UniformsLib.lightmap,
  22468. UniformsLib.emissivemap,
  22469. UniformsLib.bumpmap,
  22470. UniformsLib.normalmap,
  22471. UniformsLib.displacementmap,
  22472. UniformsLib.roughnessmap,
  22473. UniformsLib.metalnessmap,
  22474. UniformsLib.fog,
  22475. UniformsLib.lights,
  22476. {
  22477. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  22478. roughness: { value: 1.0 },
  22479. metalness: { value: 0.0 },
  22480. envMapIntensity: { value: 1 }
  22481. }
  22482. ] ),
  22483. vertexShader: ShaderChunk.meshphysical_vert,
  22484. fragmentShader: ShaderChunk.meshphysical_frag
  22485. },
  22486. toon: {
  22487. uniforms: /*@__PURE__*/ mergeUniforms( [
  22488. UniformsLib.common,
  22489. UniformsLib.aomap,
  22490. UniformsLib.lightmap,
  22491. UniformsLib.emissivemap,
  22492. UniformsLib.bumpmap,
  22493. UniformsLib.normalmap,
  22494. UniformsLib.displacementmap,
  22495. UniformsLib.gradientmap,
  22496. UniformsLib.fog,
  22497. UniformsLib.lights,
  22498. {
  22499. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  22500. }
  22501. ] ),
  22502. vertexShader: ShaderChunk.meshtoon_vert,
  22503. fragmentShader: ShaderChunk.meshtoon_frag
  22504. },
  22505. matcap: {
  22506. uniforms: /*@__PURE__*/ mergeUniforms( [
  22507. UniformsLib.common,
  22508. UniformsLib.bumpmap,
  22509. UniformsLib.normalmap,
  22510. UniformsLib.displacementmap,
  22511. UniformsLib.fog,
  22512. {
  22513. matcap: { value: null }
  22514. }
  22515. ] ),
  22516. vertexShader: ShaderChunk.meshmatcap_vert,
  22517. fragmentShader: ShaderChunk.meshmatcap_frag
  22518. },
  22519. points: {
  22520. uniforms: /*@__PURE__*/ mergeUniforms( [
  22521. UniformsLib.points,
  22522. UniformsLib.fog
  22523. ] ),
  22524. vertexShader: ShaderChunk.points_vert,
  22525. fragmentShader: ShaderChunk.points_frag
  22526. },
  22527. dashed: {
  22528. uniforms: /*@__PURE__*/ mergeUniforms( [
  22529. UniformsLib.common,
  22530. UniformsLib.fog,
  22531. {
  22532. scale: { value: 1 },
  22533. dashSize: { value: 1 },
  22534. totalSize: { value: 2 }
  22535. }
  22536. ] ),
  22537. vertexShader: ShaderChunk.linedashed_vert,
  22538. fragmentShader: ShaderChunk.linedashed_frag
  22539. },
  22540. depth: {
  22541. uniforms: /*@__PURE__*/ mergeUniforms( [
  22542. UniformsLib.common,
  22543. UniformsLib.displacementmap
  22544. ] ),
  22545. vertexShader: ShaderChunk.depth_vert,
  22546. fragmentShader: ShaderChunk.depth_frag
  22547. },
  22548. normal: {
  22549. uniforms: /*@__PURE__*/ mergeUniforms( [
  22550. UniformsLib.common,
  22551. UniformsLib.bumpmap,
  22552. UniformsLib.normalmap,
  22553. UniformsLib.displacementmap,
  22554. {
  22555. opacity: { value: 1.0 }
  22556. }
  22557. ] ),
  22558. vertexShader: ShaderChunk.meshnormal_vert,
  22559. fragmentShader: ShaderChunk.meshnormal_frag
  22560. },
  22561. sprite: {
  22562. uniforms: /*@__PURE__*/ mergeUniforms( [
  22563. UniformsLib.sprite,
  22564. UniformsLib.fog
  22565. ] ),
  22566. vertexShader: ShaderChunk.sprite_vert,
  22567. fragmentShader: ShaderChunk.sprite_frag
  22568. },
  22569. background: {
  22570. uniforms: {
  22571. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  22572. t2D: { value: null },
  22573. backgroundIntensity: { value: 1 }
  22574. },
  22575. vertexShader: ShaderChunk.background_vert,
  22576. fragmentShader: ShaderChunk.background_frag
  22577. },
  22578. backgroundCube: {
  22579. uniforms: {
  22580. envMap: { value: null },
  22581. flipEnvMap: { value: - 1 },
  22582. backgroundBlurriness: { value: 0 },
  22583. backgroundIntensity: { value: 1 },
  22584. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  22585. },
  22586. vertexShader: ShaderChunk.backgroundCube_vert,
  22587. fragmentShader: ShaderChunk.backgroundCube_frag
  22588. },
  22589. cube: {
  22590. uniforms: {
  22591. tCube: { value: null },
  22592. tFlip: { value: - 1 },
  22593. opacity: { value: 1.0 }
  22594. },
  22595. vertexShader: ShaderChunk.cube_vert,
  22596. fragmentShader: ShaderChunk.cube_frag
  22597. },
  22598. equirect: {
  22599. uniforms: {
  22600. tEquirect: { value: null },
  22601. },
  22602. vertexShader: ShaderChunk.equirect_vert,
  22603. fragmentShader: ShaderChunk.equirect_frag
  22604. },
  22605. distanceRGBA: {
  22606. uniforms: /*@__PURE__*/ mergeUniforms( [
  22607. UniformsLib.common,
  22608. UniformsLib.displacementmap,
  22609. {
  22610. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  22611. nearDistance: { value: 1 },
  22612. farDistance: { value: 1000 }
  22613. }
  22614. ] ),
  22615. vertexShader: ShaderChunk.distanceRGBA_vert,
  22616. fragmentShader: ShaderChunk.distanceRGBA_frag
  22617. },
  22618. shadow: {
  22619. uniforms: /*@__PURE__*/ mergeUniforms( [
  22620. UniformsLib.lights,
  22621. UniformsLib.fog,
  22622. {
  22623. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  22624. opacity: { value: 1.0 }
  22625. },
  22626. ] ),
  22627. vertexShader: ShaderChunk.shadow_vert,
  22628. fragmentShader: ShaderChunk.shadow_frag
  22629. }
  22630. };
  22631. ShaderLib.physical = {
  22632. uniforms: /*@__PURE__*/ mergeUniforms( [
  22633. ShaderLib.standard.uniforms,
  22634. {
  22635. clearcoat: { value: 0 },
  22636. clearcoatMap: { value: null },
  22637. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22638. clearcoatNormalMap: { value: null },
  22639. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22640. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  22641. clearcoatRoughness: { value: 0 },
  22642. clearcoatRoughnessMap: { value: null },
  22643. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22644. dispersion: { value: 0 },
  22645. iridescence: { value: 0 },
  22646. iridescenceMap: { value: null },
  22647. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22648. iridescenceIOR: { value: 1.3 },
  22649. iridescenceThicknessMinimum: { value: 100 },
  22650. iridescenceThicknessMaximum: { value: 400 },
  22651. iridescenceThicknessMap: { value: null },
  22652. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22653. sheen: { value: 0 },
  22654. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  22655. sheenColorMap: { value: null },
  22656. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22657. sheenRoughness: { value: 1 },
  22658. sheenRoughnessMap: { value: null },
  22659. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22660. transmission: { value: 0 },
  22661. transmissionMap: { value: null },
  22662. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22663. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  22664. transmissionSamplerMap: { value: null },
  22665. thickness: { value: 0 },
  22666. thicknessMap: { value: null },
  22667. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22668. attenuationDistance: { value: 0 },
  22669. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  22670. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  22671. specularColorMap: { value: null },
  22672. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22673. specularIntensity: { value: 1 },
  22674. specularIntensityMap: { value: null },
  22675. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22676. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  22677. anisotropyMap: { value: null },
  22678. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  22679. }
  22680. ] ),
  22681. vertexShader: ShaderChunk.meshphysical_vert,
  22682. fragmentShader: ShaderChunk.meshphysical_frag
  22683. };
  22684. const _rgb = { r: 0, b: 0, g: 0 };
  22685. const _e1$1 = /*@__PURE__*/ new Euler();
  22686. const _m1$1 = /*@__PURE__*/ new Matrix4();
  22687. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  22688. const clearColor = new Color( 0x000000 );
  22689. let clearAlpha = alpha === true ? 0 : 1;
  22690. let planeMesh;
  22691. let boxMesh;
  22692. let currentBackground = null;
  22693. let currentBackgroundVersion = 0;
  22694. let currentTonemapping = null;
  22695. function getBackground( scene ) {
  22696. let background = scene.isScene === true ? scene.background : null;
  22697. if ( background && background.isTexture ) {
  22698. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  22699. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  22700. }
  22701. return background;
  22702. }
  22703. function render( scene ) {
  22704. let forceClear = false;
  22705. const background = getBackground( scene );
  22706. if ( background === null ) {
  22707. setClear( clearColor, clearAlpha );
  22708. } else if ( background && background.isColor ) {
  22709. setClear( background, 1 );
  22710. forceClear = true;
  22711. }
  22712. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  22713. if ( environmentBlendMode === 'additive' ) {
  22714. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  22715. } else if ( environmentBlendMode === 'alpha-blend' ) {
  22716. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  22717. }
  22718. if ( renderer.autoClear || forceClear ) {
  22719. // buffers might not be writable which is required to ensure a correct clear
  22720. state.buffers.depth.setTest( true );
  22721. state.buffers.depth.setMask( true );
  22722. state.buffers.color.setMask( true );
  22723. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  22724. }
  22725. }
  22726. function addToRenderList( renderList, scene ) {
  22727. const background = getBackground( scene );
  22728. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  22729. if ( boxMesh === undefined ) {
  22730. boxMesh = new Mesh(
  22731. new BoxGeometry( 1, 1, 1 ),
  22732. new ShaderMaterial( {
  22733. name: 'BackgroundCubeMaterial',
  22734. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  22735. vertexShader: ShaderLib.backgroundCube.vertexShader,
  22736. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  22737. side: BackSide,
  22738. depthTest: false,
  22739. depthWrite: false,
  22740. fog: false
  22741. } )
  22742. );
  22743. boxMesh.geometry.deleteAttribute( 'normal' );
  22744. boxMesh.geometry.deleteAttribute( 'uv' );
  22745. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  22746. this.matrixWorld.copyPosition( camera.matrixWorld );
  22747. };
  22748. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  22749. Object.defineProperty( boxMesh.material, 'envMap', {
  22750. get: function () {
  22751. return this.uniforms.envMap.value;
  22752. }
  22753. } );
  22754. objects.update( boxMesh );
  22755. }
  22756. _e1$1.copy( scene.backgroundRotation );
  22757. // accommodate left-handed frame
  22758. _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1;
  22759. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  22760. // environment maps which are not cube render targets or PMREMs follow a different convention
  22761. _e1$1.y *= - 1;
  22762. _e1$1.z *= - 1;
  22763. }
  22764. boxMesh.material.uniforms.envMap.value = background;
  22765. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  22766. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  22767. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  22768. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  22769. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  22770. if ( currentBackground !== background ||
  22771. currentBackgroundVersion !== background.version ||
  22772. currentTonemapping !== renderer.toneMapping ) {
  22773. boxMesh.material.needsUpdate = true;
  22774. currentBackground = background;
  22775. currentBackgroundVersion = background.version;
  22776. currentTonemapping = renderer.toneMapping;
  22777. }
  22778. boxMesh.layers.enableAll();
  22779. // push to the pre-sorted opaque render list
  22780. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  22781. } else if ( background && background.isTexture ) {
  22782. if ( planeMesh === undefined ) {
  22783. planeMesh = new Mesh(
  22784. new PlaneGeometry( 2, 2 ),
  22785. new ShaderMaterial( {
  22786. name: 'BackgroundMaterial',
  22787. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  22788. vertexShader: ShaderLib.background.vertexShader,
  22789. fragmentShader: ShaderLib.background.fragmentShader,
  22790. side: FrontSide,
  22791. depthTest: false,
  22792. depthWrite: false,
  22793. fog: false
  22794. } )
  22795. );
  22796. planeMesh.geometry.deleteAttribute( 'normal' );
  22797. // add "map" material property so the renderer can evaluate it like for built-in materials
  22798. Object.defineProperty( planeMesh.material, 'map', {
  22799. get: function () {
  22800. return this.uniforms.t2D.value;
  22801. }
  22802. } );
  22803. objects.update( planeMesh );
  22804. }
  22805. planeMesh.material.uniforms.t2D.value = background;
  22806. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  22807. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  22808. if ( background.matrixAutoUpdate === true ) {
  22809. background.updateMatrix();
  22810. }
  22811. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  22812. if ( currentBackground !== background ||
  22813. currentBackgroundVersion !== background.version ||
  22814. currentTonemapping !== renderer.toneMapping ) {
  22815. planeMesh.material.needsUpdate = true;
  22816. currentBackground = background;
  22817. currentBackgroundVersion = background.version;
  22818. currentTonemapping = renderer.toneMapping;
  22819. }
  22820. planeMesh.layers.enableAll();
  22821. // push to the pre-sorted opaque render list
  22822. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  22823. }
  22824. }
  22825. function setClear( color, alpha ) {
  22826. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  22827. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  22828. }
  22829. function dispose() {
  22830. if ( boxMesh !== undefined ) {
  22831. boxMesh.geometry.dispose();
  22832. boxMesh.material.dispose();
  22833. }
  22834. if ( planeMesh !== undefined ) {
  22835. planeMesh.geometry.dispose();
  22836. planeMesh.material.dispose();
  22837. }
  22838. }
  22839. return {
  22840. getClearColor: function () {
  22841. return clearColor;
  22842. },
  22843. setClearColor: function ( color, alpha = 1 ) {
  22844. clearColor.set( color );
  22845. clearAlpha = alpha;
  22846. setClear( clearColor, clearAlpha );
  22847. },
  22848. getClearAlpha: function () {
  22849. return clearAlpha;
  22850. },
  22851. setClearAlpha: function ( alpha ) {
  22852. clearAlpha = alpha;
  22853. setClear( clearColor, clearAlpha );
  22854. },
  22855. render: render,
  22856. addToRenderList: addToRenderList,
  22857. dispose: dispose
  22858. };
  22859. }
  22860. function WebGLBindingStates( gl, attributes ) {
  22861. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  22862. const bindingStates = {};
  22863. const defaultState = createBindingState( null );
  22864. let currentState = defaultState;
  22865. let forceUpdate = false;
  22866. function setup( object, material, program, geometry, index ) {
  22867. let updateBuffers = false;
  22868. const state = getBindingState( geometry, program, material );
  22869. if ( currentState !== state ) {
  22870. currentState = state;
  22871. bindVertexArrayObject( currentState.object );
  22872. }
  22873. updateBuffers = needsUpdate( object, geometry, program, index );
  22874. if ( updateBuffers ) saveCache( object, geometry, program, index );
  22875. if ( index !== null ) {
  22876. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  22877. }
  22878. if ( updateBuffers || forceUpdate ) {
  22879. forceUpdate = false;
  22880. setupVertexAttributes( object, material, program, geometry );
  22881. if ( index !== null ) {
  22882. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  22883. }
  22884. }
  22885. }
  22886. function createVertexArrayObject() {
  22887. return gl.createVertexArray();
  22888. }
  22889. function bindVertexArrayObject( vao ) {
  22890. return gl.bindVertexArray( vao );
  22891. }
  22892. function deleteVertexArrayObject( vao ) {
  22893. return gl.deleteVertexArray( vao );
  22894. }
  22895. function getBindingState( geometry, program, material ) {
  22896. const wireframe = ( material.wireframe === true );
  22897. let programMap = bindingStates[ geometry.id ];
  22898. if ( programMap === undefined ) {
  22899. programMap = {};
  22900. bindingStates[ geometry.id ] = programMap;
  22901. }
  22902. let stateMap = programMap[ program.id ];
  22903. if ( stateMap === undefined ) {
  22904. stateMap = {};
  22905. programMap[ program.id ] = stateMap;
  22906. }
  22907. let state = stateMap[ wireframe ];
  22908. if ( state === undefined ) {
  22909. state = createBindingState( createVertexArrayObject() );
  22910. stateMap[ wireframe ] = state;
  22911. }
  22912. return state;
  22913. }
  22914. function createBindingState( vao ) {
  22915. const newAttributes = [];
  22916. const enabledAttributes = [];
  22917. const attributeDivisors = [];
  22918. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  22919. newAttributes[ i ] = 0;
  22920. enabledAttributes[ i ] = 0;
  22921. attributeDivisors[ i ] = 0;
  22922. }
  22923. return {
  22924. // for backward compatibility on non-VAO support browser
  22925. geometry: null,
  22926. program: null,
  22927. wireframe: false,
  22928. newAttributes: newAttributes,
  22929. enabledAttributes: enabledAttributes,
  22930. attributeDivisors: attributeDivisors,
  22931. object: vao,
  22932. attributes: {},
  22933. index: null
  22934. };
  22935. }
  22936. function needsUpdate( object, geometry, program, index ) {
  22937. const cachedAttributes = currentState.attributes;
  22938. const geometryAttributes = geometry.attributes;
  22939. let attributesNum = 0;
  22940. const programAttributes = program.getAttributes();
  22941. for ( const name in programAttributes ) {
  22942. const programAttribute = programAttributes[ name ];
  22943. if ( programAttribute.location >= 0 ) {
  22944. const cachedAttribute = cachedAttributes[ name ];
  22945. let geometryAttribute = geometryAttributes[ name ];
  22946. if ( geometryAttribute === undefined ) {
  22947. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  22948. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  22949. }
  22950. if ( cachedAttribute === undefined ) return true;
  22951. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  22952. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  22953. attributesNum ++;
  22954. }
  22955. }
  22956. if ( currentState.attributesNum !== attributesNum ) return true;
  22957. if ( currentState.index !== index ) return true;
  22958. return false;
  22959. }
  22960. function saveCache( object, geometry, program, index ) {
  22961. const cache = {};
  22962. const attributes = geometry.attributes;
  22963. let attributesNum = 0;
  22964. const programAttributes = program.getAttributes();
  22965. for ( const name in programAttributes ) {
  22966. const programAttribute = programAttributes[ name ];
  22967. if ( programAttribute.location >= 0 ) {
  22968. let attribute = attributes[ name ];
  22969. if ( attribute === undefined ) {
  22970. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  22971. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  22972. }
  22973. const data = {};
  22974. data.attribute = attribute;
  22975. if ( attribute && attribute.data ) {
  22976. data.data = attribute.data;
  22977. }
  22978. cache[ name ] = data;
  22979. attributesNum ++;
  22980. }
  22981. }
  22982. currentState.attributes = cache;
  22983. currentState.attributesNum = attributesNum;
  22984. currentState.index = index;
  22985. }
  22986. function initAttributes() {
  22987. const newAttributes = currentState.newAttributes;
  22988. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  22989. newAttributes[ i ] = 0;
  22990. }
  22991. }
  22992. function enableAttribute( attribute ) {
  22993. enableAttributeAndDivisor( attribute, 0 );
  22994. }
  22995. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  22996. const newAttributes = currentState.newAttributes;
  22997. const enabledAttributes = currentState.enabledAttributes;
  22998. const attributeDivisors = currentState.attributeDivisors;
  22999. newAttributes[ attribute ] = 1;
  23000. if ( enabledAttributes[ attribute ] === 0 ) {
  23001. gl.enableVertexAttribArray( attribute );
  23002. enabledAttributes[ attribute ] = 1;
  23003. }
  23004. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  23005. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  23006. attributeDivisors[ attribute ] = meshPerAttribute;
  23007. }
  23008. }
  23009. function disableUnusedAttributes() {
  23010. const newAttributes = currentState.newAttributes;
  23011. const enabledAttributes = currentState.enabledAttributes;
  23012. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  23013. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  23014. gl.disableVertexAttribArray( i );
  23015. enabledAttributes[ i ] = 0;
  23016. }
  23017. }
  23018. }
  23019. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  23020. if ( integer === true ) {
  23021. gl.vertexAttribIPointer( index, size, type, stride, offset );
  23022. } else {
  23023. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  23024. }
  23025. }
  23026. function setupVertexAttributes( object, material, program, geometry ) {
  23027. initAttributes();
  23028. const geometryAttributes = geometry.attributes;
  23029. const programAttributes = program.getAttributes();
  23030. const materialDefaultAttributeValues = material.defaultAttributeValues;
  23031. for ( const name in programAttributes ) {
  23032. const programAttribute = programAttributes[ name ];
  23033. if ( programAttribute.location >= 0 ) {
  23034. let geometryAttribute = geometryAttributes[ name ];
  23035. if ( geometryAttribute === undefined ) {
  23036. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  23037. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  23038. }
  23039. if ( geometryAttribute !== undefined ) {
  23040. const normalized = geometryAttribute.normalized;
  23041. const size = geometryAttribute.itemSize;
  23042. const attribute = attributes.get( geometryAttribute );
  23043. // TODO Attribute may not be available on context restore
  23044. if ( attribute === undefined ) continue;
  23045. const buffer = attribute.buffer;
  23046. const type = attribute.type;
  23047. const bytesPerElement = attribute.bytesPerElement;
  23048. // check for integer attributes
  23049. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  23050. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  23051. const data = geometryAttribute.data;
  23052. const stride = data.stride;
  23053. const offset = geometryAttribute.offset;
  23054. if ( data.isInstancedInterleavedBuffer ) {
  23055. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  23056. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  23057. }
  23058. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  23059. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  23060. }
  23061. } else {
  23062. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  23063. enableAttribute( programAttribute.location + i );
  23064. }
  23065. }
  23066. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  23067. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  23068. vertexAttribPointer(
  23069. programAttribute.location + i,
  23070. size / programAttribute.locationSize,
  23071. type,
  23072. normalized,
  23073. stride * bytesPerElement,
  23074. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  23075. integer
  23076. );
  23077. }
  23078. } else {
  23079. if ( geometryAttribute.isInstancedBufferAttribute ) {
  23080. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  23081. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  23082. }
  23083. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  23084. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  23085. }
  23086. } else {
  23087. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  23088. enableAttribute( programAttribute.location + i );
  23089. }
  23090. }
  23091. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  23092. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  23093. vertexAttribPointer(
  23094. programAttribute.location + i,
  23095. size / programAttribute.locationSize,
  23096. type,
  23097. normalized,
  23098. size * bytesPerElement,
  23099. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  23100. integer
  23101. );
  23102. }
  23103. }
  23104. } else if ( materialDefaultAttributeValues !== undefined ) {
  23105. const value = materialDefaultAttributeValues[ name ];
  23106. if ( value !== undefined ) {
  23107. switch ( value.length ) {
  23108. case 2:
  23109. gl.vertexAttrib2fv( programAttribute.location, value );
  23110. break;
  23111. case 3:
  23112. gl.vertexAttrib3fv( programAttribute.location, value );
  23113. break;
  23114. case 4:
  23115. gl.vertexAttrib4fv( programAttribute.location, value );
  23116. break;
  23117. default:
  23118. gl.vertexAttrib1fv( programAttribute.location, value );
  23119. }
  23120. }
  23121. }
  23122. }
  23123. }
  23124. disableUnusedAttributes();
  23125. }
  23126. function dispose() {
  23127. reset();
  23128. for ( const geometryId in bindingStates ) {
  23129. const programMap = bindingStates[ geometryId ];
  23130. for ( const programId in programMap ) {
  23131. const stateMap = programMap[ programId ];
  23132. for ( const wireframe in stateMap ) {
  23133. deleteVertexArrayObject( stateMap[ wireframe ].object );
  23134. delete stateMap[ wireframe ];
  23135. }
  23136. delete programMap[ programId ];
  23137. }
  23138. delete bindingStates[ geometryId ];
  23139. }
  23140. }
  23141. function releaseStatesOfGeometry( geometry ) {
  23142. if ( bindingStates[ geometry.id ] === undefined ) return;
  23143. const programMap = bindingStates[ geometry.id ];
  23144. for ( const programId in programMap ) {
  23145. const stateMap = programMap[ programId ];
  23146. for ( const wireframe in stateMap ) {
  23147. deleteVertexArrayObject( stateMap[ wireframe ].object );
  23148. delete stateMap[ wireframe ];
  23149. }
  23150. delete programMap[ programId ];
  23151. }
  23152. delete bindingStates[ geometry.id ];
  23153. }
  23154. function releaseStatesOfProgram( program ) {
  23155. for ( const geometryId in bindingStates ) {
  23156. const programMap = bindingStates[ geometryId ];
  23157. if ( programMap[ program.id ] === undefined ) continue;
  23158. const stateMap = programMap[ program.id ];
  23159. for ( const wireframe in stateMap ) {
  23160. deleteVertexArrayObject( stateMap[ wireframe ].object );
  23161. delete stateMap[ wireframe ];
  23162. }
  23163. delete programMap[ program.id ];
  23164. }
  23165. }
  23166. function reset() {
  23167. resetDefaultState();
  23168. forceUpdate = true;
  23169. if ( currentState === defaultState ) return;
  23170. currentState = defaultState;
  23171. bindVertexArrayObject( currentState.object );
  23172. }
  23173. // for backward-compatibility
  23174. function resetDefaultState() {
  23175. defaultState.geometry = null;
  23176. defaultState.program = null;
  23177. defaultState.wireframe = false;
  23178. }
  23179. return {
  23180. setup: setup,
  23181. reset: reset,
  23182. resetDefaultState: resetDefaultState,
  23183. dispose: dispose,
  23184. releaseStatesOfGeometry: releaseStatesOfGeometry,
  23185. releaseStatesOfProgram: releaseStatesOfProgram,
  23186. initAttributes: initAttributes,
  23187. enableAttribute: enableAttribute,
  23188. disableUnusedAttributes: disableUnusedAttributes
  23189. };
  23190. }
  23191. function WebGLBufferRenderer( gl, extensions, info ) {
  23192. let mode;
  23193. function setMode( value ) {
  23194. mode = value;
  23195. }
  23196. function render( start, count ) {
  23197. gl.drawArrays( mode, start, count );
  23198. info.update( count, mode, 1 );
  23199. }
  23200. function renderInstances( start, count, primcount ) {
  23201. if ( primcount === 0 ) return;
  23202. gl.drawArraysInstanced( mode, start, count, primcount );
  23203. info.update( count, mode, primcount );
  23204. }
  23205. function renderMultiDraw( starts, counts, drawCount ) {
  23206. if ( drawCount === 0 ) return;
  23207. const extension = extensions.get( 'WEBGL_multi_draw' );
  23208. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  23209. let elementCount = 0;
  23210. for ( let i = 0; i < drawCount; i ++ ) {
  23211. elementCount += counts[ i ];
  23212. }
  23213. info.update( elementCount, mode, 1 );
  23214. }
  23215. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  23216. if ( drawCount === 0 ) return;
  23217. const extension = extensions.get( 'WEBGL_multi_draw' );
  23218. if ( extension === null ) {
  23219. for ( let i = 0; i < starts.length; i ++ ) {
  23220. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  23221. }
  23222. } else {
  23223. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  23224. let elementCount = 0;
  23225. for ( let i = 0; i < drawCount; i ++ ) {
  23226. elementCount += counts[ i ] * primcount[ i ];
  23227. }
  23228. info.update( elementCount, mode, 1 );
  23229. }
  23230. }
  23231. //
  23232. this.setMode = setMode;
  23233. this.render = render;
  23234. this.renderInstances = renderInstances;
  23235. this.renderMultiDraw = renderMultiDraw;
  23236. this.renderMultiDrawInstances = renderMultiDrawInstances;
  23237. }
  23238. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  23239. let maxAnisotropy;
  23240. function getMaxAnisotropy() {
  23241. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  23242. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  23243. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  23244. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  23245. } else {
  23246. maxAnisotropy = 0;
  23247. }
  23248. return maxAnisotropy;
  23249. }
  23250. function textureFormatReadable( textureFormat ) {
  23251. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  23252. return false;
  23253. }
  23254. return true;
  23255. }
  23256. function textureTypeReadable( textureType ) {
  23257. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  23258. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  23259. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  23260. return false;
  23261. }
  23262. return true;
  23263. }
  23264. function getMaxPrecision( precision ) {
  23265. if ( precision === 'highp' ) {
  23266. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  23267. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  23268. return 'highp';
  23269. }
  23270. precision = 'mediump';
  23271. }
  23272. if ( precision === 'mediump' ) {
  23273. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  23274. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  23275. return 'mediump';
  23276. }
  23277. }
  23278. return 'lowp';
  23279. }
  23280. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  23281. const maxPrecision = getMaxPrecision( precision );
  23282. if ( maxPrecision !== precision ) {
  23283. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  23284. precision = maxPrecision;
  23285. }
  23286. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  23287. const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  23288. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  23289. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  23290. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  23291. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  23292. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  23293. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  23294. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  23295. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  23296. const vertexTextures = maxVertexTextures > 0;
  23297. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  23298. return {
  23299. isWebGL2: true, // keeping this for backwards compatibility
  23300. getMaxAnisotropy: getMaxAnisotropy,
  23301. getMaxPrecision: getMaxPrecision,
  23302. textureFormatReadable: textureFormatReadable,
  23303. textureTypeReadable: textureTypeReadable,
  23304. precision: precision,
  23305. logarithmicDepthBuffer: logarithmicDepthBuffer,
  23306. reverseDepthBuffer: reverseDepthBuffer,
  23307. maxTextures: maxTextures,
  23308. maxVertexTextures: maxVertexTextures,
  23309. maxTextureSize: maxTextureSize,
  23310. maxCubemapSize: maxCubemapSize,
  23311. maxAttributes: maxAttributes,
  23312. maxVertexUniforms: maxVertexUniforms,
  23313. maxVaryings: maxVaryings,
  23314. maxFragmentUniforms: maxFragmentUniforms,
  23315. vertexTextures: vertexTextures,
  23316. maxSamples: maxSamples
  23317. };
  23318. }
  23319. function WebGLClipping( properties ) {
  23320. const scope = this;
  23321. let globalState = null,
  23322. numGlobalPlanes = 0,
  23323. localClippingEnabled = false,
  23324. renderingShadows = false;
  23325. const plane = new Plane(),
  23326. viewNormalMatrix = new Matrix3(),
  23327. uniform = { value: null, needsUpdate: false };
  23328. this.uniform = uniform;
  23329. this.numPlanes = 0;
  23330. this.numIntersection = 0;
  23331. this.init = function ( planes, enableLocalClipping ) {
  23332. const enabled =
  23333. planes.length !== 0 ||
  23334. enableLocalClipping ||
  23335. // enable state of previous frame - the clipping code has to
  23336. // run another frame in order to reset the state:
  23337. numGlobalPlanes !== 0 ||
  23338. localClippingEnabled;
  23339. localClippingEnabled = enableLocalClipping;
  23340. numGlobalPlanes = planes.length;
  23341. return enabled;
  23342. };
  23343. this.beginShadows = function () {
  23344. renderingShadows = true;
  23345. projectPlanes( null );
  23346. };
  23347. this.endShadows = function () {
  23348. renderingShadows = false;
  23349. };
  23350. this.setGlobalState = function ( planes, camera ) {
  23351. globalState = projectPlanes( planes, camera, 0 );
  23352. };
  23353. this.setState = function ( material, camera, useCache ) {
  23354. const planes = material.clippingPlanes,
  23355. clipIntersection = material.clipIntersection,
  23356. clipShadows = material.clipShadows;
  23357. const materialProperties = properties.get( material );
  23358. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  23359. // there's no local clipping
  23360. if ( renderingShadows ) {
  23361. // there's no global clipping
  23362. projectPlanes( null );
  23363. } else {
  23364. resetGlobalState();
  23365. }
  23366. } else {
  23367. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  23368. lGlobal = nGlobal * 4;
  23369. let dstArray = materialProperties.clippingState || null;
  23370. uniform.value = dstArray; // ensure unique state
  23371. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  23372. for ( let i = 0; i !== lGlobal; ++ i ) {
  23373. dstArray[ i ] = globalState[ i ];
  23374. }
  23375. materialProperties.clippingState = dstArray;
  23376. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  23377. this.numPlanes += nGlobal;
  23378. }
  23379. };
  23380. function resetGlobalState() {
  23381. if ( uniform.value !== globalState ) {
  23382. uniform.value = globalState;
  23383. uniform.needsUpdate = numGlobalPlanes > 0;
  23384. }
  23385. scope.numPlanes = numGlobalPlanes;
  23386. scope.numIntersection = 0;
  23387. }
  23388. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  23389. const nPlanes = planes !== null ? planes.length : 0;
  23390. let dstArray = null;
  23391. if ( nPlanes !== 0 ) {
  23392. dstArray = uniform.value;
  23393. if ( skipTransform !== true || dstArray === null ) {
  23394. const flatSize = dstOffset + nPlanes * 4,
  23395. viewMatrix = camera.matrixWorldInverse;
  23396. viewNormalMatrix.getNormalMatrix( viewMatrix );
  23397. if ( dstArray === null || dstArray.length < flatSize ) {
  23398. dstArray = new Float32Array( flatSize );
  23399. }
  23400. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  23401. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  23402. plane.normal.toArray( dstArray, i4 );
  23403. dstArray[ i4 + 3 ] = plane.constant;
  23404. }
  23405. }
  23406. uniform.value = dstArray;
  23407. uniform.needsUpdate = true;
  23408. }
  23409. scope.numPlanes = nPlanes;
  23410. scope.numIntersection = 0;
  23411. return dstArray;
  23412. }
  23413. }
  23414. function WebGLCubeMaps( renderer ) {
  23415. let cubemaps = new WeakMap();
  23416. function mapTextureMapping( texture, mapping ) {
  23417. if ( mapping === EquirectangularReflectionMapping ) {
  23418. texture.mapping = CubeReflectionMapping;
  23419. } else if ( mapping === EquirectangularRefractionMapping ) {
  23420. texture.mapping = CubeRefractionMapping;
  23421. }
  23422. return texture;
  23423. }
  23424. function get( texture ) {
  23425. if ( texture && texture.isTexture ) {
  23426. const mapping = texture.mapping;
  23427. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  23428. if ( cubemaps.has( texture ) ) {
  23429. const cubemap = cubemaps.get( texture ).texture;
  23430. return mapTextureMapping( cubemap, texture.mapping );
  23431. } else {
  23432. const image = texture.image;
  23433. if ( image && image.height > 0 ) {
  23434. const renderTarget = new WebGLCubeRenderTarget( image.height );
  23435. renderTarget.fromEquirectangularTexture( renderer, texture );
  23436. cubemaps.set( texture, renderTarget );
  23437. texture.addEventListener( 'dispose', onTextureDispose );
  23438. return mapTextureMapping( renderTarget.texture, texture.mapping );
  23439. } else {
  23440. // image not yet ready. try the conversion next frame
  23441. return null;
  23442. }
  23443. }
  23444. }
  23445. }
  23446. return texture;
  23447. }
  23448. function onTextureDispose( event ) {
  23449. const texture = event.target;
  23450. texture.removeEventListener( 'dispose', onTextureDispose );
  23451. const cubemap = cubemaps.get( texture );
  23452. if ( cubemap !== undefined ) {
  23453. cubemaps.delete( texture );
  23454. cubemap.dispose();
  23455. }
  23456. }
  23457. function dispose() {
  23458. cubemaps = new WeakMap();
  23459. }
  23460. return {
  23461. get: get,
  23462. dispose: dispose
  23463. };
  23464. }
  23465. const LOD_MIN = 4;
  23466. // The standard deviations (radians) associated with the extra mips. These are
  23467. // chosen to approximate a Trowbridge-Reitz distribution function times the
  23468. // geometric shadowing function. These sigma values squared must match the
  23469. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  23470. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  23471. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  23472. // samples and exit early, but not recompile the shader.
  23473. const MAX_SAMPLES = 20;
  23474. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  23475. const _clearColor = /*@__PURE__*/ new Color();
  23476. let _oldTarget = null;
  23477. let _oldActiveCubeFace = 0;
  23478. let _oldActiveMipmapLevel = 0;
  23479. let _oldXrEnabled = false;
  23480. // Golden Ratio
  23481. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  23482. const INV_PHI = 1 / PHI;
  23483. // Vertices of a dodecahedron (except the opposites, which represent the
  23484. // same axis), used as axis directions evenly spread on a sphere.
  23485. const _axisDirections = [
  23486. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  23487. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  23488. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  23489. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  23490. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  23491. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  23492. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  23493. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  23494. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  23495. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  23496. /**
  23497. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  23498. * (PMREM) from a cubeMap environment texture. This allows different levels of
  23499. * blur to be quickly accessed based on material roughness. It is packed into a
  23500. * special CubeUV format that allows us to perform custom interpolation so that
  23501. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  23502. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  23503. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  23504. * higher roughness levels. In this way we maintain resolution to smoothly
  23505. * interpolate diffuse lighting while limiting sampling computation.
  23506. *
  23507. * Paper: Fast, Accurate Image-Based Lighting
  23508. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  23509. */
  23510. class PMREMGenerator {
  23511. constructor( renderer ) {
  23512. this._renderer = renderer;
  23513. this._pingPongRenderTarget = null;
  23514. this._lodMax = 0;
  23515. this._cubeSize = 0;
  23516. this._lodPlanes = [];
  23517. this._sizeLods = [];
  23518. this._sigmas = [];
  23519. this._blurMaterial = null;
  23520. this._cubemapMaterial = null;
  23521. this._equirectMaterial = null;
  23522. this._compileMaterial( this._blurMaterial );
  23523. }
  23524. /**
  23525. * Generates a PMREM from a supplied Scene, which can be faster than using an
  23526. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  23527. * in radians to be applied to the scene before PMREM generation. Optional near
  23528. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  23529. * is placed at the origin).
  23530. */
  23531. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  23532. _oldTarget = this._renderer.getRenderTarget();
  23533. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  23534. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  23535. _oldXrEnabled = this._renderer.xr.enabled;
  23536. this._renderer.xr.enabled = false;
  23537. this._setSize( 256 );
  23538. const cubeUVRenderTarget = this._allocateTargets();
  23539. cubeUVRenderTarget.depthBuffer = true;
  23540. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  23541. if ( sigma > 0 ) {
  23542. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  23543. }
  23544. this._applyPMREM( cubeUVRenderTarget );
  23545. this._cleanup( cubeUVRenderTarget );
  23546. return cubeUVRenderTarget;
  23547. }
  23548. /**
  23549. * Generates a PMREM from an equirectangular texture, which can be either LDR
  23550. * or HDR. The ideal input image size is 1k (1024 x 512),
  23551. * as this matches best with the 256 x 256 cubemap output.
  23552. * The smallest supported equirectangular image size is 64 x 32.
  23553. */
  23554. fromEquirectangular( equirectangular, renderTarget = null ) {
  23555. return this._fromTexture( equirectangular, renderTarget );
  23556. }
  23557. /**
  23558. * Generates a PMREM from an cubemap texture, which can be either LDR
  23559. * or HDR. The ideal input cube size is 256 x 256,
  23560. * as this matches best with the 256 x 256 cubemap output.
  23561. * The smallest supported cube size is 16 x 16.
  23562. */
  23563. fromCubemap( cubemap, renderTarget = null ) {
  23564. return this._fromTexture( cubemap, renderTarget );
  23565. }
  23566. /**
  23567. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  23568. * your texture's network fetch for increased concurrency.
  23569. */
  23570. compileCubemapShader() {
  23571. if ( this._cubemapMaterial === null ) {
  23572. this._cubemapMaterial = _getCubemapMaterial();
  23573. this._compileMaterial( this._cubemapMaterial );
  23574. }
  23575. }
  23576. /**
  23577. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  23578. * your texture's network fetch for increased concurrency.
  23579. */
  23580. compileEquirectangularShader() {
  23581. if ( this._equirectMaterial === null ) {
  23582. this._equirectMaterial = _getEquirectMaterial();
  23583. this._compileMaterial( this._equirectMaterial );
  23584. }
  23585. }
  23586. /**
  23587. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  23588. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  23589. * one of them will cause any others to also become unusable.
  23590. */
  23591. dispose() {
  23592. this._dispose();
  23593. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  23594. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  23595. }
  23596. // private interface
  23597. _setSize( cubeSize ) {
  23598. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  23599. this._cubeSize = Math.pow( 2, this._lodMax );
  23600. }
  23601. _dispose() {
  23602. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  23603. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  23604. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  23605. this._lodPlanes[ i ].dispose();
  23606. }
  23607. }
  23608. _cleanup( outputTarget ) {
  23609. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  23610. this._renderer.xr.enabled = _oldXrEnabled;
  23611. outputTarget.scissorTest = false;
  23612. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  23613. }
  23614. _fromTexture( texture, renderTarget ) {
  23615. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  23616. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  23617. } else { // Equirectangular
  23618. this._setSize( texture.image.width / 4 );
  23619. }
  23620. _oldTarget = this._renderer.getRenderTarget();
  23621. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  23622. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  23623. _oldXrEnabled = this._renderer.xr.enabled;
  23624. this._renderer.xr.enabled = false;
  23625. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  23626. this._textureToCubeUV( texture, cubeUVRenderTarget );
  23627. this._applyPMREM( cubeUVRenderTarget );
  23628. this._cleanup( cubeUVRenderTarget );
  23629. return cubeUVRenderTarget;
  23630. }
  23631. _allocateTargets() {
  23632. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  23633. const height = 4 * this._cubeSize;
  23634. const params = {
  23635. magFilter: LinearFilter,
  23636. minFilter: LinearFilter,
  23637. generateMipmaps: false,
  23638. type: HalfFloatType,
  23639. format: RGBAFormat,
  23640. colorSpace: LinearSRGBColorSpace,
  23641. depthBuffer: false
  23642. };
  23643. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  23644. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  23645. if ( this._pingPongRenderTarget !== null ) {
  23646. this._dispose();
  23647. }
  23648. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  23649. const { _lodMax } = this;
  23650. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  23651. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  23652. }
  23653. return cubeUVRenderTarget;
  23654. }
  23655. _compileMaterial( material ) {
  23656. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  23657. this._renderer.compile( tmpMesh, _flatCamera );
  23658. }
  23659. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  23660. const fov = 90;
  23661. const aspect = 1;
  23662. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  23663. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  23664. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  23665. const renderer = this._renderer;
  23666. const originalAutoClear = renderer.autoClear;
  23667. const toneMapping = renderer.toneMapping;
  23668. renderer.getClearColor( _clearColor );
  23669. renderer.toneMapping = NoToneMapping;
  23670. renderer.autoClear = false;
  23671. const backgroundMaterial = new MeshBasicMaterial( {
  23672. name: 'PMREM.Background',
  23673. side: BackSide,
  23674. depthWrite: false,
  23675. depthTest: false,
  23676. } );
  23677. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  23678. let useSolidColor = false;
  23679. const background = scene.background;
  23680. if ( background ) {
  23681. if ( background.isColor ) {
  23682. backgroundMaterial.color.copy( background );
  23683. scene.background = null;
  23684. useSolidColor = true;
  23685. }
  23686. } else {
  23687. backgroundMaterial.color.copy( _clearColor );
  23688. useSolidColor = true;
  23689. }
  23690. for ( let i = 0; i < 6; i ++ ) {
  23691. const col = i % 3;
  23692. if ( col === 0 ) {
  23693. cubeCamera.up.set( 0, upSign[ i ], 0 );
  23694. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  23695. } else if ( col === 1 ) {
  23696. cubeCamera.up.set( 0, 0, upSign[ i ] );
  23697. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  23698. } else {
  23699. cubeCamera.up.set( 0, upSign[ i ], 0 );
  23700. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  23701. }
  23702. const size = this._cubeSize;
  23703. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  23704. renderer.setRenderTarget( cubeUVRenderTarget );
  23705. if ( useSolidColor ) {
  23706. renderer.render( backgroundBox, cubeCamera );
  23707. }
  23708. renderer.render( scene, cubeCamera );
  23709. }
  23710. backgroundBox.geometry.dispose();
  23711. backgroundBox.material.dispose();
  23712. renderer.toneMapping = toneMapping;
  23713. renderer.autoClear = originalAutoClear;
  23714. scene.background = background;
  23715. }
  23716. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  23717. const renderer = this._renderer;
  23718. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  23719. if ( isCubeTexture ) {
  23720. if ( this._cubemapMaterial === null ) {
  23721. this._cubemapMaterial = _getCubemapMaterial();
  23722. }
  23723. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  23724. } else {
  23725. if ( this._equirectMaterial === null ) {
  23726. this._equirectMaterial = _getEquirectMaterial();
  23727. }
  23728. }
  23729. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  23730. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  23731. const uniforms = material.uniforms;
  23732. uniforms[ 'envMap' ].value = texture;
  23733. const size = this._cubeSize;
  23734. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  23735. renderer.setRenderTarget( cubeUVRenderTarget );
  23736. renderer.render( mesh, _flatCamera );
  23737. }
  23738. _applyPMREM( cubeUVRenderTarget ) {
  23739. const renderer = this._renderer;
  23740. const autoClear = renderer.autoClear;
  23741. renderer.autoClear = false;
  23742. const n = this._lodPlanes.length;
  23743. for ( let i = 1; i < n; i ++ ) {
  23744. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  23745. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  23746. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  23747. }
  23748. renderer.autoClear = autoClear;
  23749. }
  23750. /**
  23751. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  23752. * vertically and horizontally, but this breaks down on a cube. Here we apply
  23753. * the blur latitudinally (around the poles), and then longitudinally (towards
  23754. * the poles) to approximate the orthogonally-separable blur. It is least
  23755. * accurate at the poles, but still does a decent job.
  23756. */
  23757. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  23758. const pingPongRenderTarget = this._pingPongRenderTarget;
  23759. this._halfBlur(
  23760. cubeUVRenderTarget,
  23761. pingPongRenderTarget,
  23762. lodIn,
  23763. lodOut,
  23764. sigma,
  23765. 'latitudinal',
  23766. poleAxis );
  23767. this._halfBlur(
  23768. pingPongRenderTarget,
  23769. cubeUVRenderTarget,
  23770. lodOut,
  23771. lodOut,
  23772. sigma,
  23773. 'longitudinal',
  23774. poleAxis );
  23775. }
  23776. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  23777. const renderer = this._renderer;
  23778. const blurMaterial = this._blurMaterial;
  23779. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  23780. console.error(
  23781. 'blur direction must be either latitudinal or longitudinal!' );
  23782. }
  23783. // Number of standard deviations at which to cut off the discrete approximation.
  23784. const STANDARD_DEVIATIONS = 3;
  23785. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  23786. const blurUniforms = blurMaterial.uniforms;
  23787. const pixels = this._sizeLods[ lodIn ] - 1;
  23788. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  23789. const sigmaPixels = sigmaRadians / radiansPerPixel;
  23790. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  23791. if ( samples > MAX_SAMPLES ) {
  23792. console.warn( `sigmaRadians, ${
  23793. sigmaRadians}, is too large and will clip, as it requested ${
  23794. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  23795. }
  23796. const weights = [];
  23797. let sum = 0;
  23798. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  23799. const x = i / sigmaPixels;
  23800. const weight = Math.exp( - x * x / 2 );
  23801. weights.push( weight );
  23802. if ( i === 0 ) {
  23803. sum += weight;
  23804. } else if ( i < samples ) {
  23805. sum += 2 * weight;
  23806. }
  23807. }
  23808. for ( let i = 0; i < weights.length; i ++ ) {
  23809. weights[ i ] = weights[ i ] / sum;
  23810. }
  23811. blurUniforms[ 'envMap' ].value = targetIn.texture;
  23812. blurUniforms[ 'samples' ].value = samples;
  23813. blurUniforms[ 'weights' ].value = weights;
  23814. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  23815. if ( poleAxis ) {
  23816. blurUniforms[ 'poleAxis' ].value = poleAxis;
  23817. }
  23818. const { _lodMax } = this;
  23819. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  23820. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  23821. const outputSize = this._sizeLods[ lodOut ];
  23822. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  23823. const y = 4 * ( this._cubeSize - outputSize );
  23824. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  23825. renderer.setRenderTarget( targetOut );
  23826. renderer.render( blurMesh, _flatCamera );
  23827. }
  23828. }
  23829. function _createPlanes( lodMax ) {
  23830. const lodPlanes = [];
  23831. const sizeLods = [];
  23832. const sigmas = [];
  23833. let lod = lodMax;
  23834. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  23835. for ( let i = 0; i < totalLods; i ++ ) {
  23836. const sizeLod = Math.pow( 2, lod );
  23837. sizeLods.push( sizeLod );
  23838. let sigma = 1.0 / sizeLod;
  23839. if ( i > lodMax - LOD_MIN ) {
  23840. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  23841. } else if ( i === 0 ) {
  23842. sigma = 0;
  23843. }
  23844. sigmas.push( sigma );
  23845. const texelSize = 1.0 / ( sizeLod - 2 );
  23846. const min = - texelSize;
  23847. const max = 1 + texelSize;
  23848. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  23849. const cubeFaces = 6;
  23850. const vertices = 6;
  23851. const positionSize = 3;
  23852. const uvSize = 2;
  23853. const faceIndexSize = 1;
  23854. const position = new Float32Array( positionSize * vertices * cubeFaces );
  23855. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  23856. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  23857. for ( let face = 0; face < cubeFaces; face ++ ) {
  23858. const x = ( face % 3 ) * 2 / 3 - 1;
  23859. const y = face > 2 ? 0 : - 1;
  23860. const coordinates = [
  23861. x, y, 0,
  23862. x + 2 / 3, y, 0,
  23863. x + 2 / 3, y + 1, 0,
  23864. x, y, 0,
  23865. x + 2 / 3, y + 1, 0,
  23866. x, y + 1, 0
  23867. ];
  23868. position.set( coordinates, positionSize * vertices * face );
  23869. uv.set( uv1, uvSize * vertices * face );
  23870. const fill = [ face, face, face, face, face, face ];
  23871. faceIndex.set( fill, faceIndexSize * vertices * face );
  23872. }
  23873. const planes = new BufferGeometry();
  23874. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  23875. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  23876. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  23877. lodPlanes.push( planes );
  23878. if ( lod > LOD_MIN ) {
  23879. lod --;
  23880. }
  23881. }
  23882. return { lodPlanes, sizeLods, sigmas };
  23883. }
  23884. function _createRenderTarget( width, height, params ) {
  23885. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  23886. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  23887. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  23888. cubeUVRenderTarget.scissorTest = true;
  23889. return cubeUVRenderTarget;
  23890. }
  23891. function _setViewport( target, x, y, width, height ) {
  23892. target.viewport.set( x, y, width, height );
  23893. target.scissor.set( x, y, width, height );
  23894. }
  23895. function _getBlurShader( lodMax, width, height ) {
  23896. const weights = new Float32Array( MAX_SAMPLES );
  23897. const poleAxis = new Vector3( 0, 1, 0 );
  23898. const shaderMaterial = new ShaderMaterial( {
  23899. name: 'SphericalGaussianBlur',
  23900. defines: {
  23901. 'n': MAX_SAMPLES,
  23902. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  23903. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  23904. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  23905. },
  23906. uniforms: {
  23907. 'envMap': { value: null },
  23908. 'samples': { value: 1 },
  23909. 'weights': { value: weights },
  23910. 'latitudinal': { value: false },
  23911. 'dTheta': { value: 0 },
  23912. 'mipInt': { value: 0 },
  23913. 'poleAxis': { value: poleAxis }
  23914. },
  23915. vertexShader: _getCommonVertexShader(),
  23916. fragmentShader: /* glsl */`
  23917. precision mediump float;
  23918. precision mediump int;
  23919. varying vec3 vOutputDirection;
  23920. uniform sampler2D envMap;
  23921. uniform int samples;
  23922. uniform float weights[ n ];
  23923. uniform bool latitudinal;
  23924. uniform float dTheta;
  23925. uniform float mipInt;
  23926. uniform vec3 poleAxis;
  23927. #define ENVMAP_TYPE_CUBE_UV
  23928. #include <cube_uv_reflection_fragment>
  23929. vec3 getSample( float theta, vec3 axis ) {
  23930. float cosTheta = cos( theta );
  23931. // Rodrigues' axis-angle rotation
  23932. vec3 sampleDirection = vOutputDirection * cosTheta
  23933. + cross( axis, vOutputDirection ) * sin( theta )
  23934. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  23935. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  23936. }
  23937. void main() {
  23938. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  23939. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  23940. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  23941. }
  23942. axis = normalize( axis );
  23943. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  23944. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  23945. for ( int i = 1; i < n; i++ ) {
  23946. if ( i >= samples ) {
  23947. break;
  23948. }
  23949. float theta = dTheta * float( i );
  23950. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  23951. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  23952. }
  23953. }
  23954. `,
  23955. blending: NoBlending,
  23956. depthTest: false,
  23957. depthWrite: false
  23958. } );
  23959. return shaderMaterial;
  23960. }
  23961. function _getEquirectMaterial() {
  23962. return new ShaderMaterial( {
  23963. name: 'EquirectangularToCubeUV',
  23964. uniforms: {
  23965. 'envMap': { value: null }
  23966. },
  23967. vertexShader: _getCommonVertexShader(),
  23968. fragmentShader: /* glsl */`
  23969. precision mediump float;
  23970. precision mediump int;
  23971. varying vec3 vOutputDirection;
  23972. uniform sampler2D envMap;
  23973. #include <common>
  23974. void main() {
  23975. vec3 outputDirection = normalize( vOutputDirection );
  23976. vec2 uv = equirectUv( outputDirection );
  23977. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  23978. }
  23979. `,
  23980. blending: NoBlending,
  23981. depthTest: false,
  23982. depthWrite: false
  23983. } );
  23984. }
  23985. function _getCubemapMaterial() {
  23986. return new ShaderMaterial( {
  23987. name: 'CubemapToCubeUV',
  23988. uniforms: {
  23989. 'envMap': { value: null },
  23990. 'flipEnvMap': { value: - 1 }
  23991. },
  23992. vertexShader: _getCommonVertexShader(),
  23993. fragmentShader: /* glsl */`
  23994. precision mediump float;
  23995. precision mediump int;
  23996. uniform float flipEnvMap;
  23997. varying vec3 vOutputDirection;
  23998. uniform samplerCube envMap;
  23999. void main() {
  24000. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  24001. }
  24002. `,
  24003. blending: NoBlending,
  24004. depthTest: false,
  24005. depthWrite: false
  24006. } );
  24007. }
  24008. function _getCommonVertexShader() {
  24009. return /* glsl */`
  24010. precision mediump float;
  24011. precision mediump int;
  24012. attribute float faceIndex;
  24013. varying vec3 vOutputDirection;
  24014. // RH coordinate system; PMREM face-indexing convention
  24015. vec3 getDirection( vec2 uv, float face ) {
  24016. uv = 2.0 * uv - 1.0;
  24017. vec3 direction = vec3( uv, 1.0 );
  24018. if ( face == 0.0 ) {
  24019. direction = direction.zyx; // ( 1, v, u ) pos x
  24020. } else if ( face == 1.0 ) {
  24021. direction = direction.xzy;
  24022. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  24023. } else if ( face == 2.0 ) {
  24024. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  24025. } else if ( face == 3.0 ) {
  24026. direction = direction.zyx;
  24027. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  24028. } else if ( face == 4.0 ) {
  24029. direction = direction.xzy;
  24030. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  24031. } else if ( face == 5.0 ) {
  24032. direction.z *= -1.0; // ( u, v, -1 ) neg z
  24033. }
  24034. return direction;
  24035. }
  24036. void main() {
  24037. vOutputDirection = getDirection( uv, faceIndex );
  24038. gl_Position = vec4( position, 1.0 );
  24039. }
  24040. `;
  24041. }
  24042. function WebGLCubeUVMaps( renderer ) {
  24043. let cubeUVmaps = new WeakMap();
  24044. let pmremGenerator = null;
  24045. function get( texture ) {
  24046. if ( texture && texture.isTexture ) {
  24047. const mapping = texture.mapping;
  24048. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  24049. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  24050. // equirect/cube map to cubeUV conversion
  24051. if ( isEquirectMap || isCubeMap ) {
  24052. let renderTarget = cubeUVmaps.get( texture );
  24053. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  24054. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  24055. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  24056. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  24057. renderTarget.texture.pmremVersion = texture.pmremVersion;
  24058. cubeUVmaps.set( texture, renderTarget );
  24059. return renderTarget.texture;
  24060. } else {
  24061. if ( renderTarget !== undefined ) {
  24062. return renderTarget.texture;
  24063. } else {
  24064. const image = texture.image;
  24065. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  24066. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  24067. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  24068. renderTarget.texture.pmremVersion = texture.pmremVersion;
  24069. cubeUVmaps.set( texture, renderTarget );
  24070. texture.addEventListener( 'dispose', onTextureDispose );
  24071. return renderTarget.texture;
  24072. } else {
  24073. // image not yet ready. try the conversion next frame
  24074. return null;
  24075. }
  24076. }
  24077. }
  24078. }
  24079. }
  24080. return texture;
  24081. }
  24082. function isCubeTextureComplete( image ) {
  24083. let count = 0;
  24084. const length = 6;
  24085. for ( let i = 0; i < length; i ++ ) {
  24086. if ( image[ i ] !== undefined ) count ++;
  24087. }
  24088. return count === length;
  24089. }
  24090. function onTextureDispose( event ) {
  24091. const texture = event.target;
  24092. texture.removeEventListener( 'dispose', onTextureDispose );
  24093. const cubemapUV = cubeUVmaps.get( texture );
  24094. if ( cubemapUV !== undefined ) {
  24095. cubeUVmaps.delete( texture );
  24096. cubemapUV.dispose();
  24097. }
  24098. }
  24099. function dispose() {
  24100. cubeUVmaps = new WeakMap();
  24101. if ( pmremGenerator !== null ) {
  24102. pmremGenerator.dispose();
  24103. pmremGenerator = null;
  24104. }
  24105. }
  24106. return {
  24107. get: get,
  24108. dispose: dispose
  24109. };
  24110. }
  24111. function WebGLExtensions( gl ) {
  24112. const extensions = {};
  24113. function getExtension( name ) {
  24114. if ( extensions[ name ] !== undefined ) {
  24115. return extensions[ name ];
  24116. }
  24117. let extension;
  24118. switch ( name ) {
  24119. case 'WEBGL_depth_texture':
  24120. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  24121. break;
  24122. case 'EXT_texture_filter_anisotropic':
  24123. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  24124. break;
  24125. case 'WEBGL_compressed_texture_s3tc':
  24126. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  24127. break;
  24128. case 'WEBGL_compressed_texture_pvrtc':
  24129. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  24130. break;
  24131. default:
  24132. extension = gl.getExtension( name );
  24133. }
  24134. extensions[ name ] = extension;
  24135. return extension;
  24136. }
  24137. return {
  24138. has: function ( name ) {
  24139. return getExtension( name ) !== null;
  24140. },
  24141. init: function () {
  24142. getExtension( 'EXT_color_buffer_float' );
  24143. getExtension( 'WEBGL_clip_cull_distance' );
  24144. getExtension( 'OES_texture_float_linear' );
  24145. getExtension( 'EXT_color_buffer_half_float' );
  24146. getExtension( 'WEBGL_multisampled_render_to_texture' );
  24147. getExtension( 'WEBGL_render_shared_exponent' );
  24148. },
  24149. get: function ( name ) {
  24150. const extension = getExtension( name );
  24151. if ( extension === null ) {
  24152. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  24153. }
  24154. return extension;
  24155. }
  24156. };
  24157. }
  24158. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  24159. const geometries = {};
  24160. const wireframeAttributes = new WeakMap();
  24161. function onGeometryDispose( event ) {
  24162. const geometry = event.target;
  24163. if ( geometry.index !== null ) {
  24164. attributes.remove( geometry.index );
  24165. }
  24166. for ( const name in geometry.attributes ) {
  24167. attributes.remove( geometry.attributes[ name ] );
  24168. }
  24169. geometry.removeEventListener( 'dispose', onGeometryDispose );
  24170. delete geometries[ geometry.id ];
  24171. const attribute = wireframeAttributes.get( geometry );
  24172. if ( attribute ) {
  24173. attributes.remove( attribute );
  24174. wireframeAttributes.delete( geometry );
  24175. }
  24176. bindingStates.releaseStatesOfGeometry( geometry );
  24177. if ( geometry.isInstancedBufferGeometry === true ) {
  24178. delete geometry._maxInstanceCount;
  24179. }
  24180. //
  24181. info.memory.geometries --;
  24182. }
  24183. function get( object, geometry ) {
  24184. if ( geometries[ geometry.id ] === true ) return geometry;
  24185. geometry.addEventListener( 'dispose', onGeometryDispose );
  24186. geometries[ geometry.id ] = true;
  24187. info.memory.geometries ++;
  24188. return geometry;
  24189. }
  24190. function update( geometry ) {
  24191. const geometryAttributes = geometry.attributes;
  24192. // Updating index buffer in VAO now. See WebGLBindingStates.
  24193. for ( const name in geometryAttributes ) {
  24194. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  24195. }
  24196. }
  24197. function updateWireframeAttribute( geometry ) {
  24198. const indices = [];
  24199. const geometryIndex = geometry.index;
  24200. const geometryPosition = geometry.attributes.position;
  24201. let version = 0;
  24202. if ( geometryIndex !== null ) {
  24203. const array = geometryIndex.array;
  24204. version = geometryIndex.version;
  24205. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  24206. const a = array[ i + 0 ];
  24207. const b = array[ i + 1 ];
  24208. const c = array[ i + 2 ];
  24209. indices.push( a, b, b, c, c, a );
  24210. }
  24211. } else if ( geometryPosition !== undefined ) {
  24212. const array = geometryPosition.array;
  24213. version = geometryPosition.version;
  24214. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  24215. const a = i + 0;
  24216. const b = i + 1;
  24217. const c = i + 2;
  24218. indices.push( a, b, b, c, c, a );
  24219. }
  24220. } else {
  24221. return;
  24222. }
  24223. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  24224. attribute.version = version;
  24225. // Updating index buffer in VAO now. See WebGLBindingStates
  24226. //
  24227. const previousAttribute = wireframeAttributes.get( geometry );
  24228. if ( previousAttribute ) attributes.remove( previousAttribute );
  24229. //
  24230. wireframeAttributes.set( geometry, attribute );
  24231. }
  24232. function getWireframeAttribute( geometry ) {
  24233. const currentAttribute = wireframeAttributes.get( geometry );
  24234. if ( currentAttribute ) {
  24235. const geometryIndex = geometry.index;
  24236. if ( geometryIndex !== null ) {
  24237. // if the attribute is obsolete, create a new one
  24238. if ( currentAttribute.version < geometryIndex.version ) {
  24239. updateWireframeAttribute( geometry );
  24240. }
  24241. }
  24242. } else {
  24243. updateWireframeAttribute( geometry );
  24244. }
  24245. return wireframeAttributes.get( geometry );
  24246. }
  24247. return {
  24248. get: get,
  24249. update: update,
  24250. getWireframeAttribute: getWireframeAttribute
  24251. };
  24252. }
  24253. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  24254. let mode;
  24255. function setMode( value ) {
  24256. mode = value;
  24257. }
  24258. let type, bytesPerElement;
  24259. function setIndex( value ) {
  24260. type = value.type;
  24261. bytesPerElement = value.bytesPerElement;
  24262. }
  24263. function render( start, count ) {
  24264. gl.drawElements( mode, count, type, start * bytesPerElement );
  24265. info.update( count, mode, 1 );
  24266. }
  24267. function renderInstances( start, count, primcount ) {
  24268. if ( primcount === 0 ) return;
  24269. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  24270. info.update( count, mode, primcount );
  24271. }
  24272. function renderMultiDraw( starts, counts, drawCount ) {
  24273. if ( drawCount === 0 ) return;
  24274. const extension = extensions.get( 'WEBGL_multi_draw' );
  24275. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  24276. let elementCount = 0;
  24277. for ( let i = 0; i < drawCount; i ++ ) {
  24278. elementCount += counts[ i ];
  24279. }
  24280. info.update( elementCount, mode, 1 );
  24281. }
  24282. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  24283. if ( drawCount === 0 ) return;
  24284. const extension = extensions.get( 'WEBGL_multi_draw' );
  24285. if ( extension === null ) {
  24286. for ( let i = 0; i < starts.length; i ++ ) {
  24287. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  24288. }
  24289. } else {
  24290. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  24291. let elementCount = 0;
  24292. for ( let i = 0; i < drawCount; i ++ ) {
  24293. elementCount += counts[ i ] * primcount[ i ];
  24294. }
  24295. info.update( elementCount, mode, 1 );
  24296. }
  24297. }
  24298. //
  24299. this.setMode = setMode;
  24300. this.setIndex = setIndex;
  24301. this.render = render;
  24302. this.renderInstances = renderInstances;
  24303. this.renderMultiDraw = renderMultiDraw;
  24304. this.renderMultiDrawInstances = renderMultiDrawInstances;
  24305. }
  24306. function WebGLInfo( gl ) {
  24307. const memory = {
  24308. geometries: 0,
  24309. textures: 0
  24310. };
  24311. const render = {
  24312. frame: 0,
  24313. calls: 0,
  24314. triangles: 0,
  24315. points: 0,
  24316. lines: 0
  24317. };
  24318. function update( count, mode, instanceCount ) {
  24319. render.calls ++;
  24320. switch ( mode ) {
  24321. case gl.TRIANGLES:
  24322. render.triangles += instanceCount * ( count / 3 );
  24323. break;
  24324. case gl.LINES:
  24325. render.lines += instanceCount * ( count / 2 );
  24326. break;
  24327. case gl.LINE_STRIP:
  24328. render.lines += instanceCount * ( count - 1 );
  24329. break;
  24330. case gl.LINE_LOOP:
  24331. render.lines += instanceCount * count;
  24332. break;
  24333. case gl.POINTS:
  24334. render.points += instanceCount * count;
  24335. break;
  24336. default:
  24337. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  24338. break;
  24339. }
  24340. }
  24341. function reset() {
  24342. render.calls = 0;
  24343. render.triangles = 0;
  24344. render.points = 0;
  24345. render.lines = 0;
  24346. }
  24347. return {
  24348. memory: memory,
  24349. render: render,
  24350. programs: null,
  24351. autoReset: true,
  24352. reset: reset,
  24353. update: update
  24354. };
  24355. }
  24356. function WebGLMorphtargets( gl, capabilities, textures ) {
  24357. const morphTextures = new WeakMap();
  24358. const morph = new Vector4();
  24359. function update( object, geometry, program ) {
  24360. const objectInfluences = object.morphTargetInfluences;
  24361. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  24362. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  24363. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  24364. let entry = morphTextures.get( geometry );
  24365. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  24366. if ( entry !== undefined ) entry.texture.dispose();
  24367. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  24368. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  24369. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  24370. const morphTargets = geometry.morphAttributes.position || [];
  24371. const morphNormals = geometry.morphAttributes.normal || [];
  24372. const morphColors = geometry.morphAttributes.color || [];
  24373. let vertexDataCount = 0;
  24374. if ( hasMorphPosition === true ) vertexDataCount = 1;
  24375. if ( hasMorphNormals === true ) vertexDataCount = 2;
  24376. if ( hasMorphColors === true ) vertexDataCount = 3;
  24377. let width = geometry.attributes.position.count * vertexDataCount;
  24378. let height = 1;
  24379. if ( width > capabilities.maxTextureSize ) {
  24380. height = Math.ceil( width / capabilities.maxTextureSize );
  24381. width = capabilities.maxTextureSize;
  24382. }
  24383. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  24384. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  24385. texture.type = FloatType;
  24386. texture.needsUpdate = true;
  24387. // fill buffer
  24388. const vertexDataStride = vertexDataCount * 4;
  24389. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  24390. const morphTarget = morphTargets[ i ];
  24391. const morphNormal = morphNormals[ i ];
  24392. const morphColor = morphColors[ i ];
  24393. const offset = width * height * 4 * i;
  24394. for ( let j = 0; j < morphTarget.count; j ++ ) {
  24395. const stride = j * vertexDataStride;
  24396. if ( hasMorphPosition === true ) {
  24397. morph.fromBufferAttribute( morphTarget, j );
  24398. buffer[ offset + stride + 0 ] = morph.x;
  24399. buffer[ offset + stride + 1 ] = morph.y;
  24400. buffer[ offset + stride + 2 ] = morph.z;
  24401. buffer[ offset + stride + 3 ] = 0;
  24402. }
  24403. if ( hasMorphNormals === true ) {
  24404. morph.fromBufferAttribute( morphNormal, j );
  24405. buffer[ offset + stride + 4 ] = morph.x;
  24406. buffer[ offset + stride + 5 ] = morph.y;
  24407. buffer[ offset + stride + 6 ] = morph.z;
  24408. buffer[ offset + stride + 7 ] = 0;
  24409. }
  24410. if ( hasMorphColors === true ) {
  24411. morph.fromBufferAttribute( morphColor, j );
  24412. buffer[ offset + stride + 8 ] = morph.x;
  24413. buffer[ offset + stride + 9 ] = morph.y;
  24414. buffer[ offset + stride + 10 ] = morph.z;
  24415. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  24416. }
  24417. }
  24418. }
  24419. entry = {
  24420. count: morphTargetsCount,
  24421. texture: texture,
  24422. size: new Vector2( width, height )
  24423. };
  24424. morphTextures.set( geometry, entry );
  24425. function disposeTexture() {
  24426. texture.dispose();
  24427. morphTextures.delete( geometry );
  24428. geometry.removeEventListener( 'dispose', disposeTexture );
  24429. }
  24430. geometry.addEventListener( 'dispose', disposeTexture );
  24431. }
  24432. //
  24433. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  24434. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  24435. } else {
  24436. let morphInfluencesSum = 0;
  24437. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  24438. morphInfluencesSum += objectInfluences[ i ];
  24439. }
  24440. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  24441. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  24442. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  24443. }
  24444. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  24445. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  24446. }
  24447. return {
  24448. update: update
  24449. };
  24450. }
  24451. function WebGLObjects( gl, geometries, attributes, info ) {
  24452. let updateMap = new WeakMap();
  24453. function update( object ) {
  24454. const frame = info.render.frame;
  24455. const geometry = object.geometry;
  24456. const buffergeometry = geometries.get( object, geometry );
  24457. // Update once per frame
  24458. if ( updateMap.get( buffergeometry ) !== frame ) {
  24459. geometries.update( buffergeometry );
  24460. updateMap.set( buffergeometry, frame );
  24461. }
  24462. if ( object.isInstancedMesh ) {
  24463. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  24464. object.addEventListener( 'dispose', onInstancedMeshDispose );
  24465. }
  24466. if ( updateMap.get( object ) !== frame ) {
  24467. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  24468. if ( object.instanceColor !== null ) {
  24469. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  24470. }
  24471. updateMap.set( object, frame );
  24472. }
  24473. }
  24474. if ( object.isSkinnedMesh ) {
  24475. const skeleton = object.skeleton;
  24476. if ( updateMap.get( skeleton ) !== frame ) {
  24477. skeleton.update();
  24478. updateMap.set( skeleton, frame );
  24479. }
  24480. }
  24481. return buffergeometry;
  24482. }
  24483. function dispose() {
  24484. updateMap = new WeakMap();
  24485. }
  24486. function onInstancedMeshDispose( event ) {
  24487. const instancedMesh = event.target;
  24488. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  24489. attributes.remove( instancedMesh.instanceMatrix );
  24490. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  24491. }
  24492. return {
  24493. update: update,
  24494. dispose: dispose
  24495. };
  24496. }
  24497. /**
  24498. * Uniforms of a program.
  24499. * Those form a tree structure with a special top-level container for the root,
  24500. * which you get by calling 'new WebGLUniforms( gl, program )'.
  24501. *
  24502. *
  24503. * Properties of inner nodes including the top-level container:
  24504. *
  24505. * .seq - array of nested uniforms
  24506. * .map - nested uniforms by name
  24507. *
  24508. *
  24509. * Methods of all nodes except the top-level container:
  24510. *
  24511. * .setValue( gl, value, [textures] )
  24512. *
  24513. * uploads a uniform value(s)
  24514. * the 'textures' parameter is needed for sampler uniforms
  24515. *
  24516. *
  24517. * Static methods of the top-level container (textures factorizations):
  24518. *
  24519. * .upload( gl, seq, values, textures )
  24520. *
  24521. * sets uniforms in 'seq' to 'values[id].value'
  24522. *
  24523. * .seqWithValue( seq, values ) : filteredSeq
  24524. *
  24525. * filters 'seq' entries with corresponding entry in values
  24526. *
  24527. *
  24528. * Methods of the top-level container (textures factorizations):
  24529. *
  24530. * .setValue( gl, name, value, textures )
  24531. *
  24532. * sets uniform with name 'name' to 'value'
  24533. *
  24534. * .setOptional( gl, obj, prop )
  24535. *
  24536. * like .set for an optional property of the object
  24537. *
  24538. */
  24539. const emptyTexture = /*@__PURE__*/ new Texture();
  24540. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  24541. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  24542. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  24543. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  24544. // --- Utilities ---
  24545. // Array Caches (provide typed arrays for temporary by size)
  24546. const arrayCacheF32 = [];
  24547. const arrayCacheI32 = [];
  24548. // Float32Array caches used for uploading Matrix uniforms
  24549. const mat4array = new Float32Array( 16 );
  24550. const mat3array = new Float32Array( 9 );
  24551. const mat2array = new Float32Array( 4 );
  24552. // Flattening for arrays of vectors and matrices
  24553. function flatten( array, nBlocks, blockSize ) {
  24554. const firstElem = array[ 0 ];
  24555. if ( firstElem <= 0 || firstElem > 0 ) return array;
  24556. // unoptimized: ! isNaN( firstElem )
  24557. // see http://jacksondunstan.com/articles/983
  24558. const n = nBlocks * blockSize;
  24559. let r = arrayCacheF32[ n ];
  24560. if ( r === undefined ) {
  24561. r = new Float32Array( n );
  24562. arrayCacheF32[ n ] = r;
  24563. }
  24564. if ( nBlocks !== 0 ) {
  24565. firstElem.toArray( r, 0 );
  24566. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  24567. offset += blockSize;
  24568. array[ i ].toArray( r, offset );
  24569. }
  24570. }
  24571. return r;
  24572. }
  24573. function arraysEqual( a, b ) {
  24574. if ( a.length !== b.length ) return false;
  24575. for ( let i = 0, l = a.length; i < l; i ++ ) {
  24576. if ( a[ i ] !== b[ i ] ) return false;
  24577. }
  24578. return true;
  24579. }
  24580. function copyArray( a, b ) {
  24581. for ( let i = 0, l = b.length; i < l; i ++ ) {
  24582. a[ i ] = b[ i ];
  24583. }
  24584. }
  24585. // Texture unit allocation
  24586. function allocTexUnits( textures, n ) {
  24587. let r = arrayCacheI32[ n ];
  24588. if ( r === undefined ) {
  24589. r = new Int32Array( n );
  24590. arrayCacheI32[ n ] = r;
  24591. }
  24592. for ( let i = 0; i !== n; ++ i ) {
  24593. r[ i ] = textures.allocateTextureUnit();
  24594. }
  24595. return r;
  24596. }
  24597. // --- Setters ---
  24598. // Note: Defining these methods externally, because they come in a bunch
  24599. // and this way their names minify.
  24600. // Single scalar
  24601. function setValueV1f( gl, v ) {
  24602. const cache = this.cache;
  24603. if ( cache[ 0 ] === v ) return;
  24604. gl.uniform1f( this.addr, v );
  24605. cache[ 0 ] = v;
  24606. }
  24607. // Single float vector (from flat array or THREE.VectorN)
  24608. function setValueV2f( gl, v ) {
  24609. const cache = this.cache;
  24610. if ( v.x !== undefined ) {
  24611. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  24612. gl.uniform2f( this.addr, v.x, v.y );
  24613. cache[ 0 ] = v.x;
  24614. cache[ 1 ] = v.y;
  24615. }
  24616. } else {
  24617. if ( arraysEqual( cache, v ) ) return;
  24618. gl.uniform2fv( this.addr, v );
  24619. copyArray( cache, v );
  24620. }
  24621. }
  24622. function setValueV3f( gl, v ) {
  24623. const cache = this.cache;
  24624. if ( v.x !== undefined ) {
  24625. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  24626. gl.uniform3f( this.addr, v.x, v.y, v.z );
  24627. cache[ 0 ] = v.x;
  24628. cache[ 1 ] = v.y;
  24629. cache[ 2 ] = v.z;
  24630. }
  24631. } else if ( v.r !== undefined ) {
  24632. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  24633. gl.uniform3f( this.addr, v.r, v.g, v.b );
  24634. cache[ 0 ] = v.r;
  24635. cache[ 1 ] = v.g;
  24636. cache[ 2 ] = v.b;
  24637. }
  24638. } else {
  24639. if ( arraysEqual( cache, v ) ) return;
  24640. gl.uniform3fv( this.addr, v );
  24641. copyArray( cache, v );
  24642. }
  24643. }
  24644. function setValueV4f( gl, v ) {
  24645. const cache = this.cache;
  24646. if ( v.x !== undefined ) {
  24647. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  24648. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  24649. cache[ 0 ] = v.x;
  24650. cache[ 1 ] = v.y;
  24651. cache[ 2 ] = v.z;
  24652. cache[ 3 ] = v.w;
  24653. }
  24654. } else {
  24655. if ( arraysEqual( cache, v ) ) return;
  24656. gl.uniform4fv( this.addr, v );
  24657. copyArray( cache, v );
  24658. }
  24659. }
  24660. // Single matrix (from flat array or THREE.MatrixN)
  24661. function setValueM2( gl, v ) {
  24662. const cache = this.cache;
  24663. const elements = v.elements;
  24664. if ( elements === undefined ) {
  24665. if ( arraysEqual( cache, v ) ) return;
  24666. gl.uniformMatrix2fv( this.addr, false, v );
  24667. copyArray( cache, v );
  24668. } else {
  24669. if ( arraysEqual( cache, elements ) ) return;
  24670. mat2array.set( elements );
  24671. gl.uniformMatrix2fv( this.addr, false, mat2array );
  24672. copyArray( cache, elements );
  24673. }
  24674. }
  24675. function setValueM3( gl, v ) {
  24676. const cache = this.cache;
  24677. const elements = v.elements;
  24678. if ( elements === undefined ) {
  24679. if ( arraysEqual( cache, v ) ) return;
  24680. gl.uniformMatrix3fv( this.addr, false, v );
  24681. copyArray( cache, v );
  24682. } else {
  24683. if ( arraysEqual( cache, elements ) ) return;
  24684. mat3array.set( elements );
  24685. gl.uniformMatrix3fv( this.addr, false, mat3array );
  24686. copyArray( cache, elements );
  24687. }
  24688. }
  24689. function setValueM4( gl, v ) {
  24690. const cache = this.cache;
  24691. const elements = v.elements;
  24692. if ( elements === undefined ) {
  24693. if ( arraysEqual( cache, v ) ) return;
  24694. gl.uniformMatrix4fv( this.addr, false, v );
  24695. copyArray( cache, v );
  24696. } else {
  24697. if ( arraysEqual( cache, elements ) ) return;
  24698. mat4array.set( elements );
  24699. gl.uniformMatrix4fv( this.addr, false, mat4array );
  24700. copyArray( cache, elements );
  24701. }
  24702. }
  24703. // Single integer / boolean
  24704. function setValueV1i( gl, v ) {
  24705. const cache = this.cache;
  24706. if ( cache[ 0 ] === v ) return;
  24707. gl.uniform1i( this.addr, v );
  24708. cache[ 0 ] = v;
  24709. }
  24710. // Single integer / boolean vector (from flat array or THREE.VectorN)
  24711. function setValueV2i( gl, v ) {
  24712. const cache = this.cache;
  24713. if ( v.x !== undefined ) {
  24714. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  24715. gl.uniform2i( this.addr, v.x, v.y );
  24716. cache[ 0 ] = v.x;
  24717. cache[ 1 ] = v.y;
  24718. }
  24719. } else {
  24720. if ( arraysEqual( cache, v ) ) return;
  24721. gl.uniform2iv( this.addr, v );
  24722. copyArray( cache, v );
  24723. }
  24724. }
  24725. function setValueV3i( gl, v ) {
  24726. const cache = this.cache;
  24727. if ( v.x !== undefined ) {
  24728. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  24729. gl.uniform3i( this.addr, v.x, v.y, v.z );
  24730. cache[ 0 ] = v.x;
  24731. cache[ 1 ] = v.y;
  24732. cache[ 2 ] = v.z;
  24733. }
  24734. } else {
  24735. if ( arraysEqual( cache, v ) ) return;
  24736. gl.uniform3iv( this.addr, v );
  24737. copyArray( cache, v );
  24738. }
  24739. }
  24740. function setValueV4i( gl, v ) {
  24741. const cache = this.cache;
  24742. if ( v.x !== undefined ) {
  24743. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  24744. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  24745. cache[ 0 ] = v.x;
  24746. cache[ 1 ] = v.y;
  24747. cache[ 2 ] = v.z;
  24748. cache[ 3 ] = v.w;
  24749. }
  24750. } else {
  24751. if ( arraysEqual( cache, v ) ) return;
  24752. gl.uniform4iv( this.addr, v );
  24753. copyArray( cache, v );
  24754. }
  24755. }
  24756. // Single unsigned integer
  24757. function setValueV1ui( gl, v ) {
  24758. const cache = this.cache;
  24759. if ( cache[ 0 ] === v ) return;
  24760. gl.uniform1ui( this.addr, v );
  24761. cache[ 0 ] = v;
  24762. }
  24763. // Single unsigned integer vector (from flat array or THREE.VectorN)
  24764. function setValueV2ui( gl, v ) {
  24765. const cache = this.cache;
  24766. if ( v.x !== undefined ) {
  24767. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  24768. gl.uniform2ui( this.addr, v.x, v.y );
  24769. cache[ 0 ] = v.x;
  24770. cache[ 1 ] = v.y;
  24771. }
  24772. } else {
  24773. if ( arraysEqual( cache, v ) ) return;
  24774. gl.uniform2uiv( this.addr, v );
  24775. copyArray( cache, v );
  24776. }
  24777. }
  24778. function setValueV3ui( gl, v ) {
  24779. const cache = this.cache;
  24780. if ( v.x !== undefined ) {
  24781. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  24782. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  24783. cache[ 0 ] = v.x;
  24784. cache[ 1 ] = v.y;
  24785. cache[ 2 ] = v.z;
  24786. }
  24787. } else {
  24788. if ( arraysEqual( cache, v ) ) return;
  24789. gl.uniform3uiv( this.addr, v );
  24790. copyArray( cache, v );
  24791. }
  24792. }
  24793. function setValueV4ui( gl, v ) {
  24794. const cache = this.cache;
  24795. if ( v.x !== undefined ) {
  24796. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  24797. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  24798. cache[ 0 ] = v.x;
  24799. cache[ 1 ] = v.y;
  24800. cache[ 2 ] = v.z;
  24801. cache[ 3 ] = v.w;
  24802. }
  24803. } else {
  24804. if ( arraysEqual( cache, v ) ) return;
  24805. gl.uniform4uiv( this.addr, v );
  24806. copyArray( cache, v );
  24807. }
  24808. }
  24809. // Single texture (2D / Cube)
  24810. function setValueT1( gl, v, textures ) {
  24811. const cache = this.cache;
  24812. const unit = textures.allocateTextureUnit();
  24813. if ( cache[ 0 ] !== unit ) {
  24814. gl.uniform1i( this.addr, unit );
  24815. cache[ 0 ] = unit;
  24816. }
  24817. let emptyTexture2D;
  24818. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  24819. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  24820. emptyTexture2D = emptyShadowTexture;
  24821. } else {
  24822. emptyTexture2D = emptyTexture;
  24823. }
  24824. textures.setTexture2D( v || emptyTexture2D, unit );
  24825. }
  24826. function setValueT3D1( gl, v, textures ) {
  24827. const cache = this.cache;
  24828. const unit = textures.allocateTextureUnit();
  24829. if ( cache[ 0 ] !== unit ) {
  24830. gl.uniform1i( this.addr, unit );
  24831. cache[ 0 ] = unit;
  24832. }
  24833. textures.setTexture3D( v || empty3dTexture, unit );
  24834. }
  24835. function setValueT6( gl, v, textures ) {
  24836. const cache = this.cache;
  24837. const unit = textures.allocateTextureUnit();
  24838. if ( cache[ 0 ] !== unit ) {
  24839. gl.uniform1i( this.addr, unit );
  24840. cache[ 0 ] = unit;
  24841. }
  24842. textures.setTextureCube( v || emptyCubeTexture, unit );
  24843. }
  24844. function setValueT2DArray1( gl, v, textures ) {
  24845. const cache = this.cache;
  24846. const unit = textures.allocateTextureUnit();
  24847. if ( cache[ 0 ] !== unit ) {
  24848. gl.uniform1i( this.addr, unit );
  24849. cache[ 0 ] = unit;
  24850. }
  24851. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  24852. }
  24853. // Helper to pick the right setter for the singular case
  24854. function getSingularSetter( type ) {
  24855. switch ( type ) {
  24856. case 0x1406: return setValueV1f; // FLOAT
  24857. case 0x8b50: return setValueV2f; // _VEC2
  24858. case 0x8b51: return setValueV3f; // _VEC3
  24859. case 0x8b52: return setValueV4f; // _VEC4
  24860. case 0x8b5a: return setValueM2; // _MAT2
  24861. case 0x8b5b: return setValueM3; // _MAT3
  24862. case 0x8b5c: return setValueM4; // _MAT4
  24863. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  24864. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  24865. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  24866. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  24867. case 0x1405: return setValueV1ui; // UINT
  24868. case 0x8dc6: return setValueV2ui; // _VEC2
  24869. case 0x8dc7: return setValueV3ui; // _VEC3
  24870. case 0x8dc8: return setValueV4ui; // _VEC4
  24871. case 0x8b5e: // SAMPLER_2D
  24872. case 0x8d66: // SAMPLER_EXTERNAL_OES
  24873. case 0x8dca: // INT_SAMPLER_2D
  24874. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  24875. case 0x8b62: // SAMPLER_2D_SHADOW
  24876. return setValueT1;
  24877. case 0x8b5f: // SAMPLER_3D
  24878. case 0x8dcb: // INT_SAMPLER_3D
  24879. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  24880. return setValueT3D1;
  24881. case 0x8b60: // SAMPLER_CUBE
  24882. case 0x8dcc: // INT_SAMPLER_CUBE
  24883. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  24884. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  24885. return setValueT6;
  24886. case 0x8dc1: // SAMPLER_2D_ARRAY
  24887. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  24888. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  24889. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  24890. return setValueT2DArray1;
  24891. }
  24892. }
  24893. // Array of scalars
  24894. function setValueV1fArray( gl, v ) {
  24895. gl.uniform1fv( this.addr, v );
  24896. }
  24897. // Array of vectors (from flat array or array of THREE.VectorN)
  24898. function setValueV2fArray( gl, v ) {
  24899. const data = flatten( v, this.size, 2 );
  24900. gl.uniform2fv( this.addr, data );
  24901. }
  24902. function setValueV3fArray( gl, v ) {
  24903. const data = flatten( v, this.size, 3 );
  24904. gl.uniform3fv( this.addr, data );
  24905. }
  24906. function setValueV4fArray( gl, v ) {
  24907. const data = flatten( v, this.size, 4 );
  24908. gl.uniform4fv( this.addr, data );
  24909. }
  24910. // Array of matrices (from flat array or array of THREE.MatrixN)
  24911. function setValueM2Array( gl, v ) {
  24912. const data = flatten( v, this.size, 4 );
  24913. gl.uniformMatrix2fv( this.addr, false, data );
  24914. }
  24915. function setValueM3Array( gl, v ) {
  24916. const data = flatten( v, this.size, 9 );
  24917. gl.uniformMatrix3fv( this.addr, false, data );
  24918. }
  24919. function setValueM4Array( gl, v ) {
  24920. const data = flatten( v, this.size, 16 );
  24921. gl.uniformMatrix4fv( this.addr, false, data );
  24922. }
  24923. // Array of integer / boolean
  24924. function setValueV1iArray( gl, v ) {
  24925. gl.uniform1iv( this.addr, v );
  24926. }
  24927. // Array of integer / boolean vectors (from flat array)
  24928. function setValueV2iArray( gl, v ) {
  24929. gl.uniform2iv( this.addr, v );
  24930. }
  24931. function setValueV3iArray( gl, v ) {
  24932. gl.uniform3iv( this.addr, v );
  24933. }
  24934. function setValueV4iArray( gl, v ) {
  24935. gl.uniform4iv( this.addr, v );
  24936. }
  24937. // Array of unsigned integer
  24938. function setValueV1uiArray( gl, v ) {
  24939. gl.uniform1uiv( this.addr, v );
  24940. }
  24941. // Array of unsigned integer vectors (from flat array)
  24942. function setValueV2uiArray( gl, v ) {
  24943. gl.uniform2uiv( this.addr, v );
  24944. }
  24945. function setValueV3uiArray( gl, v ) {
  24946. gl.uniform3uiv( this.addr, v );
  24947. }
  24948. function setValueV4uiArray( gl, v ) {
  24949. gl.uniform4uiv( this.addr, v );
  24950. }
  24951. // Array of textures (2D / 3D / Cube / 2DArray)
  24952. function setValueT1Array( gl, v, textures ) {
  24953. const cache = this.cache;
  24954. const n = v.length;
  24955. const units = allocTexUnits( textures, n );
  24956. if ( ! arraysEqual( cache, units ) ) {
  24957. gl.uniform1iv( this.addr, units );
  24958. copyArray( cache, units );
  24959. }
  24960. for ( let i = 0; i !== n; ++ i ) {
  24961. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  24962. }
  24963. }
  24964. function setValueT3DArray( gl, v, textures ) {
  24965. const cache = this.cache;
  24966. const n = v.length;
  24967. const units = allocTexUnits( textures, n );
  24968. if ( ! arraysEqual( cache, units ) ) {
  24969. gl.uniform1iv( this.addr, units );
  24970. copyArray( cache, units );
  24971. }
  24972. for ( let i = 0; i !== n; ++ i ) {
  24973. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  24974. }
  24975. }
  24976. function setValueT6Array( gl, v, textures ) {
  24977. const cache = this.cache;
  24978. const n = v.length;
  24979. const units = allocTexUnits( textures, n );
  24980. if ( ! arraysEqual( cache, units ) ) {
  24981. gl.uniform1iv( this.addr, units );
  24982. copyArray( cache, units );
  24983. }
  24984. for ( let i = 0; i !== n; ++ i ) {
  24985. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  24986. }
  24987. }
  24988. function setValueT2DArrayArray( gl, v, textures ) {
  24989. const cache = this.cache;
  24990. const n = v.length;
  24991. const units = allocTexUnits( textures, n );
  24992. if ( ! arraysEqual( cache, units ) ) {
  24993. gl.uniform1iv( this.addr, units );
  24994. copyArray( cache, units );
  24995. }
  24996. for ( let i = 0; i !== n; ++ i ) {
  24997. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  24998. }
  24999. }
  25000. // Helper to pick the right setter for a pure (bottom-level) array
  25001. function getPureArraySetter( type ) {
  25002. switch ( type ) {
  25003. case 0x1406: return setValueV1fArray; // FLOAT
  25004. case 0x8b50: return setValueV2fArray; // _VEC2
  25005. case 0x8b51: return setValueV3fArray; // _VEC3
  25006. case 0x8b52: return setValueV4fArray; // _VEC4
  25007. case 0x8b5a: return setValueM2Array; // _MAT2
  25008. case 0x8b5b: return setValueM3Array; // _MAT3
  25009. case 0x8b5c: return setValueM4Array; // _MAT4
  25010. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  25011. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  25012. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  25013. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  25014. case 0x1405: return setValueV1uiArray; // UINT
  25015. case 0x8dc6: return setValueV2uiArray; // _VEC2
  25016. case 0x8dc7: return setValueV3uiArray; // _VEC3
  25017. case 0x8dc8: return setValueV4uiArray; // _VEC4
  25018. case 0x8b5e: // SAMPLER_2D
  25019. case 0x8d66: // SAMPLER_EXTERNAL_OES
  25020. case 0x8dca: // INT_SAMPLER_2D
  25021. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  25022. case 0x8b62: // SAMPLER_2D_SHADOW
  25023. return setValueT1Array;
  25024. case 0x8b5f: // SAMPLER_3D
  25025. case 0x8dcb: // INT_SAMPLER_3D
  25026. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  25027. return setValueT3DArray;
  25028. case 0x8b60: // SAMPLER_CUBE
  25029. case 0x8dcc: // INT_SAMPLER_CUBE
  25030. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  25031. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  25032. return setValueT6Array;
  25033. case 0x8dc1: // SAMPLER_2D_ARRAY
  25034. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  25035. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  25036. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  25037. return setValueT2DArrayArray;
  25038. }
  25039. }
  25040. // --- Uniform Classes ---
  25041. class SingleUniform {
  25042. constructor( id, activeInfo, addr ) {
  25043. this.id = id;
  25044. this.addr = addr;
  25045. this.cache = [];
  25046. this.type = activeInfo.type;
  25047. this.setValue = getSingularSetter( activeInfo.type );
  25048. // this.path = activeInfo.name; // DEBUG
  25049. }
  25050. }
  25051. class PureArrayUniform {
  25052. constructor( id, activeInfo, addr ) {
  25053. this.id = id;
  25054. this.addr = addr;
  25055. this.cache = [];
  25056. this.type = activeInfo.type;
  25057. this.size = activeInfo.size;
  25058. this.setValue = getPureArraySetter( activeInfo.type );
  25059. // this.path = activeInfo.name; // DEBUG
  25060. }
  25061. }
  25062. class StructuredUniform {
  25063. constructor( id ) {
  25064. this.id = id;
  25065. this.seq = [];
  25066. this.map = {};
  25067. }
  25068. setValue( gl, value, textures ) {
  25069. const seq = this.seq;
  25070. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  25071. const u = seq[ i ];
  25072. u.setValue( gl, value[ u.id ], textures );
  25073. }
  25074. }
  25075. }
  25076. // --- Top-level ---
  25077. // Parser - builds up the property tree from the path strings
  25078. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  25079. // extracts
  25080. // - the identifier (member name or array index)
  25081. // - followed by an optional right bracket (found when array index)
  25082. // - followed by an optional left bracket or dot (type of subscript)
  25083. //
  25084. // Note: These portions can be read in a non-overlapping fashion and
  25085. // allow straightforward parsing of the hierarchy that WebGL encodes
  25086. // in the uniform names.
  25087. function addUniform( container, uniformObject ) {
  25088. container.seq.push( uniformObject );
  25089. container.map[ uniformObject.id ] = uniformObject;
  25090. }
  25091. function parseUniform( activeInfo, addr, container ) {
  25092. const path = activeInfo.name,
  25093. pathLength = path.length;
  25094. // reset RegExp object, because of the early exit of a previous run
  25095. RePathPart.lastIndex = 0;
  25096. while ( true ) {
  25097. const match = RePathPart.exec( path ),
  25098. matchEnd = RePathPart.lastIndex;
  25099. let id = match[ 1 ];
  25100. const idIsIndex = match[ 2 ] === ']',
  25101. subscript = match[ 3 ];
  25102. if ( idIsIndex ) id = id | 0; // convert to integer
  25103. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  25104. // bare name or "pure" bottom-level array "[0]" suffix
  25105. addUniform( container, subscript === undefined ?
  25106. new SingleUniform( id, activeInfo, addr ) :
  25107. new PureArrayUniform( id, activeInfo, addr ) );
  25108. break;
  25109. } else {
  25110. // step into inner node / create it in case it doesn't exist
  25111. const map = container.map;
  25112. let next = map[ id ];
  25113. if ( next === undefined ) {
  25114. next = new StructuredUniform( id );
  25115. addUniform( container, next );
  25116. }
  25117. container = next;
  25118. }
  25119. }
  25120. }
  25121. // Root Container
  25122. class WebGLUniforms {
  25123. constructor( gl, program ) {
  25124. this.seq = [];
  25125. this.map = {};
  25126. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  25127. for ( let i = 0; i < n; ++ i ) {
  25128. const info = gl.getActiveUniform( program, i ),
  25129. addr = gl.getUniformLocation( program, info.name );
  25130. parseUniform( info, addr, this );
  25131. }
  25132. }
  25133. setValue( gl, name, value, textures ) {
  25134. const u = this.map[ name ];
  25135. if ( u !== undefined ) u.setValue( gl, value, textures );
  25136. }
  25137. setOptional( gl, object, name ) {
  25138. const v = object[ name ];
  25139. if ( v !== undefined ) this.setValue( gl, name, v );
  25140. }
  25141. static upload( gl, seq, values, textures ) {
  25142. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  25143. const u = seq[ i ],
  25144. v = values[ u.id ];
  25145. if ( v.needsUpdate !== false ) {
  25146. // note: always updating when .needsUpdate is undefined
  25147. u.setValue( gl, v.value, textures );
  25148. }
  25149. }
  25150. }
  25151. static seqWithValue( seq, values ) {
  25152. const r = [];
  25153. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  25154. const u = seq[ i ];
  25155. if ( u.id in values ) r.push( u );
  25156. }
  25157. return r;
  25158. }
  25159. }
  25160. function WebGLShader( gl, type, string ) {
  25161. const shader = gl.createShader( type );
  25162. gl.shaderSource( shader, string );
  25163. gl.compileShader( shader );
  25164. return shader;
  25165. }
  25166. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  25167. const COMPLETION_STATUS_KHR = 0x91B1;
  25168. let programIdCount = 0;
  25169. function handleSource( string, errorLine ) {
  25170. const lines = string.split( '\n' );
  25171. const lines2 = [];
  25172. const from = Math.max( errorLine - 6, 0 );
  25173. const to = Math.min( errorLine + 6, lines.length );
  25174. for ( let i = from; i < to; i ++ ) {
  25175. const line = i + 1;
  25176. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  25177. }
  25178. return lines2.join( '\n' );
  25179. }
  25180. const _m0 = /*@__PURE__*/ new Matrix3();
  25181. function getEncodingComponents( colorSpace ) {
  25182. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  25183. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  25184. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  25185. case LinearTransfer:
  25186. return [ encodingMatrix, 'LinearTransferOETF' ];
  25187. case SRGBTransfer:
  25188. return [ encodingMatrix, 'sRGBTransferOETF' ];
  25189. default:
  25190. console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace );
  25191. return [ encodingMatrix, 'LinearTransferOETF' ];
  25192. }
  25193. }
  25194. function getShaderErrors( gl, shader, type ) {
  25195. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  25196. const errors = gl.getShaderInfoLog( shader ).trim();
  25197. if ( status && errors === '' ) return '';
  25198. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  25199. if ( errorMatches ) {
  25200. // --enable-privileged-webgl-extension
  25201. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  25202. const errorLine = parseInt( errorMatches[ 1 ] );
  25203. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  25204. } else {
  25205. return errors;
  25206. }
  25207. }
  25208. function getTexelEncodingFunction( functionName, colorSpace ) {
  25209. const components = getEncodingComponents( colorSpace );
  25210. return [
  25211. `vec4 ${functionName}( vec4 value ) {`,
  25212. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  25213. '}',
  25214. ].join( '\n' );
  25215. }
  25216. function getToneMappingFunction( functionName, toneMapping ) {
  25217. let toneMappingName;
  25218. switch ( toneMapping ) {
  25219. case LinearToneMapping:
  25220. toneMappingName = 'Linear';
  25221. break;
  25222. case ReinhardToneMapping:
  25223. toneMappingName = 'Reinhard';
  25224. break;
  25225. case CineonToneMapping:
  25226. toneMappingName = 'Cineon';
  25227. break;
  25228. case ACESFilmicToneMapping:
  25229. toneMappingName = 'ACESFilmic';
  25230. break;
  25231. case AgXToneMapping:
  25232. toneMappingName = 'AgX';
  25233. break;
  25234. case NeutralToneMapping:
  25235. toneMappingName = 'Neutral';
  25236. break;
  25237. case CustomToneMapping:
  25238. toneMappingName = 'Custom';
  25239. break;
  25240. default:
  25241. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  25242. toneMappingName = 'Linear';
  25243. }
  25244. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  25245. }
  25246. const _v0 = /*@__PURE__*/ new Vector3();
  25247. function getLuminanceFunction() {
  25248. ColorManagement.getLuminanceCoefficients( _v0 );
  25249. const r = _v0.x.toFixed( 4 );
  25250. const g = _v0.y.toFixed( 4 );
  25251. const b = _v0.z.toFixed( 4 );
  25252. return [
  25253. 'float luminance( const in vec3 rgb ) {',
  25254. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  25255. ' return dot( weights, rgb );',
  25256. '}'
  25257. ].join( '\n' );
  25258. }
  25259. function generateVertexExtensions( parameters ) {
  25260. const chunks = [
  25261. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  25262. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  25263. ];
  25264. return chunks.filter( filterEmptyLine ).join( '\n' );
  25265. }
  25266. function generateDefines( defines ) {
  25267. const chunks = [];
  25268. for ( const name in defines ) {
  25269. const value = defines[ name ];
  25270. if ( value === false ) continue;
  25271. chunks.push( '#define ' + name + ' ' + value );
  25272. }
  25273. return chunks.join( '\n' );
  25274. }
  25275. function fetchAttributeLocations( gl, program ) {
  25276. const attributes = {};
  25277. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  25278. for ( let i = 0; i < n; i ++ ) {
  25279. const info = gl.getActiveAttrib( program, i );
  25280. const name = info.name;
  25281. let locationSize = 1;
  25282. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  25283. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  25284. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  25285. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  25286. attributes[ name ] = {
  25287. type: info.type,
  25288. location: gl.getAttribLocation( program, name ),
  25289. locationSize: locationSize
  25290. };
  25291. }
  25292. return attributes;
  25293. }
  25294. function filterEmptyLine( string ) {
  25295. return string !== '';
  25296. }
  25297. function replaceLightNums( string, parameters ) {
  25298. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  25299. return string
  25300. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  25301. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  25302. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  25303. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  25304. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  25305. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  25306. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  25307. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  25308. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  25309. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  25310. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  25311. }
  25312. function replaceClippingPlaneNums( string, parameters ) {
  25313. return string
  25314. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  25315. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  25316. }
  25317. // Resolve Includes
  25318. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  25319. function resolveIncludes( string ) {
  25320. return string.replace( includePattern, includeReplacer );
  25321. }
  25322. const shaderChunkMap = new Map();
  25323. function includeReplacer( match, include ) {
  25324. let string = ShaderChunk[ include ];
  25325. if ( string === undefined ) {
  25326. const newInclude = shaderChunkMap.get( include );
  25327. if ( newInclude !== undefined ) {
  25328. string = ShaderChunk[ newInclude ];
  25329. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  25330. } else {
  25331. throw new Error( 'Can not resolve #include <' + include + '>' );
  25332. }
  25333. }
  25334. return resolveIncludes( string );
  25335. }
  25336. // Unroll Loops
  25337. 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;
  25338. function unrollLoops( string ) {
  25339. return string.replace( unrollLoopPattern, loopReplacer );
  25340. }
  25341. function loopReplacer( match, start, end, snippet ) {
  25342. let string = '';
  25343. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  25344. string += snippet
  25345. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  25346. .replace( /UNROLLED_LOOP_INDEX/g, i );
  25347. }
  25348. return string;
  25349. }
  25350. //
  25351. function generatePrecision( parameters ) {
  25352. let precisionstring = `precision ${parameters.precision} float;
  25353. precision ${parameters.precision} int;
  25354. precision ${parameters.precision} sampler2D;
  25355. precision ${parameters.precision} samplerCube;
  25356. precision ${parameters.precision} sampler3D;
  25357. precision ${parameters.precision} sampler2DArray;
  25358. precision ${parameters.precision} sampler2DShadow;
  25359. precision ${parameters.precision} samplerCubeShadow;
  25360. precision ${parameters.precision} sampler2DArrayShadow;
  25361. precision ${parameters.precision} isampler2D;
  25362. precision ${parameters.precision} isampler3D;
  25363. precision ${parameters.precision} isamplerCube;
  25364. precision ${parameters.precision} isampler2DArray;
  25365. precision ${parameters.precision} usampler2D;
  25366. precision ${parameters.precision} usampler3D;
  25367. precision ${parameters.precision} usamplerCube;
  25368. precision ${parameters.precision} usampler2DArray;
  25369. `;
  25370. if ( parameters.precision === 'highp' ) {
  25371. precisionstring += '\n#define HIGH_PRECISION';
  25372. } else if ( parameters.precision === 'mediump' ) {
  25373. precisionstring += '\n#define MEDIUM_PRECISION';
  25374. } else if ( parameters.precision === 'lowp' ) {
  25375. precisionstring += '\n#define LOW_PRECISION';
  25376. }
  25377. return precisionstring;
  25378. }
  25379. function generateShadowMapTypeDefine( parameters ) {
  25380. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  25381. if ( parameters.shadowMapType === PCFShadowMap ) {
  25382. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  25383. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  25384. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  25385. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  25386. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  25387. }
  25388. return shadowMapTypeDefine;
  25389. }
  25390. function generateEnvMapTypeDefine( parameters ) {
  25391. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  25392. if ( parameters.envMap ) {
  25393. switch ( parameters.envMapMode ) {
  25394. case CubeReflectionMapping:
  25395. case CubeRefractionMapping:
  25396. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  25397. break;
  25398. case CubeUVReflectionMapping:
  25399. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  25400. break;
  25401. }
  25402. }
  25403. return envMapTypeDefine;
  25404. }
  25405. function generateEnvMapModeDefine( parameters ) {
  25406. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  25407. if ( parameters.envMap ) {
  25408. switch ( parameters.envMapMode ) {
  25409. case CubeRefractionMapping:
  25410. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  25411. break;
  25412. }
  25413. }
  25414. return envMapModeDefine;
  25415. }
  25416. function generateEnvMapBlendingDefine( parameters ) {
  25417. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  25418. if ( parameters.envMap ) {
  25419. switch ( parameters.combine ) {
  25420. case MultiplyOperation:
  25421. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  25422. break;
  25423. case MixOperation:
  25424. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  25425. break;
  25426. case AddOperation:
  25427. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  25428. break;
  25429. }
  25430. }
  25431. return envMapBlendingDefine;
  25432. }
  25433. function generateCubeUVSize( parameters ) {
  25434. const imageHeight = parameters.envMapCubeUVHeight;
  25435. if ( imageHeight === null ) return null;
  25436. const maxMip = Math.log2( imageHeight ) - 2;
  25437. const texelHeight = 1.0 / imageHeight;
  25438. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  25439. return { texelWidth, texelHeight, maxMip };
  25440. }
  25441. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  25442. // TODO Send this event to Three.js DevTools
  25443. // console.log( 'WebGLProgram', cacheKey );
  25444. const gl = renderer.getContext();
  25445. const defines = parameters.defines;
  25446. let vertexShader = parameters.vertexShader;
  25447. let fragmentShader = parameters.fragmentShader;
  25448. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  25449. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  25450. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  25451. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  25452. const envMapCubeUVSize = generateCubeUVSize( parameters );
  25453. const customVertexExtensions = generateVertexExtensions( parameters );
  25454. const customDefines = generateDefines( defines );
  25455. const program = gl.createProgram();
  25456. let prefixVertex, prefixFragment;
  25457. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  25458. if ( parameters.isRawShaderMaterial ) {
  25459. prefixVertex = [
  25460. '#define SHADER_TYPE ' + parameters.shaderType,
  25461. '#define SHADER_NAME ' + parameters.shaderName,
  25462. customDefines
  25463. ].filter( filterEmptyLine ).join( '\n' );
  25464. if ( prefixVertex.length > 0 ) {
  25465. prefixVertex += '\n';
  25466. }
  25467. prefixFragment = [
  25468. '#define SHADER_TYPE ' + parameters.shaderType,
  25469. '#define SHADER_NAME ' + parameters.shaderName,
  25470. customDefines
  25471. ].filter( filterEmptyLine ).join( '\n' );
  25472. if ( prefixFragment.length > 0 ) {
  25473. prefixFragment += '\n';
  25474. }
  25475. } else {
  25476. prefixVertex = [
  25477. generatePrecision( parameters ),
  25478. '#define SHADER_TYPE ' + parameters.shaderType,
  25479. '#define SHADER_NAME ' + parameters.shaderName,
  25480. customDefines,
  25481. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  25482. parameters.batching ? '#define USE_BATCHING' : '',
  25483. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  25484. parameters.instancing ? '#define USE_INSTANCING' : '',
  25485. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  25486. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  25487. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  25488. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  25489. parameters.map ? '#define USE_MAP' : '',
  25490. parameters.envMap ? '#define USE_ENVMAP' : '',
  25491. parameters.envMap ? '#define ' + envMapModeDefine : '',
  25492. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  25493. parameters.aoMap ? '#define USE_AOMAP' : '',
  25494. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  25495. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  25496. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  25497. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  25498. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  25499. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  25500. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  25501. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  25502. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  25503. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  25504. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  25505. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  25506. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  25507. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  25508. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  25509. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  25510. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  25511. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  25512. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  25513. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  25514. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  25515. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  25516. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  25517. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  25518. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  25519. //
  25520. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  25521. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  25522. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  25523. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  25524. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  25525. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  25526. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  25527. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  25528. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  25529. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  25530. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  25531. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  25532. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  25533. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  25534. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  25535. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  25536. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  25537. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  25538. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  25539. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  25540. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  25541. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  25542. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  25543. //
  25544. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  25545. parameters.vertexColors ? '#define USE_COLOR' : '',
  25546. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  25547. parameters.vertexUv1s ? '#define USE_UV1' : '',
  25548. parameters.vertexUv2s ? '#define USE_UV2' : '',
  25549. parameters.vertexUv3s ? '#define USE_UV3' : '',
  25550. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  25551. parameters.flatShading ? '#define FLAT_SHADED' : '',
  25552. parameters.skinning ? '#define USE_SKINNING' : '',
  25553. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  25554. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  25555. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  25556. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  25557. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  25558. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  25559. parameters.flipSided ? '#define FLIP_SIDED' : '',
  25560. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  25561. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  25562. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  25563. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  25564. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  25565. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  25566. 'uniform mat4 modelMatrix;',
  25567. 'uniform mat4 modelViewMatrix;',
  25568. 'uniform mat4 projectionMatrix;',
  25569. 'uniform mat4 viewMatrix;',
  25570. 'uniform mat3 normalMatrix;',
  25571. 'uniform vec3 cameraPosition;',
  25572. 'uniform bool isOrthographic;',
  25573. '#ifdef USE_INSTANCING',
  25574. ' attribute mat4 instanceMatrix;',
  25575. '#endif',
  25576. '#ifdef USE_INSTANCING_COLOR',
  25577. ' attribute vec3 instanceColor;',
  25578. '#endif',
  25579. '#ifdef USE_INSTANCING_MORPH',
  25580. ' uniform sampler2D morphTexture;',
  25581. '#endif',
  25582. 'attribute vec3 position;',
  25583. 'attribute vec3 normal;',
  25584. 'attribute vec2 uv;',
  25585. '#ifdef USE_UV1',
  25586. ' attribute vec2 uv1;',
  25587. '#endif',
  25588. '#ifdef USE_UV2',
  25589. ' attribute vec2 uv2;',
  25590. '#endif',
  25591. '#ifdef USE_UV3',
  25592. ' attribute vec2 uv3;',
  25593. '#endif',
  25594. '#ifdef USE_TANGENT',
  25595. ' attribute vec4 tangent;',
  25596. '#endif',
  25597. '#if defined( USE_COLOR_ALPHA )',
  25598. ' attribute vec4 color;',
  25599. '#elif defined( USE_COLOR )',
  25600. ' attribute vec3 color;',
  25601. '#endif',
  25602. '#ifdef USE_SKINNING',
  25603. ' attribute vec4 skinIndex;',
  25604. ' attribute vec4 skinWeight;',
  25605. '#endif',
  25606. '\n'
  25607. ].filter( filterEmptyLine ).join( '\n' );
  25608. prefixFragment = [
  25609. generatePrecision( parameters ),
  25610. '#define SHADER_TYPE ' + parameters.shaderType,
  25611. '#define SHADER_NAME ' + parameters.shaderName,
  25612. customDefines,
  25613. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  25614. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  25615. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  25616. parameters.map ? '#define USE_MAP' : '',
  25617. parameters.matcap ? '#define USE_MATCAP' : '',
  25618. parameters.envMap ? '#define USE_ENVMAP' : '',
  25619. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  25620. parameters.envMap ? '#define ' + envMapModeDefine : '',
  25621. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  25622. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  25623. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  25624. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  25625. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  25626. parameters.aoMap ? '#define USE_AOMAP' : '',
  25627. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  25628. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  25629. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  25630. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  25631. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  25632. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  25633. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  25634. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  25635. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  25636. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  25637. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  25638. parameters.dispersion ? '#define USE_DISPERSION' : '',
  25639. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  25640. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  25641. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  25642. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  25643. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  25644. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  25645. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  25646. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  25647. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  25648. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  25649. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  25650. parameters.sheen ? '#define USE_SHEEN' : '',
  25651. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  25652. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  25653. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  25654. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  25655. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  25656. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  25657. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  25658. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  25659. parameters.vertexUv1s ? '#define USE_UV1' : '',
  25660. parameters.vertexUv2s ? '#define USE_UV2' : '',
  25661. parameters.vertexUv3s ? '#define USE_UV3' : '',
  25662. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  25663. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  25664. parameters.flatShading ? '#define FLAT_SHADED' : '',
  25665. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  25666. parameters.flipSided ? '#define FLIP_SIDED' : '',
  25667. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  25668. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  25669. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  25670. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  25671. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  25672. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  25673. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  25674. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  25675. 'uniform mat4 viewMatrix;',
  25676. 'uniform vec3 cameraPosition;',
  25677. 'uniform bool isOrthographic;',
  25678. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  25679. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  25680. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  25681. parameters.dithering ? '#define DITHERING' : '',
  25682. parameters.opaque ? '#define OPAQUE' : '',
  25683. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  25684. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  25685. getLuminanceFunction(),
  25686. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  25687. '\n'
  25688. ].filter( filterEmptyLine ).join( '\n' );
  25689. }
  25690. vertexShader = resolveIncludes( vertexShader );
  25691. vertexShader = replaceLightNums( vertexShader, parameters );
  25692. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  25693. fragmentShader = resolveIncludes( fragmentShader );
  25694. fragmentShader = replaceLightNums( fragmentShader, parameters );
  25695. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  25696. vertexShader = unrollLoops( vertexShader );
  25697. fragmentShader = unrollLoops( fragmentShader );
  25698. if ( parameters.isRawShaderMaterial !== true ) {
  25699. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  25700. versionString = '#version 300 es\n';
  25701. prefixVertex = [
  25702. customVertexExtensions,
  25703. '#define attribute in',
  25704. '#define varying out',
  25705. '#define texture2D texture'
  25706. ].join( '\n' ) + '\n' + prefixVertex;
  25707. prefixFragment = [
  25708. '#define varying in',
  25709. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  25710. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  25711. '#define gl_FragDepthEXT gl_FragDepth',
  25712. '#define texture2D texture',
  25713. '#define textureCube texture',
  25714. '#define texture2DProj textureProj',
  25715. '#define texture2DLodEXT textureLod',
  25716. '#define texture2DProjLodEXT textureProjLod',
  25717. '#define textureCubeLodEXT textureLod',
  25718. '#define texture2DGradEXT textureGrad',
  25719. '#define texture2DProjGradEXT textureProjGrad',
  25720. '#define textureCubeGradEXT textureGrad'
  25721. ].join( '\n' ) + '\n' + prefixFragment;
  25722. }
  25723. const vertexGlsl = versionString + prefixVertex + vertexShader;
  25724. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  25725. // console.log( '*VERTEX*', vertexGlsl );
  25726. // console.log( '*FRAGMENT*', fragmentGlsl );
  25727. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  25728. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  25729. gl.attachShader( program, glVertexShader );
  25730. gl.attachShader( program, glFragmentShader );
  25731. // Force a particular attribute to index 0.
  25732. if ( parameters.index0AttributeName !== undefined ) {
  25733. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  25734. } else if ( parameters.morphTargets === true ) {
  25735. // programs with morphTargets displace position out of attribute 0
  25736. gl.bindAttribLocation( program, 0, 'position' );
  25737. }
  25738. gl.linkProgram( program );
  25739. function onFirstUse( self ) {
  25740. // check for link errors
  25741. if ( renderer.debug.checkShaderErrors ) {
  25742. const programLog = gl.getProgramInfoLog( program ).trim();
  25743. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  25744. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  25745. let runnable = true;
  25746. let haveDiagnostics = true;
  25747. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  25748. runnable = false;
  25749. if ( typeof renderer.debug.onShaderError === 'function' ) {
  25750. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  25751. } else {
  25752. // default error reporting
  25753. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  25754. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  25755. console.error(
  25756. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  25757. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  25758. 'Material Name: ' + self.name + '\n' +
  25759. 'Material Type: ' + self.type + '\n\n' +
  25760. 'Program Info Log: ' + programLog + '\n' +
  25761. vertexErrors + '\n' +
  25762. fragmentErrors
  25763. );
  25764. }
  25765. } else if ( programLog !== '' ) {
  25766. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  25767. } else if ( vertexLog === '' || fragmentLog === '' ) {
  25768. haveDiagnostics = false;
  25769. }
  25770. if ( haveDiagnostics ) {
  25771. self.diagnostics = {
  25772. runnable: runnable,
  25773. programLog: programLog,
  25774. vertexShader: {
  25775. log: vertexLog,
  25776. prefix: prefixVertex
  25777. },
  25778. fragmentShader: {
  25779. log: fragmentLog,
  25780. prefix: prefixFragment
  25781. }
  25782. };
  25783. }
  25784. }
  25785. // Clean up
  25786. // Crashes in iOS9 and iOS10. #18402
  25787. // gl.detachShader( program, glVertexShader );
  25788. // gl.detachShader( program, glFragmentShader );
  25789. gl.deleteShader( glVertexShader );
  25790. gl.deleteShader( glFragmentShader );
  25791. cachedUniforms = new WebGLUniforms( gl, program );
  25792. cachedAttributes = fetchAttributeLocations( gl, program );
  25793. }
  25794. // set up caching for uniform locations
  25795. let cachedUniforms;
  25796. this.getUniforms = function () {
  25797. if ( cachedUniforms === undefined ) {
  25798. // Populates cachedUniforms and cachedAttributes
  25799. onFirstUse( this );
  25800. }
  25801. return cachedUniforms;
  25802. };
  25803. // set up caching for attribute locations
  25804. let cachedAttributes;
  25805. this.getAttributes = function () {
  25806. if ( cachedAttributes === undefined ) {
  25807. // Populates cachedAttributes and cachedUniforms
  25808. onFirstUse( this );
  25809. }
  25810. return cachedAttributes;
  25811. };
  25812. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  25813. // flag the program as ready immediately. It may cause a stall when it's first used.
  25814. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  25815. this.isReady = function () {
  25816. if ( programReady === false ) {
  25817. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  25818. }
  25819. return programReady;
  25820. };
  25821. // free resource
  25822. this.destroy = function () {
  25823. bindingStates.releaseStatesOfProgram( this );
  25824. gl.deleteProgram( program );
  25825. this.program = undefined;
  25826. };
  25827. //
  25828. this.type = parameters.shaderType;
  25829. this.name = parameters.shaderName;
  25830. this.id = programIdCount ++;
  25831. this.cacheKey = cacheKey;
  25832. this.usedTimes = 1;
  25833. this.program = program;
  25834. this.vertexShader = glVertexShader;
  25835. this.fragmentShader = glFragmentShader;
  25836. return this;
  25837. }
  25838. let _id = 0;
  25839. class WebGLShaderCache {
  25840. constructor() {
  25841. this.shaderCache = new Map();
  25842. this.materialCache = new Map();
  25843. }
  25844. update( material ) {
  25845. const vertexShader = material.vertexShader;
  25846. const fragmentShader = material.fragmentShader;
  25847. const vertexShaderStage = this._getShaderStage( vertexShader );
  25848. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  25849. const materialShaders = this._getShaderCacheForMaterial( material );
  25850. if ( materialShaders.has( vertexShaderStage ) === false ) {
  25851. materialShaders.add( vertexShaderStage );
  25852. vertexShaderStage.usedTimes ++;
  25853. }
  25854. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  25855. materialShaders.add( fragmentShaderStage );
  25856. fragmentShaderStage.usedTimes ++;
  25857. }
  25858. return this;
  25859. }
  25860. remove( material ) {
  25861. const materialShaders = this.materialCache.get( material );
  25862. for ( const shaderStage of materialShaders ) {
  25863. shaderStage.usedTimes --;
  25864. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  25865. }
  25866. this.materialCache.delete( material );
  25867. return this;
  25868. }
  25869. getVertexShaderID( material ) {
  25870. return this._getShaderStage( material.vertexShader ).id;
  25871. }
  25872. getFragmentShaderID( material ) {
  25873. return this._getShaderStage( material.fragmentShader ).id;
  25874. }
  25875. dispose() {
  25876. this.shaderCache.clear();
  25877. this.materialCache.clear();
  25878. }
  25879. _getShaderCacheForMaterial( material ) {
  25880. const cache = this.materialCache;
  25881. let set = cache.get( material );
  25882. if ( set === undefined ) {
  25883. set = new Set();
  25884. cache.set( material, set );
  25885. }
  25886. return set;
  25887. }
  25888. _getShaderStage( code ) {
  25889. const cache = this.shaderCache;
  25890. let stage = cache.get( code );
  25891. if ( stage === undefined ) {
  25892. stage = new WebGLShaderStage( code );
  25893. cache.set( code, stage );
  25894. }
  25895. return stage;
  25896. }
  25897. }
  25898. class WebGLShaderStage {
  25899. constructor( code ) {
  25900. this.id = _id ++;
  25901. this.code = code;
  25902. this.usedTimes = 0;
  25903. }
  25904. }
  25905. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  25906. const _programLayers = new Layers();
  25907. const _customShaders = new WebGLShaderCache();
  25908. const _activeChannels = new Set();
  25909. const programs = [];
  25910. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  25911. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  25912. let precision = capabilities.precision;
  25913. const shaderIDs = {
  25914. MeshDepthMaterial: 'depth',
  25915. MeshDistanceMaterial: 'distanceRGBA',
  25916. MeshNormalMaterial: 'normal',
  25917. MeshBasicMaterial: 'basic',
  25918. MeshLambertMaterial: 'lambert',
  25919. MeshPhongMaterial: 'phong',
  25920. MeshToonMaterial: 'toon',
  25921. MeshStandardMaterial: 'physical',
  25922. MeshPhysicalMaterial: 'physical',
  25923. MeshMatcapMaterial: 'matcap',
  25924. LineBasicMaterial: 'basic',
  25925. LineDashedMaterial: 'dashed',
  25926. PointsMaterial: 'points',
  25927. ShadowMaterial: 'shadow',
  25928. SpriteMaterial: 'sprite'
  25929. };
  25930. function getChannel( value ) {
  25931. _activeChannels.add( value );
  25932. if ( value === 0 ) return 'uv';
  25933. return `uv${ value }`;
  25934. }
  25935. function getParameters( material, lights, shadows, scene, object ) {
  25936. const fog = scene.fog;
  25937. const geometry = object.geometry;
  25938. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  25939. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  25940. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  25941. const shaderID = shaderIDs[ material.type ];
  25942. // heuristics to create shader parameters according to lights in the scene
  25943. // (not to blow over maxLights budget)
  25944. if ( material.precision !== null ) {
  25945. precision = capabilities.getMaxPrecision( material.precision );
  25946. if ( precision !== material.precision ) {
  25947. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  25948. }
  25949. }
  25950. //
  25951. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25952. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25953. let morphTextureStride = 0;
  25954. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  25955. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  25956. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  25957. //
  25958. let vertexShader, fragmentShader;
  25959. let customVertexShaderID, customFragmentShaderID;
  25960. if ( shaderID ) {
  25961. const shader = ShaderLib[ shaderID ];
  25962. vertexShader = shader.vertexShader;
  25963. fragmentShader = shader.fragmentShader;
  25964. } else {
  25965. vertexShader = material.vertexShader;
  25966. fragmentShader = material.fragmentShader;
  25967. _customShaders.update( material );
  25968. customVertexShaderID = _customShaders.getVertexShaderID( material );
  25969. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  25970. }
  25971. const currentRenderTarget = renderer.getRenderTarget();
  25972. const reverseDepthBuffer = renderer.state.buffers.depth.getReversed();
  25973. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  25974. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  25975. const HAS_MAP = !! material.map;
  25976. const HAS_MATCAP = !! material.matcap;
  25977. const HAS_ENVMAP = !! envMap;
  25978. const HAS_AOMAP = !! material.aoMap;
  25979. const HAS_LIGHTMAP = !! material.lightMap;
  25980. const HAS_BUMPMAP = !! material.bumpMap;
  25981. const HAS_NORMALMAP = !! material.normalMap;
  25982. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  25983. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  25984. const HAS_METALNESSMAP = !! material.metalnessMap;
  25985. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  25986. const HAS_ANISOTROPY = material.anisotropy > 0;
  25987. const HAS_CLEARCOAT = material.clearcoat > 0;
  25988. const HAS_DISPERSION = material.dispersion > 0;
  25989. const HAS_IRIDESCENCE = material.iridescence > 0;
  25990. const HAS_SHEEN = material.sheen > 0;
  25991. const HAS_TRANSMISSION = material.transmission > 0;
  25992. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  25993. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  25994. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  25995. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  25996. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  25997. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  25998. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  25999. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  26000. const HAS_SPECULARMAP = !! material.specularMap;
  26001. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  26002. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  26003. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  26004. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  26005. const HAS_GRADIENTMAP = !! material.gradientMap;
  26006. const HAS_ALPHAMAP = !! material.alphaMap;
  26007. const HAS_ALPHATEST = material.alphaTest > 0;
  26008. const HAS_ALPHAHASH = !! material.alphaHash;
  26009. const HAS_EXTENSIONS = !! material.extensions;
  26010. let toneMapping = NoToneMapping;
  26011. if ( material.toneMapped ) {
  26012. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  26013. toneMapping = renderer.toneMapping;
  26014. }
  26015. }
  26016. const parameters = {
  26017. shaderID: shaderID,
  26018. shaderType: material.type,
  26019. shaderName: material.name,
  26020. vertexShader: vertexShader,
  26021. fragmentShader: fragmentShader,
  26022. defines: material.defines,
  26023. customVertexShaderID: customVertexShaderID,
  26024. customFragmentShaderID: customFragmentShaderID,
  26025. isRawShaderMaterial: material.isRawShaderMaterial === true,
  26026. glslVersion: material.glslVersion,
  26027. precision: precision,
  26028. batching: IS_BATCHEDMESH,
  26029. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  26030. instancing: IS_INSTANCEDMESH,
  26031. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  26032. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  26033. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  26034. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  26035. alphaToCoverage: !! material.alphaToCoverage,
  26036. map: HAS_MAP,
  26037. matcap: HAS_MATCAP,
  26038. envMap: HAS_ENVMAP,
  26039. envMapMode: HAS_ENVMAP && envMap.mapping,
  26040. envMapCubeUVHeight: envMapCubeUVHeight,
  26041. aoMap: HAS_AOMAP,
  26042. lightMap: HAS_LIGHTMAP,
  26043. bumpMap: HAS_BUMPMAP,
  26044. normalMap: HAS_NORMALMAP,
  26045. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  26046. emissiveMap: HAS_EMISSIVEMAP,
  26047. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  26048. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  26049. metalnessMap: HAS_METALNESSMAP,
  26050. roughnessMap: HAS_ROUGHNESSMAP,
  26051. anisotropy: HAS_ANISOTROPY,
  26052. anisotropyMap: HAS_ANISOTROPYMAP,
  26053. clearcoat: HAS_CLEARCOAT,
  26054. clearcoatMap: HAS_CLEARCOATMAP,
  26055. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  26056. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  26057. dispersion: HAS_DISPERSION,
  26058. iridescence: HAS_IRIDESCENCE,
  26059. iridescenceMap: HAS_IRIDESCENCEMAP,
  26060. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  26061. sheen: HAS_SHEEN,
  26062. sheenColorMap: HAS_SHEEN_COLORMAP,
  26063. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  26064. specularMap: HAS_SPECULARMAP,
  26065. specularColorMap: HAS_SPECULAR_COLORMAP,
  26066. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  26067. transmission: HAS_TRANSMISSION,
  26068. transmissionMap: HAS_TRANSMISSIONMAP,
  26069. thicknessMap: HAS_THICKNESSMAP,
  26070. gradientMap: HAS_GRADIENTMAP,
  26071. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  26072. alphaMap: HAS_ALPHAMAP,
  26073. alphaTest: HAS_ALPHATEST,
  26074. alphaHash: HAS_ALPHAHASH,
  26075. combine: material.combine,
  26076. //
  26077. mapUv: HAS_MAP && getChannel( material.map.channel ),
  26078. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  26079. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  26080. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  26081. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  26082. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  26083. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  26084. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  26085. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  26086. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  26087. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  26088. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  26089. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  26090. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  26091. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  26092. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  26093. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  26094. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  26095. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  26096. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  26097. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  26098. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  26099. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  26100. //
  26101. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  26102. vertexColors: material.vertexColors,
  26103. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  26104. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  26105. fog: !! fog,
  26106. useFog: material.fog === true,
  26107. fogExp2: ( !! fog && fog.isFogExp2 ),
  26108. flatShading: material.flatShading === true,
  26109. sizeAttenuation: material.sizeAttenuation === true,
  26110. logarithmicDepthBuffer: logarithmicDepthBuffer,
  26111. reverseDepthBuffer: reverseDepthBuffer,
  26112. skinning: object.isSkinnedMesh === true,
  26113. morphTargets: geometry.morphAttributes.position !== undefined,
  26114. morphNormals: geometry.morphAttributes.normal !== undefined,
  26115. morphColors: geometry.morphAttributes.color !== undefined,
  26116. morphTargetsCount: morphTargetsCount,
  26117. morphTextureStride: morphTextureStride,
  26118. numDirLights: lights.directional.length,
  26119. numPointLights: lights.point.length,
  26120. numSpotLights: lights.spot.length,
  26121. numSpotLightMaps: lights.spotLightMap.length,
  26122. numRectAreaLights: lights.rectArea.length,
  26123. numHemiLights: lights.hemi.length,
  26124. numDirLightShadows: lights.directionalShadowMap.length,
  26125. numPointLightShadows: lights.pointShadowMap.length,
  26126. numSpotLightShadows: lights.spotShadowMap.length,
  26127. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  26128. numLightProbes: lights.numLightProbes,
  26129. numClippingPlanes: clipping.numPlanes,
  26130. numClipIntersection: clipping.numIntersection,
  26131. dithering: material.dithering,
  26132. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  26133. shadowMapType: renderer.shadowMap.type,
  26134. toneMapping: toneMapping,
  26135. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  26136. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  26137. premultipliedAlpha: material.premultipliedAlpha,
  26138. doubleSided: material.side === DoubleSide,
  26139. flipSided: material.side === BackSide,
  26140. useDepthPacking: material.depthPacking >= 0,
  26141. depthPacking: material.depthPacking || 0,
  26142. index0AttributeName: material.index0AttributeName,
  26143. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  26144. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  26145. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  26146. customProgramCacheKey: material.customProgramCacheKey()
  26147. };
  26148. // the usage of getChannel() determines the active texture channels for this shader
  26149. parameters.vertexUv1s = _activeChannels.has( 1 );
  26150. parameters.vertexUv2s = _activeChannels.has( 2 );
  26151. parameters.vertexUv3s = _activeChannels.has( 3 );
  26152. _activeChannels.clear();
  26153. return parameters;
  26154. }
  26155. function getProgramCacheKey( parameters ) {
  26156. const array = [];
  26157. if ( parameters.shaderID ) {
  26158. array.push( parameters.shaderID );
  26159. } else {
  26160. array.push( parameters.customVertexShaderID );
  26161. array.push( parameters.customFragmentShaderID );
  26162. }
  26163. if ( parameters.defines !== undefined ) {
  26164. for ( const name in parameters.defines ) {
  26165. array.push( name );
  26166. array.push( parameters.defines[ name ] );
  26167. }
  26168. }
  26169. if ( parameters.isRawShaderMaterial === false ) {
  26170. getProgramCacheKeyParameters( array, parameters );
  26171. getProgramCacheKeyBooleans( array, parameters );
  26172. array.push( renderer.outputColorSpace );
  26173. }
  26174. array.push( parameters.customProgramCacheKey );
  26175. return array.join();
  26176. }
  26177. function getProgramCacheKeyParameters( array, parameters ) {
  26178. array.push( parameters.precision );
  26179. array.push( parameters.outputColorSpace );
  26180. array.push( parameters.envMapMode );
  26181. array.push( parameters.envMapCubeUVHeight );
  26182. array.push( parameters.mapUv );
  26183. array.push( parameters.alphaMapUv );
  26184. array.push( parameters.lightMapUv );
  26185. array.push( parameters.aoMapUv );
  26186. array.push( parameters.bumpMapUv );
  26187. array.push( parameters.normalMapUv );
  26188. array.push( parameters.displacementMapUv );
  26189. array.push( parameters.emissiveMapUv );
  26190. array.push( parameters.metalnessMapUv );
  26191. array.push( parameters.roughnessMapUv );
  26192. array.push( parameters.anisotropyMapUv );
  26193. array.push( parameters.clearcoatMapUv );
  26194. array.push( parameters.clearcoatNormalMapUv );
  26195. array.push( parameters.clearcoatRoughnessMapUv );
  26196. array.push( parameters.iridescenceMapUv );
  26197. array.push( parameters.iridescenceThicknessMapUv );
  26198. array.push( parameters.sheenColorMapUv );
  26199. array.push( parameters.sheenRoughnessMapUv );
  26200. array.push( parameters.specularMapUv );
  26201. array.push( parameters.specularColorMapUv );
  26202. array.push( parameters.specularIntensityMapUv );
  26203. array.push( parameters.transmissionMapUv );
  26204. array.push( parameters.thicknessMapUv );
  26205. array.push( parameters.combine );
  26206. array.push( parameters.fogExp2 );
  26207. array.push( parameters.sizeAttenuation );
  26208. array.push( parameters.morphTargetsCount );
  26209. array.push( parameters.morphAttributeCount );
  26210. array.push( parameters.numDirLights );
  26211. array.push( parameters.numPointLights );
  26212. array.push( parameters.numSpotLights );
  26213. array.push( parameters.numSpotLightMaps );
  26214. array.push( parameters.numHemiLights );
  26215. array.push( parameters.numRectAreaLights );
  26216. array.push( parameters.numDirLightShadows );
  26217. array.push( parameters.numPointLightShadows );
  26218. array.push( parameters.numSpotLightShadows );
  26219. array.push( parameters.numSpotLightShadowsWithMaps );
  26220. array.push( parameters.numLightProbes );
  26221. array.push( parameters.shadowMapType );
  26222. array.push( parameters.toneMapping );
  26223. array.push( parameters.numClippingPlanes );
  26224. array.push( parameters.numClipIntersection );
  26225. array.push( parameters.depthPacking );
  26226. }
  26227. function getProgramCacheKeyBooleans( array, parameters ) {
  26228. _programLayers.disableAll();
  26229. if ( parameters.supportsVertexTextures )
  26230. _programLayers.enable( 0 );
  26231. if ( parameters.instancing )
  26232. _programLayers.enable( 1 );
  26233. if ( parameters.instancingColor )
  26234. _programLayers.enable( 2 );
  26235. if ( parameters.instancingMorph )
  26236. _programLayers.enable( 3 );
  26237. if ( parameters.matcap )
  26238. _programLayers.enable( 4 );
  26239. if ( parameters.envMap )
  26240. _programLayers.enable( 5 );
  26241. if ( parameters.normalMapObjectSpace )
  26242. _programLayers.enable( 6 );
  26243. if ( parameters.normalMapTangentSpace )
  26244. _programLayers.enable( 7 );
  26245. if ( parameters.clearcoat )
  26246. _programLayers.enable( 8 );
  26247. if ( parameters.iridescence )
  26248. _programLayers.enable( 9 );
  26249. if ( parameters.alphaTest )
  26250. _programLayers.enable( 10 );
  26251. if ( parameters.vertexColors )
  26252. _programLayers.enable( 11 );
  26253. if ( parameters.vertexAlphas )
  26254. _programLayers.enable( 12 );
  26255. if ( parameters.vertexUv1s )
  26256. _programLayers.enable( 13 );
  26257. if ( parameters.vertexUv2s )
  26258. _programLayers.enable( 14 );
  26259. if ( parameters.vertexUv3s )
  26260. _programLayers.enable( 15 );
  26261. if ( parameters.vertexTangents )
  26262. _programLayers.enable( 16 );
  26263. if ( parameters.anisotropy )
  26264. _programLayers.enable( 17 );
  26265. if ( parameters.alphaHash )
  26266. _programLayers.enable( 18 );
  26267. if ( parameters.batching )
  26268. _programLayers.enable( 19 );
  26269. if ( parameters.dispersion )
  26270. _programLayers.enable( 20 );
  26271. if ( parameters.batchingColor )
  26272. _programLayers.enable( 21 );
  26273. array.push( _programLayers.mask );
  26274. _programLayers.disableAll();
  26275. if ( parameters.fog )
  26276. _programLayers.enable( 0 );
  26277. if ( parameters.useFog )
  26278. _programLayers.enable( 1 );
  26279. if ( parameters.flatShading )
  26280. _programLayers.enable( 2 );
  26281. if ( parameters.logarithmicDepthBuffer )
  26282. _programLayers.enable( 3 );
  26283. if ( parameters.reverseDepthBuffer )
  26284. _programLayers.enable( 4 );
  26285. if ( parameters.skinning )
  26286. _programLayers.enable( 5 );
  26287. if ( parameters.morphTargets )
  26288. _programLayers.enable( 6 );
  26289. if ( parameters.morphNormals )
  26290. _programLayers.enable( 7 );
  26291. if ( parameters.morphColors )
  26292. _programLayers.enable( 8 );
  26293. if ( parameters.premultipliedAlpha )
  26294. _programLayers.enable( 9 );
  26295. if ( parameters.shadowMapEnabled )
  26296. _programLayers.enable( 10 );
  26297. if ( parameters.doubleSided )
  26298. _programLayers.enable( 11 );
  26299. if ( parameters.flipSided )
  26300. _programLayers.enable( 12 );
  26301. if ( parameters.useDepthPacking )
  26302. _programLayers.enable( 13 );
  26303. if ( parameters.dithering )
  26304. _programLayers.enable( 14 );
  26305. if ( parameters.transmission )
  26306. _programLayers.enable( 15 );
  26307. if ( parameters.sheen )
  26308. _programLayers.enable( 16 );
  26309. if ( parameters.opaque )
  26310. _programLayers.enable( 17 );
  26311. if ( parameters.pointsUvs )
  26312. _programLayers.enable( 18 );
  26313. if ( parameters.decodeVideoTexture )
  26314. _programLayers.enable( 19 );
  26315. if ( parameters.decodeVideoTextureEmissive )
  26316. _programLayers.enable( 20 );
  26317. if ( parameters.alphaToCoverage )
  26318. _programLayers.enable( 21 );
  26319. array.push( _programLayers.mask );
  26320. }
  26321. function getUniforms( material ) {
  26322. const shaderID = shaderIDs[ material.type ];
  26323. let uniforms;
  26324. if ( shaderID ) {
  26325. const shader = ShaderLib[ shaderID ];
  26326. uniforms = UniformsUtils.clone( shader.uniforms );
  26327. } else {
  26328. uniforms = material.uniforms;
  26329. }
  26330. return uniforms;
  26331. }
  26332. function acquireProgram( parameters, cacheKey ) {
  26333. let program;
  26334. // Check if code has been already compiled
  26335. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  26336. const preexistingProgram = programs[ p ];
  26337. if ( preexistingProgram.cacheKey === cacheKey ) {
  26338. program = preexistingProgram;
  26339. ++ program.usedTimes;
  26340. break;
  26341. }
  26342. }
  26343. if ( program === undefined ) {
  26344. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  26345. programs.push( program );
  26346. }
  26347. return program;
  26348. }
  26349. function releaseProgram( program ) {
  26350. if ( -- program.usedTimes === 0 ) {
  26351. // Remove from unordered set
  26352. const i = programs.indexOf( program );
  26353. programs[ i ] = programs[ programs.length - 1 ];
  26354. programs.pop();
  26355. // Free WebGL resources
  26356. program.destroy();
  26357. }
  26358. }
  26359. function releaseShaderCache( material ) {
  26360. _customShaders.remove( material );
  26361. }
  26362. function dispose() {
  26363. _customShaders.dispose();
  26364. }
  26365. return {
  26366. getParameters: getParameters,
  26367. getProgramCacheKey: getProgramCacheKey,
  26368. getUniforms: getUniforms,
  26369. acquireProgram: acquireProgram,
  26370. releaseProgram: releaseProgram,
  26371. releaseShaderCache: releaseShaderCache,
  26372. // Exposed for resource monitoring & error feedback via renderer.info:
  26373. programs: programs,
  26374. dispose: dispose
  26375. };
  26376. }
  26377. function WebGLProperties() {
  26378. let properties = new WeakMap();
  26379. function has( object ) {
  26380. return properties.has( object );
  26381. }
  26382. function get( object ) {
  26383. let map = properties.get( object );
  26384. if ( map === undefined ) {
  26385. map = {};
  26386. properties.set( object, map );
  26387. }
  26388. return map;
  26389. }
  26390. function remove( object ) {
  26391. properties.delete( object );
  26392. }
  26393. function update( object, key, value ) {
  26394. properties.get( object )[ key ] = value;
  26395. }
  26396. function dispose() {
  26397. properties = new WeakMap();
  26398. }
  26399. return {
  26400. has: has,
  26401. get: get,
  26402. remove: remove,
  26403. update: update,
  26404. dispose: dispose
  26405. };
  26406. }
  26407. function painterSortStable( a, b ) {
  26408. if ( a.groupOrder !== b.groupOrder ) {
  26409. return a.groupOrder - b.groupOrder;
  26410. } else if ( a.renderOrder !== b.renderOrder ) {
  26411. return a.renderOrder - b.renderOrder;
  26412. } else if ( a.material.id !== b.material.id ) {
  26413. return a.material.id - b.material.id;
  26414. } else if ( a.z !== b.z ) {
  26415. return a.z - b.z;
  26416. } else {
  26417. return a.id - b.id;
  26418. }
  26419. }
  26420. function reversePainterSortStable( a, b ) {
  26421. if ( a.groupOrder !== b.groupOrder ) {
  26422. return a.groupOrder - b.groupOrder;
  26423. } else if ( a.renderOrder !== b.renderOrder ) {
  26424. return a.renderOrder - b.renderOrder;
  26425. } else if ( a.z !== b.z ) {
  26426. return b.z - a.z;
  26427. } else {
  26428. return a.id - b.id;
  26429. }
  26430. }
  26431. function WebGLRenderList() {
  26432. const renderItems = [];
  26433. let renderItemsIndex = 0;
  26434. const opaque = [];
  26435. const transmissive = [];
  26436. const transparent = [];
  26437. function init() {
  26438. renderItemsIndex = 0;
  26439. opaque.length = 0;
  26440. transmissive.length = 0;
  26441. transparent.length = 0;
  26442. }
  26443. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  26444. let renderItem = renderItems[ renderItemsIndex ];
  26445. if ( renderItem === undefined ) {
  26446. renderItem = {
  26447. id: object.id,
  26448. object: object,
  26449. geometry: geometry,
  26450. material: material,
  26451. groupOrder: groupOrder,
  26452. renderOrder: object.renderOrder,
  26453. z: z,
  26454. group: group
  26455. };
  26456. renderItems[ renderItemsIndex ] = renderItem;
  26457. } else {
  26458. renderItem.id = object.id;
  26459. renderItem.object = object;
  26460. renderItem.geometry = geometry;
  26461. renderItem.material = material;
  26462. renderItem.groupOrder = groupOrder;
  26463. renderItem.renderOrder = object.renderOrder;
  26464. renderItem.z = z;
  26465. renderItem.group = group;
  26466. }
  26467. renderItemsIndex ++;
  26468. return renderItem;
  26469. }
  26470. function push( object, geometry, material, groupOrder, z, group ) {
  26471. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  26472. if ( material.transmission > 0.0 ) {
  26473. transmissive.push( renderItem );
  26474. } else if ( material.transparent === true ) {
  26475. transparent.push( renderItem );
  26476. } else {
  26477. opaque.push( renderItem );
  26478. }
  26479. }
  26480. function unshift( object, geometry, material, groupOrder, z, group ) {
  26481. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  26482. if ( material.transmission > 0.0 ) {
  26483. transmissive.unshift( renderItem );
  26484. } else if ( material.transparent === true ) {
  26485. transparent.unshift( renderItem );
  26486. } else {
  26487. opaque.unshift( renderItem );
  26488. }
  26489. }
  26490. function sort( customOpaqueSort, customTransparentSort ) {
  26491. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  26492. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  26493. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  26494. }
  26495. function finish() {
  26496. // Clear references from inactive renderItems in the list
  26497. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  26498. const renderItem = renderItems[ i ];
  26499. if ( renderItem.id === null ) break;
  26500. renderItem.id = null;
  26501. renderItem.object = null;
  26502. renderItem.geometry = null;
  26503. renderItem.material = null;
  26504. renderItem.group = null;
  26505. }
  26506. }
  26507. return {
  26508. opaque: opaque,
  26509. transmissive: transmissive,
  26510. transparent: transparent,
  26511. init: init,
  26512. push: push,
  26513. unshift: unshift,
  26514. finish: finish,
  26515. sort: sort
  26516. };
  26517. }
  26518. function WebGLRenderLists() {
  26519. let lists = new WeakMap();
  26520. function get( scene, renderCallDepth ) {
  26521. const listArray = lists.get( scene );
  26522. let list;
  26523. if ( listArray === undefined ) {
  26524. list = new WebGLRenderList();
  26525. lists.set( scene, [ list ] );
  26526. } else {
  26527. if ( renderCallDepth >= listArray.length ) {
  26528. list = new WebGLRenderList();
  26529. listArray.push( list );
  26530. } else {
  26531. list = listArray[ renderCallDepth ];
  26532. }
  26533. }
  26534. return list;
  26535. }
  26536. function dispose() {
  26537. lists = new WeakMap();
  26538. }
  26539. return {
  26540. get: get,
  26541. dispose: dispose
  26542. };
  26543. }
  26544. function UniformsCache() {
  26545. const lights = {};
  26546. return {
  26547. get: function ( light ) {
  26548. if ( lights[ light.id ] !== undefined ) {
  26549. return lights[ light.id ];
  26550. }
  26551. let uniforms;
  26552. switch ( light.type ) {
  26553. case 'DirectionalLight':
  26554. uniforms = {
  26555. direction: new Vector3(),
  26556. color: new Color()
  26557. };
  26558. break;
  26559. case 'SpotLight':
  26560. uniforms = {
  26561. position: new Vector3(),
  26562. direction: new Vector3(),
  26563. color: new Color(),
  26564. distance: 0,
  26565. coneCos: 0,
  26566. penumbraCos: 0,
  26567. decay: 0
  26568. };
  26569. break;
  26570. case 'PointLight':
  26571. uniforms = {
  26572. position: new Vector3(),
  26573. color: new Color(),
  26574. distance: 0,
  26575. decay: 0
  26576. };
  26577. break;
  26578. case 'HemisphereLight':
  26579. uniforms = {
  26580. direction: new Vector3(),
  26581. skyColor: new Color(),
  26582. groundColor: new Color()
  26583. };
  26584. break;
  26585. case 'RectAreaLight':
  26586. uniforms = {
  26587. color: new Color(),
  26588. position: new Vector3(),
  26589. halfWidth: new Vector3(),
  26590. halfHeight: new Vector3()
  26591. };
  26592. break;
  26593. }
  26594. lights[ light.id ] = uniforms;
  26595. return uniforms;
  26596. }
  26597. };
  26598. }
  26599. function ShadowUniformsCache() {
  26600. const lights = {};
  26601. return {
  26602. get: function ( light ) {
  26603. if ( lights[ light.id ] !== undefined ) {
  26604. return lights[ light.id ];
  26605. }
  26606. let uniforms;
  26607. switch ( light.type ) {
  26608. case 'DirectionalLight':
  26609. uniforms = {
  26610. shadowIntensity: 1,
  26611. shadowBias: 0,
  26612. shadowNormalBias: 0,
  26613. shadowRadius: 1,
  26614. shadowMapSize: new Vector2()
  26615. };
  26616. break;
  26617. case 'SpotLight':
  26618. uniforms = {
  26619. shadowIntensity: 1,
  26620. shadowBias: 0,
  26621. shadowNormalBias: 0,
  26622. shadowRadius: 1,
  26623. shadowMapSize: new Vector2()
  26624. };
  26625. break;
  26626. case 'PointLight':
  26627. uniforms = {
  26628. shadowIntensity: 1,
  26629. shadowBias: 0,
  26630. shadowNormalBias: 0,
  26631. shadowRadius: 1,
  26632. shadowMapSize: new Vector2(),
  26633. shadowCameraNear: 1,
  26634. shadowCameraFar: 1000
  26635. };
  26636. break;
  26637. // TODO (abelnation): set RectAreaLight shadow uniforms
  26638. }
  26639. lights[ light.id ] = uniforms;
  26640. return uniforms;
  26641. }
  26642. };
  26643. }
  26644. let nextVersion = 0;
  26645. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  26646. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  26647. }
  26648. function WebGLLights( extensions ) {
  26649. const cache = new UniformsCache();
  26650. const shadowCache = ShadowUniformsCache();
  26651. const state = {
  26652. version: 0,
  26653. hash: {
  26654. directionalLength: - 1,
  26655. pointLength: - 1,
  26656. spotLength: - 1,
  26657. rectAreaLength: - 1,
  26658. hemiLength: - 1,
  26659. numDirectionalShadows: - 1,
  26660. numPointShadows: - 1,
  26661. numSpotShadows: - 1,
  26662. numSpotMaps: - 1,
  26663. numLightProbes: - 1
  26664. },
  26665. ambient: [ 0, 0, 0 ],
  26666. probe: [],
  26667. directional: [],
  26668. directionalShadow: [],
  26669. directionalShadowMap: [],
  26670. directionalShadowMatrix: [],
  26671. spot: [],
  26672. spotLightMap: [],
  26673. spotShadow: [],
  26674. spotShadowMap: [],
  26675. spotLightMatrix: [],
  26676. rectArea: [],
  26677. rectAreaLTC1: null,
  26678. rectAreaLTC2: null,
  26679. point: [],
  26680. pointShadow: [],
  26681. pointShadowMap: [],
  26682. pointShadowMatrix: [],
  26683. hemi: [],
  26684. numSpotLightShadowsWithMaps: 0,
  26685. numLightProbes: 0
  26686. };
  26687. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  26688. const vector3 = new Vector3();
  26689. const matrix4 = new Matrix4();
  26690. const matrix42 = new Matrix4();
  26691. function setup( lights ) {
  26692. let r = 0, g = 0, b = 0;
  26693. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  26694. let directionalLength = 0;
  26695. let pointLength = 0;
  26696. let spotLength = 0;
  26697. let rectAreaLength = 0;
  26698. let hemiLength = 0;
  26699. let numDirectionalShadows = 0;
  26700. let numPointShadows = 0;
  26701. let numSpotShadows = 0;
  26702. let numSpotMaps = 0;
  26703. let numSpotShadowsWithMaps = 0;
  26704. let numLightProbes = 0;
  26705. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  26706. lights.sort( shadowCastingAndTexturingLightsFirst );
  26707. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  26708. const light = lights[ i ];
  26709. const color = light.color;
  26710. const intensity = light.intensity;
  26711. const distance = light.distance;
  26712. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  26713. if ( light.isAmbientLight ) {
  26714. r += color.r * intensity;
  26715. g += color.g * intensity;
  26716. b += color.b * intensity;
  26717. } else if ( light.isLightProbe ) {
  26718. for ( let j = 0; j < 9; j ++ ) {
  26719. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  26720. }
  26721. numLightProbes ++;
  26722. } else if ( light.isDirectionalLight ) {
  26723. const uniforms = cache.get( light );
  26724. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  26725. if ( light.castShadow ) {
  26726. const shadow = light.shadow;
  26727. const shadowUniforms = shadowCache.get( light );
  26728. shadowUniforms.shadowIntensity = shadow.intensity;
  26729. shadowUniforms.shadowBias = shadow.bias;
  26730. shadowUniforms.shadowNormalBias = shadow.normalBias;
  26731. shadowUniforms.shadowRadius = shadow.radius;
  26732. shadowUniforms.shadowMapSize = shadow.mapSize;
  26733. state.directionalShadow[ directionalLength ] = shadowUniforms;
  26734. state.directionalShadowMap[ directionalLength ] = shadowMap;
  26735. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  26736. numDirectionalShadows ++;
  26737. }
  26738. state.directional[ directionalLength ] = uniforms;
  26739. directionalLength ++;
  26740. } else if ( light.isSpotLight ) {
  26741. const uniforms = cache.get( light );
  26742. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  26743. uniforms.color.copy( color ).multiplyScalar( intensity );
  26744. uniforms.distance = distance;
  26745. uniforms.coneCos = Math.cos( light.angle );
  26746. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  26747. uniforms.decay = light.decay;
  26748. state.spot[ spotLength ] = uniforms;
  26749. const shadow = light.shadow;
  26750. if ( light.map ) {
  26751. state.spotLightMap[ numSpotMaps ] = light.map;
  26752. numSpotMaps ++;
  26753. // make sure the lightMatrix is up to date
  26754. // TODO : do it if required only
  26755. shadow.updateMatrices( light );
  26756. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  26757. }
  26758. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  26759. if ( light.castShadow ) {
  26760. const shadowUniforms = shadowCache.get( light );
  26761. shadowUniforms.shadowIntensity = shadow.intensity;
  26762. shadowUniforms.shadowBias = shadow.bias;
  26763. shadowUniforms.shadowNormalBias = shadow.normalBias;
  26764. shadowUniforms.shadowRadius = shadow.radius;
  26765. shadowUniforms.shadowMapSize = shadow.mapSize;
  26766. state.spotShadow[ spotLength ] = shadowUniforms;
  26767. state.spotShadowMap[ spotLength ] = shadowMap;
  26768. numSpotShadows ++;
  26769. }
  26770. spotLength ++;
  26771. } else if ( light.isRectAreaLight ) {
  26772. const uniforms = cache.get( light );
  26773. uniforms.color.copy( color ).multiplyScalar( intensity );
  26774. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  26775. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  26776. state.rectArea[ rectAreaLength ] = uniforms;
  26777. rectAreaLength ++;
  26778. } else if ( light.isPointLight ) {
  26779. const uniforms = cache.get( light );
  26780. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  26781. uniforms.distance = light.distance;
  26782. uniforms.decay = light.decay;
  26783. if ( light.castShadow ) {
  26784. const shadow = light.shadow;
  26785. const shadowUniforms = shadowCache.get( light );
  26786. shadowUniforms.shadowIntensity = shadow.intensity;
  26787. shadowUniforms.shadowBias = shadow.bias;
  26788. shadowUniforms.shadowNormalBias = shadow.normalBias;
  26789. shadowUniforms.shadowRadius = shadow.radius;
  26790. shadowUniforms.shadowMapSize = shadow.mapSize;
  26791. shadowUniforms.shadowCameraNear = shadow.camera.near;
  26792. shadowUniforms.shadowCameraFar = shadow.camera.far;
  26793. state.pointShadow[ pointLength ] = shadowUniforms;
  26794. state.pointShadowMap[ pointLength ] = shadowMap;
  26795. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  26796. numPointShadows ++;
  26797. }
  26798. state.point[ pointLength ] = uniforms;
  26799. pointLength ++;
  26800. } else if ( light.isHemisphereLight ) {
  26801. const uniforms = cache.get( light );
  26802. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  26803. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  26804. state.hemi[ hemiLength ] = uniforms;
  26805. hemiLength ++;
  26806. }
  26807. }
  26808. if ( rectAreaLength > 0 ) {
  26809. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  26810. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  26811. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  26812. } else {
  26813. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  26814. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  26815. }
  26816. }
  26817. state.ambient[ 0 ] = r;
  26818. state.ambient[ 1 ] = g;
  26819. state.ambient[ 2 ] = b;
  26820. const hash = state.hash;
  26821. if ( hash.directionalLength !== directionalLength ||
  26822. hash.pointLength !== pointLength ||
  26823. hash.spotLength !== spotLength ||
  26824. hash.rectAreaLength !== rectAreaLength ||
  26825. hash.hemiLength !== hemiLength ||
  26826. hash.numDirectionalShadows !== numDirectionalShadows ||
  26827. hash.numPointShadows !== numPointShadows ||
  26828. hash.numSpotShadows !== numSpotShadows ||
  26829. hash.numSpotMaps !== numSpotMaps ||
  26830. hash.numLightProbes !== numLightProbes ) {
  26831. state.directional.length = directionalLength;
  26832. state.spot.length = spotLength;
  26833. state.rectArea.length = rectAreaLength;
  26834. state.point.length = pointLength;
  26835. state.hemi.length = hemiLength;
  26836. state.directionalShadow.length = numDirectionalShadows;
  26837. state.directionalShadowMap.length = numDirectionalShadows;
  26838. state.pointShadow.length = numPointShadows;
  26839. state.pointShadowMap.length = numPointShadows;
  26840. state.spotShadow.length = numSpotShadows;
  26841. state.spotShadowMap.length = numSpotShadows;
  26842. state.directionalShadowMatrix.length = numDirectionalShadows;
  26843. state.pointShadowMatrix.length = numPointShadows;
  26844. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  26845. state.spotLightMap.length = numSpotMaps;
  26846. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  26847. state.numLightProbes = numLightProbes;
  26848. hash.directionalLength = directionalLength;
  26849. hash.pointLength = pointLength;
  26850. hash.spotLength = spotLength;
  26851. hash.rectAreaLength = rectAreaLength;
  26852. hash.hemiLength = hemiLength;
  26853. hash.numDirectionalShadows = numDirectionalShadows;
  26854. hash.numPointShadows = numPointShadows;
  26855. hash.numSpotShadows = numSpotShadows;
  26856. hash.numSpotMaps = numSpotMaps;
  26857. hash.numLightProbes = numLightProbes;
  26858. state.version = nextVersion ++;
  26859. }
  26860. }
  26861. function setupView( lights, camera ) {
  26862. let directionalLength = 0;
  26863. let pointLength = 0;
  26864. let spotLength = 0;
  26865. let rectAreaLength = 0;
  26866. let hemiLength = 0;
  26867. const viewMatrix = camera.matrixWorldInverse;
  26868. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  26869. const light = lights[ i ];
  26870. if ( light.isDirectionalLight ) {
  26871. const uniforms = state.directional[ directionalLength ];
  26872. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  26873. vector3.setFromMatrixPosition( light.target.matrixWorld );
  26874. uniforms.direction.sub( vector3 );
  26875. uniforms.direction.transformDirection( viewMatrix );
  26876. directionalLength ++;
  26877. } else if ( light.isSpotLight ) {
  26878. const uniforms = state.spot[ spotLength ];
  26879. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  26880. uniforms.position.applyMatrix4( viewMatrix );
  26881. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  26882. vector3.setFromMatrixPosition( light.target.matrixWorld );
  26883. uniforms.direction.sub( vector3 );
  26884. uniforms.direction.transformDirection( viewMatrix );
  26885. spotLength ++;
  26886. } else if ( light.isRectAreaLight ) {
  26887. const uniforms = state.rectArea[ rectAreaLength ];
  26888. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  26889. uniforms.position.applyMatrix4( viewMatrix );
  26890. // extract local rotation of light to derive width/height half vectors
  26891. matrix42.identity();
  26892. matrix4.copy( light.matrixWorld );
  26893. matrix4.premultiply( viewMatrix );
  26894. matrix42.extractRotation( matrix4 );
  26895. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  26896. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  26897. uniforms.halfWidth.applyMatrix4( matrix42 );
  26898. uniforms.halfHeight.applyMatrix4( matrix42 );
  26899. rectAreaLength ++;
  26900. } else if ( light.isPointLight ) {
  26901. const uniforms = state.point[ pointLength ];
  26902. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  26903. uniforms.position.applyMatrix4( viewMatrix );
  26904. pointLength ++;
  26905. } else if ( light.isHemisphereLight ) {
  26906. const uniforms = state.hemi[ hemiLength ];
  26907. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  26908. uniforms.direction.transformDirection( viewMatrix );
  26909. hemiLength ++;
  26910. }
  26911. }
  26912. }
  26913. return {
  26914. setup: setup,
  26915. setupView: setupView,
  26916. state: state
  26917. };
  26918. }
  26919. function WebGLRenderState( extensions ) {
  26920. const lights = new WebGLLights( extensions );
  26921. const lightsArray = [];
  26922. const shadowsArray = [];
  26923. function init( camera ) {
  26924. state.camera = camera;
  26925. lightsArray.length = 0;
  26926. shadowsArray.length = 0;
  26927. }
  26928. function pushLight( light ) {
  26929. lightsArray.push( light );
  26930. }
  26931. function pushShadow( shadowLight ) {
  26932. shadowsArray.push( shadowLight );
  26933. }
  26934. function setupLights() {
  26935. lights.setup( lightsArray );
  26936. }
  26937. function setupLightsView( camera ) {
  26938. lights.setupView( lightsArray, camera );
  26939. }
  26940. const state = {
  26941. lightsArray: lightsArray,
  26942. shadowsArray: shadowsArray,
  26943. camera: null,
  26944. lights: lights,
  26945. transmissionRenderTarget: {}
  26946. };
  26947. return {
  26948. init: init,
  26949. state: state,
  26950. setupLights: setupLights,
  26951. setupLightsView: setupLightsView,
  26952. pushLight: pushLight,
  26953. pushShadow: pushShadow
  26954. };
  26955. }
  26956. function WebGLRenderStates( extensions ) {
  26957. let renderStates = new WeakMap();
  26958. function get( scene, renderCallDepth = 0 ) {
  26959. const renderStateArray = renderStates.get( scene );
  26960. let renderState;
  26961. if ( renderStateArray === undefined ) {
  26962. renderState = new WebGLRenderState( extensions );
  26963. renderStates.set( scene, [ renderState ] );
  26964. } else {
  26965. if ( renderCallDepth >= renderStateArray.length ) {
  26966. renderState = new WebGLRenderState( extensions );
  26967. renderStateArray.push( renderState );
  26968. } else {
  26969. renderState = renderStateArray[ renderCallDepth ];
  26970. }
  26971. }
  26972. return renderState;
  26973. }
  26974. function dispose() {
  26975. renderStates = new WeakMap();
  26976. }
  26977. return {
  26978. get: get,
  26979. dispose: dispose
  26980. };
  26981. }
  26982. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  26983. 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}";
  26984. function WebGLShadowMap( renderer, objects, capabilities ) {
  26985. let _frustum = new Frustum();
  26986. const _shadowMapSize = new Vector2(),
  26987. _viewportSize = new Vector2(),
  26988. _viewport = new Vector4(),
  26989. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  26990. _distanceMaterial = new MeshDistanceMaterial(),
  26991. _materialCache = {},
  26992. _maxTextureSize = capabilities.maxTextureSize;
  26993. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  26994. const shadowMaterialVertical = new ShaderMaterial( {
  26995. defines: {
  26996. VSM_SAMPLES: 8
  26997. },
  26998. uniforms: {
  26999. shadow_pass: { value: null },
  27000. resolution: { value: new Vector2() },
  27001. radius: { value: 4.0 }
  27002. },
  27003. vertexShader: vertex,
  27004. fragmentShader: fragment
  27005. } );
  27006. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  27007. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  27008. const fullScreenTri = new BufferGeometry();
  27009. fullScreenTri.setAttribute(
  27010. 'position',
  27011. new BufferAttribute(
  27012. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  27013. 3
  27014. )
  27015. );
  27016. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  27017. const scope = this;
  27018. this.enabled = false;
  27019. this.autoUpdate = true;
  27020. this.needsUpdate = false;
  27021. this.type = PCFShadowMap;
  27022. let _previousType = this.type;
  27023. this.render = function ( lights, scene, camera ) {
  27024. if ( scope.enabled === false ) return;
  27025. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  27026. if ( lights.length === 0 ) return;
  27027. const currentRenderTarget = renderer.getRenderTarget();
  27028. const activeCubeFace = renderer.getActiveCubeFace();
  27029. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  27030. const _state = renderer.state;
  27031. // Set GL state for depth map.
  27032. _state.setBlending( NoBlending );
  27033. _state.buffers.color.setClear( 1, 1, 1, 1 );
  27034. _state.buffers.depth.setTest( true );
  27035. _state.setScissorTest( false );
  27036. // check for shadow map type changes
  27037. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  27038. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  27039. // render depth map
  27040. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  27041. const light = lights[ i ];
  27042. const shadow = light.shadow;
  27043. if ( shadow === undefined ) {
  27044. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  27045. continue;
  27046. }
  27047. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  27048. _shadowMapSize.copy( shadow.mapSize );
  27049. const shadowFrameExtents = shadow.getFrameExtents();
  27050. _shadowMapSize.multiply( shadowFrameExtents );
  27051. _viewportSize.copy( shadow.mapSize );
  27052. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  27053. if ( _shadowMapSize.x > _maxTextureSize ) {
  27054. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  27055. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  27056. shadow.mapSize.x = _viewportSize.x;
  27057. }
  27058. if ( _shadowMapSize.y > _maxTextureSize ) {
  27059. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  27060. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  27061. shadow.mapSize.y = _viewportSize.y;
  27062. }
  27063. }
  27064. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  27065. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  27066. if ( shadow.map !== null ) {
  27067. shadow.map.dispose();
  27068. }
  27069. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  27070. shadow.map.texture.name = light.name + '.shadowMap';
  27071. shadow.camera.updateProjectionMatrix();
  27072. }
  27073. renderer.setRenderTarget( shadow.map );
  27074. renderer.clear();
  27075. const viewportCount = shadow.getViewportCount();
  27076. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  27077. const viewport = shadow.getViewport( vp );
  27078. _viewport.set(
  27079. _viewportSize.x * viewport.x,
  27080. _viewportSize.y * viewport.y,
  27081. _viewportSize.x * viewport.z,
  27082. _viewportSize.y * viewport.w
  27083. );
  27084. _state.viewport( _viewport );
  27085. shadow.updateMatrices( light, vp );
  27086. _frustum = shadow.getFrustum();
  27087. renderObject( scene, camera, shadow.camera, light, this.type );
  27088. }
  27089. // do blur pass for VSM
  27090. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  27091. VSMPass( shadow, camera );
  27092. }
  27093. shadow.needsUpdate = false;
  27094. }
  27095. _previousType = this.type;
  27096. scope.needsUpdate = false;
  27097. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  27098. };
  27099. function VSMPass( shadow, camera ) {
  27100. const geometry = objects.update( fullScreenMesh );
  27101. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  27102. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  27103. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  27104. shadowMaterialVertical.needsUpdate = true;
  27105. shadowMaterialHorizontal.needsUpdate = true;
  27106. }
  27107. if ( shadow.mapPass === null ) {
  27108. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  27109. }
  27110. // vertical pass
  27111. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  27112. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  27113. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  27114. renderer.setRenderTarget( shadow.mapPass );
  27115. renderer.clear();
  27116. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  27117. // horizontal pass
  27118. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  27119. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  27120. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  27121. renderer.setRenderTarget( shadow.map );
  27122. renderer.clear();
  27123. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  27124. }
  27125. function getDepthMaterial( object, material, light, type ) {
  27126. let result = null;
  27127. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  27128. if ( customMaterial !== undefined ) {
  27129. result = customMaterial;
  27130. } else {
  27131. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  27132. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  27133. ( material.displacementMap && material.displacementScale !== 0 ) ||
  27134. ( material.alphaMap && material.alphaTest > 0 ) ||
  27135. ( material.map && material.alphaTest > 0 ) ) {
  27136. // in this case we need a unique material instance reflecting the
  27137. // appropriate state
  27138. const keyA = result.uuid, keyB = material.uuid;
  27139. let materialsForVariant = _materialCache[ keyA ];
  27140. if ( materialsForVariant === undefined ) {
  27141. materialsForVariant = {};
  27142. _materialCache[ keyA ] = materialsForVariant;
  27143. }
  27144. let cachedMaterial = materialsForVariant[ keyB ];
  27145. if ( cachedMaterial === undefined ) {
  27146. cachedMaterial = result.clone();
  27147. materialsForVariant[ keyB ] = cachedMaterial;
  27148. material.addEventListener( 'dispose', onMaterialDispose );
  27149. }
  27150. result = cachedMaterial;
  27151. }
  27152. }
  27153. result.visible = material.visible;
  27154. result.wireframe = material.wireframe;
  27155. if ( type === VSMShadowMap ) {
  27156. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  27157. } else {
  27158. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  27159. }
  27160. result.alphaMap = material.alphaMap;
  27161. result.alphaTest = material.alphaTest;
  27162. result.map = material.map;
  27163. result.clipShadows = material.clipShadows;
  27164. result.clippingPlanes = material.clippingPlanes;
  27165. result.clipIntersection = material.clipIntersection;
  27166. result.displacementMap = material.displacementMap;
  27167. result.displacementScale = material.displacementScale;
  27168. result.displacementBias = material.displacementBias;
  27169. result.wireframeLinewidth = material.wireframeLinewidth;
  27170. result.linewidth = material.linewidth;
  27171. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  27172. const materialProperties = renderer.properties.get( result );
  27173. materialProperties.light = light;
  27174. }
  27175. return result;
  27176. }
  27177. function renderObject( object, camera, shadowCamera, light, type ) {
  27178. if ( object.visible === false ) return;
  27179. const visible = object.layers.test( camera.layers );
  27180. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  27181. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  27182. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  27183. const geometry = objects.update( object );
  27184. const material = object.material;
  27185. if ( Array.isArray( material ) ) {
  27186. const groups = geometry.groups;
  27187. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  27188. const group = groups[ k ];
  27189. const groupMaterial = material[ group.materialIndex ];
  27190. if ( groupMaterial && groupMaterial.visible ) {
  27191. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  27192. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  27193. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  27194. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  27195. }
  27196. }
  27197. } else if ( material.visible ) {
  27198. const depthMaterial = getDepthMaterial( object, material, light, type );
  27199. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  27200. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  27201. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  27202. }
  27203. }
  27204. }
  27205. const children = object.children;
  27206. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27207. renderObject( children[ i ], camera, shadowCamera, light, type );
  27208. }
  27209. }
  27210. function onMaterialDispose( event ) {
  27211. const material = event.target;
  27212. material.removeEventListener( 'dispose', onMaterialDispose );
  27213. // make sure to remove the unique distance/depth materials used for shadow map rendering
  27214. for ( const id in _materialCache ) {
  27215. const cache = _materialCache[ id ];
  27216. const uuid = event.target.uuid;
  27217. if ( uuid in cache ) {
  27218. const shadowMaterial = cache[ uuid ];
  27219. shadowMaterial.dispose();
  27220. delete cache[ uuid ];
  27221. }
  27222. }
  27223. }
  27224. }
  27225. const reversedFuncs = {
  27226. [ NeverDepth ]: AlwaysDepth,
  27227. [ LessDepth ]: GreaterDepth,
  27228. [ EqualDepth ]: NotEqualDepth,
  27229. [ LessEqualDepth ]: GreaterEqualDepth,
  27230. [ AlwaysDepth ]: NeverDepth,
  27231. [ GreaterDepth ]: LessDepth,
  27232. [ NotEqualDepth ]: EqualDepth,
  27233. [ GreaterEqualDepth ]: LessEqualDepth,
  27234. };
  27235. function WebGLState( gl, extensions ) {
  27236. function ColorBuffer() {
  27237. let locked = false;
  27238. const color = new Vector4();
  27239. let currentColorMask = null;
  27240. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  27241. return {
  27242. setMask: function ( colorMask ) {
  27243. if ( currentColorMask !== colorMask && ! locked ) {
  27244. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  27245. currentColorMask = colorMask;
  27246. }
  27247. },
  27248. setLocked: function ( lock ) {
  27249. locked = lock;
  27250. },
  27251. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  27252. if ( premultipliedAlpha === true ) {
  27253. r *= a; g *= a; b *= a;
  27254. }
  27255. color.set( r, g, b, a );
  27256. if ( currentColorClear.equals( color ) === false ) {
  27257. gl.clearColor( r, g, b, a );
  27258. currentColorClear.copy( color );
  27259. }
  27260. },
  27261. reset: function () {
  27262. locked = false;
  27263. currentColorMask = null;
  27264. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  27265. }
  27266. };
  27267. }
  27268. function DepthBuffer() {
  27269. let locked = false;
  27270. let reversed = false;
  27271. let currentDepthMask = null;
  27272. let currentDepthFunc = null;
  27273. let currentDepthClear = null;
  27274. return {
  27275. setReversed: function ( value ) {
  27276. if ( reversed !== value ) {
  27277. const ext = extensions.get( 'EXT_clip_control' );
  27278. if ( reversed ) {
  27279. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  27280. } else {
  27281. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  27282. }
  27283. const oldDepth = currentDepthClear;
  27284. currentDepthClear = null;
  27285. this.setClear( oldDepth );
  27286. }
  27287. reversed = value;
  27288. },
  27289. getReversed: function () {
  27290. return reversed;
  27291. },
  27292. setTest: function ( depthTest ) {
  27293. if ( depthTest ) {
  27294. enable( gl.DEPTH_TEST );
  27295. } else {
  27296. disable( gl.DEPTH_TEST );
  27297. }
  27298. },
  27299. setMask: function ( depthMask ) {
  27300. if ( currentDepthMask !== depthMask && ! locked ) {
  27301. gl.depthMask( depthMask );
  27302. currentDepthMask = depthMask;
  27303. }
  27304. },
  27305. setFunc: function ( depthFunc ) {
  27306. if ( reversed ) depthFunc = reversedFuncs[ depthFunc ];
  27307. if ( currentDepthFunc !== depthFunc ) {
  27308. switch ( depthFunc ) {
  27309. case NeverDepth:
  27310. gl.depthFunc( gl.NEVER );
  27311. break;
  27312. case AlwaysDepth:
  27313. gl.depthFunc( gl.ALWAYS );
  27314. break;
  27315. case LessDepth:
  27316. gl.depthFunc( gl.LESS );
  27317. break;
  27318. case LessEqualDepth:
  27319. gl.depthFunc( gl.LEQUAL );
  27320. break;
  27321. case EqualDepth:
  27322. gl.depthFunc( gl.EQUAL );
  27323. break;
  27324. case GreaterEqualDepth:
  27325. gl.depthFunc( gl.GEQUAL );
  27326. break;
  27327. case GreaterDepth:
  27328. gl.depthFunc( gl.GREATER );
  27329. break;
  27330. case NotEqualDepth:
  27331. gl.depthFunc( gl.NOTEQUAL );
  27332. break;
  27333. default:
  27334. gl.depthFunc( gl.LEQUAL );
  27335. }
  27336. currentDepthFunc = depthFunc;
  27337. }
  27338. },
  27339. setLocked: function ( lock ) {
  27340. locked = lock;
  27341. },
  27342. setClear: function ( depth ) {
  27343. if ( currentDepthClear !== depth ) {
  27344. if ( reversed ) {
  27345. depth = 1 - depth;
  27346. }
  27347. gl.clearDepth( depth );
  27348. currentDepthClear = depth;
  27349. }
  27350. },
  27351. reset: function () {
  27352. locked = false;
  27353. currentDepthMask = null;
  27354. currentDepthFunc = null;
  27355. currentDepthClear = null;
  27356. reversed = false;
  27357. }
  27358. };
  27359. }
  27360. function StencilBuffer() {
  27361. let locked = false;
  27362. let currentStencilMask = null;
  27363. let currentStencilFunc = null;
  27364. let currentStencilRef = null;
  27365. let currentStencilFuncMask = null;
  27366. let currentStencilFail = null;
  27367. let currentStencilZFail = null;
  27368. let currentStencilZPass = null;
  27369. let currentStencilClear = null;
  27370. return {
  27371. setTest: function ( stencilTest ) {
  27372. if ( ! locked ) {
  27373. if ( stencilTest ) {
  27374. enable( gl.STENCIL_TEST );
  27375. } else {
  27376. disable( gl.STENCIL_TEST );
  27377. }
  27378. }
  27379. },
  27380. setMask: function ( stencilMask ) {
  27381. if ( currentStencilMask !== stencilMask && ! locked ) {
  27382. gl.stencilMask( stencilMask );
  27383. currentStencilMask = stencilMask;
  27384. }
  27385. },
  27386. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  27387. if ( currentStencilFunc !== stencilFunc ||
  27388. currentStencilRef !== stencilRef ||
  27389. currentStencilFuncMask !== stencilMask ) {
  27390. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  27391. currentStencilFunc = stencilFunc;
  27392. currentStencilRef = stencilRef;
  27393. currentStencilFuncMask = stencilMask;
  27394. }
  27395. },
  27396. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  27397. if ( currentStencilFail !== stencilFail ||
  27398. currentStencilZFail !== stencilZFail ||
  27399. currentStencilZPass !== stencilZPass ) {
  27400. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  27401. currentStencilFail = stencilFail;
  27402. currentStencilZFail = stencilZFail;
  27403. currentStencilZPass = stencilZPass;
  27404. }
  27405. },
  27406. setLocked: function ( lock ) {
  27407. locked = lock;
  27408. },
  27409. setClear: function ( stencil ) {
  27410. if ( currentStencilClear !== stencil ) {
  27411. gl.clearStencil( stencil );
  27412. currentStencilClear = stencil;
  27413. }
  27414. },
  27415. reset: function () {
  27416. locked = false;
  27417. currentStencilMask = null;
  27418. currentStencilFunc = null;
  27419. currentStencilRef = null;
  27420. currentStencilFuncMask = null;
  27421. currentStencilFail = null;
  27422. currentStencilZFail = null;
  27423. currentStencilZPass = null;
  27424. currentStencilClear = null;
  27425. }
  27426. };
  27427. }
  27428. //
  27429. const colorBuffer = new ColorBuffer();
  27430. const depthBuffer = new DepthBuffer();
  27431. const stencilBuffer = new StencilBuffer();
  27432. const uboBindings = new WeakMap();
  27433. const uboProgramMap = new WeakMap();
  27434. let enabledCapabilities = {};
  27435. let currentBoundFramebuffers = {};
  27436. let currentDrawbuffers = new WeakMap();
  27437. let defaultDrawbuffers = [];
  27438. let currentProgram = null;
  27439. let currentBlendingEnabled = false;
  27440. let currentBlending = null;
  27441. let currentBlendEquation = null;
  27442. let currentBlendSrc = null;
  27443. let currentBlendDst = null;
  27444. let currentBlendEquationAlpha = null;
  27445. let currentBlendSrcAlpha = null;
  27446. let currentBlendDstAlpha = null;
  27447. let currentBlendColor = new Color( 0, 0, 0 );
  27448. let currentBlendAlpha = 0;
  27449. let currentPremultipledAlpha = false;
  27450. let currentFlipSided = null;
  27451. let currentCullFace = null;
  27452. let currentLineWidth = null;
  27453. let currentPolygonOffsetFactor = null;
  27454. let currentPolygonOffsetUnits = null;
  27455. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  27456. let lineWidthAvailable = false;
  27457. let version = 0;
  27458. const glVersion = gl.getParameter( gl.VERSION );
  27459. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  27460. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  27461. lineWidthAvailable = ( version >= 1.0 );
  27462. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  27463. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  27464. lineWidthAvailable = ( version >= 2.0 );
  27465. }
  27466. let currentTextureSlot = null;
  27467. let currentBoundTextures = {};
  27468. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  27469. const viewportParam = gl.getParameter( gl.VIEWPORT );
  27470. const currentScissor = new Vector4().fromArray( scissorParam );
  27471. const currentViewport = new Vector4().fromArray( viewportParam );
  27472. function createTexture( type, target, count, dimensions ) {
  27473. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  27474. const texture = gl.createTexture();
  27475. gl.bindTexture( type, texture );
  27476. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  27477. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  27478. for ( let i = 0; i < count; i ++ ) {
  27479. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  27480. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  27481. } else {
  27482. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  27483. }
  27484. }
  27485. return texture;
  27486. }
  27487. const emptyTextures = {};
  27488. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  27489. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  27490. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  27491. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  27492. // init
  27493. colorBuffer.setClear( 0, 0, 0, 1 );
  27494. depthBuffer.setClear( 1 );
  27495. stencilBuffer.setClear( 0 );
  27496. enable( gl.DEPTH_TEST );
  27497. depthBuffer.setFunc( LessEqualDepth );
  27498. setFlipSided( false );
  27499. setCullFace( CullFaceBack );
  27500. enable( gl.CULL_FACE );
  27501. setBlending( NoBlending );
  27502. //
  27503. function enable( id ) {
  27504. if ( enabledCapabilities[ id ] !== true ) {
  27505. gl.enable( id );
  27506. enabledCapabilities[ id ] = true;
  27507. }
  27508. }
  27509. function disable( id ) {
  27510. if ( enabledCapabilities[ id ] !== false ) {
  27511. gl.disable( id );
  27512. enabledCapabilities[ id ] = false;
  27513. }
  27514. }
  27515. function bindFramebuffer( target, framebuffer ) {
  27516. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  27517. gl.bindFramebuffer( target, framebuffer );
  27518. currentBoundFramebuffers[ target ] = framebuffer;
  27519. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  27520. if ( target === gl.DRAW_FRAMEBUFFER ) {
  27521. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  27522. }
  27523. if ( target === gl.FRAMEBUFFER ) {
  27524. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  27525. }
  27526. return true;
  27527. }
  27528. return false;
  27529. }
  27530. function drawBuffers( renderTarget, framebuffer ) {
  27531. let drawBuffers = defaultDrawbuffers;
  27532. let needsUpdate = false;
  27533. if ( renderTarget ) {
  27534. drawBuffers = currentDrawbuffers.get( framebuffer );
  27535. if ( drawBuffers === undefined ) {
  27536. drawBuffers = [];
  27537. currentDrawbuffers.set( framebuffer, drawBuffers );
  27538. }
  27539. const textures = renderTarget.textures;
  27540. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  27541. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  27542. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  27543. }
  27544. drawBuffers.length = textures.length;
  27545. needsUpdate = true;
  27546. }
  27547. } else {
  27548. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  27549. drawBuffers[ 0 ] = gl.BACK;
  27550. needsUpdate = true;
  27551. }
  27552. }
  27553. if ( needsUpdate ) {
  27554. gl.drawBuffers( drawBuffers );
  27555. }
  27556. }
  27557. function useProgram( program ) {
  27558. if ( currentProgram !== program ) {
  27559. gl.useProgram( program );
  27560. currentProgram = program;
  27561. return true;
  27562. }
  27563. return false;
  27564. }
  27565. const equationToGL = {
  27566. [ AddEquation ]: gl.FUNC_ADD,
  27567. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  27568. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  27569. };
  27570. equationToGL[ MinEquation ] = gl.MIN;
  27571. equationToGL[ MaxEquation ] = gl.MAX;
  27572. const factorToGL = {
  27573. [ ZeroFactor ]: gl.ZERO,
  27574. [ OneFactor ]: gl.ONE,
  27575. [ SrcColorFactor ]: gl.SRC_COLOR,
  27576. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  27577. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  27578. [ DstColorFactor ]: gl.DST_COLOR,
  27579. [ DstAlphaFactor ]: gl.DST_ALPHA,
  27580. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  27581. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  27582. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  27583. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  27584. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  27585. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  27586. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  27587. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  27588. };
  27589. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  27590. if ( blending === NoBlending ) {
  27591. if ( currentBlendingEnabled === true ) {
  27592. disable( gl.BLEND );
  27593. currentBlendingEnabled = false;
  27594. }
  27595. return;
  27596. }
  27597. if ( currentBlendingEnabled === false ) {
  27598. enable( gl.BLEND );
  27599. currentBlendingEnabled = true;
  27600. }
  27601. if ( blending !== CustomBlending ) {
  27602. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  27603. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  27604. gl.blendEquation( gl.FUNC_ADD );
  27605. currentBlendEquation = AddEquation;
  27606. currentBlendEquationAlpha = AddEquation;
  27607. }
  27608. if ( premultipliedAlpha ) {
  27609. switch ( blending ) {
  27610. case NormalBlending:
  27611. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  27612. break;
  27613. case AdditiveBlending:
  27614. gl.blendFunc( gl.ONE, gl.ONE );
  27615. break;
  27616. case SubtractiveBlending:
  27617. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  27618. break;
  27619. case MultiplyBlending:
  27620. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  27621. break;
  27622. default:
  27623. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  27624. break;
  27625. }
  27626. } else {
  27627. switch ( blending ) {
  27628. case NormalBlending:
  27629. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  27630. break;
  27631. case AdditiveBlending:
  27632. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  27633. break;
  27634. case SubtractiveBlending:
  27635. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  27636. break;
  27637. case MultiplyBlending:
  27638. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  27639. break;
  27640. default:
  27641. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  27642. break;
  27643. }
  27644. }
  27645. currentBlendSrc = null;
  27646. currentBlendDst = null;
  27647. currentBlendSrcAlpha = null;
  27648. currentBlendDstAlpha = null;
  27649. currentBlendColor.set( 0, 0, 0 );
  27650. currentBlendAlpha = 0;
  27651. currentBlending = blending;
  27652. currentPremultipledAlpha = premultipliedAlpha;
  27653. }
  27654. return;
  27655. }
  27656. // custom blending
  27657. blendEquationAlpha = blendEquationAlpha || blendEquation;
  27658. blendSrcAlpha = blendSrcAlpha || blendSrc;
  27659. blendDstAlpha = blendDstAlpha || blendDst;
  27660. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  27661. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  27662. currentBlendEquation = blendEquation;
  27663. currentBlendEquationAlpha = blendEquationAlpha;
  27664. }
  27665. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  27666. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  27667. currentBlendSrc = blendSrc;
  27668. currentBlendDst = blendDst;
  27669. currentBlendSrcAlpha = blendSrcAlpha;
  27670. currentBlendDstAlpha = blendDstAlpha;
  27671. }
  27672. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  27673. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  27674. currentBlendColor.copy( blendColor );
  27675. currentBlendAlpha = blendAlpha;
  27676. }
  27677. currentBlending = blending;
  27678. currentPremultipledAlpha = false;
  27679. }
  27680. function setMaterial( material, frontFaceCW ) {
  27681. material.side === DoubleSide
  27682. ? disable( gl.CULL_FACE )
  27683. : enable( gl.CULL_FACE );
  27684. let flipSided = ( material.side === BackSide );
  27685. if ( frontFaceCW ) flipSided = ! flipSided;
  27686. setFlipSided( flipSided );
  27687. ( material.blending === NormalBlending && material.transparent === false )
  27688. ? setBlending( NoBlending )
  27689. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  27690. depthBuffer.setFunc( material.depthFunc );
  27691. depthBuffer.setTest( material.depthTest );
  27692. depthBuffer.setMask( material.depthWrite );
  27693. colorBuffer.setMask( material.colorWrite );
  27694. const stencilWrite = material.stencilWrite;
  27695. stencilBuffer.setTest( stencilWrite );
  27696. if ( stencilWrite ) {
  27697. stencilBuffer.setMask( material.stencilWriteMask );
  27698. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  27699. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  27700. }
  27701. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  27702. material.alphaToCoverage === true
  27703. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  27704. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  27705. }
  27706. //
  27707. function setFlipSided( flipSided ) {
  27708. if ( currentFlipSided !== flipSided ) {
  27709. if ( flipSided ) {
  27710. gl.frontFace( gl.CW );
  27711. } else {
  27712. gl.frontFace( gl.CCW );
  27713. }
  27714. currentFlipSided = flipSided;
  27715. }
  27716. }
  27717. function setCullFace( cullFace ) {
  27718. if ( cullFace !== CullFaceNone ) {
  27719. enable( gl.CULL_FACE );
  27720. if ( cullFace !== currentCullFace ) {
  27721. if ( cullFace === CullFaceBack ) {
  27722. gl.cullFace( gl.BACK );
  27723. } else if ( cullFace === CullFaceFront ) {
  27724. gl.cullFace( gl.FRONT );
  27725. } else {
  27726. gl.cullFace( gl.FRONT_AND_BACK );
  27727. }
  27728. }
  27729. } else {
  27730. disable( gl.CULL_FACE );
  27731. }
  27732. currentCullFace = cullFace;
  27733. }
  27734. function setLineWidth( width ) {
  27735. if ( width !== currentLineWidth ) {
  27736. if ( lineWidthAvailable ) gl.lineWidth( width );
  27737. currentLineWidth = width;
  27738. }
  27739. }
  27740. function setPolygonOffset( polygonOffset, factor, units ) {
  27741. if ( polygonOffset ) {
  27742. enable( gl.POLYGON_OFFSET_FILL );
  27743. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  27744. gl.polygonOffset( factor, units );
  27745. currentPolygonOffsetFactor = factor;
  27746. currentPolygonOffsetUnits = units;
  27747. }
  27748. } else {
  27749. disable( gl.POLYGON_OFFSET_FILL );
  27750. }
  27751. }
  27752. function setScissorTest( scissorTest ) {
  27753. if ( scissorTest ) {
  27754. enable( gl.SCISSOR_TEST );
  27755. } else {
  27756. disable( gl.SCISSOR_TEST );
  27757. }
  27758. }
  27759. // texture
  27760. function activeTexture( webglSlot ) {
  27761. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  27762. if ( currentTextureSlot !== webglSlot ) {
  27763. gl.activeTexture( webglSlot );
  27764. currentTextureSlot = webglSlot;
  27765. }
  27766. }
  27767. function bindTexture( webglType, webglTexture, webglSlot ) {
  27768. if ( webglSlot === undefined ) {
  27769. if ( currentTextureSlot === null ) {
  27770. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  27771. } else {
  27772. webglSlot = currentTextureSlot;
  27773. }
  27774. }
  27775. let boundTexture = currentBoundTextures[ webglSlot ];
  27776. if ( boundTexture === undefined ) {
  27777. boundTexture = { type: undefined, texture: undefined };
  27778. currentBoundTextures[ webglSlot ] = boundTexture;
  27779. }
  27780. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  27781. if ( currentTextureSlot !== webglSlot ) {
  27782. gl.activeTexture( webglSlot );
  27783. currentTextureSlot = webglSlot;
  27784. }
  27785. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  27786. boundTexture.type = webglType;
  27787. boundTexture.texture = webglTexture;
  27788. }
  27789. }
  27790. function unbindTexture() {
  27791. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  27792. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  27793. gl.bindTexture( boundTexture.type, null );
  27794. boundTexture.type = undefined;
  27795. boundTexture.texture = undefined;
  27796. }
  27797. }
  27798. function compressedTexImage2D() {
  27799. try {
  27800. gl.compressedTexImage2D.apply( gl, arguments );
  27801. } catch ( error ) {
  27802. console.error( 'THREE.WebGLState:', error );
  27803. }
  27804. }
  27805. function compressedTexImage3D() {
  27806. try {
  27807. gl.compressedTexImage3D.apply( gl, arguments );
  27808. } catch ( error ) {
  27809. console.error( 'THREE.WebGLState:', error );
  27810. }
  27811. }
  27812. function texSubImage2D() {
  27813. try {
  27814. gl.texSubImage2D.apply( gl, arguments );
  27815. } catch ( error ) {
  27816. console.error( 'THREE.WebGLState:', error );
  27817. }
  27818. }
  27819. function texSubImage3D() {
  27820. try {
  27821. gl.texSubImage3D.apply( gl, arguments );
  27822. } catch ( error ) {
  27823. console.error( 'THREE.WebGLState:', error );
  27824. }
  27825. }
  27826. function compressedTexSubImage2D() {
  27827. try {
  27828. gl.compressedTexSubImage2D.apply( gl, arguments );
  27829. } catch ( error ) {
  27830. console.error( 'THREE.WebGLState:', error );
  27831. }
  27832. }
  27833. function compressedTexSubImage3D() {
  27834. try {
  27835. gl.compressedTexSubImage3D.apply( gl, arguments );
  27836. } catch ( error ) {
  27837. console.error( 'THREE.WebGLState:', error );
  27838. }
  27839. }
  27840. function texStorage2D() {
  27841. try {
  27842. gl.texStorage2D.apply( gl, arguments );
  27843. } catch ( error ) {
  27844. console.error( 'THREE.WebGLState:', error );
  27845. }
  27846. }
  27847. function texStorage3D() {
  27848. try {
  27849. gl.texStorage3D.apply( gl, arguments );
  27850. } catch ( error ) {
  27851. console.error( 'THREE.WebGLState:', error );
  27852. }
  27853. }
  27854. function texImage2D() {
  27855. try {
  27856. gl.texImage2D.apply( gl, arguments );
  27857. } catch ( error ) {
  27858. console.error( 'THREE.WebGLState:', error );
  27859. }
  27860. }
  27861. function texImage3D() {
  27862. try {
  27863. gl.texImage3D.apply( gl, arguments );
  27864. } catch ( error ) {
  27865. console.error( 'THREE.WebGLState:', error );
  27866. }
  27867. }
  27868. //
  27869. function scissor( scissor ) {
  27870. if ( currentScissor.equals( scissor ) === false ) {
  27871. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  27872. currentScissor.copy( scissor );
  27873. }
  27874. }
  27875. function viewport( viewport ) {
  27876. if ( currentViewport.equals( viewport ) === false ) {
  27877. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  27878. currentViewport.copy( viewport );
  27879. }
  27880. }
  27881. function updateUBOMapping( uniformsGroup, program ) {
  27882. let mapping = uboProgramMap.get( program );
  27883. if ( mapping === undefined ) {
  27884. mapping = new WeakMap();
  27885. uboProgramMap.set( program, mapping );
  27886. }
  27887. let blockIndex = mapping.get( uniformsGroup );
  27888. if ( blockIndex === undefined ) {
  27889. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  27890. mapping.set( uniformsGroup, blockIndex );
  27891. }
  27892. }
  27893. function uniformBlockBinding( uniformsGroup, program ) {
  27894. const mapping = uboProgramMap.get( program );
  27895. const blockIndex = mapping.get( uniformsGroup );
  27896. if ( uboBindings.get( program ) !== blockIndex ) {
  27897. // bind shader specific block index to global block point
  27898. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  27899. uboBindings.set( program, blockIndex );
  27900. }
  27901. }
  27902. //
  27903. function reset() {
  27904. // reset state
  27905. gl.disable( gl.BLEND );
  27906. gl.disable( gl.CULL_FACE );
  27907. gl.disable( gl.DEPTH_TEST );
  27908. gl.disable( gl.POLYGON_OFFSET_FILL );
  27909. gl.disable( gl.SCISSOR_TEST );
  27910. gl.disable( gl.STENCIL_TEST );
  27911. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  27912. gl.blendEquation( gl.FUNC_ADD );
  27913. gl.blendFunc( gl.ONE, gl.ZERO );
  27914. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  27915. gl.blendColor( 0, 0, 0, 0 );
  27916. gl.colorMask( true, true, true, true );
  27917. gl.clearColor( 0, 0, 0, 0 );
  27918. gl.depthMask( true );
  27919. gl.depthFunc( gl.LESS );
  27920. depthBuffer.setReversed( false );
  27921. gl.clearDepth( 1 );
  27922. gl.stencilMask( 0xffffffff );
  27923. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  27924. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  27925. gl.clearStencil( 0 );
  27926. gl.cullFace( gl.BACK );
  27927. gl.frontFace( gl.CCW );
  27928. gl.polygonOffset( 0, 0 );
  27929. gl.activeTexture( gl.TEXTURE0 );
  27930. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  27931. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  27932. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  27933. gl.useProgram( null );
  27934. gl.lineWidth( 1 );
  27935. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  27936. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  27937. // reset internals
  27938. enabledCapabilities = {};
  27939. currentTextureSlot = null;
  27940. currentBoundTextures = {};
  27941. currentBoundFramebuffers = {};
  27942. currentDrawbuffers = new WeakMap();
  27943. defaultDrawbuffers = [];
  27944. currentProgram = null;
  27945. currentBlendingEnabled = false;
  27946. currentBlending = null;
  27947. currentBlendEquation = null;
  27948. currentBlendSrc = null;
  27949. currentBlendDst = null;
  27950. currentBlendEquationAlpha = null;
  27951. currentBlendSrcAlpha = null;
  27952. currentBlendDstAlpha = null;
  27953. currentBlendColor = new Color( 0, 0, 0 );
  27954. currentBlendAlpha = 0;
  27955. currentPremultipledAlpha = false;
  27956. currentFlipSided = null;
  27957. currentCullFace = null;
  27958. currentLineWidth = null;
  27959. currentPolygonOffsetFactor = null;
  27960. currentPolygonOffsetUnits = null;
  27961. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  27962. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  27963. colorBuffer.reset();
  27964. depthBuffer.reset();
  27965. stencilBuffer.reset();
  27966. }
  27967. return {
  27968. buffers: {
  27969. color: colorBuffer,
  27970. depth: depthBuffer,
  27971. stencil: stencilBuffer
  27972. },
  27973. enable: enable,
  27974. disable: disable,
  27975. bindFramebuffer: bindFramebuffer,
  27976. drawBuffers: drawBuffers,
  27977. useProgram: useProgram,
  27978. setBlending: setBlending,
  27979. setMaterial: setMaterial,
  27980. setFlipSided: setFlipSided,
  27981. setCullFace: setCullFace,
  27982. setLineWidth: setLineWidth,
  27983. setPolygonOffset: setPolygonOffset,
  27984. setScissorTest: setScissorTest,
  27985. activeTexture: activeTexture,
  27986. bindTexture: bindTexture,
  27987. unbindTexture: unbindTexture,
  27988. compressedTexImage2D: compressedTexImage2D,
  27989. compressedTexImage3D: compressedTexImage3D,
  27990. texImage2D: texImage2D,
  27991. texImage3D: texImage3D,
  27992. updateUBOMapping: updateUBOMapping,
  27993. uniformBlockBinding: uniformBlockBinding,
  27994. texStorage2D: texStorage2D,
  27995. texStorage3D: texStorage3D,
  27996. texSubImage2D: texSubImage2D,
  27997. texSubImage3D: texSubImage3D,
  27998. compressedTexSubImage2D: compressedTexSubImage2D,
  27999. compressedTexSubImage3D: compressedTexSubImage3D,
  28000. scissor: scissor,
  28001. viewport: viewport,
  28002. reset: reset
  28003. };
  28004. }
  28005. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  28006. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  28007. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  28008. const _imageDimensions = new Vector2();
  28009. const _videoTextures = new WeakMap();
  28010. let _canvas;
  28011. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  28012. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  28013. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  28014. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  28015. let useOffscreenCanvas = false;
  28016. try {
  28017. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  28018. // eslint-disable-next-line compat/compat
  28019. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  28020. } catch ( err ) {
  28021. // Ignore any errors
  28022. }
  28023. function createCanvas( width, height ) {
  28024. // Use OffscreenCanvas when available. Specially needed in web workers
  28025. return useOffscreenCanvas ?
  28026. // eslint-disable-next-line compat/compat
  28027. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  28028. }
  28029. function resizeImage( image, needsNewCanvas, maxSize ) {
  28030. let scale = 1;
  28031. const dimensions = getDimensions( image );
  28032. // handle case if texture exceeds max size
  28033. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  28034. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  28035. }
  28036. // only perform resize if necessary
  28037. if ( scale < 1 ) {
  28038. // only perform resize for certain image types
  28039. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  28040. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  28041. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  28042. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  28043. const width = Math.floor( scale * dimensions.width );
  28044. const height = Math.floor( scale * dimensions.height );
  28045. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  28046. // cube textures can't reuse the same canvas
  28047. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  28048. canvas.width = width;
  28049. canvas.height = height;
  28050. const context = canvas.getContext( '2d' );
  28051. context.drawImage( image, 0, 0, width, height );
  28052. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  28053. return canvas;
  28054. } else {
  28055. if ( 'data' in image ) {
  28056. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  28057. }
  28058. return image;
  28059. }
  28060. }
  28061. return image;
  28062. }
  28063. function textureNeedsGenerateMipmaps( texture ) {
  28064. return texture.generateMipmaps;
  28065. }
  28066. function generateMipmap( target ) {
  28067. _gl.generateMipmap( target );
  28068. }
  28069. function getTargetType( texture ) {
  28070. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  28071. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  28072. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  28073. return _gl.TEXTURE_2D;
  28074. }
  28075. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  28076. if ( internalFormatName !== null ) {
  28077. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  28078. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  28079. }
  28080. let internalFormat = glFormat;
  28081. if ( glFormat === _gl.RED ) {
  28082. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  28083. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  28084. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  28085. }
  28086. if ( glFormat === _gl.RED_INTEGER ) {
  28087. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  28088. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  28089. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  28090. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  28091. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  28092. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  28093. }
  28094. if ( glFormat === _gl.RG ) {
  28095. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  28096. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  28097. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  28098. }
  28099. if ( glFormat === _gl.RG_INTEGER ) {
  28100. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  28101. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  28102. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  28103. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  28104. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  28105. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  28106. }
  28107. if ( glFormat === _gl.RGB_INTEGER ) {
  28108. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  28109. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  28110. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  28111. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  28112. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  28113. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  28114. }
  28115. if ( glFormat === _gl.RGBA_INTEGER ) {
  28116. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  28117. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  28118. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  28119. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  28120. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  28121. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  28122. }
  28123. if ( glFormat === _gl.RGB ) {
  28124. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  28125. }
  28126. if ( glFormat === _gl.RGBA ) {
  28127. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  28128. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  28129. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  28130. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  28131. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  28132. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  28133. }
  28134. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  28135. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  28136. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  28137. extensions.get( 'EXT_color_buffer_float' );
  28138. }
  28139. return internalFormat;
  28140. }
  28141. function getInternalDepthFormat( useStencil, depthType ) {
  28142. let glInternalFormat;
  28143. if ( useStencil ) {
  28144. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  28145. glInternalFormat = _gl.DEPTH24_STENCIL8;
  28146. } else if ( depthType === FloatType ) {
  28147. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  28148. } else if ( depthType === UnsignedShortType ) {
  28149. glInternalFormat = _gl.DEPTH24_STENCIL8;
  28150. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  28151. }
  28152. } else {
  28153. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  28154. glInternalFormat = _gl.DEPTH_COMPONENT24;
  28155. } else if ( depthType === FloatType ) {
  28156. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  28157. } else if ( depthType === UnsignedShortType ) {
  28158. glInternalFormat = _gl.DEPTH_COMPONENT16;
  28159. }
  28160. }
  28161. return glInternalFormat;
  28162. }
  28163. function getMipLevels( texture, image ) {
  28164. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  28165. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  28166. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  28167. // user-defined mipmaps
  28168. return texture.mipmaps.length;
  28169. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  28170. return image.mipmaps.length;
  28171. } else {
  28172. // texture without mipmaps (only base level)
  28173. return 1;
  28174. }
  28175. }
  28176. //
  28177. function onTextureDispose( event ) {
  28178. const texture = event.target;
  28179. texture.removeEventListener( 'dispose', onTextureDispose );
  28180. deallocateTexture( texture );
  28181. if ( texture.isVideoTexture ) {
  28182. _videoTextures.delete( texture );
  28183. }
  28184. }
  28185. function onRenderTargetDispose( event ) {
  28186. const renderTarget = event.target;
  28187. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  28188. deallocateRenderTarget( renderTarget );
  28189. }
  28190. //
  28191. function deallocateTexture( texture ) {
  28192. const textureProperties = properties.get( texture );
  28193. if ( textureProperties.__webglInit === undefined ) return;
  28194. // check if it's necessary to remove the WebGLTexture object
  28195. const source = texture.source;
  28196. const webglTextures = _sources.get( source );
  28197. if ( webglTextures ) {
  28198. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  28199. webglTexture.usedTimes --;
  28200. // the WebGLTexture object is not used anymore, remove it
  28201. if ( webglTexture.usedTimes === 0 ) {
  28202. deleteTexture( texture );
  28203. }
  28204. // remove the weak map entry if no WebGLTexture uses the source anymore
  28205. if ( Object.keys( webglTextures ).length === 0 ) {
  28206. _sources.delete( source );
  28207. }
  28208. }
  28209. properties.remove( texture );
  28210. }
  28211. function deleteTexture( texture ) {
  28212. const textureProperties = properties.get( texture );
  28213. _gl.deleteTexture( textureProperties.__webglTexture );
  28214. const source = texture.source;
  28215. const webglTextures = _sources.get( source );
  28216. delete webglTextures[ textureProperties.__cacheKey ];
  28217. info.memory.textures --;
  28218. }
  28219. function deallocateRenderTarget( renderTarget ) {
  28220. const renderTargetProperties = properties.get( renderTarget );
  28221. if ( renderTarget.depthTexture ) {
  28222. renderTarget.depthTexture.dispose();
  28223. properties.remove( renderTarget.depthTexture );
  28224. }
  28225. if ( renderTarget.isWebGLCubeRenderTarget ) {
  28226. for ( let i = 0; i < 6; i ++ ) {
  28227. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  28228. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  28229. } else {
  28230. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  28231. }
  28232. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  28233. }
  28234. } else {
  28235. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  28236. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  28237. } else {
  28238. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  28239. }
  28240. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  28241. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  28242. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  28243. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  28244. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  28245. }
  28246. }
  28247. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  28248. }
  28249. const textures = renderTarget.textures;
  28250. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  28251. const attachmentProperties = properties.get( textures[ i ] );
  28252. if ( attachmentProperties.__webglTexture ) {
  28253. _gl.deleteTexture( attachmentProperties.__webglTexture );
  28254. info.memory.textures --;
  28255. }
  28256. properties.remove( textures[ i ] );
  28257. }
  28258. properties.remove( renderTarget );
  28259. }
  28260. //
  28261. let textureUnits = 0;
  28262. function resetTextureUnits() {
  28263. textureUnits = 0;
  28264. }
  28265. function allocateTextureUnit() {
  28266. const textureUnit = textureUnits;
  28267. if ( textureUnit >= capabilities.maxTextures ) {
  28268. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  28269. }
  28270. textureUnits += 1;
  28271. return textureUnit;
  28272. }
  28273. function getTextureCacheKey( texture ) {
  28274. const array = [];
  28275. array.push( texture.wrapS );
  28276. array.push( texture.wrapT );
  28277. array.push( texture.wrapR || 0 );
  28278. array.push( texture.magFilter );
  28279. array.push( texture.minFilter );
  28280. array.push( texture.anisotropy );
  28281. array.push( texture.internalFormat );
  28282. array.push( texture.format );
  28283. array.push( texture.type );
  28284. array.push( texture.generateMipmaps );
  28285. array.push( texture.premultiplyAlpha );
  28286. array.push( texture.flipY );
  28287. array.push( texture.unpackAlignment );
  28288. array.push( texture.colorSpace );
  28289. return array.join();
  28290. }
  28291. //
  28292. function setTexture2D( texture, slot ) {
  28293. const textureProperties = properties.get( texture );
  28294. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  28295. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  28296. const image = texture.image;
  28297. if ( image === null ) {
  28298. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  28299. } else if ( image.complete === false ) {
  28300. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  28301. } else {
  28302. uploadTexture( textureProperties, texture, slot );
  28303. return;
  28304. }
  28305. }
  28306. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  28307. }
  28308. function setTexture2DArray( texture, slot ) {
  28309. const textureProperties = properties.get( texture );
  28310. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  28311. uploadTexture( textureProperties, texture, slot );
  28312. return;
  28313. }
  28314. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  28315. }
  28316. function setTexture3D( texture, slot ) {
  28317. const textureProperties = properties.get( texture );
  28318. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  28319. uploadTexture( textureProperties, texture, slot );
  28320. return;
  28321. }
  28322. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  28323. }
  28324. function setTextureCube( texture, slot ) {
  28325. const textureProperties = properties.get( texture );
  28326. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  28327. uploadCubeTexture( textureProperties, texture, slot );
  28328. return;
  28329. }
  28330. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  28331. }
  28332. const wrappingToGL = {
  28333. [ RepeatWrapping ]: _gl.REPEAT,
  28334. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  28335. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  28336. };
  28337. const filterToGL = {
  28338. [ NearestFilter ]: _gl.NEAREST,
  28339. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  28340. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  28341. [ LinearFilter ]: _gl.LINEAR,
  28342. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  28343. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  28344. };
  28345. const compareToGL = {
  28346. [ NeverCompare ]: _gl.NEVER,
  28347. [ AlwaysCompare ]: _gl.ALWAYS,
  28348. [ LessCompare ]: _gl.LESS,
  28349. [ LessEqualCompare ]: _gl.LEQUAL,
  28350. [ EqualCompare ]: _gl.EQUAL,
  28351. [ GreaterEqualCompare ]: _gl.GEQUAL,
  28352. [ GreaterCompare ]: _gl.GREATER,
  28353. [ NotEqualCompare ]: _gl.NOTEQUAL
  28354. };
  28355. function setTextureParameters( textureType, texture ) {
  28356. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  28357. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  28358. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  28359. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  28360. }
  28361. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  28362. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  28363. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  28364. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  28365. }
  28366. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  28367. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  28368. if ( texture.compareFunction ) {
  28369. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  28370. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  28371. }
  28372. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  28373. if ( texture.magFilter === NearestFilter ) return;
  28374. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  28375. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  28376. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  28377. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  28378. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  28379. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  28380. }
  28381. }
  28382. }
  28383. function initTexture( textureProperties, texture ) {
  28384. let forceUpload = false;
  28385. if ( textureProperties.__webglInit === undefined ) {
  28386. textureProperties.__webglInit = true;
  28387. texture.addEventListener( 'dispose', onTextureDispose );
  28388. }
  28389. // create Source <-> WebGLTextures mapping if necessary
  28390. const source = texture.source;
  28391. let webglTextures = _sources.get( source );
  28392. if ( webglTextures === undefined ) {
  28393. webglTextures = {};
  28394. _sources.set( source, webglTextures );
  28395. }
  28396. // check if there is already a WebGLTexture object for the given texture parameters
  28397. const textureCacheKey = getTextureCacheKey( texture );
  28398. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  28399. // if not, create a new instance of WebGLTexture
  28400. if ( webglTextures[ textureCacheKey ] === undefined ) {
  28401. // create new entry
  28402. webglTextures[ textureCacheKey ] = {
  28403. texture: _gl.createTexture(),
  28404. usedTimes: 0
  28405. };
  28406. info.memory.textures ++;
  28407. // when a new instance of WebGLTexture was created, a texture upload is required
  28408. // even if the image contents are identical
  28409. forceUpload = true;
  28410. }
  28411. webglTextures[ textureCacheKey ].usedTimes ++;
  28412. // every time the texture cache key changes, it's necessary to check if an instance of
  28413. // WebGLTexture can be deleted in order to avoid a memory leak.
  28414. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  28415. if ( webglTexture !== undefined ) {
  28416. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  28417. if ( webglTexture.usedTimes === 0 ) {
  28418. deleteTexture( texture );
  28419. }
  28420. }
  28421. // store references to cache key and WebGLTexture object
  28422. textureProperties.__cacheKey = textureCacheKey;
  28423. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  28424. }
  28425. return forceUpload;
  28426. }
  28427. function uploadTexture( textureProperties, texture, slot ) {
  28428. let textureType = _gl.TEXTURE_2D;
  28429. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  28430. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  28431. const forceUpload = initTexture( textureProperties, texture );
  28432. const source = texture.source;
  28433. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  28434. const sourceProperties = properties.get( source );
  28435. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  28436. state.activeTexture( _gl.TEXTURE0 + slot );
  28437. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  28438. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  28439. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  28440. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  28441. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  28442. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  28443. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  28444. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  28445. image = verifyColorSpace( texture, image );
  28446. const glFormat = utils.convert( texture.format, texture.colorSpace );
  28447. const glType = utils.convert( texture.type );
  28448. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  28449. setTextureParameters( textureType, texture );
  28450. let mipmap;
  28451. const mipmaps = texture.mipmaps;
  28452. const useTexStorage = ( texture.isVideoTexture !== true );
  28453. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  28454. const dataReady = source.dataReady;
  28455. const levels = getMipLevels( texture, image );
  28456. if ( texture.isDepthTexture ) {
  28457. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  28458. //
  28459. if ( allocateMemory ) {
  28460. if ( useTexStorage ) {
  28461. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  28462. } else {
  28463. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  28464. }
  28465. }
  28466. } else if ( texture.isDataTexture ) {
  28467. // use manually created mipmaps if available
  28468. // if there are no manual mipmaps
  28469. // set 0 level mipmap and then use GL to generate other mipmap levels
  28470. if ( mipmaps.length > 0 ) {
  28471. if ( useTexStorage && allocateMemory ) {
  28472. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  28473. }
  28474. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  28475. mipmap = mipmaps[ i ];
  28476. if ( useTexStorage ) {
  28477. if ( dataReady ) {
  28478. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  28479. }
  28480. } else {
  28481. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  28482. }
  28483. }
  28484. texture.generateMipmaps = false;
  28485. } else {
  28486. if ( useTexStorage ) {
  28487. if ( allocateMemory ) {
  28488. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  28489. }
  28490. if ( dataReady ) {
  28491. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  28492. }
  28493. } else {
  28494. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  28495. }
  28496. }
  28497. } else if ( texture.isCompressedTexture ) {
  28498. if ( texture.isCompressedArrayTexture ) {
  28499. if ( useTexStorage && allocateMemory ) {
  28500. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  28501. }
  28502. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  28503. mipmap = mipmaps[ i ];
  28504. if ( texture.format !== RGBAFormat ) {
  28505. if ( glFormat !== null ) {
  28506. if ( useTexStorage ) {
  28507. if ( dataReady ) {
  28508. if ( texture.layerUpdates.size > 0 ) {
  28509. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  28510. for ( const layerIndex of texture.layerUpdates ) {
  28511. const layerData = mipmap.data.subarray(
  28512. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  28513. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  28514. );
  28515. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  28516. }
  28517. texture.clearLayerUpdates();
  28518. } else {
  28519. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  28520. }
  28521. }
  28522. } else {
  28523. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  28524. }
  28525. } else {
  28526. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  28527. }
  28528. } else {
  28529. if ( useTexStorage ) {
  28530. if ( dataReady ) {
  28531. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  28532. }
  28533. } else {
  28534. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  28535. }
  28536. }
  28537. }
  28538. } else {
  28539. if ( useTexStorage && allocateMemory ) {
  28540. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  28541. }
  28542. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  28543. mipmap = mipmaps[ i ];
  28544. if ( texture.format !== RGBAFormat ) {
  28545. if ( glFormat !== null ) {
  28546. if ( useTexStorage ) {
  28547. if ( dataReady ) {
  28548. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  28549. }
  28550. } else {
  28551. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  28552. }
  28553. } else {
  28554. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  28555. }
  28556. } else {
  28557. if ( useTexStorage ) {
  28558. if ( dataReady ) {
  28559. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  28560. }
  28561. } else {
  28562. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  28563. }
  28564. }
  28565. }
  28566. }
  28567. } else if ( texture.isDataArrayTexture ) {
  28568. if ( useTexStorage ) {
  28569. if ( allocateMemory ) {
  28570. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  28571. }
  28572. if ( dataReady ) {
  28573. if ( texture.layerUpdates.size > 0 ) {
  28574. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  28575. for ( const layerIndex of texture.layerUpdates ) {
  28576. const layerData = image.data.subarray(
  28577. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  28578. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  28579. );
  28580. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  28581. }
  28582. texture.clearLayerUpdates();
  28583. } else {
  28584. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  28585. }
  28586. }
  28587. } else {
  28588. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  28589. }
  28590. } else if ( texture.isData3DTexture ) {
  28591. if ( useTexStorage ) {
  28592. if ( allocateMemory ) {
  28593. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  28594. }
  28595. if ( dataReady ) {
  28596. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  28597. }
  28598. } else {
  28599. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  28600. }
  28601. } else if ( texture.isFramebufferTexture ) {
  28602. if ( allocateMemory ) {
  28603. if ( useTexStorage ) {
  28604. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  28605. } else {
  28606. let width = image.width, height = image.height;
  28607. for ( let i = 0; i < levels; i ++ ) {
  28608. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  28609. width >>= 1;
  28610. height >>= 1;
  28611. }
  28612. }
  28613. }
  28614. } else {
  28615. // regular Texture (image, video, canvas)
  28616. // use manually created mipmaps if available
  28617. // if there are no manual mipmaps
  28618. // set 0 level mipmap and then use GL to generate other mipmap levels
  28619. if ( mipmaps.length > 0 ) {
  28620. if ( useTexStorage && allocateMemory ) {
  28621. const dimensions = getDimensions( mipmaps[ 0 ] );
  28622. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  28623. }
  28624. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  28625. mipmap = mipmaps[ i ];
  28626. if ( useTexStorage ) {
  28627. if ( dataReady ) {
  28628. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  28629. }
  28630. } else {
  28631. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  28632. }
  28633. }
  28634. texture.generateMipmaps = false;
  28635. } else {
  28636. if ( useTexStorage ) {
  28637. if ( allocateMemory ) {
  28638. const dimensions = getDimensions( image );
  28639. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  28640. }
  28641. if ( dataReady ) {
  28642. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  28643. }
  28644. } else {
  28645. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  28646. }
  28647. }
  28648. }
  28649. if ( textureNeedsGenerateMipmaps( texture ) ) {
  28650. generateMipmap( textureType );
  28651. }
  28652. sourceProperties.__version = source.version;
  28653. if ( texture.onUpdate ) texture.onUpdate( texture );
  28654. }
  28655. textureProperties.__version = texture.version;
  28656. }
  28657. function uploadCubeTexture( textureProperties, texture, slot ) {
  28658. if ( texture.image.length !== 6 ) return;
  28659. const forceUpload = initTexture( textureProperties, texture );
  28660. const source = texture.source;
  28661. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  28662. const sourceProperties = properties.get( source );
  28663. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  28664. state.activeTexture( _gl.TEXTURE0 + slot );
  28665. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  28666. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  28667. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  28668. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  28669. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  28670. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  28671. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  28672. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  28673. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  28674. const cubeImage = [];
  28675. for ( let i = 0; i < 6; i ++ ) {
  28676. if ( ! isCompressed && ! isDataTexture ) {
  28677. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  28678. } else {
  28679. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  28680. }
  28681. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  28682. }
  28683. const image = cubeImage[ 0 ],
  28684. glFormat = utils.convert( texture.format, texture.colorSpace ),
  28685. glType = utils.convert( texture.type ),
  28686. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  28687. const useTexStorage = ( texture.isVideoTexture !== true );
  28688. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  28689. const dataReady = source.dataReady;
  28690. let levels = getMipLevels( texture, image );
  28691. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  28692. let mipmaps;
  28693. if ( isCompressed ) {
  28694. if ( useTexStorage && allocateMemory ) {
  28695. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  28696. }
  28697. for ( let i = 0; i < 6; i ++ ) {
  28698. mipmaps = cubeImage[ i ].mipmaps;
  28699. for ( let j = 0; j < mipmaps.length; j ++ ) {
  28700. const mipmap = mipmaps[ j ];
  28701. if ( texture.format !== RGBAFormat ) {
  28702. if ( glFormat !== null ) {
  28703. if ( useTexStorage ) {
  28704. if ( dataReady ) {
  28705. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  28706. }
  28707. } else {
  28708. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  28709. }
  28710. } else {
  28711. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  28712. }
  28713. } else {
  28714. if ( useTexStorage ) {
  28715. if ( dataReady ) {
  28716. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  28717. }
  28718. } else {
  28719. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  28720. }
  28721. }
  28722. }
  28723. }
  28724. } else {
  28725. mipmaps = texture.mipmaps;
  28726. if ( useTexStorage && allocateMemory ) {
  28727. // TODO: Uniformly handle mipmap definitions
  28728. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  28729. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  28730. if ( mipmaps.length > 0 ) levels ++;
  28731. const dimensions = getDimensions( cubeImage[ 0 ] );
  28732. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  28733. }
  28734. for ( let i = 0; i < 6; i ++ ) {
  28735. if ( isDataTexture ) {
  28736. if ( useTexStorage ) {
  28737. if ( dataReady ) {
  28738. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  28739. }
  28740. } else {
  28741. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  28742. }
  28743. for ( let j = 0; j < mipmaps.length; j ++ ) {
  28744. const mipmap = mipmaps[ j ];
  28745. const mipmapImage = mipmap.image[ i ].image;
  28746. if ( useTexStorage ) {
  28747. if ( dataReady ) {
  28748. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  28749. }
  28750. } else {
  28751. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  28752. }
  28753. }
  28754. } else {
  28755. if ( useTexStorage ) {
  28756. if ( dataReady ) {
  28757. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  28758. }
  28759. } else {
  28760. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  28761. }
  28762. for ( let j = 0; j < mipmaps.length; j ++ ) {
  28763. const mipmap = mipmaps[ j ];
  28764. if ( useTexStorage ) {
  28765. if ( dataReady ) {
  28766. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  28767. }
  28768. } else {
  28769. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  28770. }
  28771. }
  28772. }
  28773. }
  28774. }
  28775. if ( textureNeedsGenerateMipmaps( texture ) ) {
  28776. // We assume images for cube map have the same size.
  28777. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  28778. }
  28779. sourceProperties.__version = source.version;
  28780. if ( texture.onUpdate ) texture.onUpdate( texture );
  28781. }
  28782. textureProperties.__version = texture.version;
  28783. }
  28784. // Render targets
  28785. // Setup storage for target texture and bind it to correct framebuffer
  28786. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  28787. const glFormat = utils.convert( texture.format, texture.colorSpace );
  28788. const glType = utils.convert( texture.type );
  28789. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  28790. const renderTargetProperties = properties.get( renderTarget );
  28791. const textureProperties = properties.get( texture );
  28792. textureProperties.__renderTarget = renderTarget;
  28793. if ( ! renderTargetProperties.__hasExternalTextures ) {
  28794. const width = Math.max( 1, renderTarget.width >> level );
  28795. const height = Math.max( 1, renderTarget.height >> level );
  28796. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  28797. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  28798. } else {
  28799. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  28800. }
  28801. }
  28802. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  28803. if ( useMultisampledRTT( renderTarget ) ) {
  28804. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  28805. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  28806. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  28807. }
  28808. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  28809. }
  28810. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  28811. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  28812. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  28813. if ( renderTarget.depthBuffer ) {
  28814. // retrieve the depth attachment types
  28815. const depthTexture = renderTarget.depthTexture;
  28816. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  28817. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  28818. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  28819. // set up the attachment
  28820. const samples = getRenderTargetSamples( renderTarget );
  28821. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  28822. if ( isUseMultisampledRTT ) {
  28823. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  28824. } else if ( isMultisample ) {
  28825. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  28826. } else {
  28827. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  28828. }
  28829. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  28830. } else {
  28831. const textures = renderTarget.textures;
  28832. for ( let i = 0; i < textures.length; i ++ ) {
  28833. const texture = textures[ i ];
  28834. const glFormat = utils.convert( texture.format, texture.colorSpace );
  28835. const glType = utils.convert( texture.type );
  28836. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  28837. const samples = getRenderTargetSamples( renderTarget );
  28838. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  28839. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  28840. } else if ( useMultisampledRTT( renderTarget ) ) {
  28841. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  28842. } else {
  28843. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  28844. }
  28845. }
  28846. }
  28847. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  28848. }
  28849. // Setup resources for a Depth Texture for a FBO (needs an extension)
  28850. function setupDepthTexture( framebuffer, renderTarget ) {
  28851. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  28852. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  28853. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  28854. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  28855. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  28856. }
  28857. const textureProperties = properties.get( renderTarget.depthTexture );
  28858. textureProperties.__renderTarget = renderTarget;
  28859. // upload an empty depth texture with framebuffer size
  28860. if ( ! textureProperties.__webglTexture ||
  28861. renderTarget.depthTexture.image.width !== renderTarget.width ||
  28862. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  28863. renderTarget.depthTexture.image.width = renderTarget.width;
  28864. renderTarget.depthTexture.image.height = renderTarget.height;
  28865. renderTarget.depthTexture.needsUpdate = true;
  28866. }
  28867. setTexture2D( renderTarget.depthTexture, 0 );
  28868. const webglDepthTexture = textureProperties.__webglTexture;
  28869. const samples = getRenderTargetSamples( renderTarget );
  28870. if ( renderTarget.depthTexture.format === DepthFormat ) {
  28871. if ( useMultisampledRTT( renderTarget ) ) {
  28872. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  28873. } else {
  28874. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  28875. }
  28876. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  28877. if ( useMultisampledRTT( renderTarget ) ) {
  28878. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  28879. } else {
  28880. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  28881. }
  28882. } else {
  28883. throw new Error( 'Unknown depthTexture format' );
  28884. }
  28885. }
  28886. // Setup GL resources for a non-texture depth buffer
  28887. function setupDepthRenderbuffer( renderTarget ) {
  28888. const renderTargetProperties = properties.get( renderTarget );
  28889. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  28890. // if the bound depth texture has changed
  28891. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  28892. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  28893. const depthTexture = renderTarget.depthTexture;
  28894. if ( renderTargetProperties.__depthDisposeCallback ) {
  28895. renderTargetProperties.__depthDisposeCallback();
  28896. }
  28897. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  28898. if ( depthTexture ) {
  28899. const disposeEvent = () => {
  28900. delete renderTargetProperties.__boundDepthTexture;
  28901. delete renderTargetProperties.__depthDisposeCallback;
  28902. depthTexture.removeEventListener( 'dispose', disposeEvent );
  28903. };
  28904. depthTexture.addEventListener( 'dispose', disposeEvent );
  28905. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  28906. }
  28907. renderTargetProperties.__boundDepthTexture = depthTexture;
  28908. }
  28909. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  28910. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  28911. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  28912. } else {
  28913. if ( isCube ) {
  28914. renderTargetProperties.__webglDepthbuffer = [];
  28915. for ( let i = 0; i < 6; i ++ ) {
  28916. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  28917. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  28918. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  28919. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  28920. } else {
  28921. // attach buffer if it's been created already
  28922. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  28923. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  28924. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  28925. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  28926. }
  28927. }
  28928. } else {
  28929. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  28930. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  28931. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  28932. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  28933. } else {
  28934. // attach buffer if it's been created already
  28935. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  28936. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  28937. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  28938. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  28939. }
  28940. }
  28941. }
  28942. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  28943. }
  28944. // rebind framebuffer with external textures
  28945. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  28946. const renderTargetProperties = properties.get( renderTarget );
  28947. if ( colorTexture !== undefined ) {
  28948. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  28949. }
  28950. if ( depthTexture !== undefined ) {
  28951. setupDepthRenderbuffer( renderTarget );
  28952. }
  28953. }
  28954. // Set up GL resources for the render target
  28955. function setupRenderTarget( renderTarget ) {
  28956. const texture = renderTarget.texture;
  28957. const renderTargetProperties = properties.get( renderTarget );
  28958. const textureProperties = properties.get( texture );
  28959. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  28960. const textures = renderTarget.textures;
  28961. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  28962. const isMultipleRenderTargets = ( textures.length > 1 );
  28963. if ( ! isMultipleRenderTargets ) {
  28964. if ( textureProperties.__webglTexture === undefined ) {
  28965. textureProperties.__webglTexture = _gl.createTexture();
  28966. }
  28967. textureProperties.__version = texture.version;
  28968. info.memory.textures ++;
  28969. }
  28970. // Setup framebuffer
  28971. if ( isCube ) {
  28972. renderTargetProperties.__webglFramebuffer = [];
  28973. for ( let i = 0; i < 6; i ++ ) {
  28974. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  28975. renderTargetProperties.__webglFramebuffer[ i ] = [];
  28976. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  28977. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  28978. }
  28979. } else {
  28980. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  28981. }
  28982. }
  28983. } else {
  28984. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  28985. renderTargetProperties.__webglFramebuffer = [];
  28986. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  28987. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  28988. }
  28989. } else {
  28990. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  28991. }
  28992. if ( isMultipleRenderTargets ) {
  28993. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  28994. const attachmentProperties = properties.get( textures[ i ] );
  28995. if ( attachmentProperties.__webglTexture === undefined ) {
  28996. attachmentProperties.__webglTexture = _gl.createTexture();
  28997. info.memory.textures ++;
  28998. }
  28999. }
  29000. }
  29001. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  29002. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  29003. renderTargetProperties.__webglColorRenderbuffer = [];
  29004. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  29005. for ( let i = 0; i < textures.length; i ++ ) {
  29006. const texture = textures[ i ];
  29007. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  29008. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  29009. const glFormat = utils.convert( texture.format, texture.colorSpace );
  29010. const glType = utils.convert( texture.type );
  29011. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  29012. const samples = getRenderTargetSamples( renderTarget );
  29013. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  29014. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  29015. }
  29016. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  29017. if ( renderTarget.depthBuffer ) {
  29018. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  29019. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  29020. }
  29021. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  29022. }
  29023. }
  29024. // Setup color buffer
  29025. if ( isCube ) {
  29026. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  29027. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  29028. for ( let i = 0; i < 6; i ++ ) {
  29029. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  29030. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  29031. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  29032. }
  29033. } else {
  29034. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  29035. }
  29036. }
  29037. if ( textureNeedsGenerateMipmaps( texture ) ) {
  29038. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  29039. }
  29040. state.unbindTexture();
  29041. } else if ( isMultipleRenderTargets ) {
  29042. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  29043. const attachment = textures[ i ];
  29044. const attachmentProperties = properties.get( attachment );
  29045. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  29046. setTextureParameters( _gl.TEXTURE_2D, attachment );
  29047. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  29048. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  29049. generateMipmap( _gl.TEXTURE_2D );
  29050. }
  29051. }
  29052. state.unbindTexture();
  29053. } else {
  29054. let glTextureType = _gl.TEXTURE_2D;
  29055. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  29056. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  29057. }
  29058. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  29059. setTextureParameters( glTextureType, texture );
  29060. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  29061. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  29062. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  29063. }
  29064. } else {
  29065. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  29066. }
  29067. if ( textureNeedsGenerateMipmaps( texture ) ) {
  29068. generateMipmap( glTextureType );
  29069. }
  29070. state.unbindTexture();
  29071. }
  29072. // Setup depth and stencil buffers
  29073. if ( renderTarget.depthBuffer ) {
  29074. setupDepthRenderbuffer( renderTarget );
  29075. }
  29076. }
  29077. function updateRenderTargetMipmap( renderTarget ) {
  29078. const textures = renderTarget.textures;
  29079. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  29080. const texture = textures[ i ];
  29081. if ( textureNeedsGenerateMipmaps( texture ) ) {
  29082. const targetType = getTargetType( renderTarget );
  29083. const webglTexture = properties.get( texture ).__webglTexture;
  29084. state.bindTexture( targetType, webglTexture );
  29085. generateMipmap( targetType );
  29086. state.unbindTexture();
  29087. }
  29088. }
  29089. }
  29090. const invalidationArrayRead = [];
  29091. const invalidationArrayDraw = [];
  29092. function updateMultisampleRenderTarget( renderTarget ) {
  29093. if ( renderTarget.samples > 0 ) {
  29094. if ( useMultisampledRTT( renderTarget ) === false ) {
  29095. const textures = renderTarget.textures;
  29096. const width = renderTarget.width;
  29097. const height = renderTarget.height;
  29098. let mask = _gl.COLOR_BUFFER_BIT;
  29099. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  29100. const renderTargetProperties = properties.get( renderTarget );
  29101. const isMultipleRenderTargets = ( textures.length > 1 );
  29102. // If MRT we need to remove FBO attachments
  29103. if ( isMultipleRenderTargets ) {
  29104. for ( let i = 0; i < textures.length; i ++ ) {
  29105. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  29106. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  29107. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  29108. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  29109. }
  29110. }
  29111. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  29112. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  29113. for ( let i = 0; i < textures.length; i ++ ) {
  29114. if ( renderTarget.resolveDepthBuffer ) {
  29115. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  29116. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  29117. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  29118. }
  29119. if ( isMultipleRenderTargets ) {
  29120. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  29121. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  29122. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  29123. }
  29124. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  29125. if ( supportsInvalidateFramebuffer === true ) {
  29126. invalidationArrayRead.length = 0;
  29127. invalidationArrayDraw.length = 0;
  29128. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  29129. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  29130. invalidationArrayRead.push( depthStyle );
  29131. invalidationArrayDraw.push( depthStyle );
  29132. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  29133. }
  29134. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  29135. }
  29136. }
  29137. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  29138. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  29139. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  29140. if ( isMultipleRenderTargets ) {
  29141. for ( let i = 0; i < textures.length; i ++ ) {
  29142. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  29143. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  29144. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  29145. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  29146. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  29147. }
  29148. }
  29149. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  29150. } else {
  29151. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  29152. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  29153. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  29154. }
  29155. }
  29156. }
  29157. }
  29158. function getRenderTargetSamples( renderTarget ) {
  29159. return Math.min( capabilities.maxSamples, renderTarget.samples );
  29160. }
  29161. function useMultisampledRTT( renderTarget ) {
  29162. const renderTargetProperties = properties.get( renderTarget );
  29163. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  29164. }
  29165. function updateVideoTexture( texture ) {
  29166. const frame = info.render.frame;
  29167. // Check the last frame we updated the VideoTexture
  29168. if ( _videoTextures.get( texture ) !== frame ) {
  29169. _videoTextures.set( texture, frame );
  29170. texture.update();
  29171. }
  29172. }
  29173. function verifyColorSpace( texture, image ) {
  29174. const colorSpace = texture.colorSpace;
  29175. const format = texture.format;
  29176. const type = texture.type;
  29177. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  29178. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  29179. // sRGB
  29180. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  29181. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  29182. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  29183. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  29184. }
  29185. } else {
  29186. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  29187. }
  29188. }
  29189. return image;
  29190. }
  29191. function getDimensions( image ) {
  29192. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  29193. // if intrinsic data are not available, fallback to width/height
  29194. _imageDimensions.width = image.naturalWidth || image.width;
  29195. _imageDimensions.height = image.naturalHeight || image.height;
  29196. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  29197. _imageDimensions.width = image.displayWidth;
  29198. _imageDimensions.height = image.displayHeight;
  29199. } else {
  29200. _imageDimensions.width = image.width;
  29201. _imageDimensions.height = image.height;
  29202. }
  29203. return _imageDimensions;
  29204. }
  29205. //
  29206. this.allocateTextureUnit = allocateTextureUnit;
  29207. this.resetTextureUnits = resetTextureUnits;
  29208. this.setTexture2D = setTexture2D;
  29209. this.setTexture2DArray = setTexture2DArray;
  29210. this.setTexture3D = setTexture3D;
  29211. this.setTextureCube = setTextureCube;
  29212. this.rebindTextures = rebindTextures;
  29213. this.setupRenderTarget = setupRenderTarget;
  29214. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  29215. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  29216. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  29217. this.setupFrameBufferTexture = setupFrameBufferTexture;
  29218. this.useMultisampledRTT = useMultisampledRTT;
  29219. }
  29220. function WebGLUtils( gl, extensions ) {
  29221. function convert( p, colorSpace = NoColorSpace ) {
  29222. let extension;
  29223. const transfer = ColorManagement.getTransfer( colorSpace );
  29224. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  29225. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  29226. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  29227. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  29228. if ( p === ByteType ) return gl.BYTE;
  29229. if ( p === ShortType ) return gl.SHORT;
  29230. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  29231. if ( p === IntType ) return gl.INT;
  29232. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  29233. if ( p === FloatType ) return gl.FLOAT;
  29234. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  29235. if ( p === AlphaFormat ) return gl.ALPHA;
  29236. if ( p === RGBFormat ) return gl.RGB;
  29237. if ( p === RGBAFormat ) return gl.RGBA;
  29238. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  29239. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  29240. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  29241. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  29242. // WebGL2 formats.
  29243. if ( p === RedFormat ) return gl.RED;
  29244. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  29245. if ( p === RGFormat ) return gl.RG;
  29246. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  29247. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  29248. // S3TC
  29249. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  29250. if ( transfer === SRGBTransfer ) {
  29251. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  29252. if ( extension !== null ) {
  29253. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  29254. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  29255. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  29256. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  29257. } else {
  29258. return null;
  29259. }
  29260. } else {
  29261. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  29262. if ( extension !== null ) {
  29263. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  29264. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  29265. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  29266. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  29267. } else {
  29268. return null;
  29269. }
  29270. }
  29271. }
  29272. // PVRTC
  29273. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  29274. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  29275. if ( extension !== null ) {
  29276. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  29277. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  29278. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  29279. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  29280. } else {
  29281. return null;
  29282. }
  29283. }
  29284. // ETC
  29285. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  29286. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  29287. if ( extension !== null ) {
  29288. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  29289. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  29290. } else {
  29291. return null;
  29292. }
  29293. }
  29294. // ASTC
  29295. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  29296. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  29297. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  29298. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  29299. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  29300. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  29301. if ( extension !== null ) {
  29302. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  29303. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  29304. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  29305. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  29306. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  29307. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  29308. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  29309. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  29310. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  29311. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  29312. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  29313. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  29314. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  29315. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  29316. } else {
  29317. return null;
  29318. }
  29319. }
  29320. // BPTC
  29321. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  29322. extension = extensions.get( 'EXT_texture_compression_bptc' );
  29323. if ( extension !== null ) {
  29324. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  29325. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  29326. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  29327. } else {
  29328. return null;
  29329. }
  29330. }
  29331. // RGTC
  29332. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  29333. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  29334. if ( extension !== null ) {
  29335. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  29336. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  29337. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  29338. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  29339. } else {
  29340. return null;
  29341. }
  29342. }
  29343. //
  29344. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  29345. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  29346. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  29347. }
  29348. return { convert: convert };
  29349. }
  29350. const _moveEvent = { type: 'move' };
  29351. class WebXRController {
  29352. constructor() {
  29353. this._targetRay = null;
  29354. this._grip = null;
  29355. this._hand = null;
  29356. }
  29357. getHandSpace() {
  29358. if ( this._hand === null ) {
  29359. this._hand = new Group();
  29360. this._hand.matrixAutoUpdate = false;
  29361. this._hand.visible = false;
  29362. this._hand.joints = {};
  29363. this._hand.inputState = { pinching: false };
  29364. }
  29365. return this._hand;
  29366. }
  29367. getTargetRaySpace() {
  29368. if ( this._targetRay === null ) {
  29369. this._targetRay = new Group();
  29370. this._targetRay.matrixAutoUpdate = false;
  29371. this._targetRay.visible = false;
  29372. this._targetRay.hasLinearVelocity = false;
  29373. this._targetRay.linearVelocity = new Vector3();
  29374. this._targetRay.hasAngularVelocity = false;
  29375. this._targetRay.angularVelocity = new Vector3();
  29376. }
  29377. return this._targetRay;
  29378. }
  29379. getGripSpace() {
  29380. if ( this._grip === null ) {
  29381. this._grip = new Group();
  29382. this._grip.matrixAutoUpdate = false;
  29383. this._grip.visible = false;
  29384. this._grip.hasLinearVelocity = false;
  29385. this._grip.linearVelocity = new Vector3();
  29386. this._grip.hasAngularVelocity = false;
  29387. this._grip.angularVelocity = new Vector3();
  29388. }
  29389. return this._grip;
  29390. }
  29391. dispatchEvent( event ) {
  29392. if ( this._targetRay !== null ) {
  29393. this._targetRay.dispatchEvent( event );
  29394. }
  29395. if ( this._grip !== null ) {
  29396. this._grip.dispatchEvent( event );
  29397. }
  29398. if ( this._hand !== null ) {
  29399. this._hand.dispatchEvent( event );
  29400. }
  29401. return this;
  29402. }
  29403. connect( inputSource ) {
  29404. if ( inputSource && inputSource.hand ) {
  29405. const hand = this._hand;
  29406. if ( hand ) {
  29407. for ( const inputjoint of inputSource.hand.values() ) {
  29408. // Initialize hand with joints when connected
  29409. this._getHandJoint( hand, inputjoint );
  29410. }
  29411. }
  29412. }
  29413. this.dispatchEvent( { type: 'connected', data: inputSource } );
  29414. return this;
  29415. }
  29416. disconnect( inputSource ) {
  29417. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  29418. if ( this._targetRay !== null ) {
  29419. this._targetRay.visible = false;
  29420. }
  29421. if ( this._grip !== null ) {
  29422. this._grip.visible = false;
  29423. }
  29424. if ( this._hand !== null ) {
  29425. this._hand.visible = false;
  29426. }
  29427. return this;
  29428. }
  29429. update( inputSource, frame, referenceSpace ) {
  29430. let inputPose = null;
  29431. let gripPose = null;
  29432. let handPose = null;
  29433. const targetRay = this._targetRay;
  29434. const grip = this._grip;
  29435. const hand = this._hand;
  29436. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  29437. if ( hand && inputSource.hand ) {
  29438. handPose = true;
  29439. for ( const inputjoint of inputSource.hand.values() ) {
  29440. // Update the joints groups with the XRJoint poses
  29441. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  29442. // The transform of this joint will be updated with the joint pose on each frame
  29443. const joint = this._getHandJoint( hand, inputjoint );
  29444. if ( jointPose !== null ) {
  29445. joint.matrix.fromArray( jointPose.transform.matrix );
  29446. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  29447. joint.matrixWorldNeedsUpdate = true;
  29448. joint.jointRadius = jointPose.radius;
  29449. }
  29450. joint.visible = jointPose !== null;
  29451. }
  29452. // Custom events
  29453. // Check pinchz
  29454. const indexTip = hand.joints[ 'index-finger-tip' ];
  29455. const thumbTip = hand.joints[ 'thumb-tip' ];
  29456. const distance = indexTip.position.distanceTo( thumbTip.position );
  29457. const distanceToPinch = 0.02;
  29458. const threshold = 0.005;
  29459. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  29460. hand.inputState.pinching = false;
  29461. this.dispatchEvent( {
  29462. type: 'pinchend',
  29463. handedness: inputSource.handedness,
  29464. target: this
  29465. } );
  29466. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  29467. hand.inputState.pinching = true;
  29468. this.dispatchEvent( {
  29469. type: 'pinchstart',
  29470. handedness: inputSource.handedness,
  29471. target: this
  29472. } );
  29473. }
  29474. } else {
  29475. if ( grip !== null && inputSource.gripSpace ) {
  29476. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  29477. if ( gripPose !== null ) {
  29478. grip.matrix.fromArray( gripPose.transform.matrix );
  29479. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  29480. grip.matrixWorldNeedsUpdate = true;
  29481. if ( gripPose.linearVelocity ) {
  29482. grip.hasLinearVelocity = true;
  29483. grip.linearVelocity.copy( gripPose.linearVelocity );
  29484. } else {
  29485. grip.hasLinearVelocity = false;
  29486. }
  29487. if ( gripPose.angularVelocity ) {
  29488. grip.hasAngularVelocity = true;
  29489. grip.angularVelocity.copy( gripPose.angularVelocity );
  29490. } else {
  29491. grip.hasAngularVelocity = false;
  29492. }
  29493. }
  29494. }
  29495. }
  29496. if ( targetRay !== null ) {
  29497. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  29498. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  29499. if ( inputPose === null && gripPose !== null ) {
  29500. inputPose = gripPose;
  29501. }
  29502. if ( inputPose !== null ) {
  29503. targetRay.matrix.fromArray( inputPose.transform.matrix );
  29504. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  29505. targetRay.matrixWorldNeedsUpdate = true;
  29506. if ( inputPose.linearVelocity ) {
  29507. targetRay.hasLinearVelocity = true;
  29508. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  29509. } else {
  29510. targetRay.hasLinearVelocity = false;
  29511. }
  29512. if ( inputPose.angularVelocity ) {
  29513. targetRay.hasAngularVelocity = true;
  29514. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  29515. } else {
  29516. targetRay.hasAngularVelocity = false;
  29517. }
  29518. this.dispatchEvent( _moveEvent );
  29519. }
  29520. }
  29521. }
  29522. if ( targetRay !== null ) {
  29523. targetRay.visible = ( inputPose !== null );
  29524. }
  29525. if ( grip !== null ) {
  29526. grip.visible = ( gripPose !== null );
  29527. }
  29528. if ( hand !== null ) {
  29529. hand.visible = ( handPose !== null );
  29530. }
  29531. return this;
  29532. }
  29533. // private method
  29534. _getHandJoint( hand, inputjoint ) {
  29535. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  29536. const joint = new Group();
  29537. joint.matrixAutoUpdate = false;
  29538. joint.visible = false;
  29539. hand.joints[ inputjoint.jointName ] = joint;
  29540. hand.add( joint );
  29541. }
  29542. return hand.joints[ inputjoint.jointName ];
  29543. }
  29544. }
  29545. const _occlusion_vertex = `
  29546. void main() {
  29547. gl_Position = vec4( position, 1.0 );
  29548. }`;
  29549. const _occlusion_fragment = `
  29550. uniform sampler2DArray depthColor;
  29551. uniform float depthWidth;
  29552. uniform float depthHeight;
  29553. void main() {
  29554. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  29555. if ( coord.x >= 1.0 ) {
  29556. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  29557. } else {
  29558. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  29559. }
  29560. }`;
  29561. class WebXRDepthSensing {
  29562. constructor() {
  29563. this.texture = null;
  29564. this.mesh = null;
  29565. this.depthNear = 0;
  29566. this.depthFar = 0;
  29567. }
  29568. init( renderer, depthData, renderState ) {
  29569. if ( this.texture === null ) {
  29570. const texture = new Texture();
  29571. const texProps = renderer.properties.get( texture );
  29572. texProps.__webglTexture = depthData.texture;
  29573. if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) {
  29574. this.depthNear = depthData.depthNear;
  29575. this.depthFar = depthData.depthFar;
  29576. }
  29577. this.texture = texture;
  29578. }
  29579. }
  29580. getMesh( cameraXR ) {
  29581. if ( this.texture !== null ) {
  29582. if ( this.mesh === null ) {
  29583. const viewport = cameraXR.cameras[ 0 ].viewport;
  29584. const material = new ShaderMaterial( {
  29585. vertexShader: _occlusion_vertex,
  29586. fragmentShader: _occlusion_fragment,
  29587. uniforms: {
  29588. depthColor: { value: this.texture },
  29589. depthWidth: { value: viewport.z },
  29590. depthHeight: { value: viewport.w }
  29591. }
  29592. } );
  29593. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  29594. }
  29595. }
  29596. return this.mesh;
  29597. }
  29598. reset() {
  29599. this.texture = null;
  29600. this.mesh = null;
  29601. }
  29602. getDepthTexture() {
  29603. return this.texture;
  29604. }
  29605. }
  29606. class WebXRManager extends EventDispatcher {
  29607. constructor( renderer, gl ) {
  29608. super();
  29609. const scope = this;
  29610. let session = null;
  29611. let framebufferScaleFactor = 1.0;
  29612. let referenceSpace = null;
  29613. let referenceSpaceType = 'local-floor';
  29614. // Set default foveation to maximum.
  29615. let foveation = 1.0;
  29616. let customReferenceSpace = null;
  29617. let pose = null;
  29618. let glBinding = null;
  29619. let glProjLayer = null;
  29620. let glBaseLayer = null;
  29621. let xrFrame = null;
  29622. const depthSensing = new WebXRDepthSensing();
  29623. const attributes = gl.getContextAttributes();
  29624. let initialRenderTarget = null;
  29625. let newRenderTarget = null;
  29626. const controllers = [];
  29627. const controllerInputSources = [];
  29628. const currentSize = new Vector2();
  29629. let currentPixelRatio = null;
  29630. //
  29631. const cameraL = new PerspectiveCamera();
  29632. cameraL.viewport = new Vector4();
  29633. const cameraR = new PerspectiveCamera();
  29634. cameraR.viewport = new Vector4();
  29635. const cameras = [ cameraL, cameraR ];
  29636. const cameraXR = new ArrayCamera();
  29637. let _currentDepthNear = null;
  29638. let _currentDepthFar = null;
  29639. //
  29640. this.cameraAutoUpdate = true;
  29641. this.enabled = false;
  29642. this.isPresenting = false;
  29643. this.getController = function ( index ) {
  29644. let controller = controllers[ index ];
  29645. if ( controller === undefined ) {
  29646. controller = new WebXRController();
  29647. controllers[ index ] = controller;
  29648. }
  29649. return controller.getTargetRaySpace();
  29650. };
  29651. this.getControllerGrip = function ( index ) {
  29652. let controller = controllers[ index ];
  29653. if ( controller === undefined ) {
  29654. controller = new WebXRController();
  29655. controllers[ index ] = controller;
  29656. }
  29657. return controller.getGripSpace();
  29658. };
  29659. this.getHand = function ( index ) {
  29660. let controller = controllers[ index ];
  29661. if ( controller === undefined ) {
  29662. controller = new WebXRController();
  29663. controllers[ index ] = controller;
  29664. }
  29665. return controller.getHandSpace();
  29666. };
  29667. //
  29668. function onSessionEvent( event ) {
  29669. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  29670. if ( controllerIndex === - 1 ) {
  29671. return;
  29672. }
  29673. const controller = controllers[ controllerIndex ];
  29674. if ( controller !== undefined ) {
  29675. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  29676. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  29677. }
  29678. }
  29679. function onSessionEnd() {
  29680. session.removeEventListener( 'select', onSessionEvent );
  29681. session.removeEventListener( 'selectstart', onSessionEvent );
  29682. session.removeEventListener( 'selectend', onSessionEvent );
  29683. session.removeEventListener( 'squeeze', onSessionEvent );
  29684. session.removeEventListener( 'squeezestart', onSessionEvent );
  29685. session.removeEventListener( 'squeezeend', onSessionEvent );
  29686. session.removeEventListener( 'end', onSessionEnd );
  29687. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  29688. for ( let i = 0; i < controllers.length; i ++ ) {
  29689. const inputSource = controllerInputSources[ i ];
  29690. if ( inputSource === null ) continue;
  29691. controllerInputSources[ i ] = null;
  29692. controllers[ i ].disconnect( inputSource );
  29693. }
  29694. _currentDepthNear = null;
  29695. _currentDepthFar = null;
  29696. depthSensing.reset();
  29697. // restore framebuffer/rendering state
  29698. renderer.setRenderTarget( initialRenderTarget );
  29699. glBaseLayer = null;
  29700. glProjLayer = null;
  29701. glBinding = null;
  29702. session = null;
  29703. newRenderTarget = null;
  29704. //
  29705. animation.stop();
  29706. scope.isPresenting = false;
  29707. renderer.setPixelRatio( currentPixelRatio );
  29708. renderer.setSize( currentSize.width, currentSize.height, false );
  29709. scope.dispatchEvent( { type: 'sessionend' } );
  29710. }
  29711. this.setFramebufferScaleFactor = function ( value ) {
  29712. framebufferScaleFactor = value;
  29713. if ( scope.isPresenting === true ) {
  29714. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  29715. }
  29716. };
  29717. this.setReferenceSpaceType = function ( value ) {
  29718. referenceSpaceType = value;
  29719. if ( scope.isPresenting === true ) {
  29720. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  29721. }
  29722. };
  29723. this.getReferenceSpace = function () {
  29724. return customReferenceSpace || referenceSpace;
  29725. };
  29726. this.setReferenceSpace = function ( space ) {
  29727. customReferenceSpace = space;
  29728. };
  29729. this.getBaseLayer = function () {
  29730. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  29731. };
  29732. this.getBinding = function () {
  29733. return glBinding;
  29734. };
  29735. this.getFrame = function () {
  29736. return xrFrame;
  29737. };
  29738. this.getSession = function () {
  29739. return session;
  29740. };
  29741. this.setSession = async function ( value ) {
  29742. session = value;
  29743. if ( session !== null ) {
  29744. initialRenderTarget = renderer.getRenderTarget();
  29745. session.addEventListener( 'select', onSessionEvent );
  29746. session.addEventListener( 'selectstart', onSessionEvent );
  29747. session.addEventListener( 'selectend', onSessionEvent );
  29748. session.addEventListener( 'squeeze', onSessionEvent );
  29749. session.addEventListener( 'squeezestart', onSessionEvent );
  29750. session.addEventListener( 'squeezeend', onSessionEvent );
  29751. session.addEventListener( 'end', onSessionEnd );
  29752. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  29753. if ( attributes.xrCompatible !== true ) {
  29754. await gl.makeXRCompatible();
  29755. }
  29756. currentPixelRatio = renderer.getPixelRatio();
  29757. renderer.getSize( currentSize );
  29758. if ( session.renderState.layers === undefined ) {
  29759. const layerInit = {
  29760. antialias: attributes.antialias,
  29761. alpha: true,
  29762. depth: attributes.depth,
  29763. stencil: attributes.stencil,
  29764. framebufferScaleFactor: framebufferScaleFactor
  29765. };
  29766. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  29767. session.updateRenderState( { baseLayer: glBaseLayer } );
  29768. renderer.setPixelRatio( 1 );
  29769. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  29770. newRenderTarget = new WebGLRenderTarget(
  29771. glBaseLayer.framebufferWidth,
  29772. glBaseLayer.framebufferHeight,
  29773. {
  29774. format: RGBAFormat,
  29775. type: UnsignedByteType,
  29776. colorSpace: renderer.outputColorSpace,
  29777. stencilBuffer: attributes.stencil
  29778. }
  29779. );
  29780. } else {
  29781. let depthFormat = null;
  29782. let depthType = null;
  29783. let glDepthFormat = null;
  29784. if ( attributes.depth ) {
  29785. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  29786. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  29787. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  29788. }
  29789. const projectionlayerInit = {
  29790. colorFormat: gl.RGBA8,
  29791. depthFormat: glDepthFormat,
  29792. scaleFactor: framebufferScaleFactor
  29793. };
  29794. glBinding = new XRWebGLBinding( session, gl );
  29795. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  29796. session.updateRenderState( { layers: [ glProjLayer ] } );
  29797. renderer.setPixelRatio( 1 );
  29798. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  29799. newRenderTarget = new WebGLRenderTarget(
  29800. glProjLayer.textureWidth,
  29801. glProjLayer.textureHeight,
  29802. {
  29803. format: RGBAFormat,
  29804. type: UnsignedByteType,
  29805. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  29806. stencilBuffer: attributes.stencil,
  29807. colorSpace: renderer.outputColorSpace,
  29808. samples: attributes.antialias ? 4 : 0,
  29809. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false )
  29810. } );
  29811. }
  29812. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  29813. this.setFoveation( foveation );
  29814. customReferenceSpace = null;
  29815. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  29816. animation.setContext( session );
  29817. animation.start();
  29818. scope.isPresenting = true;
  29819. scope.dispatchEvent( { type: 'sessionstart' } );
  29820. }
  29821. };
  29822. this.getEnvironmentBlendMode = function () {
  29823. if ( session !== null ) {
  29824. return session.environmentBlendMode;
  29825. }
  29826. };
  29827. this.getDepthTexture = function () {
  29828. return depthSensing.getDepthTexture();
  29829. };
  29830. function onInputSourcesChange( event ) {
  29831. // Notify disconnected
  29832. for ( let i = 0; i < event.removed.length; i ++ ) {
  29833. const inputSource = event.removed[ i ];
  29834. const index = controllerInputSources.indexOf( inputSource );
  29835. if ( index >= 0 ) {
  29836. controllerInputSources[ index ] = null;
  29837. controllers[ index ].disconnect( inputSource );
  29838. }
  29839. }
  29840. // Notify connected
  29841. for ( let i = 0; i < event.added.length; i ++ ) {
  29842. const inputSource = event.added[ i ];
  29843. let controllerIndex = controllerInputSources.indexOf( inputSource );
  29844. if ( controllerIndex === - 1 ) {
  29845. // Assign input source a controller that currently has no input source
  29846. for ( let i = 0; i < controllers.length; i ++ ) {
  29847. if ( i >= controllerInputSources.length ) {
  29848. controllerInputSources.push( inputSource );
  29849. controllerIndex = i;
  29850. break;
  29851. } else if ( controllerInputSources[ i ] === null ) {
  29852. controllerInputSources[ i ] = inputSource;
  29853. controllerIndex = i;
  29854. break;
  29855. }
  29856. }
  29857. // If all controllers do currently receive input we ignore new ones
  29858. if ( controllerIndex === - 1 ) break;
  29859. }
  29860. const controller = controllers[ controllerIndex ];
  29861. if ( controller ) {
  29862. controller.connect( inputSource );
  29863. }
  29864. }
  29865. }
  29866. //
  29867. const cameraLPos = new Vector3();
  29868. const cameraRPos = new Vector3();
  29869. /**
  29870. * Assumes 2 cameras that are parallel and share an X-axis, and that
  29871. * the cameras' projection and world matrices have already been set.
  29872. * And that near and far planes are identical for both cameras.
  29873. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  29874. */
  29875. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  29876. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  29877. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  29878. const ipd = cameraLPos.distanceTo( cameraRPos );
  29879. const projL = cameraL.projectionMatrix.elements;
  29880. const projR = cameraR.projectionMatrix.elements;
  29881. // VR systems will have identical far and near planes, and
  29882. // most likely identical top and bottom frustum extents.
  29883. // Use the left camera for these values.
  29884. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  29885. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  29886. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  29887. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  29888. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  29889. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  29890. const left = near * leftFov;
  29891. const right = near * rightFov;
  29892. // Calculate the new camera's position offset from the
  29893. // left camera. xOffset should be roughly half `ipd`.
  29894. const zOffset = ipd / ( - leftFov + rightFov );
  29895. const xOffset = zOffset * - leftFov;
  29896. // TODO: Better way to apply this offset?
  29897. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  29898. camera.translateX( xOffset );
  29899. camera.translateZ( zOffset );
  29900. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  29901. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  29902. // Check if the projection uses an infinite far plane.
  29903. if ( projL[ 10 ] === - 1.0 ) {
  29904. // Use the projection matrix from the left eye.
  29905. // The camera offset is sufficient to include the view volumes
  29906. // of both eyes (assuming symmetric projections).
  29907. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  29908. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  29909. } else {
  29910. // Find the union of the frustum values of the cameras and scale
  29911. // the values so that the near plane's position does not change in world space,
  29912. // although must now be relative to the new union camera.
  29913. const near2 = near + zOffset;
  29914. const far2 = far + zOffset;
  29915. const left2 = left - xOffset;
  29916. const right2 = right + ( ipd - xOffset );
  29917. const top2 = topFov * far / far2 * near2;
  29918. const bottom2 = bottomFov * far / far2 * near2;
  29919. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  29920. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  29921. }
  29922. }
  29923. function updateCamera( camera, parent ) {
  29924. if ( parent === null ) {
  29925. camera.matrixWorld.copy( camera.matrix );
  29926. } else {
  29927. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  29928. }
  29929. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  29930. }
  29931. this.updateCamera = function ( camera ) {
  29932. if ( session === null ) return;
  29933. let depthNear = camera.near;
  29934. let depthFar = camera.far;
  29935. if ( depthSensing.texture !== null ) {
  29936. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  29937. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  29938. }
  29939. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  29940. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  29941. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  29942. // Note that the new renderState won't apply until the next frame. See #18320
  29943. session.updateRenderState( {
  29944. depthNear: cameraXR.near,
  29945. depthFar: cameraXR.far
  29946. } );
  29947. _currentDepthNear = cameraXR.near;
  29948. _currentDepthFar = cameraXR.far;
  29949. }
  29950. cameraL.layers.mask = camera.layers.mask | 0b010;
  29951. cameraR.layers.mask = camera.layers.mask | 0b100;
  29952. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  29953. const parent = camera.parent;
  29954. const cameras = cameraXR.cameras;
  29955. updateCamera( cameraXR, parent );
  29956. for ( let i = 0; i < cameras.length; i ++ ) {
  29957. updateCamera( cameras[ i ], parent );
  29958. }
  29959. // update projection matrix for proper view frustum culling
  29960. if ( cameras.length === 2 ) {
  29961. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  29962. } else {
  29963. // assume single camera setup (AR)
  29964. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  29965. }
  29966. // update user camera and its children
  29967. updateUserCamera( camera, cameraXR, parent );
  29968. };
  29969. function updateUserCamera( camera, cameraXR, parent ) {
  29970. if ( parent === null ) {
  29971. camera.matrix.copy( cameraXR.matrixWorld );
  29972. } else {
  29973. camera.matrix.copy( parent.matrixWorld );
  29974. camera.matrix.invert();
  29975. camera.matrix.multiply( cameraXR.matrixWorld );
  29976. }
  29977. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  29978. camera.updateMatrixWorld( true );
  29979. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  29980. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  29981. if ( camera.isPerspectiveCamera ) {
  29982. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  29983. camera.zoom = 1;
  29984. }
  29985. }
  29986. this.getCamera = function () {
  29987. return cameraXR;
  29988. };
  29989. this.getFoveation = function () {
  29990. if ( glProjLayer === null && glBaseLayer === null ) {
  29991. return undefined;
  29992. }
  29993. return foveation;
  29994. };
  29995. this.setFoveation = function ( value ) {
  29996. // 0 = no foveation = full resolution
  29997. // 1 = maximum foveation = the edges render at lower resolution
  29998. foveation = value;
  29999. if ( glProjLayer !== null ) {
  30000. glProjLayer.fixedFoveation = value;
  30001. }
  30002. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  30003. glBaseLayer.fixedFoveation = value;
  30004. }
  30005. };
  30006. this.hasDepthSensing = function () {
  30007. return depthSensing.texture !== null;
  30008. };
  30009. this.getDepthSensingMesh = function () {
  30010. return depthSensing.getMesh( cameraXR );
  30011. };
  30012. // Animation Loop
  30013. let onAnimationFrameCallback = null;
  30014. function onAnimationFrame( time, frame ) {
  30015. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  30016. xrFrame = frame;
  30017. if ( pose !== null ) {
  30018. const views = pose.views;
  30019. if ( glBaseLayer !== null ) {
  30020. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  30021. renderer.setRenderTarget( newRenderTarget );
  30022. }
  30023. let cameraXRNeedsUpdate = false;
  30024. // check if it's necessary to rebuild cameraXR's camera list
  30025. if ( views.length !== cameraXR.cameras.length ) {
  30026. cameraXR.cameras.length = 0;
  30027. cameraXRNeedsUpdate = true;
  30028. }
  30029. for ( let i = 0; i < views.length; i ++ ) {
  30030. const view = views[ i ];
  30031. let viewport = null;
  30032. if ( glBaseLayer !== null ) {
  30033. viewport = glBaseLayer.getViewport( view );
  30034. } else {
  30035. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  30036. viewport = glSubImage.viewport;
  30037. // For side-by-side projection, we only produce a single texture for both eyes.
  30038. if ( i === 0 ) {
  30039. renderer.setRenderTargetTextures(
  30040. newRenderTarget,
  30041. glSubImage.colorTexture,
  30042. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  30043. renderer.setRenderTarget( newRenderTarget );
  30044. }
  30045. }
  30046. let camera = cameras[ i ];
  30047. if ( camera === undefined ) {
  30048. camera = new PerspectiveCamera();
  30049. camera.layers.enable( i );
  30050. camera.viewport = new Vector4();
  30051. cameras[ i ] = camera;
  30052. }
  30053. camera.matrix.fromArray( view.transform.matrix );
  30054. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  30055. camera.projectionMatrix.fromArray( view.projectionMatrix );
  30056. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  30057. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  30058. if ( i === 0 ) {
  30059. cameraXR.matrix.copy( camera.matrix );
  30060. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  30061. }
  30062. if ( cameraXRNeedsUpdate === true ) {
  30063. cameraXR.cameras.push( camera );
  30064. }
  30065. }
  30066. //
  30067. const enabledFeatures = session.enabledFeatures;
  30068. if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) {
  30069. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  30070. if ( depthData && depthData.isValid && depthData.texture ) {
  30071. depthSensing.init( renderer, depthData, session.renderState );
  30072. }
  30073. }
  30074. }
  30075. //
  30076. for ( let i = 0; i < controllers.length; i ++ ) {
  30077. const inputSource = controllerInputSources[ i ];
  30078. const controller = controllers[ i ];
  30079. if ( inputSource !== null && controller !== undefined ) {
  30080. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  30081. }
  30082. }
  30083. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  30084. if ( frame.detectedPlanes ) {
  30085. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  30086. }
  30087. xrFrame = null;
  30088. }
  30089. const animation = new WebGLAnimation();
  30090. animation.setAnimationLoop( onAnimationFrame );
  30091. this.setAnimationLoop = function ( callback ) {
  30092. onAnimationFrameCallback = callback;
  30093. };
  30094. this.dispose = function () {};
  30095. }
  30096. }
  30097. const _e1 = /*@__PURE__*/ new Euler();
  30098. const _m1 = /*@__PURE__*/ new Matrix4();
  30099. function WebGLMaterials( renderer, properties ) {
  30100. function refreshTransformUniform( map, uniform ) {
  30101. if ( map.matrixAutoUpdate === true ) {
  30102. map.updateMatrix();
  30103. }
  30104. uniform.value.copy( map.matrix );
  30105. }
  30106. function refreshFogUniforms( uniforms, fog ) {
  30107. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  30108. if ( fog.isFog ) {
  30109. uniforms.fogNear.value = fog.near;
  30110. uniforms.fogFar.value = fog.far;
  30111. } else if ( fog.isFogExp2 ) {
  30112. uniforms.fogDensity.value = fog.density;
  30113. }
  30114. }
  30115. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  30116. if ( material.isMeshBasicMaterial ) {
  30117. refreshUniformsCommon( uniforms, material );
  30118. } else if ( material.isMeshLambertMaterial ) {
  30119. refreshUniformsCommon( uniforms, material );
  30120. } else if ( material.isMeshToonMaterial ) {
  30121. refreshUniformsCommon( uniforms, material );
  30122. refreshUniformsToon( uniforms, material );
  30123. } else if ( material.isMeshPhongMaterial ) {
  30124. refreshUniformsCommon( uniforms, material );
  30125. refreshUniformsPhong( uniforms, material );
  30126. } else if ( material.isMeshStandardMaterial ) {
  30127. refreshUniformsCommon( uniforms, material );
  30128. refreshUniformsStandard( uniforms, material );
  30129. if ( material.isMeshPhysicalMaterial ) {
  30130. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  30131. }
  30132. } else if ( material.isMeshMatcapMaterial ) {
  30133. refreshUniformsCommon( uniforms, material );
  30134. refreshUniformsMatcap( uniforms, material );
  30135. } else if ( material.isMeshDepthMaterial ) {
  30136. refreshUniformsCommon( uniforms, material );
  30137. } else if ( material.isMeshDistanceMaterial ) {
  30138. refreshUniformsCommon( uniforms, material );
  30139. refreshUniformsDistance( uniforms, material );
  30140. } else if ( material.isMeshNormalMaterial ) {
  30141. refreshUniformsCommon( uniforms, material );
  30142. } else if ( material.isLineBasicMaterial ) {
  30143. refreshUniformsLine( uniforms, material );
  30144. if ( material.isLineDashedMaterial ) {
  30145. refreshUniformsDash( uniforms, material );
  30146. }
  30147. } else if ( material.isPointsMaterial ) {
  30148. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  30149. } else if ( material.isSpriteMaterial ) {
  30150. refreshUniformsSprites( uniforms, material );
  30151. } else if ( material.isShadowMaterial ) {
  30152. uniforms.color.value.copy( material.color );
  30153. uniforms.opacity.value = material.opacity;
  30154. } else if ( material.isShaderMaterial ) {
  30155. material.uniformsNeedUpdate = false; // #15581
  30156. }
  30157. }
  30158. function refreshUniformsCommon( uniforms, material ) {
  30159. uniforms.opacity.value = material.opacity;
  30160. if ( material.color ) {
  30161. uniforms.diffuse.value.copy( material.color );
  30162. }
  30163. if ( material.emissive ) {
  30164. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  30165. }
  30166. if ( material.map ) {
  30167. uniforms.map.value = material.map;
  30168. refreshTransformUniform( material.map, uniforms.mapTransform );
  30169. }
  30170. if ( material.alphaMap ) {
  30171. uniforms.alphaMap.value = material.alphaMap;
  30172. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  30173. }
  30174. if ( material.bumpMap ) {
  30175. uniforms.bumpMap.value = material.bumpMap;
  30176. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  30177. uniforms.bumpScale.value = material.bumpScale;
  30178. if ( material.side === BackSide ) {
  30179. uniforms.bumpScale.value *= - 1;
  30180. }
  30181. }
  30182. if ( material.normalMap ) {
  30183. uniforms.normalMap.value = material.normalMap;
  30184. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  30185. uniforms.normalScale.value.copy( material.normalScale );
  30186. if ( material.side === BackSide ) {
  30187. uniforms.normalScale.value.negate();
  30188. }
  30189. }
  30190. if ( material.displacementMap ) {
  30191. uniforms.displacementMap.value = material.displacementMap;
  30192. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  30193. uniforms.displacementScale.value = material.displacementScale;
  30194. uniforms.displacementBias.value = material.displacementBias;
  30195. }
  30196. if ( material.emissiveMap ) {
  30197. uniforms.emissiveMap.value = material.emissiveMap;
  30198. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  30199. }
  30200. if ( material.specularMap ) {
  30201. uniforms.specularMap.value = material.specularMap;
  30202. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  30203. }
  30204. if ( material.alphaTest > 0 ) {
  30205. uniforms.alphaTest.value = material.alphaTest;
  30206. }
  30207. const materialProperties = properties.get( material );
  30208. const envMap = materialProperties.envMap;
  30209. const envMapRotation = materialProperties.envMapRotation;
  30210. if ( envMap ) {
  30211. uniforms.envMap.value = envMap;
  30212. _e1.copy( envMapRotation );
  30213. // accommodate left-handed frame
  30214. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  30215. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  30216. // environment maps which are not cube render targets or PMREMs follow a different convention
  30217. _e1.y *= - 1;
  30218. _e1.z *= - 1;
  30219. }
  30220. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  30221. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  30222. uniforms.reflectivity.value = material.reflectivity;
  30223. uniforms.ior.value = material.ior;
  30224. uniforms.refractionRatio.value = material.refractionRatio;
  30225. }
  30226. if ( material.lightMap ) {
  30227. uniforms.lightMap.value = material.lightMap;
  30228. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  30229. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  30230. }
  30231. if ( material.aoMap ) {
  30232. uniforms.aoMap.value = material.aoMap;
  30233. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  30234. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  30235. }
  30236. }
  30237. function refreshUniformsLine( uniforms, material ) {
  30238. uniforms.diffuse.value.copy( material.color );
  30239. uniforms.opacity.value = material.opacity;
  30240. if ( material.map ) {
  30241. uniforms.map.value = material.map;
  30242. refreshTransformUniform( material.map, uniforms.mapTransform );
  30243. }
  30244. }
  30245. function refreshUniformsDash( uniforms, material ) {
  30246. uniforms.dashSize.value = material.dashSize;
  30247. uniforms.totalSize.value = material.dashSize + material.gapSize;
  30248. uniforms.scale.value = material.scale;
  30249. }
  30250. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  30251. uniforms.diffuse.value.copy( material.color );
  30252. uniforms.opacity.value = material.opacity;
  30253. uniforms.size.value = material.size * pixelRatio;
  30254. uniforms.scale.value = height * 0.5;
  30255. if ( material.map ) {
  30256. uniforms.map.value = material.map;
  30257. refreshTransformUniform( material.map, uniforms.uvTransform );
  30258. }
  30259. if ( material.alphaMap ) {
  30260. uniforms.alphaMap.value = material.alphaMap;
  30261. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  30262. }
  30263. if ( material.alphaTest > 0 ) {
  30264. uniforms.alphaTest.value = material.alphaTest;
  30265. }
  30266. }
  30267. function refreshUniformsSprites( uniforms, material ) {
  30268. uniforms.diffuse.value.copy( material.color );
  30269. uniforms.opacity.value = material.opacity;
  30270. uniforms.rotation.value = material.rotation;
  30271. if ( material.map ) {
  30272. uniforms.map.value = material.map;
  30273. refreshTransformUniform( material.map, uniforms.mapTransform );
  30274. }
  30275. if ( material.alphaMap ) {
  30276. uniforms.alphaMap.value = material.alphaMap;
  30277. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  30278. }
  30279. if ( material.alphaTest > 0 ) {
  30280. uniforms.alphaTest.value = material.alphaTest;
  30281. }
  30282. }
  30283. function refreshUniformsPhong( uniforms, material ) {
  30284. uniforms.specular.value.copy( material.specular );
  30285. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  30286. }
  30287. function refreshUniformsToon( uniforms, material ) {
  30288. if ( material.gradientMap ) {
  30289. uniforms.gradientMap.value = material.gradientMap;
  30290. }
  30291. }
  30292. function refreshUniformsStandard( uniforms, material ) {
  30293. uniforms.metalness.value = material.metalness;
  30294. if ( material.metalnessMap ) {
  30295. uniforms.metalnessMap.value = material.metalnessMap;
  30296. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  30297. }
  30298. uniforms.roughness.value = material.roughness;
  30299. if ( material.roughnessMap ) {
  30300. uniforms.roughnessMap.value = material.roughnessMap;
  30301. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  30302. }
  30303. if ( material.envMap ) {
  30304. //uniforms.envMap.value = material.envMap; // part of uniforms common
  30305. uniforms.envMapIntensity.value = material.envMapIntensity;
  30306. }
  30307. }
  30308. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  30309. uniforms.ior.value = material.ior; // also part of uniforms common
  30310. if ( material.sheen > 0 ) {
  30311. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  30312. uniforms.sheenRoughness.value = material.sheenRoughness;
  30313. if ( material.sheenColorMap ) {
  30314. uniforms.sheenColorMap.value = material.sheenColorMap;
  30315. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  30316. }
  30317. if ( material.sheenRoughnessMap ) {
  30318. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  30319. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  30320. }
  30321. }
  30322. if ( material.clearcoat > 0 ) {
  30323. uniforms.clearcoat.value = material.clearcoat;
  30324. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  30325. if ( material.clearcoatMap ) {
  30326. uniforms.clearcoatMap.value = material.clearcoatMap;
  30327. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  30328. }
  30329. if ( material.clearcoatRoughnessMap ) {
  30330. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  30331. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  30332. }
  30333. if ( material.clearcoatNormalMap ) {
  30334. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  30335. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  30336. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  30337. if ( material.side === BackSide ) {
  30338. uniforms.clearcoatNormalScale.value.negate();
  30339. }
  30340. }
  30341. }
  30342. if ( material.dispersion > 0 ) {
  30343. uniforms.dispersion.value = material.dispersion;
  30344. }
  30345. if ( material.iridescence > 0 ) {
  30346. uniforms.iridescence.value = material.iridescence;
  30347. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  30348. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  30349. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  30350. if ( material.iridescenceMap ) {
  30351. uniforms.iridescenceMap.value = material.iridescenceMap;
  30352. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  30353. }
  30354. if ( material.iridescenceThicknessMap ) {
  30355. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  30356. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  30357. }
  30358. }
  30359. if ( material.transmission > 0 ) {
  30360. uniforms.transmission.value = material.transmission;
  30361. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  30362. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  30363. if ( material.transmissionMap ) {
  30364. uniforms.transmissionMap.value = material.transmissionMap;
  30365. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  30366. }
  30367. uniforms.thickness.value = material.thickness;
  30368. if ( material.thicknessMap ) {
  30369. uniforms.thicknessMap.value = material.thicknessMap;
  30370. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  30371. }
  30372. uniforms.attenuationDistance.value = material.attenuationDistance;
  30373. uniforms.attenuationColor.value.copy( material.attenuationColor );
  30374. }
  30375. if ( material.anisotropy > 0 ) {
  30376. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  30377. if ( material.anisotropyMap ) {
  30378. uniforms.anisotropyMap.value = material.anisotropyMap;
  30379. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  30380. }
  30381. }
  30382. uniforms.specularIntensity.value = material.specularIntensity;
  30383. uniforms.specularColor.value.copy( material.specularColor );
  30384. if ( material.specularColorMap ) {
  30385. uniforms.specularColorMap.value = material.specularColorMap;
  30386. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  30387. }
  30388. if ( material.specularIntensityMap ) {
  30389. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  30390. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  30391. }
  30392. }
  30393. function refreshUniformsMatcap( uniforms, material ) {
  30394. if ( material.matcap ) {
  30395. uniforms.matcap.value = material.matcap;
  30396. }
  30397. }
  30398. function refreshUniformsDistance( uniforms, material ) {
  30399. const light = properties.get( material ).light;
  30400. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  30401. uniforms.nearDistance.value = light.shadow.camera.near;
  30402. uniforms.farDistance.value = light.shadow.camera.far;
  30403. }
  30404. return {
  30405. refreshFogUniforms: refreshFogUniforms,
  30406. refreshMaterialUniforms: refreshMaterialUniforms
  30407. };
  30408. }
  30409. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  30410. let buffers = {};
  30411. let updateList = {};
  30412. let allocatedBindingPoints = [];
  30413. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  30414. function bind( uniformsGroup, program ) {
  30415. const webglProgram = program.program;
  30416. state.uniformBlockBinding( uniformsGroup, webglProgram );
  30417. }
  30418. function update( uniformsGroup, program ) {
  30419. let buffer = buffers[ uniformsGroup.id ];
  30420. if ( buffer === undefined ) {
  30421. prepareUniformsGroup( uniformsGroup );
  30422. buffer = createBuffer( uniformsGroup );
  30423. buffers[ uniformsGroup.id ] = buffer;
  30424. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  30425. }
  30426. // ensure to update the binding points/block indices mapping for this program
  30427. const webglProgram = program.program;
  30428. state.updateUBOMapping( uniformsGroup, webglProgram );
  30429. // update UBO once per frame
  30430. const frame = info.render.frame;
  30431. if ( updateList[ uniformsGroup.id ] !== frame ) {
  30432. updateBufferData( uniformsGroup );
  30433. updateList[ uniformsGroup.id ] = frame;
  30434. }
  30435. }
  30436. function createBuffer( uniformsGroup ) {
  30437. // the setup of an UBO is independent of a particular shader program but global
  30438. const bindingPointIndex = allocateBindingPointIndex();
  30439. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  30440. const buffer = gl.createBuffer();
  30441. const size = uniformsGroup.__size;
  30442. const usage = uniformsGroup.usage;
  30443. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  30444. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  30445. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  30446. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  30447. return buffer;
  30448. }
  30449. function allocateBindingPointIndex() {
  30450. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  30451. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  30452. allocatedBindingPoints.push( i );
  30453. return i;
  30454. }
  30455. }
  30456. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  30457. return 0;
  30458. }
  30459. function updateBufferData( uniformsGroup ) {
  30460. const buffer = buffers[ uniformsGroup.id ];
  30461. const uniforms = uniformsGroup.uniforms;
  30462. const cache = uniformsGroup.__cache;
  30463. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  30464. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  30465. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  30466. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  30467. const uniform = uniformArray[ j ];
  30468. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  30469. const offset = uniform.__offset;
  30470. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  30471. let arrayOffset = 0;
  30472. for ( let k = 0; k < values.length; k ++ ) {
  30473. const value = values[ k ];
  30474. const info = getUniformSize( value );
  30475. // TODO add integer and struct support
  30476. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  30477. uniform.__data[ 0 ] = value;
  30478. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  30479. } else if ( value.isMatrix3 ) {
  30480. // manually converting 3x3 to 3x4
  30481. uniform.__data[ 0 ] = value.elements[ 0 ];
  30482. uniform.__data[ 1 ] = value.elements[ 1 ];
  30483. uniform.__data[ 2 ] = value.elements[ 2 ];
  30484. uniform.__data[ 3 ] = 0;
  30485. uniform.__data[ 4 ] = value.elements[ 3 ];
  30486. uniform.__data[ 5 ] = value.elements[ 4 ];
  30487. uniform.__data[ 6 ] = value.elements[ 5 ];
  30488. uniform.__data[ 7 ] = 0;
  30489. uniform.__data[ 8 ] = value.elements[ 6 ];
  30490. uniform.__data[ 9 ] = value.elements[ 7 ];
  30491. uniform.__data[ 10 ] = value.elements[ 8 ];
  30492. uniform.__data[ 11 ] = 0;
  30493. } else {
  30494. value.toArray( uniform.__data, arrayOffset );
  30495. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  30496. }
  30497. }
  30498. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  30499. }
  30500. }
  30501. }
  30502. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  30503. }
  30504. function hasUniformChanged( uniform, index, indexArray, cache ) {
  30505. const value = uniform.value;
  30506. const indexString = index + '_' + indexArray;
  30507. if ( cache[ indexString ] === undefined ) {
  30508. // cache entry does not exist so far
  30509. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  30510. cache[ indexString ] = value;
  30511. } else {
  30512. cache[ indexString ] = value.clone();
  30513. }
  30514. return true;
  30515. } else {
  30516. const cachedObject = cache[ indexString ];
  30517. // compare current value with cached entry
  30518. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  30519. if ( cachedObject !== value ) {
  30520. cache[ indexString ] = value;
  30521. return true;
  30522. }
  30523. } else {
  30524. if ( cachedObject.equals( value ) === false ) {
  30525. cachedObject.copy( value );
  30526. return true;
  30527. }
  30528. }
  30529. }
  30530. return false;
  30531. }
  30532. function prepareUniformsGroup( uniformsGroup ) {
  30533. // determine total buffer size according to the STD140 layout
  30534. // Hint: STD140 is the only supported layout in WebGL 2
  30535. const uniforms = uniformsGroup.uniforms;
  30536. let offset = 0; // global buffer offset in bytes
  30537. const chunkSize = 16; // size of a chunk in bytes
  30538. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  30539. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  30540. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  30541. const uniform = uniformArray[ j ];
  30542. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  30543. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  30544. const value = values[ k ];
  30545. const info = getUniformSize( value );
  30546. const chunkOffset = offset % chunkSize; // offset in the current chunk
  30547. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  30548. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  30549. offset += chunkPadding;
  30550. // Check for chunk overflow
  30551. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  30552. // Add padding and adjust offset
  30553. offset += ( chunkSize - chunkStart );
  30554. }
  30555. // the following two properties will be used for partial buffer updates
  30556. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  30557. uniform.__offset = offset;
  30558. // Update the global offset
  30559. offset += info.storage;
  30560. }
  30561. }
  30562. }
  30563. // ensure correct final padding
  30564. const chunkOffset = offset % chunkSize;
  30565. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  30566. //
  30567. uniformsGroup.__size = offset;
  30568. uniformsGroup.__cache = {};
  30569. return this;
  30570. }
  30571. function getUniformSize( value ) {
  30572. const info = {
  30573. boundary: 0, // bytes
  30574. storage: 0 // bytes
  30575. };
  30576. // determine sizes according to STD140
  30577. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  30578. // float/int/bool
  30579. info.boundary = 4;
  30580. info.storage = 4;
  30581. } else if ( value.isVector2 ) {
  30582. // vec2
  30583. info.boundary = 8;
  30584. info.storage = 8;
  30585. } else if ( value.isVector3 || value.isColor ) {
  30586. // vec3
  30587. info.boundary = 16;
  30588. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  30589. } else if ( value.isVector4 ) {
  30590. // vec4
  30591. info.boundary = 16;
  30592. info.storage = 16;
  30593. } else if ( value.isMatrix3 ) {
  30594. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  30595. info.boundary = 48;
  30596. info.storage = 48;
  30597. } else if ( value.isMatrix4 ) {
  30598. // mat4
  30599. info.boundary = 64;
  30600. info.storage = 64;
  30601. } else if ( value.isTexture ) {
  30602. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  30603. } else {
  30604. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  30605. }
  30606. return info;
  30607. }
  30608. function onUniformsGroupsDispose( event ) {
  30609. const uniformsGroup = event.target;
  30610. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  30611. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  30612. allocatedBindingPoints.splice( index, 1 );
  30613. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  30614. delete buffers[ uniformsGroup.id ];
  30615. delete updateList[ uniformsGroup.id ];
  30616. }
  30617. function dispose() {
  30618. for ( const id in buffers ) {
  30619. gl.deleteBuffer( buffers[ id ] );
  30620. }
  30621. allocatedBindingPoints = [];
  30622. buffers = {};
  30623. updateList = {};
  30624. }
  30625. return {
  30626. bind: bind,
  30627. update: update,
  30628. dispose: dispose
  30629. };
  30630. }
  30631. class WebGLRenderer {
  30632. constructor( parameters = {} ) {
  30633. const {
  30634. canvas = createCanvasElement(),
  30635. context = null,
  30636. depth = true,
  30637. stencil = false,
  30638. alpha = false,
  30639. antialias = false,
  30640. premultipliedAlpha = true,
  30641. preserveDrawingBuffer = false,
  30642. powerPreference = 'default',
  30643. failIfMajorPerformanceCaveat = false,
  30644. reverseDepthBuffer = false,
  30645. } = parameters;
  30646. this.isWebGLRenderer = true;
  30647. let _alpha;
  30648. if ( context !== null ) {
  30649. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  30650. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  30651. }
  30652. _alpha = context.getContextAttributes().alpha;
  30653. } else {
  30654. _alpha = alpha;
  30655. }
  30656. const uintClearColor = new Uint32Array( 4 );
  30657. const intClearColor = new Int32Array( 4 );
  30658. let currentRenderList = null;
  30659. let currentRenderState = null;
  30660. // render() can be called from within a callback triggered by another render.
  30661. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  30662. const renderListStack = [];
  30663. const renderStateStack = [];
  30664. // public properties
  30665. this.domElement = canvas;
  30666. // Debug configuration container
  30667. this.debug = {
  30668. /**
  30669. * Enables error checking and reporting when shader programs are being compiled
  30670. * @type {boolean}
  30671. */
  30672. checkShaderErrors: true,
  30673. /**
  30674. * Callback for custom error reporting.
  30675. * @type {?Function}
  30676. */
  30677. onShaderError: null
  30678. };
  30679. // clearing
  30680. this.autoClear = true;
  30681. this.autoClearColor = true;
  30682. this.autoClearDepth = true;
  30683. this.autoClearStencil = true;
  30684. // scene graph
  30685. this.sortObjects = true;
  30686. // user-defined clipping
  30687. this.clippingPlanes = [];
  30688. this.localClippingEnabled = false;
  30689. // physically based shading
  30690. this._outputColorSpace = SRGBColorSpace;
  30691. // tone mapping
  30692. this.toneMapping = NoToneMapping;
  30693. this.toneMappingExposure = 1.0;
  30694. // internal properties
  30695. const _this = this;
  30696. let _isContextLost = false;
  30697. // internal state cache
  30698. let _currentActiveCubeFace = 0;
  30699. let _currentActiveMipmapLevel = 0;
  30700. let _currentRenderTarget = null;
  30701. let _currentMaterialId = - 1;
  30702. let _currentCamera = null;
  30703. const _currentViewport = new Vector4();
  30704. const _currentScissor = new Vector4();
  30705. let _currentScissorTest = null;
  30706. const _currentClearColor = new Color( 0x000000 );
  30707. let _currentClearAlpha = 0;
  30708. //
  30709. let _width = canvas.width;
  30710. let _height = canvas.height;
  30711. let _pixelRatio = 1;
  30712. let _opaqueSort = null;
  30713. let _transparentSort = null;
  30714. const _viewport = new Vector4( 0, 0, _width, _height );
  30715. const _scissor = new Vector4( 0, 0, _width, _height );
  30716. let _scissorTest = false;
  30717. // frustum
  30718. const _frustum = new Frustum();
  30719. // clipping
  30720. let _clippingEnabled = false;
  30721. let _localClippingEnabled = false;
  30722. // camera matrices cache
  30723. const _currentProjectionMatrix = new Matrix4();
  30724. const _projScreenMatrix = new Matrix4();
  30725. const _vector3 = new Vector3();
  30726. const _vector4 = new Vector4();
  30727. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  30728. let _renderBackground = false;
  30729. function getTargetPixelRatio() {
  30730. return _currentRenderTarget === null ? _pixelRatio : 1;
  30731. }
  30732. // initialize
  30733. let _gl = context;
  30734. function getContext( contextName, contextAttributes ) {
  30735. return canvas.getContext( contextName, contextAttributes );
  30736. }
  30737. try {
  30738. const contextAttributes = {
  30739. alpha: true,
  30740. depth,
  30741. stencil,
  30742. antialias,
  30743. premultipliedAlpha,
  30744. preserveDrawingBuffer,
  30745. powerPreference,
  30746. failIfMajorPerformanceCaveat,
  30747. };
  30748. // OffscreenCanvas does not have setAttribute, see #22811
  30749. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  30750. // event listeners must be registered before WebGL context is created, see #12753
  30751. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  30752. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  30753. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  30754. if ( _gl === null ) {
  30755. const contextName = 'webgl2';
  30756. _gl = getContext( contextName, contextAttributes );
  30757. if ( _gl === null ) {
  30758. if ( getContext( contextName ) ) {
  30759. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  30760. } else {
  30761. throw new Error( 'Error creating WebGL context.' );
  30762. }
  30763. }
  30764. }
  30765. } catch ( error ) {
  30766. console.error( 'THREE.WebGLRenderer: ' + error.message );
  30767. throw error;
  30768. }
  30769. let extensions, capabilities, state, info;
  30770. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  30771. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  30772. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  30773. let utils, bindingStates, uniformsGroups;
  30774. function initGLContext() {
  30775. extensions = new WebGLExtensions( _gl );
  30776. extensions.init();
  30777. utils = new WebGLUtils( _gl, extensions );
  30778. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  30779. state = new WebGLState( _gl, extensions );
  30780. if ( capabilities.reverseDepthBuffer && reverseDepthBuffer ) {
  30781. state.buffers.depth.setReversed( true );
  30782. }
  30783. info = new WebGLInfo( _gl );
  30784. properties = new WebGLProperties();
  30785. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  30786. cubemaps = new WebGLCubeMaps( _this );
  30787. cubeuvmaps = new WebGLCubeUVMaps( _this );
  30788. attributes = new WebGLAttributes( _gl );
  30789. bindingStates = new WebGLBindingStates( _gl, attributes );
  30790. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  30791. objects = new WebGLObjects( _gl, geometries, attributes, info );
  30792. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  30793. clipping = new WebGLClipping( properties );
  30794. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  30795. materials = new WebGLMaterials( _this, properties );
  30796. renderLists = new WebGLRenderLists();
  30797. renderStates = new WebGLRenderStates( extensions );
  30798. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  30799. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  30800. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  30801. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  30802. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  30803. info.programs = programCache.programs;
  30804. _this.capabilities = capabilities;
  30805. _this.extensions = extensions;
  30806. _this.properties = properties;
  30807. _this.renderLists = renderLists;
  30808. _this.shadowMap = shadowMap;
  30809. _this.state = state;
  30810. _this.info = info;
  30811. }
  30812. initGLContext();
  30813. // xr
  30814. const xr = new WebXRManager( _this, _gl );
  30815. this.xr = xr;
  30816. // API
  30817. this.getContext = function () {
  30818. return _gl;
  30819. };
  30820. this.getContextAttributes = function () {
  30821. return _gl.getContextAttributes();
  30822. };
  30823. this.forceContextLoss = function () {
  30824. const extension = extensions.get( 'WEBGL_lose_context' );
  30825. if ( extension ) extension.loseContext();
  30826. };
  30827. this.forceContextRestore = function () {
  30828. const extension = extensions.get( 'WEBGL_lose_context' );
  30829. if ( extension ) extension.restoreContext();
  30830. };
  30831. this.getPixelRatio = function () {
  30832. return _pixelRatio;
  30833. };
  30834. this.setPixelRatio = function ( value ) {
  30835. if ( value === undefined ) return;
  30836. _pixelRatio = value;
  30837. this.setSize( _width, _height, false );
  30838. };
  30839. this.getSize = function ( target ) {
  30840. return target.set( _width, _height );
  30841. };
  30842. this.setSize = function ( width, height, updateStyle = true ) {
  30843. if ( xr.isPresenting ) {
  30844. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  30845. return;
  30846. }
  30847. _width = width;
  30848. _height = height;
  30849. canvas.width = Math.floor( width * _pixelRatio );
  30850. canvas.height = Math.floor( height * _pixelRatio );
  30851. if ( updateStyle === true ) {
  30852. canvas.style.width = width + 'px';
  30853. canvas.style.height = height + 'px';
  30854. }
  30855. this.setViewport( 0, 0, width, height );
  30856. };
  30857. this.getDrawingBufferSize = function ( target ) {
  30858. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  30859. };
  30860. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  30861. _width = width;
  30862. _height = height;
  30863. _pixelRatio = pixelRatio;
  30864. canvas.width = Math.floor( width * pixelRatio );
  30865. canvas.height = Math.floor( height * pixelRatio );
  30866. this.setViewport( 0, 0, width, height );
  30867. };
  30868. this.getCurrentViewport = function ( target ) {
  30869. return target.copy( _currentViewport );
  30870. };
  30871. this.getViewport = function ( target ) {
  30872. return target.copy( _viewport );
  30873. };
  30874. this.setViewport = function ( x, y, width, height ) {
  30875. if ( x.isVector4 ) {
  30876. _viewport.set( x.x, x.y, x.z, x.w );
  30877. } else {
  30878. _viewport.set( x, y, width, height );
  30879. }
  30880. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  30881. };
  30882. this.getScissor = function ( target ) {
  30883. return target.copy( _scissor );
  30884. };
  30885. this.setScissor = function ( x, y, width, height ) {
  30886. if ( x.isVector4 ) {
  30887. _scissor.set( x.x, x.y, x.z, x.w );
  30888. } else {
  30889. _scissor.set( x, y, width, height );
  30890. }
  30891. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  30892. };
  30893. this.getScissorTest = function () {
  30894. return _scissorTest;
  30895. };
  30896. this.setScissorTest = function ( boolean ) {
  30897. state.setScissorTest( _scissorTest = boolean );
  30898. };
  30899. this.setOpaqueSort = function ( method ) {
  30900. _opaqueSort = method;
  30901. };
  30902. this.setTransparentSort = function ( method ) {
  30903. _transparentSort = method;
  30904. };
  30905. // Clearing
  30906. this.getClearColor = function ( target ) {
  30907. return target.copy( background.getClearColor() );
  30908. };
  30909. this.setClearColor = function () {
  30910. background.setClearColor.apply( background, arguments );
  30911. };
  30912. this.getClearAlpha = function () {
  30913. return background.getClearAlpha();
  30914. };
  30915. this.setClearAlpha = function () {
  30916. background.setClearAlpha.apply( background, arguments );
  30917. };
  30918. this.clear = function ( color = true, depth = true, stencil = true ) {
  30919. let bits = 0;
  30920. if ( color ) {
  30921. // check if we're trying to clear an integer target
  30922. let isIntegerFormat = false;
  30923. if ( _currentRenderTarget !== null ) {
  30924. const targetFormat = _currentRenderTarget.texture.format;
  30925. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  30926. targetFormat === RGIntegerFormat ||
  30927. targetFormat === RedIntegerFormat;
  30928. }
  30929. // use the appropriate clear functions to clear the target if it's a signed
  30930. // or unsigned integer target
  30931. if ( isIntegerFormat ) {
  30932. const targetType = _currentRenderTarget.texture.type;
  30933. const isUnsignedType = targetType === UnsignedByteType ||
  30934. targetType === UnsignedIntType ||
  30935. targetType === UnsignedShortType ||
  30936. targetType === UnsignedInt248Type ||
  30937. targetType === UnsignedShort4444Type ||
  30938. targetType === UnsignedShort5551Type;
  30939. const clearColor = background.getClearColor();
  30940. const a = background.getClearAlpha();
  30941. const r = clearColor.r;
  30942. const g = clearColor.g;
  30943. const b = clearColor.b;
  30944. if ( isUnsignedType ) {
  30945. uintClearColor[ 0 ] = r;
  30946. uintClearColor[ 1 ] = g;
  30947. uintClearColor[ 2 ] = b;
  30948. uintClearColor[ 3 ] = a;
  30949. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  30950. } else {
  30951. intClearColor[ 0 ] = r;
  30952. intClearColor[ 1 ] = g;
  30953. intClearColor[ 2 ] = b;
  30954. intClearColor[ 3 ] = a;
  30955. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  30956. }
  30957. } else {
  30958. bits |= _gl.COLOR_BUFFER_BIT;
  30959. }
  30960. }
  30961. if ( depth ) {
  30962. bits |= _gl.DEPTH_BUFFER_BIT;
  30963. }
  30964. if ( stencil ) {
  30965. bits |= _gl.STENCIL_BUFFER_BIT;
  30966. this.state.buffers.stencil.setMask( 0xffffffff );
  30967. }
  30968. _gl.clear( bits );
  30969. };
  30970. this.clearColor = function () {
  30971. this.clear( true, false, false );
  30972. };
  30973. this.clearDepth = function () {
  30974. this.clear( false, true, false );
  30975. };
  30976. this.clearStencil = function () {
  30977. this.clear( false, false, true );
  30978. };
  30979. //
  30980. this.dispose = function () {
  30981. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  30982. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  30983. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  30984. background.dispose();
  30985. renderLists.dispose();
  30986. renderStates.dispose();
  30987. properties.dispose();
  30988. cubemaps.dispose();
  30989. cubeuvmaps.dispose();
  30990. objects.dispose();
  30991. bindingStates.dispose();
  30992. uniformsGroups.dispose();
  30993. programCache.dispose();
  30994. xr.dispose();
  30995. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  30996. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  30997. animation.stop();
  30998. };
  30999. // Events
  31000. function onContextLost( event ) {
  31001. event.preventDefault();
  31002. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  31003. _isContextLost = true;
  31004. }
  31005. function onContextRestore( /* event */ ) {
  31006. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  31007. _isContextLost = false;
  31008. const infoAutoReset = info.autoReset;
  31009. const shadowMapEnabled = shadowMap.enabled;
  31010. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  31011. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  31012. const shadowMapType = shadowMap.type;
  31013. initGLContext();
  31014. info.autoReset = infoAutoReset;
  31015. shadowMap.enabled = shadowMapEnabled;
  31016. shadowMap.autoUpdate = shadowMapAutoUpdate;
  31017. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  31018. shadowMap.type = shadowMapType;
  31019. }
  31020. function onContextCreationError( event ) {
  31021. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  31022. }
  31023. function onMaterialDispose( event ) {
  31024. const material = event.target;
  31025. material.removeEventListener( 'dispose', onMaterialDispose );
  31026. deallocateMaterial( material );
  31027. }
  31028. // Buffer deallocation
  31029. function deallocateMaterial( material ) {
  31030. releaseMaterialProgramReferences( material );
  31031. properties.remove( material );
  31032. }
  31033. function releaseMaterialProgramReferences( material ) {
  31034. const programs = properties.get( material ).programs;
  31035. if ( programs !== undefined ) {
  31036. programs.forEach( function ( program ) {
  31037. programCache.releaseProgram( program );
  31038. } );
  31039. if ( material.isShaderMaterial ) {
  31040. programCache.releaseShaderCache( material );
  31041. }
  31042. }
  31043. }
  31044. // Buffer rendering
  31045. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  31046. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  31047. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  31048. const program = setProgram( camera, scene, geometry, material, object );
  31049. state.setMaterial( material, frontFaceCW );
  31050. //
  31051. let index = geometry.index;
  31052. let rangeFactor = 1;
  31053. if ( material.wireframe === true ) {
  31054. index = geometries.getWireframeAttribute( geometry );
  31055. if ( index === undefined ) return;
  31056. rangeFactor = 2;
  31057. }
  31058. //
  31059. const drawRange = geometry.drawRange;
  31060. const position = geometry.attributes.position;
  31061. let drawStart = drawRange.start * rangeFactor;
  31062. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  31063. if ( group !== null ) {
  31064. drawStart = Math.max( drawStart, group.start * rangeFactor );
  31065. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  31066. }
  31067. if ( index !== null ) {
  31068. drawStart = Math.max( drawStart, 0 );
  31069. drawEnd = Math.min( drawEnd, index.count );
  31070. } else if ( position !== undefined && position !== null ) {
  31071. drawStart = Math.max( drawStart, 0 );
  31072. drawEnd = Math.min( drawEnd, position.count );
  31073. }
  31074. const drawCount = drawEnd - drawStart;
  31075. if ( drawCount < 0 || drawCount === Infinity ) return;
  31076. //
  31077. bindingStates.setup( object, material, program, geometry, index );
  31078. let attribute;
  31079. let renderer = bufferRenderer;
  31080. if ( index !== null ) {
  31081. attribute = attributes.get( index );
  31082. renderer = indexedBufferRenderer;
  31083. renderer.setIndex( attribute );
  31084. }
  31085. //
  31086. if ( object.isMesh ) {
  31087. if ( material.wireframe === true ) {
  31088. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  31089. renderer.setMode( _gl.LINES );
  31090. } else {
  31091. renderer.setMode( _gl.TRIANGLES );
  31092. }
  31093. } else if ( object.isLine ) {
  31094. let lineWidth = material.linewidth;
  31095. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  31096. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  31097. if ( object.isLineSegments ) {
  31098. renderer.setMode( _gl.LINES );
  31099. } else if ( object.isLineLoop ) {
  31100. renderer.setMode( _gl.LINE_LOOP );
  31101. } else {
  31102. renderer.setMode( _gl.LINE_STRIP );
  31103. }
  31104. } else if ( object.isPoints ) {
  31105. renderer.setMode( _gl.POINTS );
  31106. } else if ( object.isSprite ) {
  31107. renderer.setMode( _gl.TRIANGLES );
  31108. }
  31109. if ( object.isBatchedMesh ) {
  31110. if ( object._multiDrawInstances !== null ) {
  31111. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  31112. } else {
  31113. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  31114. const starts = object._multiDrawStarts;
  31115. const counts = object._multiDrawCounts;
  31116. const drawCount = object._multiDrawCount;
  31117. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  31118. const uniforms = properties.get( material ).currentProgram.getUniforms();
  31119. for ( let i = 0; i < drawCount; i ++ ) {
  31120. uniforms.setValue( _gl, '_gl_DrawID', i );
  31121. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  31122. }
  31123. } else {
  31124. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  31125. }
  31126. }
  31127. } else if ( object.isInstancedMesh ) {
  31128. renderer.renderInstances( drawStart, drawCount, object.count );
  31129. } else if ( geometry.isInstancedBufferGeometry ) {
  31130. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  31131. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  31132. renderer.renderInstances( drawStart, drawCount, instanceCount );
  31133. } else {
  31134. renderer.render( drawStart, drawCount );
  31135. }
  31136. };
  31137. // Compile
  31138. function prepareMaterial( material, scene, object ) {
  31139. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  31140. material.side = BackSide;
  31141. material.needsUpdate = true;
  31142. getProgram( material, scene, object );
  31143. material.side = FrontSide;
  31144. material.needsUpdate = true;
  31145. getProgram( material, scene, object );
  31146. material.side = DoubleSide;
  31147. } else {
  31148. getProgram( material, scene, object );
  31149. }
  31150. }
  31151. this.compile = function ( scene, camera, targetScene = null ) {
  31152. if ( targetScene === null ) targetScene = scene;
  31153. currentRenderState = renderStates.get( targetScene );
  31154. currentRenderState.init( camera );
  31155. renderStateStack.push( currentRenderState );
  31156. // gather lights from both the target scene and the new object that will be added to the scene.
  31157. targetScene.traverseVisible( function ( object ) {
  31158. if ( object.isLight && object.layers.test( camera.layers ) ) {
  31159. currentRenderState.pushLight( object );
  31160. if ( object.castShadow ) {
  31161. currentRenderState.pushShadow( object );
  31162. }
  31163. }
  31164. } );
  31165. if ( scene !== targetScene ) {
  31166. scene.traverseVisible( function ( object ) {
  31167. if ( object.isLight && object.layers.test( camera.layers ) ) {
  31168. currentRenderState.pushLight( object );
  31169. if ( object.castShadow ) {
  31170. currentRenderState.pushShadow( object );
  31171. }
  31172. }
  31173. } );
  31174. }
  31175. currentRenderState.setupLights();
  31176. // Only initialize materials in the new scene, not the targetScene.
  31177. const materials = new Set();
  31178. scene.traverse( function ( object ) {
  31179. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  31180. return;
  31181. }
  31182. const material = object.material;
  31183. if ( material ) {
  31184. if ( Array.isArray( material ) ) {
  31185. for ( let i = 0; i < material.length; i ++ ) {
  31186. const material2 = material[ i ];
  31187. prepareMaterial( material2, targetScene, object );
  31188. materials.add( material2 );
  31189. }
  31190. } else {
  31191. prepareMaterial( material, targetScene, object );
  31192. materials.add( material );
  31193. }
  31194. }
  31195. } );
  31196. renderStateStack.pop();
  31197. currentRenderState = null;
  31198. return materials;
  31199. };
  31200. // compileAsync
  31201. this.compileAsync = function ( scene, camera, targetScene = null ) {
  31202. const materials = this.compile( scene, camera, targetScene );
  31203. // Wait for all the materials in the new object to indicate that they're
  31204. // ready to be used before resolving the promise.
  31205. return new Promise( ( resolve ) => {
  31206. function checkMaterialsReady() {
  31207. materials.forEach( function ( material ) {
  31208. const materialProperties = properties.get( material );
  31209. const program = materialProperties.currentProgram;
  31210. if ( program.isReady() ) {
  31211. // remove any programs that report they're ready to use from the list
  31212. materials.delete( material );
  31213. }
  31214. } );
  31215. // once the list of compiling materials is empty, call the callback
  31216. if ( materials.size === 0 ) {
  31217. resolve( scene );
  31218. return;
  31219. }
  31220. // if some materials are still not ready, wait a bit and check again
  31221. setTimeout( checkMaterialsReady, 10 );
  31222. }
  31223. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  31224. // If we can check the compilation status of the materials without
  31225. // blocking then do so right away.
  31226. checkMaterialsReady();
  31227. } else {
  31228. // Otherwise start by waiting a bit to give the materials we just
  31229. // initialized a chance to finish.
  31230. setTimeout( checkMaterialsReady, 10 );
  31231. }
  31232. } );
  31233. };
  31234. // Animation Loop
  31235. let onAnimationFrameCallback = null;
  31236. function onAnimationFrame( time ) {
  31237. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  31238. }
  31239. function onXRSessionStart() {
  31240. animation.stop();
  31241. }
  31242. function onXRSessionEnd() {
  31243. animation.start();
  31244. }
  31245. const animation = new WebGLAnimation();
  31246. animation.setAnimationLoop( onAnimationFrame );
  31247. if ( typeof self !== 'undefined' ) animation.setContext( self );
  31248. this.setAnimationLoop = function ( callback ) {
  31249. onAnimationFrameCallback = callback;
  31250. xr.setAnimationLoop( callback );
  31251. ( callback === null ) ? animation.stop() : animation.start();
  31252. };
  31253. xr.addEventListener( 'sessionstart', onXRSessionStart );
  31254. xr.addEventListener( 'sessionend', onXRSessionEnd );
  31255. // Rendering
  31256. this.render = function ( scene, camera ) {
  31257. if ( camera !== undefined && camera.isCamera !== true ) {
  31258. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  31259. return;
  31260. }
  31261. if ( _isContextLost === true ) return;
  31262. // update scene graph
  31263. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  31264. // update camera matrices and frustum
  31265. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  31266. if ( xr.enabled === true && xr.isPresenting === true ) {
  31267. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  31268. camera = xr.getCamera(); // use XR camera for rendering
  31269. }
  31270. //
  31271. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  31272. currentRenderState = renderStates.get( scene, renderStateStack.length );
  31273. currentRenderState.init( camera );
  31274. renderStateStack.push( currentRenderState );
  31275. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  31276. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  31277. _localClippingEnabled = this.localClippingEnabled;
  31278. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  31279. currentRenderList = renderLists.get( scene, renderListStack.length );
  31280. currentRenderList.init();
  31281. renderListStack.push( currentRenderList );
  31282. if ( xr.enabled === true && xr.isPresenting === true ) {
  31283. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  31284. if ( depthSensingMesh !== null ) {
  31285. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  31286. }
  31287. }
  31288. projectObject( scene, camera, 0, _this.sortObjects );
  31289. currentRenderList.finish();
  31290. if ( _this.sortObjects === true ) {
  31291. currentRenderList.sort( _opaqueSort, _transparentSort );
  31292. }
  31293. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  31294. if ( _renderBackground ) {
  31295. background.addToRenderList( currentRenderList, scene );
  31296. }
  31297. //
  31298. this.info.render.frame ++;
  31299. if ( _clippingEnabled === true ) clipping.beginShadows();
  31300. const shadowsArray = currentRenderState.state.shadowsArray;
  31301. shadowMap.render( shadowsArray, scene, camera );
  31302. if ( _clippingEnabled === true ) clipping.endShadows();
  31303. //
  31304. if ( this.info.autoReset === true ) this.info.reset();
  31305. // render scene
  31306. const opaqueObjects = currentRenderList.opaque;
  31307. const transmissiveObjects = currentRenderList.transmissive;
  31308. currentRenderState.setupLights();
  31309. if ( camera.isArrayCamera ) {
  31310. const cameras = camera.cameras;
  31311. if ( transmissiveObjects.length > 0 ) {
  31312. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  31313. const camera2 = cameras[ i ];
  31314. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  31315. }
  31316. }
  31317. if ( _renderBackground ) background.render( scene );
  31318. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  31319. const camera2 = cameras[ i ];
  31320. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  31321. }
  31322. } else {
  31323. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  31324. if ( _renderBackground ) background.render( scene );
  31325. renderScene( currentRenderList, scene, camera );
  31326. }
  31327. //
  31328. if ( _currentRenderTarget !== null ) {
  31329. // resolve multisample renderbuffers to a single-sample texture if necessary
  31330. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  31331. // Generate mipmap if we're using any kind of mipmap filtering
  31332. textures.updateRenderTargetMipmap( _currentRenderTarget );
  31333. }
  31334. //
  31335. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  31336. // _gl.finish();
  31337. bindingStates.resetDefaultState();
  31338. _currentMaterialId = - 1;
  31339. _currentCamera = null;
  31340. renderStateStack.pop();
  31341. if ( renderStateStack.length > 0 ) {
  31342. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  31343. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  31344. } else {
  31345. currentRenderState = null;
  31346. }
  31347. renderListStack.pop();
  31348. if ( renderListStack.length > 0 ) {
  31349. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  31350. } else {
  31351. currentRenderList = null;
  31352. }
  31353. };
  31354. function projectObject( object, camera, groupOrder, sortObjects ) {
  31355. if ( object.visible === false ) return;
  31356. const visible = object.layers.test( camera.layers );
  31357. if ( visible ) {
  31358. if ( object.isGroup ) {
  31359. groupOrder = object.renderOrder;
  31360. } else if ( object.isLOD ) {
  31361. if ( object.autoUpdate === true ) object.update( camera );
  31362. } else if ( object.isLight ) {
  31363. currentRenderState.pushLight( object );
  31364. if ( object.castShadow ) {
  31365. currentRenderState.pushShadow( object );
  31366. }
  31367. } else if ( object.isSprite ) {
  31368. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  31369. if ( sortObjects ) {
  31370. _vector4.setFromMatrixPosition( object.matrixWorld )
  31371. .applyMatrix4( _projScreenMatrix );
  31372. }
  31373. const geometry = objects.update( object );
  31374. const material = object.material;
  31375. if ( material.visible ) {
  31376. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  31377. }
  31378. }
  31379. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  31380. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  31381. const geometry = objects.update( object );
  31382. const material = object.material;
  31383. if ( sortObjects ) {
  31384. if ( object.boundingSphere !== undefined ) {
  31385. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  31386. _vector4.copy( object.boundingSphere.center );
  31387. } else {
  31388. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  31389. _vector4.copy( geometry.boundingSphere.center );
  31390. }
  31391. _vector4
  31392. .applyMatrix4( object.matrixWorld )
  31393. .applyMatrix4( _projScreenMatrix );
  31394. }
  31395. if ( Array.isArray( material ) ) {
  31396. const groups = geometry.groups;
  31397. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  31398. const group = groups[ i ];
  31399. const groupMaterial = material[ group.materialIndex ];
  31400. if ( groupMaterial && groupMaterial.visible ) {
  31401. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  31402. }
  31403. }
  31404. } else if ( material.visible ) {
  31405. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  31406. }
  31407. }
  31408. }
  31409. }
  31410. const children = object.children;
  31411. for ( let i = 0, l = children.length; i < l; i ++ ) {
  31412. projectObject( children[ i ], camera, groupOrder, sortObjects );
  31413. }
  31414. }
  31415. function renderScene( currentRenderList, scene, camera, viewport ) {
  31416. const opaqueObjects = currentRenderList.opaque;
  31417. const transmissiveObjects = currentRenderList.transmissive;
  31418. const transparentObjects = currentRenderList.transparent;
  31419. currentRenderState.setupLightsView( camera );
  31420. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  31421. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  31422. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  31423. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  31424. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  31425. // Ensure depth buffer writing is enabled so it can be cleared on next render
  31426. state.buffers.depth.setTest( true );
  31427. state.buffers.depth.setMask( true );
  31428. state.buffers.color.setMask( true );
  31429. state.setPolygonOffset( false );
  31430. }
  31431. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  31432. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  31433. if ( overrideMaterial !== null ) {
  31434. return;
  31435. }
  31436. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  31437. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  31438. generateMipmaps: true,
  31439. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  31440. minFilter: LinearMipmapLinearFilter,
  31441. samples: 4,
  31442. stencilBuffer: stencil,
  31443. resolveDepthBuffer: false,
  31444. resolveStencilBuffer: false,
  31445. colorSpace: ColorManagement.workingColorSpace,
  31446. } );
  31447. // debug
  31448. /*
  31449. const geometry = new PlaneGeometry();
  31450. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  31451. const mesh = new Mesh( geometry, material );
  31452. scene.add( mesh );
  31453. */
  31454. }
  31455. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  31456. const activeViewport = camera.viewport || _currentViewport;
  31457. transmissionRenderTarget.setSize( activeViewport.z, activeViewport.w );
  31458. //
  31459. const currentRenderTarget = _this.getRenderTarget();
  31460. _this.setRenderTarget( transmissionRenderTarget );
  31461. _this.getClearColor( _currentClearColor );
  31462. _currentClearAlpha = _this.getClearAlpha();
  31463. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  31464. _this.clear();
  31465. if ( _renderBackground ) background.render( scene );
  31466. // Turn off the features which can affect the frag color for opaque objects pass.
  31467. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  31468. const currentToneMapping = _this.toneMapping;
  31469. _this.toneMapping = NoToneMapping;
  31470. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  31471. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  31472. const currentCameraViewport = camera.viewport;
  31473. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  31474. currentRenderState.setupLightsView( camera );
  31475. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  31476. renderObjects( opaqueObjects, scene, camera );
  31477. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  31478. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  31479. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  31480. let renderTargetNeedsUpdate = false;
  31481. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  31482. const renderItem = transmissiveObjects[ i ];
  31483. const object = renderItem.object;
  31484. const geometry = renderItem.geometry;
  31485. const material = renderItem.material;
  31486. const group = renderItem.group;
  31487. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  31488. const currentSide = material.side;
  31489. material.side = BackSide;
  31490. material.needsUpdate = true;
  31491. renderObject( object, scene, camera, geometry, material, group );
  31492. material.side = currentSide;
  31493. material.needsUpdate = true;
  31494. renderTargetNeedsUpdate = true;
  31495. }
  31496. }
  31497. if ( renderTargetNeedsUpdate === true ) {
  31498. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  31499. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  31500. }
  31501. }
  31502. _this.setRenderTarget( currentRenderTarget );
  31503. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  31504. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  31505. _this.toneMapping = currentToneMapping;
  31506. }
  31507. function renderObjects( renderList, scene, camera ) {
  31508. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  31509. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  31510. const renderItem = renderList[ i ];
  31511. const object = renderItem.object;
  31512. const geometry = renderItem.geometry;
  31513. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  31514. const group = renderItem.group;
  31515. if ( object.layers.test( camera.layers ) ) {
  31516. renderObject( object, scene, camera, geometry, material, group );
  31517. }
  31518. }
  31519. }
  31520. function renderObject( object, scene, camera, geometry, material, group ) {
  31521. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  31522. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  31523. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  31524. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  31525. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  31526. material.side = BackSide;
  31527. material.needsUpdate = true;
  31528. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  31529. material.side = FrontSide;
  31530. material.needsUpdate = true;
  31531. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  31532. material.side = DoubleSide;
  31533. } else {
  31534. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  31535. }
  31536. object.onAfterRender( _this, scene, camera, geometry, material, group );
  31537. }
  31538. function getProgram( material, scene, object ) {
  31539. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  31540. const materialProperties = properties.get( material );
  31541. const lights = currentRenderState.state.lights;
  31542. const shadowsArray = currentRenderState.state.shadowsArray;
  31543. const lightsStateVersion = lights.state.version;
  31544. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  31545. const programCacheKey = programCache.getProgramCacheKey( parameters );
  31546. let programs = materialProperties.programs;
  31547. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  31548. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  31549. materialProperties.fog = scene.fog;
  31550. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  31551. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  31552. if ( programs === undefined ) {
  31553. // new material
  31554. material.addEventListener( 'dispose', onMaterialDispose );
  31555. programs = new Map();
  31556. materialProperties.programs = programs;
  31557. }
  31558. let program = programs.get( programCacheKey );
  31559. if ( program !== undefined ) {
  31560. // early out if program and light state is identical
  31561. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  31562. updateCommonMaterialProperties( material, parameters );
  31563. return program;
  31564. }
  31565. } else {
  31566. parameters.uniforms = programCache.getUniforms( material );
  31567. material.onBeforeCompile( parameters, _this );
  31568. program = programCache.acquireProgram( parameters, programCacheKey );
  31569. programs.set( programCacheKey, program );
  31570. materialProperties.uniforms = parameters.uniforms;
  31571. }
  31572. const uniforms = materialProperties.uniforms;
  31573. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  31574. uniforms.clippingPlanes = clipping.uniform;
  31575. }
  31576. updateCommonMaterialProperties( material, parameters );
  31577. // store the light setup it was created for
  31578. materialProperties.needsLights = materialNeedsLights( material );
  31579. materialProperties.lightsStateVersion = lightsStateVersion;
  31580. if ( materialProperties.needsLights ) {
  31581. // wire up the material to this renderer's lighting state
  31582. uniforms.ambientLightColor.value = lights.state.ambient;
  31583. uniforms.lightProbe.value = lights.state.probe;
  31584. uniforms.directionalLights.value = lights.state.directional;
  31585. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  31586. uniforms.spotLights.value = lights.state.spot;
  31587. uniforms.spotLightShadows.value = lights.state.spotShadow;
  31588. uniforms.rectAreaLights.value = lights.state.rectArea;
  31589. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  31590. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  31591. uniforms.pointLights.value = lights.state.point;
  31592. uniforms.pointLightShadows.value = lights.state.pointShadow;
  31593. uniforms.hemisphereLights.value = lights.state.hemi;
  31594. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  31595. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  31596. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  31597. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  31598. uniforms.spotLightMap.value = lights.state.spotLightMap;
  31599. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  31600. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  31601. // TODO (abelnation): add area lights shadow info to uniforms
  31602. }
  31603. materialProperties.currentProgram = program;
  31604. materialProperties.uniformsList = null;
  31605. return program;
  31606. }
  31607. function getUniformList( materialProperties ) {
  31608. if ( materialProperties.uniformsList === null ) {
  31609. const progUniforms = materialProperties.currentProgram.getUniforms();
  31610. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  31611. }
  31612. return materialProperties.uniformsList;
  31613. }
  31614. function updateCommonMaterialProperties( material, parameters ) {
  31615. const materialProperties = properties.get( material );
  31616. materialProperties.outputColorSpace = parameters.outputColorSpace;
  31617. materialProperties.batching = parameters.batching;
  31618. materialProperties.batchingColor = parameters.batchingColor;
  31619. materialProperties.instancing = parameters.instancing;
  31620. materialProperties.instancingColor = parameters.instancingColor;
  31621. materialProperties.instancingMorph = parameters.instancingMorph;
  31622. materialProperties.skinning = parameters.skinning;
  31623. materialProperties.morphTargets = parameters.morphTargets;
  31624. materialProperties.morphNormals = parameters.morphNormals;
  31625. materialProperties.morphColors = parameters.morphColors;
  31626. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  31627. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  31628. materialProperties.numIntersection = parameters.numClipIntersection;
  31629. materialProperties.vertexAlphas = parameters.vertexAlphas;
  31630. materialProperties.vertexTangents = parameters.vertexTangents;
  31631. materialProperties.toneMapping = parameters.toneMapping;
  31632. }
  31633. function setProgram( camera, scene, geometry, material, object ) {
  31634. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  31635. textures.resetTextureUnits();
  31636. const fog = scene.fog;
  31637. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  31638. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  31639. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  31640. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  31641. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  31642. const morphTargets = !! geometry.morphAttributes.position;
  31643. const morphNormals = !! geometry.morphAttributes.normal;
  31644. const morphColors = !! geometry.morphAttributes.color;
  31645. let toneMapping = NoToneMapping;
  31646. if ( material.toneMapped ) {
  31647. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  31648. toneMapping = _this.toneMapping;
  31649. }
  31650. }
  31651. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  31652. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  31653. const materialProperties = properties.get( material );
  31654. const lights = currentRenderState.state.lights;
  31655. if ( _clippingEnabled === true ) {
  31656. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  31657. const useCache =
  31658. camera === _currentCamera &&
  31659. material.id === _currentMaterialId;
  31660. // we might want to call this function with some ClippingGroup
  31661. // object instead of the material, once it becomes feasible
  31662. // (#8465, #8379)
  31663. clipping.setState( material, camera, useCache );
  31664. }
  31665. }
  31666. //
  31667. let needsProgramChange = false;
  31668. if ( material.version === materialProperties.__version ) {
  31669. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  31670. needsProgramChange = true;
  31671. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  31672. needsProgramChange = true;
  31673. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  31674. needsProgramChange = true;
  31675. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  31676. needsProgramChange = true;
  31677. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  31678. needsProgramChange = true;
  31679. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  31680. needsProgramChange = true;
  31681. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  31682. needsProgramChange = true;
  31683. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  31684. needsProgramChange = true;
  31685. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  31686. needsProgramChange = true;
  31687. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  31688. needsProgramChange = true;
  31689. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  31690. needsProgramChange = true;
  31691. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  31692. needsProgramChange = true;
  31693. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  31694. needsProgramChange = true;
  31695. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  31696. needsProgramChange = true;
  31697. } else if ( materialProperties.envMap !== envMap ) {
  31698. needsProgramChange = true;
  31699. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  31700. needsProgramChange = true;
  31701. } else if ( materialProperties.numClippingPlanes !== undefined &&
  31702. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  31703. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  31704. needsProgramChange = true;
  31705. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  31706. needsProgramChange = true;
  31707. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  31708. needsProgramChange = true;
  31709. } else if ( materialProperties.morphTargets !== morphTargets ) {
  31710. needsProgramChange = true;
  31711. } else if ( materialProperties.morphNormals !== morphNormals ) {
  31712. needsProgramChange = true;
  31713. } else if ( materialProperties.morphColors !== morphColors ) {
  31714. needsProgramChange = true;
  31715. } else if ( materialProperties.toneMapping !== toneMapping ) {
  31716. needsProgramChange = true;
  31717. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  31718. needsProgramChange = true;
  31719. }
  31720. } else {
  31721. needsProgramChange = true;
  31722. materialProperties.__version = material.version;
  31723. }
  31724. //
  31725. let program = materialProperties.currentProgram;
  31726. if ( needsProgramChange === true ) {
  31727. program = getProgram( material, scene, object );
  31728. }
  31729. let refreshProgram = false;
  31730. let refreshMaterial = false;
  31731. let refreshLights = false;
  31732. const p_uniforms = program.getUniforms(),
  31733. m_uniforms = materialProperties.uniforms;
  31734. if ( state.useProgram( program.program ) ) {
  31735. refreshProgram = true;
  31736. refreshMaterial = true;
  31737. refreshLights = true;
  31738. }
  31739. if ( material.id !== _currentMaterialId ) {
  31740. _currentMaterialId = material.id;
  31741. refreshMaterial = true;
  31742. }
  31743. if ( refreshProgram || _currentCamera !== camera ) {
  31744. // common camera uniforms
  31745. const reverseDepthBuffer = state.buffers.depth.getReversed();
  31746. if ( reverseDepthBuffer ) {
  31747. _currentProjectionMatrix.copy( camera.projectionMatrix );
  31748. toNormalizedProjectionMatrix( _currentProjectionMatrix );
  31749. toReversedProjectionMatrix( _currentProjectionMatrix );
  31750. p_uniforms.setValue( _gl, 'projectionMatrix', _currentProjectionMatrix );
  31751. } else {
  31752. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  31753. }
  31754. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  31755. const uCamPos = p_uniforms.map.cameraPosition;
  31756. if ( uCamPos !== undefined ) {
  31757. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  31758. }
  31759. if ( capabilities.logarithmicDepthBuffer ) {
  31760. p_uniforms.setValue( _gl, 'logDepthBufFC',
  31761. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  31762. }
  31763. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  31764. if ( material.isMeshPhongMaterial ||
  31765. material.isMeshToonMaterial ||
  31766. material.isMeshLambertMaterial ||
  31767. material.isMeshBasicMaterial ||
  31768. material.isMeshStandardMaterial ||
  31769. material.isShaderMaterial ) {
  31770. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  31771. }
  31772. if ( _currentCamera !== camera ) {
  31773. _currentCamera = camera;
  31774. // lighting uniforms depend on the camera so enforce an update
  31775. // now, in case this material supports lights - or later, when
  31776. // the next material that does gets activated:
  31777. refreshMaterial = true; // set to true on material change
  31778. refreshLights = true; // remains set until update done
  31779. }
  31780. }
  31781. // skinning and morph target uniforms must be set even if material didn't change
  31782. // auto-setting of texture unit for bone and morph texture must go before other textures
  31783. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  31784. if ( object.isSkinnedMesh ) {
  31785. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  31786. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  31787. const skeleton = object.skeleton;
  31788. if ( skeleton ) {
  31789. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  31790. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  31791. }
  31792. }
  31793. if ( object.isBatchedMesh ) {
  31794. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  31795. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  31796. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  31797. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  31798. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  31799. if ( object._colorsTexture !== null ) {
  31800. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  31801. }
  31802. }
  31803. const morphAttributes = geometry.morphAttributes;
  31804. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  31805. morphtargets.update( object, geometry, program );
  31806. }
  31807. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  31808. materialProperties.receiveShadow = object.receiveShadow;
  31809. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  31810. }
  31811. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  31812. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  31813. m_uniforms.envMap.value = envMap;
  31814. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  31815. }
  31816. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  31817. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  31818. }
  31819. if ( refreshMaterial ) {
  31820. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  31821. if ( materialProperties.needsLights ) {
  31822. // the current material requires lighting info
  31823. // note: all lighting uniforms are always set correctly
  31824. // they simply reference the renderer's state for their
  31825. // values
  31826. //
  31827. // use the current material's .needsUpdate flags to set
  31828. // the GL state when required
  31829. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  31830. }
  31831. // refresh uniforms common to several materials
  31832. if ( fog && material.fog === true ) {
  31833. materials.refreshFogUniforms( m_uniforms, fog );
  31834. }
  31835. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  31836. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  31837. }
  31838. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  31839. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  31840. material.uniformsNeedUpdate = false;
  31841. }
  31842. if ( material.isSpriteMaterial ) {
  31843. p_uniforms.setValue( _gl, 'center', object.center );
  31844. }
  31845. // common matrices
  31846. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  31847. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  31848. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  31849. // UBOs
  31850. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  31851. const groups = material.uniformsGroups;
  31852. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  31853. const group = groups[ i ];
  31854. uniformsGroups.update( group, program );
  31855. uniformsGroups.bind( group, program );
  31856. }
  31857. }
  31858. return program;
  31859. }
  31860. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  31861. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  31862. uniforms.ambientLightColor.needsUpdate = value;
  31863. uniforms.lightProbe.needsUpdate = value;
  31864. uniforms.directionalLights.needsUpdate = value;
  31865. uniforms.directionalLightShadows.needsUpdate = value;
  31866. uniforms.pointLights.needsUpdate = value;
  31867. uniforms.pointLightShadows.needsUpdate = value;
  31868. uniforms.spotLights.needsUpdate = value;
  31869. uniforms.spotLightShadows.needsUpdate = value;
  31870. uniforms.rectAreaLights.needsUpdate = value;
  31871. uniforms.hemisphereLights.needsUpdate = value;
  31872. }
  31873. function materialNeedsLights( material ) {
  31874. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  31875. material.isMeshStandardMaterial || material.isShadowMaterial ||
  31876. ( material.isShaderMaterial && material.lights === true );
  31877. }
  31878. this.getActiveCubeFace = function () {
  31879. return _currentActiveCubeFace;
  31880. };
  31881. this.getActiveMipmapLevel = function () {
  31882. return _currentActiveMipmapLevel;
  31883. };
  31884. this.getRenderTarget = function () {
  31885. return _currentRenderTarget;
  31886. };
  31887. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  31888. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  31889. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  31890. const renderTargetProperties = properties.get( renderTarget );
  31891. renderTargetProperties.__hasExternalTextures = true;
  31892. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  31893. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  31894. // The multisample_render_to_texture extension doesn't work properly if there
  31895. // are midframe flushes and an external depth buffer. Disable use of the extension.
  31896. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  31897. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  31898. renderTargetProperties.__useRenderToTexture = false;
  31899. }
  31900. }
  31901. };
  31902. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  31903. const renderTargetProperties = properties.get( renderTarget );
  31904. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  31905. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  31906. };
  31907. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  31908. _currentRenderTarget = renderTarget;
  31909. _currentActiveCubeFace = activeCubeFace;
  31910. _currentActiveMipmapLevel = activeMipmapLevel;
  31911. let useDefaultFramebuffer = true;
  31912. let framebuffer = null;
  31913. let isCube = false;
  31914. let isRenderTarget3D = false;
  31915. if ( renderTarget ) {
  31916. const renderTargetProperties = properties.get( renderTarget );
  31917. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  31918. // We need to make sure to rebind the framebuffer.
  31919. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  31920. useDefaultFramebuffer = false;
  31921. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  31922. textures.setupRenderTarget( renderTarget );
  31923. } else if ( renderTargetProperties.__hasExternalTextures ) {
  31924. // Color and depth texture must be rebound in order for the swapchain to update.
  31925. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  31926. } else if ( renderTarget.depthBuffer ) {
  31927. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  31928. const depthTexture = renderTarget.depthTexture;
  31929. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  31930. // check if the depth texture is compatible
  31931. if (
  31932. depthTexture !== null &&
  31933. properties.has( depthTexture ) &&
  31934. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  31935. ) {
  31936. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  31937. }
  31938. // Swap the depth buffer to the currently attached one
  31939. textures.setupDepthRenderbuffer( renderTarget );
  31940. }
  31941. }
  31942. const texture = renderTarget.texture;
  31943. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  31944. isRenderTarget3D = true;
  31945. }
  31946. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  31947. if ( renderTarget.isWebGLCubeRenderTarget ) {
  31948. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  31949. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  31950. } else {
  31951. framebuffer = __webglFramebuffer[ activeCubeFace ];
  31952. }
  31953. isCube = true;
  31954. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  31955. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  31956. } else {
  31957. if ( Array.isArray( __webglFramebuffer ) ) {
  31958. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  31959. } else {
  31960. framebuffer = __webglFramebuffer;
  31961. }
  31962. }
  31963. _currentViewport.copy( renderTarget.viewport );
  31964. _currentScissor.copy( renderTarget.scissor );
  31965. _currentScissorTest = renderTarget.scissorTest;
  31966. } else {
  31967. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  31968. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  31969. _currentScissorTest = _scissorTest;
  31970. }
  31971. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  31972. if ( framebufferBound && useDefaultFramebuffer ) {
  31973. state.drawBuffers( renderTarget, framebuffer );
  31974. }
  31975. state.viewport( _currentViewport );
  31976. state.scissor( _currentScissor );
  31977. state.setScissorTest( _currentScissorTest );
  31978. if ( isCube ) {
  31979. const textureProperties = properties.get( renderTarget.texture );
  31980. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  31981. } else if ( isRenderTarget3D ) {
  31982. const textureProperties = properties.get( renderTarget.texture );
  31983. const layer = activeCubeFace || 0;
  31984. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  31985. }
  31986. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  31987. };
  31988. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  31989. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  31990. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  31991. return;
  31992. }
  31993. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  31994. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  31995. framebuffer = framebuffer[ activeCubeFaceIndex ];
  31996. }
  31997. if ( framebuffer ) {
  31998. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  31999. try {
  32000. const texture = renderTarget.texture;
  32001. const textureFormat = texture.format;
  32002. const textureType = texture.type;
  32003. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  32004. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  32005. return;
  32006. }
  32007. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  32008. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  32009. return;
  32010. }
  32011. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  32012. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  32013. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  32014. }
  32015. } finally {
  32016. // restore framebuffer of current render target if necessary
  32017. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  32018. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  32019. }
  32020. }
  32021. };
  32022. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  32023. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  32024. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  32025. }
  32026. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  32027. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  32028. framebuffer = framebuffer[ activeCubeFaceIndex ];
  32029. }
  32030. if ( framebuffer ) {
  32031. const texture = renderTarget.texture;
  32032. const textureFormat = texture.format;
  32033. const textureType = texture.type;
  32034. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  32035. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  32036. }
  32037. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  32038. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  32039. }
  32040. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  32041. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  32042. // set the active frame buffer to the one we want to read
  32043. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  32044. const glBuffer = _gl.createBuffer();
  32045. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  32046. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  32047. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  32048. // reset the frame buffer to the currently set buffer before waiting
  32049. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  32050. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  32051. // check if the commands have finished every 8 ms
  32052. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  32053. _gl.flush();
  32054. await probeAsync( _gl, sync, 4 );
  32055. // read the data and delete the buffer
  32056. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  32057. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  32058. _gl.deleteBuffer( glBuffer );
  32059. _gl.deleteSync( sync );
  32060. return buffer;
  32061. } else {
  32062. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  32063. }
  32064. }
  32065. };
  32066. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  32067. // support previous signature with position first
  32068. if ( texture.isTexture !== true ) {
  32069. // @deprecated, r165
  32070. warnOnce( 'WebGLRenderer: copyFramebufferToTexture function signature has changed.' );
  32071. position = arguments[ 0 ] || null;
  32072. texture = arguments[ 1 ];
  32073. }
  32074. const levelScale = Math.pow( 2, - level );
  32075. const width = Math.floor( texture.image.width * levelScale );
  32076. const height = Math.floor( texture.image.height * levelScale );
  32077. const x = position !== null ? position.x : 0;
  32078. const y = position !== null ? position.y : 0;
  32079. textures.setTexture2D( texture, 0 );
  32080. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  32081. state.unbindTexture();
  32082. };
  32083. const _srcFramebuffer = _gl.createFramebuffer();
  32084. const _dstFramebuffer = _gl.createFramebuffer();
  32085. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  32086. // support previous signature with dstPosition first
  32087. if ( srcTexture.isTexture !== true ) {
  32088. // @deprecated, r165
  32089. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  32090. dstPosition = arguments[ 0 ] || null;
  32091. srcTexture = arguments[ 1 ];
  32092. dstTexture = arguments[ 2 ];
  32093. dstLevel = arguments[ 3 ] || 0;
  32094. srcRegion = null;
  32095. }
  32096. // support the previous signature with just a single dst mipmap level
  32097. if ( dstLevel === null ) {
  32098. if ( srcLevel !== 0 ) {
  32099. // @deprecated, r171
  32100. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  32101. dstLevel = srcLevel;
  32102. srcLevel = 0;
  32103. } else {
  32104. dstLevel = 0;
  32105. }
  32106. }
  32107. // gather the necessary dimensions to copy
  32108. let width, height, depth, minX, minY, minZ;
  32109. let dstX, dstY, dstZ;
  32110. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  32111. if ( srcRegion !== null ) {
  32112. width = srcRegion.max.x - srcRegion.min.x;
  32113. height = srcRegion.max.y - srcRegion.min.y;
  32114. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  32115. minX = srcRegion.min.x;
  32116. minY = srcRegion.min.y;
  32117. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  32118. } else {
  32119. const levelScale = Math.pow( 2, - srcLevel );
  32120. width = Math.floor( image.width * levelScale );
  32121. height = Math.floor( image.height * levelScale );
  32122. if ( srcTexture.isDataArrayTexture ) {
  32123. depth = image.depth;
  32124. } else if ( srcTexture.isData3DTexture ) {
  32125. depth = Math.floor( image.depth * levelScale );
  32126. } else {
  32127. depth = 1;
  32128. }
  32129. minX = 0;
  32130. minY = 0;
  32131. minZ = 0;
  32132. }
  32133. if ( dstPosition !== null ) {
  32134. dstX = dstPosition.x;
  32135. dstY = dstPosition.y;
  32136. dstZ = dstPosition.z;
  32137. } else {
  32138. dstX = 0;
  32139. dstY = 0;
  32140. dstZ = 0;
  32141. }
  32142. // Set up the destination target
  32143. const glFormat = utils.convert( dstTexture.format );
  32144. const glType = utils.convert( dstTexture.type );
  32145. let glTarget;
  32146. if ( dstTexture.isData3DTexture ) {
  32147. textures.setTexture3D( dstTexture, 0 );
  32148. glTarget = _gl.TEXTURE_3D;
  32149. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  32150. textures.setTexture2DArray( dstTexture, 0 );
  32151. glTarget = _gl.TEXTURE_2D_ARRAY;
  32152. } else {
  32153. textures.setTexture2D( dstTexture, 0 );
  32154. glTarget = _gl.TEXTURE_2D;
  32155. }
  32156. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  32157. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  32158. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  32159. // used for copying data from cpu
  32160. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  32161. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  32162. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  32163. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  32164. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  32165. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  32166. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  32167. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  32168. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  32169. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  32170. // set up the src texture
  32171. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  32172. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  32173. if ( srcTexture.isDepthTexture ) {
  32174. const srcTextureProperties = properties.get( srcTexture );
  32175. const dstTextureProperties = properties.get( dstTexture );
  32176. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  32177. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  32178. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  32179. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  32180. for ( let i = 0; i < depth; i ++ ) {
  32181. // if the source or destination are a 3d target then a layer needs to be bound
  32182. if ( isSrc3D ) {
  32183. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  32184. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  32185. }
  32186. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  32187. }
  32188. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  32189. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  32190. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  32191. // get the appropriate frame buffers
  32192. const srcTextureProperties = properties.get( srcTexture );
  32193. const dstTextureProperties = properties.get( dstTexture );
  32194. // bind the frame buffer targets
  32195. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  32196. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  32197. for ( let i = 0; i < depth; i ++ ) {
  32198. // assign the correct layers and mip maps to the frame buffers
  32199. if ( isSrc3D ) {
  32200. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  32201. } else {
  32202. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  32203. }
  32204. if ( isDst3D ) {
  32205. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  32206. } else {
  32207. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  32208. }
  32209. // copy the data using the fastest function that can achieve the copy
  32210. if ( srcLevel !== 0 ) {
  32211. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  32212. } else if ( isDst3D ) {
  32213. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  32214. } else {
  32215. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  32216. }
  32217. }
  32218. // unbind read, draw buffers
  32219. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  32220. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  32221. } else {
  32222. if ( isDst3D ) {
  32223. // copy data into the 3d texture
  32224. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  32225. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  32226. } else if ( dstTexture.isCompressedArrayTexture ) {
  32227. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  32228. } else {
  32229. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  32230. }
  32231. } else {
  32232. // copy data into the 2d texture
  32233. if ( srcTexture.isDataTexture ) {
  32234. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  32235. } else if ( srcTexture.isCompressedTexture ) {
  32236. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  32237. } else {
  32238. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  32239. }
  32240. }
  32241. }
  32242. // reset values
  32243. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  32244. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  32245. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  32246. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  32247. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  32248. // Generate mipmaps only when copying level 0
  32249. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  32250. _gl.generateMipmap( glTarget );
  32251. }
  32252. state.unbindTexture();
  32253. };
  32254. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  32255. // support previous signature with source box first
  32256. if ( srcTexture.isTexture !== true ) {
  32257. // @deprecated, r165
  32258. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  32259. srcRegion = arguments[ 0 ] || null;
  32260. dstPosition = arguments[ 1 ] || null;
  32261. srcTexture = arguments[ 2 ];
  32262. dstTexture = arguments[ 3 ];
  32263. level = arguments[ 4 ] || 0;
  32264. }
  32265. // @deprecated, r170
  32266. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.' );
  32267. return this.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  32268. };
  32269. this.initRenderTarget = function ( target ) {
  32270. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  32271. textures.setupRenderTarget( target );
  32272. }
  32273. };
  32274. this.initTexture = function ( texture ) {
  32275. if ( texture.isCubeTexture ) {
  32276. textures.setTextureCube( texture, 0 );
  32277. } else if ( texture.isData3DTexture ) {
  32278. textures.setTexture3D( texture, 0 );
  32279. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  32280. textures.setTexture2DArray( texture, 0 );
  32281. } else {
  32282. textures.setTexture2D( texture, 0 );
  32283. }
  32284. state.unbindTexture();
  32285. };
  32286. this.resetState = function () {
  32287. _currentActiveCubeFace = 0;
  32288. _currentActiveMipmapLevel = 0;
  32289. _currentRenderTarget = null;
  32290. state.reset();
  32291. bindingStates.reset();
  32292. };
  32293. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32294. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32295. }
  32296. }
  32297. get coordinateSystem() {
  32298. return WebGLCoordinateSystem;
  32299. }
  32300. get outputColorSpace() {
  32301. return this._outputColorSpace;
  32302. }
  32303. set outputColorSpace( colorSpace ) {
  32304. this._outputColorSpace = colorSpace;
  32305. const gl = this.getContext();
  32306. gl.drawingBufferColorspace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  32307. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  32308. }
  32309. }
  32310. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  32311. exports.AddEquation = AddEquation;
  32312. exports.AddOperation = AddOperation;
  32313. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  32314. exports.AdditiveBlending = AdditiveBlending;
  32315. exports.AgXToneMapping = AgXToneMapping;
  32316. exports.AlphaFormat = AlphaFormat;
  32317. exports.AlwaysCompare = AlwaysCompare;
  32318. exports.AlwaysDepth = AlwaysDepth;
  32319. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  32320. exports.AmbientLight = AmbientLight;
  32321. exports.AnimationAction = AnimationAction;
  32322. exports.AnimationClip = AnimationClip;
  32323. exports.AnimationLoader = AnimationLoader;
  32324. exports.AnimationMixer = AnimationMixer;
  32325. exports.AnimationObjectGroup = AnimationObjectGroup;
  32326. exports.AnimationUtils = AnimationUtils;
  32327. exports.ArcCurve = ArcCurve;
  32328. exports.ArrayCamera = ArrayCamera;
  32329. exports.ArrowHelper = ArrowHelper;
  32330. exports.AttachedBindMode = AttachedBindMode;
  32331. exports.Audio = Audio;
  32332. exports.AudioAnalyser = AudioAnalyser;
  32333. exports.AudioContext = AudioContext;
  32334. exports.AudioListener = AudioListener;
  32335. exports.AudioLoader = AudioLoader;
  32336. exports.AxesHelper = AxesHelper;
  32337. exports.BackSide = BackSide;
  32338. exports.BasicDepthPacking = BasicDepthPacking;
  32339. exports.BasicShadowMap = BasicShadowMap;
  32340. exports.BatchedMesh = BatchedMesh;
  32341. exports.Bone = Bone;
  32342. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  32343. exports.Box2 = Box2;
  32344. exports.Box3 = Box3;
  32345. exports.Box3Helper = Box3Helper;
  32346. exports.BoxGeometry = BoxGeometry;
  32347. exports.BoxHelper = BoxHelper;
  32348. exports.BufferAttribute = BufferAttribute;
  32349. exports.BufferGeometry = BufferGeometry;
  32350. exports.BufferGeometryLoader = BufferGeometryLoader;
  32351. exports.ByteType = ByteType;
  32352. exports.Cache = Cache;
  32353. exports.Camera = Camera;
  32354. exports.CameraHelper = CameraHelper;
  32355. exports.CanvasTexture = CanvasTexture;
  32356. exports.CapsuleGeometry = CapsuleGeometry;
  32357. exports.CatmullRomCurve3 = CatmullRomCurve3;
  32358. exports.CineonToneMapping = CineonToneMapping;
  32359. exports.CircleGeometry = CircleGeometry;
  32360. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  32361. exports.Clock = Clock;
  32362. exports.Color = Color;
  32363. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  32364. exports.ColorManagement = ColorManagement;
  32365. exports.CompressedArrayTexture = CompressedArrayTexture;
  32366. exports.CompressedCubeTexture = CompressedCubeTexture;
  32367. exports.CompressedTexture = CompressedTexture;
  32368. exports.CompressedTextureLoader = CompressedTextureLoader;
  32369. exports.ConeGeometry = ConeGeometry;
  32370. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  32371. exports.ConstantColorFactor = ConstantColorFactor;
  32372. exports.Controls = Controls;
  32373. exports.CubeCamera = CubeCamera;
  32374. exports.CubeReflectionMapping = CubeReflectionMapping;
  32375. exports.CubeRefractionMapping = CubeRefractionMapping;
  32376. exports.CubeTexture = CubeTexture;
  32377. exports.CubeTextureLoader = CubeTextureLoader;
  32378. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  32379. exports.CubicBezierCurve = CubicBezierCurve;
  32380. exports.CubicBezierCurve3 = CubicBezierCurve3;
  32381. exports.CubicInterpolant = CubicInterpolant;
  32382. exports.CullFaceBack = CullFaceBack;
  32383. exports.CullFaceFront = CullFaceFront;
  32384. exports.CullFaceFrontBack = CullFaceFrontBack;
  32385. exports.CullFaceNone = CullFaceNone;
  32386. exports.Curve = Curve;
  32387. exports.CurvePath = CurvePath;
  32388. exports.CustomBlending = CustomBlending;
  32389. exports.CustomToneMapping = CustomToneMapping;
  32390. exports.CylinderGeometry = CylinderGeometry;
  32391. exports.Cylindrical = Cylindrical;
  32392. exports.Data3DTexture = Data3DTexture;
  32393. exports.DataArrayTexture = DataArrayTexture;
  32394. exports.DataTexture = DataTexture;
  32395. exports.DataTextureLoader = DataTextureLoader;
  32396. exports.DataUtils = DataUtils;
  32397. exports.DecrementStencilOp = DecrementStencilOp;
  32398. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  32399. exports.DefaultLoadingManager = DefaultLoadingManager;
  32400. exports.DepthFormat = DepthFormat;
  32401. exports.DepthStencilFormat = DepthStencilFormat;
  32402. exports.DepthTexture = DepthTexture;
  32403. exports.DetachedBindMode = DetachedBindMode;
  32404. exports.DirectionalLight = DirectionalLight;
  32405. exports.DirectionalLightHelper = DirectionalLightHelper;
  32406. exports.DiscreteInterpolant = DiscreteInterpolant;
  32407. exports.DodecahedronGeometry = DodecahedronGeometry;
  32408. exports.DoubleSide = DoubleSide;
  32409. exports.DstAlphaFactor = DstAlphaFactor;
  32410. exports.DstColorFactor = DstColorFactor;
  32411. exports.DynamicCopyUsage = DynamicCopyUsage;
  32412. exports.DynamicDrawUsage = DynamicDrawUsage;
  32413. exports.DynamicReadUsage = DynamicReadUsage;
  32414. exports.EdgesGeometry = EdgesGeometry;
  32415. exports.EllipseCurve = EllipseCurve;
  32416. exports.EqualCompare = EqualCompare;
  32417. exports.EqualDepth = EqualDepth;
  32418. exports.EqualStencilFunc = EqualStencilFunc;
  32419. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  32420. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  32421. exports.Euler = Euler;
  32422. exports.EventDispatcher = EventDispatcher;
  32423. exports.ExtrudeGeometry = ExtrudeGeometry;
  32424. exports.FileLoader = FileLoader;
  32425. exports.Float16BufferAttribute = Float16BufferAttribute;
  32426. exports.Float32BufferAttribute = Float32BufferAttribute;
  32427. exports.FloatType = FloatType;
  32428. exports.Fog = Fog;
  32429. exports.FogExp2 = FogExp2;
  32430. exports.FramebufferTexture = FramebufferTexture;
  32431. exports.FrontSide = FrontSide;
  32432. exports.Frustum = Frustum;
  32433. exports.GLBufferAttribute = GLBufferAttribute;
  32434. exports.GLSL1 = GLSL1;
  32435. exports.GLSL3 = GLSL3;
  32436. exports.GreaterCompare = GreaterCompare;
  32437. exports.GreaterDepth = GreaterDepth;
  32438. exports.GreaterEqualCompare = GreaterEqualCompare;
  32439. exports.GreaterEqualDepth = GreaterEqualDepth;
  32440. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  32441. exports.GreaterStencilFunc = GreaterStencilFunc;
  32442. exports.GridHelper = GridHelper;
  32443. exports.Group = Group;
  32444. exports.HalfFloatType = HalfFloatType;
  32445. exports.HemisphereLight = HemisphereLight;
  32446. exports.HemisphereLightHelper = HemisphereLightHelper;
  32447. exports.IcosahedronGeometry = IcosahedronGeometry;
  32448. exports.ImageBitmapLoader = ImageBitmapLoader;
  32449. exports.ImageLoader = ImageLoader;
  32450. exports.ImageUtils = ImageUtils;
  32451. exports.IncrementStencilOp = IncrementStencilOp;
  32452. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  32453. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  32454. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  32455. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  32456. exports.InstancedMesh = InstancedMesh;
  32457. exports.Int16BufferAttribute = Int16BufferAttribute;
  32458. exports.Int32BufferAttribute = Int32BufferAttribute;
  32459. exports.Int8BufferAttribute = Int8BufferAttribute;
  32460. exports.IntType = IntType;
  32461. exports.InterleavedBuffer = InterleavedBuffer;
  32462. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  32463. exports.Interpolant = Interpolant;
  32464. exports.InterpolateDiscrete = InterpolateDiscrete;
  32465. exports.InterpolateLinear = InterpolateLinear;
  32466. exports.InterpolateSmooth = InterpolateSmooth;
  32467. exports.InvertStencilOp = InvertStencilOp;
  32468. exports.KeepStencilOp = KeepStencilOp;
  32469. exports.KeyframeTrack = KeyframeTrack;
  32470. exports.LOD = LOD;
  32471. exports.LatheGeometry = LatheGeometry;
  32472. exports.Layers = Layers;
  32473. exports.LessCompare = LessCompare;
  32474. exports.LessDepth = LessDepth;
  32475. exports.LessEqualCompare = LessEqualCompare;
  32476. exports.LessEqualDepth = LessEqualDepth;
  32477. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  32478. exports.LessStencilFunc = LessStencilFunc;
  32479. exports.Light = Light;
  32480. exports.LightProbe = LightProbe;
  32481. exports.Line = Line;
  32482. exports.Line3 = Line3;
  32483. exports.LineBasicMaterial = LineBasicMaterial;
  32484. exports.LineCurve = LineCurve;
  32485. exports.LineCurve3 = LineCurve3;
  32486. exports.LineDashedMaterial = LineDashedMaterial;
  32487. exports.LineLoop = LineLoop;
  32488. exports.LineSegments = LineSegments;
  32489. exports.LinearFilter = LinearFilter;
  32490. exports.LinearInterpolant = LinearInterpolant;
  32491. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  32492. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  32493. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  32494. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  32495. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  32496. exports.LinearToneMapping = LinearToneMapping;
  32497. exports.LinearTransfer = LinearTransfer;
  32498. exports.Loader = Loader;
  32499. exports.LoaderUtils = LoaderUtils;
  32500. exports.LoadingManager = LoadingManager;
  32501. exports.LoopOnce = LoopOnce;
  32502. exports.LoopPingPong = LoopPingPong;
  32503. exports.LoopRepeat = LoopRepeat;
  32504. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  32505. exports.LuminanceFormat = LuminanceFormat;
  32506. exports.MOUSE = MOUSE;
  32507. exports.Material = Material;
  32508. exports.MaterialLoader = MaterialLoader;
  32509. exports.MathUtils = MathUtils;
  32510. exports.Matrix2 = Matrix2;
  32511. exports.Matrix3 = Matrix3;
  32512. exports.Matrix4 = Matrix4;
  32513. exports.MaxEquation = MaxEquation;
  32514. exports.Mesh = Mesh;
  32515. exports.MeshBasicMaterial = MeshBasicMaterial;
  32516. exports.MeshDepthMaterial = MeshDepthMaterial;
  32517. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  32518. exports.MeshLambertMaterial = MeshLambertMaterial;
  32519. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  32520. exports.MeshNormalMaterial = MeshNormalMaterial;
  32521. exports.MeshPhongMaterial = MeshPhongMaterial;
  32522. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  32523. exports.MeshStandardMaterial = MeshStandardMaterial;
  32524. exports.MeshToonMaterial = MeshToonMaterial;
  32525. exports.MinEquation = MinEquation;
  32526. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  32527. exports.MixOperation = MixOperation;
  32528. exports.MultiplyBlending = MultiplyBlending;
  32529. exports.MultiplyOperation = MultiplyOperation;
  32530. exports.NearestFilter = NearestFilter;
  32531. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  32532. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  32533. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  32534. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  32535. exports.NeutralToneMapping = NeutralToneMapping;
  32536. exports.NeverCompare = NeverCompare;
  32537. exports.NeverDepth = NeverDepth;
  32538. exports.NeverStencilFunc = NeverStencilFunc;
  32539. exports.NoBlending = NoBlending;
  32540. exports.NoColorSpace = NoColorSpace;
  32541. exports.NoToneMapping = NoToneMapping;
  32542. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  32543. exports.NormalBlending = NormalBlending;
  32544. exports.NotEqualCompare = NotEqualCompare;
  32545. exports.NotEqualDepth = NotEqualDepth;
  32546. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  32547. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  32548. exports.Object3D = Object3D;
  32549. exports.ObjectLoader = ObjectLoader;
  32550. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  32551. exports.OctahedronGeometry = OctahedronGeometry;
  32552. exports.OneFactor = OneFactor;
  32553. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  32554. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  32555. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  32556. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  32557. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  32558. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  32559. exports.OrthographicCamera = OrthographicCamera;
  32560. exports.PCFShadowMap = PCFShadowMap;
  32561. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  32562. exports.PMREMGenerator = PMREMGenerator;
  32563. exports.Path = Path;
  32564. exports.PerspectiveCamera = PerspectiveCamera;
  32565. exports.Plane = Plane;
  32566. exports.PlaneGeometry = PlaneGeometry;
  32567. exports.PlaneHelper = PlaneHelper;
  32568. exports.PointLight = PointLight;
  32569. exports.PointLightHelper = PointLightHelper;
  32570. exports.Points = Points;
  32571. exports.PointsMaterial = PointsMaterial;
  32572. exports.PolarGridHelper = PolarGridHelper;
  32573. exports.PolyhedronGeometry = PolyhedronGeometry;
  32574. exports.PositionalAudio = PositionalAudio;
  32575. exports.PropertyBinding = PropertyBinding;
  32576. exports.PropertyMixer = PropertyMixer;
  32577. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  32578. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  32579. exports.Quaternion = Quaternion;
  32580. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  32581. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  32582. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  32583. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  32584. exports.REVISION = REVISION;
  32585. exports.RGBADepthPacking = RGBADepthPacking;
  32586. exports.RGBAFormat = RGBAFormat;
  32587. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  32588. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  32589. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  32590. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  32591. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  32592. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  32593. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  32594. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  32595. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  32596. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  32597. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  32598. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  32599. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  32600. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  32601. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  32602. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  32603. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  32604. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  32605. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  32606. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  32607. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  32608. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  32609. exports.RGBDepthPacking = RGBDepthPacking;
  32610. exports.RGBFormat = RGBFormat;
  32611. exports.RGBIntegerFormat = RGBIntegerFormat;
  32612. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  32613. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  32614. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  32615. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  32616. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  32617. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  32618. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  32619. exports.RGDepthPacking = RGDepthPacking;
  32620. exports.RGFormat = RGFormat;
  32621. exports.RGIntegerFormat = RGIntegerFormat;
  32622. exports.RawShaderMaterial = RawShaderMaterial;
  32623. exports.Ray = Ray;
  32624. exports.Raycaster = Raycaster;
  32625. exports.RectAreaLight = RectAreaLight;
  32626. exports.RedFormat = RedFormat;
  32627. exports.RedIntegerFormat = RedIntegerFormat;
  32628. exports.ReinhardToneMapping = ReinhardToneMapping;
  32629. exports.RenderTarget = RenderTarget;
  32630. exports.RepeatWrapping = RepeatWrapping;
  32631. exports.ReplaceStencilOp = ReplaceStencilOp;
  32632. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  32633. exports.RingGeometry = RingGeometry;
  32634. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  32635. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  32636. exports.SRGBColorSpace = SRGBColorSpace;
  32637. exports.SRGBTransfer = SRGBTransfer;
  32638. exports.Scene = Scene;
  32639. exports.ShaderChunk = ShaderChunk;
  32640. exports.ShaderLib = ShaderLib;
  32641. exports.ShaderMaterial = ShaderMaterial;
  32642. exports.ShadowMaterial = ShadowMaterial;
  32643. exports.Shape = Shape;
  32644. exports.ShapeGeometry = ShapeGeometry;
  32645. exports.ShapePath = ShapePath;
  32646. exports.ShapeUtils = ShapeUtils;
  32647. exports.ShortType = ShortType;
  32648. exports.Skeleton = Skeleton;
  32649. exports.SkeletonHelper = SkeletonHelper;
  32650. exports.SkinnedMesh = SkinnedMesh;
  32651. exports.Source = Source;
  32652. exports.Sphere = Sphere;
  32653. exports.SphereGeometry = SphereGeometry;
  32654. exports.Spherical = Spherical;
  32655. exports.SphericalHarmonics3 = SphericalHarmonics3;
  32656. exports.SplineCurve = SplineCurve;
  32657. exports.SpotLight = SpotLight;
  32658. exports.SpotLightHelper = SpotLightHelper;
  32659. exports.Sprite = Sprite;
  32660. exports.SpriteMaterial = SpriteMaterial;
  32661. exports.SrcAlphaFactor = SrcAlphaFactor;
  32662. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  32663. exports.SrcColorFactor = SrcColorFactor;
  32664. exports.StaticCopyUsage = StaticCopyUsage;
  32665. exports.StaticDrawUsage = StaticDrawUsage;
  32666. exports.StaticReadUsage = StaticReadUsage;
  32667. exports.StereoCamera = StereoCamera;
  32668. exports.StreamCopyUsage = StreamCopyUsage;
  32669. exports.StreamDrawUsage = StreamDrawUsage;
  32670. exports.StreamReadUsage = StreamReadUsage;
  32671. exports.StringKeyframeTrack = StringKeyframeTrack;
  32672. exports.SubtractEquation = SubtractEquation;
  32673. exports.SubtractiveBlending = SubtractiveBlending;
  32674. exports.TOUCH = TOUCH;
  32675. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  32676. exports.TetrahedronGeometry = TetrahedronGeometry;
  32677. exports.Texture = Texture;
  32678. exports.TextureLoader = TextureLoader;
  32679. exports.TextureUtils = TextureUtils;
  32680. exports.TorusGeometry = TorusGeometry;
  32681. exports.TorusKnotGeometry = TorusKnotGeometry;
  32682. exports.Triangle = Triangle;
  32683. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  32684. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  32685. exports.TrianglesDrawMode = TrianglesDrawMode;
  32686. exports.TubeGeometry = TubeGeometry;
  32687. exports.UVMapping = UVMapping;
  32688. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  32689. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  32690. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  32691. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  32692. exports.Uniform = Uniform;
  32693. exports.UniformsGroup = UniformsGroup;
  32694. exports.UniformsLib = UniformsLib;
  32695. exports.UniformsUtils = UniformsUtils;
  32696. exports.UnsignedByteType = UnsignedByteType;
  32697. exports.UnsignedInt248Type = UnsignedInt248Type;
  32698. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  32699. exports.UnsignedIntType = UnsignedIntType;
  32700. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  32701. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  32702. exports.UnsignedShortType = UnsignedShortType;
  32703. exports.VSMShadowMap = VSMShadowMap;
  32704. exports.Vector2 = Vector2;
  32705. exports.Vector3 = Vector3;
  32706. exports.Vector4 = Vector4;
  32707. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  32708. exports.VideoTexture = VideoTexture;
  32709. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  32710. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  32711. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  32712. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  32713. exports.WebGLRenderTarget = WebGLRenderTarget;
  32714. exports.WebGLRenderer = WebGLRenderer;
  32715. exports.WebGLUtils = WebGLUtils;
  32716. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  32717. exports.WireframeGeometry = WireframeGeometry;
  32718. exports.WrapAroundEnding = WrapAroundEnding;
  32719. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  32720. exports.ZeroFactor = ZeroFactor;
  32721. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  32722. exports.ZeroStencilOp = ZeroStencilOp;
  32723. exports.createCanvasElement = createCanvasElement;
粤ICP备19079148号