three.cjs 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '174dev';
  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. const TimestampQuery = {
  208. COMPUTE: 'compute',
  209. RENDER: 'render'
  210. };
  211. /**
  212. * This modules allows to dispatch event objects on custom JavaScript objects.
  213. *
  214. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  215. *
  216. * Code Example:
  217. * ```js
  218. * class Car extends EventDispatcher {
  219. * start() {
  220. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  221. * }
  222. *};
  223. *
  224. * // Using events with the custom object
  225. * const car = new Car();
  226. * car.addEventListener( 'start', function ( event ) {
  227. * alert( event.message );
  228. * } );
  229. *
  230. * car.start();
  231. * ```
  232. */
  233. class EventDispatcher {
  234. /**
  235. * Adds the given event listener to the given event type.
  236. *
  237. * @param {string} type - The type of event to listen to.
  238. * @param {Function} listener - The function that gets called when the event is fired.
  239. */
  240. addEventListener( type, listener ) {
  241. if ( this._listeners === undefined ) this._listeners = {};
  242. const listeners = this._listeners;
  243. if ( listeners[ type ] === undefined ) {
  244. listeners[ type ] = [];
  245. }
  246. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  247. listeners[ type ].push( listener );
  248. }
  249. }
  250. /**
  251. * Returns `true` if the given event listener has been added to the given event type.
  252. *
  253. * @param {string} type - The type of event.
  254. * @param {Function} listener - The listener to check.
  255. * @return {boolean} Whether the given event listener has been added to the given event type.
  256. */
  257. hasEventListener( type, listener ) {
  258. const listeners = this._listeners;
  259. if ( listeners === undefined ) return false;
  260. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  261. }
  262. /**
  263. * Removes the given event listener from the given event type.
  264. *
  265. * @param {string} type - The type of event.
  266. * @param {Function} listener - The listener to remove.
  267. */
  268. removeEventListener( type, listener ) {
  269. const listeners = this._listeners;
  270. if ( listeners === undefined ) return;
  271. const listenerArray = listeners[ type ];
  272. if ( listenerArray !== undefined ) {
  273. const index = listenerArray.indexOf( listener );
  274. if ( index !== -1 ) {
  275. listenerArray.splice( index, 1 );
  276. }
  277. }
  278. }
  279. /**
  280. * Dispatches an event object.
  281. *
  282. * @param {Object} event - The event that gets fired.
  283. */
  284. dispatchEvent( event ) {
  285. const listeners = this._listeners;
  286. if ( listeners === undefined ) return;
  287. const listenerArray = listeners[ event.type ];
  288. if ( listenerArray !== undefined ) {
  289. event.target = this;
  290. // Make a copy, in case listeners are removed while iterating.
  291. const array = listenerArray.slice( 0 );
  292. for ( let i = 0, l = array.length; i < l; i ++ ) {
  293. array[ i ].call( this, event );
  294. }
  295. event.target = null;
  296. }
  297. }
  298. }
  299. 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' ];
  300. let _seed = 1234567;
  301. const DEG2RAD = Math.PI / 180;
  302. const RAD2DEG = 180 / Math.PI;
  303. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  304. function generateUUID() {
  305. const d0 = Math.random() * 0xffffffff | 0;
  306. const d1 = Math.random() * 0xffffffff | 0;
  307. const d2 = Math.random() * 0xffffffff | 0;
  308. const d3 = Math.random() * 0xffffffff | 0;
  309. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  310. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  311. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  312. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  313. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  314. return uuid.toLowerCase();
  315. }
  316. function clamp( value, min, max ) {
  317. return Math.max( min, Math.min( max, value ) );
  318. }
  319. // compute euclidean modulo of m % n
  320. // https://en.wikipedia.org/wiki/Modulo_operation
  321. function euclideanModulo( n, m ) {
  322. return ( ( n % m ) + m ) % m;
  323. }
  324. // Linear mapping from range <a1, a2> to range <b1, b2>
  325. function mapLinear( x, a1, a2, b1, b2 ) {
  326. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  327. }
  328. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  329. function inverseLerp( x, y, value ) {
  330. if ( x !== y ) {
  331. return ( value - x ) / ( y - x );
  332. } else {
  333. return 0;
  334. }
  335. }
  336. // https://en.wikipedia.org/wiki/Linear_interpolation
  337. function lerp( x, y, t ) {
  338. return ( 1 - t ) * x + t * y;
  339. }
  340. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  341. function damp( x, y, lambda, dt ) {
  342. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  343. }
  344. // https://www.desmos.com/calculator/vcsjnyz7x4
  345. function pingpong( x, length = 1 ) {
  346. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  347. }
  348. // http://en.wikipedia.org/wiki/Smoothstep
  349. function smoothstep( x, min, max ) {
  350. if ( x <= min ) return 0;
  351. if ( x >= max ) return 1;
  352. x = ( x - min ) / ( max - min );
  353. return x * x * ( 3 - 2 * x );
  354. }
  355. function smootherstep( x, min, max ) {
  356. if ( x <= min ) return 0;
  357. if ( x >= max ) return 1;
  358. x = ( x - min ) / ( max - min );
  359. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  360. }
  361. // Random integer from <low, high> interval
  362. function randInt( low, high ) {
  363. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  364. }
  365. // Random float from <low, high> interval
  366. function randFloat( low, high ) {
  367. return low + Math.random() * ( high - low );
  368. }
  369. // Random float from <-range/2, range/2> interval
  370. function randFloatSpread( range ) {
  371. return range * ( 0.5 - Math.random() );
  372. }
  373. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  374. function seededRandom( s ) {
  375. if ( s !== undefined ) _seed = s;
  376. // Mulberry32 generator
  377. let t = _seed += 0x6D2B79F5;
  378. t = Math.imul( t ^ t >>> 15, t | 1 );
  379. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  380. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  381. }
  382. function degToRad( degrees ) {
  383. return degrees * DEG2RAD;
  384. }
  385. function radToDeg( radians ) {
  386. return radians * RAD2DEG;
  387. }
  388. function isPowerOfTwo( value ) {
  389. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  390. }
  391. function ceilPowerOfTwo( value ) {
  392. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  393. }
  394. function floorPowerOfTwo( value ) {
  395. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  396. }
  397. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  398. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  399. // rotations are applied to the axes in the order specified by 'order'
  400. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  401. // angles are in radians
  402. const cos = Math.cos;
  403. const sin = Math.sin;
  404. const c2 = cos( b / 2 );
  405. const s2 = sin( b / 2 );
  406. const c13 = cos( ( a + c ) / 2 );
  407. const s13 = sin( ( a + c ) / 2 );
  408. const c1_3 = cos( ( a - c ) / 2 );
  409. const s1_3 = sin( ( a - c ) / 2 );
  410. const c3_1 = cos( ( c - a ) / 2 );
  411. const s3_1 = sin( ( c - a ) / 2 );
  412. switch ( order ) {
  413. case 'XYX':
  414. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  415. break;
  416. case 'YZY':
  417. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  418. break;
  419. case 'ZXZ':
  420. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  421. break;
  422. case 'XZX':
  423. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  424. break;
  425. case 'YXY':
  426. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  427. break;
  428. case 'ZYZ':
  429. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  430. break;
  431. default:
  432. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  433. }
  434. }
  435. function denormalize( value, array ) {
  436. switch ( array.constructor ) {
  437. case Float32Array:
  438. return value;
  439. case Uint32Array:
  440. return value / 4294967295.0;
  441. case Uint16Array:
  442. return value / 65535.0;
  443. case Uint8Array:
  444. return value / 255.0;
  445. case Int32Array:
  446. return Math.max( value / 2147483647.0, -1 );
  447. case Int16Array:
  448. return Math.max( value / 32767.0, -1 );
  449. case Int8Array:
  450. return Math.max( value / 127.0, -1 );
  451. default:
  452. throw new Error( 'Invalid component type.' );
  453. }
  454. }
  455. function normalize( value, array ) {
  456. switch ( array.constructor ) {
  457. case Float32Array:
  458. return value;
  459. case Uint32Array:
  460. return Math.round( value * 4294967295.0 );
  461. case Uint16Array:
  462. return Math.round( value * 65535.0 );
  463. case Uint8Array:
  464. return Math.round( value * 255.0 );
  465. case Int32Array:
  466. return Math.round( value * 2147483647.0 );
  467. case Int16Array:
  468. return Math.round( value * 32767.0 );
  469. case Int8Array:
  470. return Math.round( value * 127.0 );
  471. default:
  472. throw new Error( 'Invalid component type.' );
  473. }
  474. }
  475. const MathUtils = {
  476. DEG2RAD: DEG2RAD,
  477. RAD2DEG: RAD2DEG,
  478. generateUUID: generateUUID,
  479. clamp: clamp,
  480. euclideanModulo: euclideanModulo,
  481. mapLinear: mapLinear,
  482. inverseLerp: inverseLerp,
  483. lerp: lerp,
  484. damp: damp,
  485. pingpong: pingpong,
  486. smoothstep: smoothstep,
  487. smootherstep: smootherstep,
  488. randInt: randInt,
  489. randFloat: randFloat,
  490. randFloatSpread: randFloatSpread,
  491. seededRandom: seededRandom,
  492. degToRad: degToRad,
  493. radToDeg: radToDeg,
  494. isPowerOfTwo: isPowerOfTwo,
  495. ceilPowerOfTwo: ceilPowerOfTwo,
  496. floorPowerOfTwo: floorPowerOfTwo,
  497. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  498. normalize: normalize,
  499. denormalize: denormalize
  500. };
  501. class Vector2 {
  502. constructor( x = 0, y = 0 ) {
  503. Vector2.prototype.isVector2 = true;
  504. this.x = x;
  505. this.y = y;
  506. }
  507. get width() {
  508. return this.x;
  509. }
  510. set width( value ) {
  511. this.x = value;
  512. }
  513. get height() {
  514. return this.y;
  515. }
  516. set height( value ) {
  517. this.y = value;
  518. }
  519. set( x, y ) {
  520. this.x = x;
  521. this.y = y;
  522. return this;
  523. }
  524. setScalar( scalar ) {
  525. this.x = scalar;
  526. this.y = scalar;
  527. return this;
  528. }
  529. setX( x ) {
  530. this.x = x;
  531. return this;
  532. }
  533. setY( y ) {
  534. this.y = y;
  535. return this;
  536. }
  537. setComponent( index, value ) {
  538. switch ( index ) {
  539. case 0: this.x = value; break;
  540. case 1: this.y = value; break;
  541. default: throw new Error( 'index is out of range: ' + index );
  542. }
  543. return this;
  544. }
  545. getComponent( index ) {
  546. switch ( index ) {
  547. case 0: return this.x;
  548. case 1: return this.y;
  549. default: throw new Error( 'index is out of range: ' + index );
  550. }
  551. }
  552. clone() {
  553. return new this.constructor( this.x, this.y );
  554. }
  555. copy( v ) {
  556. this.x = v.x;
  557. this.y = v.y;
  558. return this;
  559. }
  560. add( v ) {
  561. this.x += v.x;
  562. this.y += v.y;
  563. return this;
  564. }
  565. addScalar( s ) {
  566. this.x += s;
  567. this.y += s;
  568. return this;
  569. }
  570. addVectors( a, b ) {
  571. this.x = a.x + b.x;
  572. this.y = a.y + b.y;
  573. return this;
  574. }
  575. addScaledVector( v, s ) {
  576. this.x += v.x * s;
  577. this.y += v.y * s;
  578. return this;
  579. }
  580. sub( v ) {
  581. this.x -= v.x;
  582. this.y -= v.y;
  583. return this;
  584. }
  585. subScalar( s ) {
  586. this.x -= s;
  587. this.y -= s;
  588. return this;
  589. }
  590. subVectors( a, b ) {
  591. this.x = a.x - b.x;
  592. this.y = a.y - b.y;
  593. return this;
  594. }
  595. multiply( v ) {
  596. this.x *= v.x;
  597. this.y *= v.y;
  598. return this;
  599. }
  600. multiplyScalar( scalar ) {
  601. this.x *= scalar;
  602. this.y *= scalar;
  603. return this;
  604. }
  605. divide( v ) {
  606. this.x /= v.x;
  607. this.y /= v.y;
  608. return this;
  609. }
  610. divideScalar( scalar ) {
  611. return this.multiplyScalar( 1 / scalar );
  612. }
  613. applyMatrix3( m ) {
  614. const x = this.x, y = this.y;
  615. const e = m.elements;
  616. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  617. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  618. return this;
  619. }
  620. min( v ) {
  621. this.x = Math.min( this.x, v.x );
  622. this.y = Math.min( this.y, v.y );
  623. return this;
  624. }
  625. max( v ) {
  626. this.x = Math.max( this.x, v.x );
  627. this.y = Math.max( this.y, v.y );
  628. return this;
  629. }
  630. clamp( min, max ) {
  631. // assumes min < max, componentwise
  632. this.x = clamp( this.x, min.x, max.x );
  633. this.y = clamp( this.y, min.y, max.y );
  634. return this;
  635. }
  636. clampScalar( minVal, maxVal ) {
  637. this.x = clamp( this.x, minVal, maxVal );
  638. this.y = clamp( this.y, minVal, maxVal );
  639. return this;
  640. }
  641. clampLength( min, max ) {
  642. const length = this.length();
  643. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  644. }
  645. floor() {
  646. this.x = Math.floor( this.x );
  647. this.y = Math.floor( this.y );
  648. return this;
  649. }
  650. ceil() {
  651. this.x = Math.ceil( this.x );
  652. this.y = Math.ceil( this.y );
  653. return this;
  654. }
  655. round() {
  656. this.x = Math.round( this.x );
  657. this.y = Math.round( this.y );
  658. return this;
  659. }
  660. roundToZero() {
  661. this.x = Math.trunc( this.x );
  662. this.y = Math.trunc( this.y );
  663. return this;
  664. }
  665. negate() {
  666. this.x = - this.x;
  667. this.y = - this.y;
  668. return this;
  669. }
  670. dot( v ) {
  671. return this.x * v.x + this.y * v.y;
  672. }
  673. cross( v ) {
  674. return this.x * v.y - this.y * v.x;
  675. }
  676. lengthSq() {
  677. return this.x * this.x + this.y * this.y;
  678. }
  679. length() {
  680. return Math.sqrt( this.x * this.x + this.y * this.y );
  681. }
  682. manhattanLength() {
  683. return Math.abs( this.x ) + Math.abs( this.y );
  684. }
  685. normalize() {
  686. return this.divideScalar( this.length() || 1 );
  687. }
  688. angle() {
  689. // computes the angle in radians with respect to the positive x-axis
  690. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  691. return angle;
  692. }
  693. angleTo( v ) {
  694. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  695. if ( denominator === 0 ) return Math.PI / 2;
  696. const theta = this.dot( v ) / denominator;
  697. // clamp, to handle numerical problems
  698. return Math.acos( clamp( theta, -1, 1 ) );
  699. }
  700. distanceTo( v ) {
  701. return Math.sqrt( this.distanceToSquared( v ) );
  702. }
  703. distanceToSquared( v ) {
  704. const dx = this.x - v.x, dy = this.y - v.y;
  705. return dx * dx + dy * dy;
  706. }
  707. manhattanDistanceTo( v ) {
  708. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  709. }
  710. setLength( length ) {
  711. return this.normalize().multiplyScalar( length );
  712. }
  713. lerp( v, alpha ) {
  714. this.x += ( v.x - this.x ) * alpha;
  715. this.y += ( v.y - this.y ) * alpha;
  716. return this;
  717. }
  718. lerpVectors( v1, v2, alpha ) {
  719. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  720. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  721. return this;
  722. }
  723. equals( v ) {
  724. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  725. }
  726. fromArray( array, offset = 0 ) {
  727. this.x = array[ offset ];
  728. this.y = array[ offset + 1 ];
  729. return this;
  730. }
  731. toArray( array = [], offset = 0 ) {
  732. array[ offset ] = this.x;
  733. array[ offset + 1 ] = this.y;
  734. return array;
  735. }
  736. fromBufferAttribute( attribute, index ) {
  737. this.x = attribute.getX( index );
  738. this.y = attribute.getY( index );
  739. return this;
  740. }
  741. rotateAround( center, angle ) {
  742. const c = Math.cos( angle ), s = Math.sin( angle );
  743. const x = this.x - center.x;
  744. const y = this.y - center.y;
  745. this.x = x * c - y * s + center.x;
  746. this.y = x * s + y * c + center.y;
  747. return this;
  748. }
  749. random() {
  750. this.x = Math.random();
  751. this.y = Math.random();
  752. return this;
  753. }
  754. *[ Symbol.iterator ]() {
  755. yield this.x;
  756. yield this.y;
  757. }
  758. }
  759. class Matrix3 {
  760. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  761. Matrix3.prototype.isMatrix3 = true;
  762. this.elements = [
  763. 1, 0, 0,
  764. 0, 1, 0,
  765. 0, 0, 1
  766. ];
  767. if ( n11 !== undefined ) {
  768. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  769. }
  770. }
  771. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  772. const te = this.elements;
  773. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  774. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  775. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  776. return this;
  777. }
  778. identity() {
  779. this.set(
  780. 1, 0, 0,
  781. 0, 1, 0,
  782. 0, 0, 1
  783. );
  784. return this;
  785. }
  786. copy( m ) {
  787. const te = this.elements;
  788. const me = m.elements;
  789. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  790. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  791. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  792. return this;
  793. }
  794. extractBasis( xAxis, yAxis, zAxis ) {
  795. xAxis.setFromMatrix3Column( this, 0 );
  796. yAxis.setFromMatrix3Column( this, 1 );
  797. zAxis.setFromMatrix3Column( this, 2 );
  798. return this;
  799. }
  800. setFromMatrix4( m ) {
  801. const me = m.elements;
  802. this.set(
  803. me[ 0 ], me[ 4 ], me[ 8 ],
  804. me[ 1 ], me[ 5 ], me[ 9 ],
  805. me[ 2 ], me[ 6 ], me[ 10 ]
  806. );
  807. return this;
  808. }
  809. multiply( m ) {
  810. return this.multiplyMatrices( this, m );
  811. }
  812. premultiply( m ) {
  813. return this.multiplyMatrices( m, this );
  814. }
  815. multiplyMatrices( a, b ) {
  816. const ae = a.elements;
  817. const be = b.elements;
  818. const te = this.elements;
  819. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  820. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  821. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  822. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  823. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  824. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  825. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  826. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  827. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  828. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  829. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  830. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  831. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  832. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  833. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  834. return this;
  835. }
  836. multiplyScalar( s ) {
  837. const te = this.elements;
  838. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  839. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  840. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  841. return this;
  842. }
  843. determinant() {
  844. const te = this.elements;
  845. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  846. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  847. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  848. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  849. }
  850. invert() {
  851. const te = this.elements,
  852. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  853. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  854. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  855. t11 = n33 * n22 - n32 * n23,
  856. t12 = n32 * n13 - n33 * n12,
  857. t13 = n23 * n12 - n22 * n13,
  858. det = n11 * t11 + n21 * t12 + n31 * t13;
  859. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  860. const detInv = 1 / det;
  861. te[ 0 ] = t11 * detInv;
  862. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  863. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  864. te[ 3 ] = t12 * detInv;
  865. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  866. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  867. te[ 6 ] = t13 * detInv;
  868. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  869. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  870. return this;
  871. }
  872. transpose() {
  873. let tmp;
  874. const m = this.elements;
  875. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  876. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  877. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  878. return this;
  879. }
  880. getNormalMatrix( matrix4 ) {
  881. return this.setFromMatrix4( matrix4 ).invert().transpose();
  882. }
  883. transposeIntoArray( r ) {
  884. const m = this.elements;
  885. r[ 0 ] = m[ 0 ];
  886. r[ 1 ] = m[ 3 ];
  887. r[ 2 ] = m[ 6 ];
  888. r[ 3 ] = m[ 1 ];
  889. r[ 4 ] = m[ 4 ];
  890. r[ 5 ] = m[ 7 ];
  891. r[ 6 ] = m[ 2 ];
  892. r[ 7 ] = m[ 5 ];
  893. r[ 8 ] = m[ 8 ];
  894. return this;
  895. }
  896. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  897. const c = Math.cos( rotation );
  898. const s = Math.sin( rotation );
  899. this.set(
  900. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  901. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  902. 0, 0, 1
  903. );
  904. return this;
  905. }
  906. //
  907. scale( sx, sy ) {
  908. this.premultiply( _m3.makeScale( sx, sy ) );
  909. return this;
  910. }
  911. rotate( theta ) {
  912. this.premultiply( _m3.makeRotation( - theta ) );
  913. return this;
  914. }
  915. translate( tx, ty ) {
  916. this.premultiply( _m3.makeTranslation( tx, ty ) );
  917. return this;
  918. }
  919. // for 2D Transforms
  920. makeTranslation( x, y ) {
  921. if ( x.isVector2 ) {
  922. this.set(
  923. 1, 0, x.x,
  924. 0, 1, x.y,
  925. 0, 0, 1
  926. );
  927. } else {
  928. this.set(
  929. 1, 0, x,
  930. 0, 1, y,
  931. 0, 0, 1
  932. );
  933. }
  934. return this;
  935. }
  936. makeRotation( theta ) {
  937. // counterclockwise
  938. const c = Math.cos( theta );
  939. const s = Math.sin( theta );
  940. this.set(
  941. c, - s, 0,
  942. s, c, 0,
  943. 0, 0, 1
  944. );
  945. return this;
  946. }
  947. makeScale( x, y ) {
  948. this.set(
  949. x, 0, 0,
  950. 0, y, 0,
  951. 0, 0, 1
  952. );
  953. return this;
  954. }
  955. //
  956. equals( matrix ) {
  957. const te = this.elements;
  958. const me = matrix.elements;
  959. for ( let i = 0; i < 9; i ++ ) {
  960. if ( te[ i ] !== me[ i ] ) return false;
  961. }
  962. return true;
  963. }
  964. fromArray( array, offset = 0 ) {
  965. for ( let i = 0; i < 9; i ++ ) {
  966. this.elements[ i ] = array[ i + offset ];
  967. }
  968. return this;
  969. }
  970. toArray( array = [], offset = 0 ) {
  971. const te = this.elements;
  972. array[ offset ] = te[ 0 ];
  973. array[ offset + 1 ] = te[ 1 ];
  974. array[ offset + 2 ] = te[ 2 ];
  975. array[ offset + 3 ] = te[ 3 ];
  976. array[ offset + 4 ] = te[ 4 ];
  977. array[ offset + 5 ] = te[ 5 ];
  978. array[ offset + 6 ] = te[ 6 ];
  979. array[ offset + 7 ] = te[ 7 ];
  980. array[ offset + 8 ] = te[ 8 ];
  981. return array;
  982. }
  983. clone() {
  984. return new this.constructor().fromArray( this.elements );
  985. }
  986. }
  987. const _m3 = /*@__PURE__*/ new Matrix3();
  988. function arrayNeedsUint32( array ) {
  989. // assumes larger values usually on last
  990. for ( let i = array.length - 1; i >= 0; -- i ) {
  991. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  992. }
  993. return false;
  994. }
  995. const TYPED_ARRAYS = {
  996. Int8Array: Int8Array,
  997. Uint8Array: Uint8Array,
  998. Uint8ClampedArray: Uint8ClampedArray,
  999. Int16Array: Int16Array,
  1000. Uint16Array: Uint16Array,
  1001. Int32Array: Int32Array,
  1002. Uint32Array: Uint32Array,
  1003. Float32Array: Float32Array,
  1004. Float64Array: Float64Array
  1005. };
  1006. function getTypedArray( type, buffer ) {
  1007. return new TYPED_ARRAYS[ type ]( buffer );
  1008. }
  1009. function createElementNS( name ) {
  1010. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1011. }
  1012. function createCanvasElement() {
  1013. const canvas = createElementNS( 'canvas' );
  1014. canvas.style.display = 'block';
  1015. return canvas;
  1016. }
  1017. const _cache = {};
  1018. function warnOnce( message ) {
  1019. if ( message in _cache ) return;
  1020. _cache[ message ] = true;
  1021. console.warn( message );
  1022. }
  1023. function probeAsync( gl, sync, interval ) {
  1024. return new Promise( function ( resolve, reject ) {
  1025. function probe() {
  1026. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1027. case gl.WAIT_FAILED:
  1028. reject();
  1029. break;
  1030. case gl.TIMEOUT_EXPIRED:
  1031. setTimeout( probe, interval );
  1032. break;
  1033. default:
  1034. resolve();
  1035. }
  1036. }
  1037. setTimeout( probe, interval );
  1038. } );
  1039. }
  1040. function toNormalizedProjectionMatrix( projectionMatrix ) {
  1041. const m = projectionMatrix.elements;
  1042. // Convert [-1, 1] to [0, 1] projection matrix
  1043. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  1044. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  1045. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  1046. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  1047. }
  1048. function toReversedProjectionMatrix( projectionMatrix ) {
  1049. const m = projectionMatrix.elements;
  1050. const isPerspectiveMatrix = m[ 11 ] === -1;
  1051. // Reverse [0, 1] projection matrix
  1052. if ( isPerspectiveMatrix ) {
  1053. m[ 10 ] = - m[ 10 ] - 1;
  1054. m[ 14 ] = - m[ 14 ];
  1055. } else {
  1056. m[ 10 ] = - m[ 10 ];
  1057. m[ 14 ] = - m[ 14 ] + 1;
  1058. }
  1059. }
  1060. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1061. 0.4123908, 0.3575843, 0.1804808,
  1062. 0.2126390, 0.7151687, 0.0721923,
  1063. 0.0193308, 0.1191948, 0.9505322
  1064. );
  1065. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1066. 3.2409699, -1.5373832, -0.4986108,
  1067. -0.9692436, 1.8759675, 0.0415551,
  1068. 0.0556301, -0.203977, 1.0569715
  1069. );
  1070. function createColorManagement() {
  1071. const ColorManagement = {
  1072. enabled: true,
  1073. workingColorSpace: LinearSRGBColorSpace,
  1074. /**
  1075. * Implementations of supported color spaces.
  1076. *
  1077. * Required:
  1078. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  1079. * - whitePoint: reference white [ x y ]
  1080. * - transfer: transfer function (pre-defined)
  1081. * - toXYZ: Matrix3 RGB to XYZ transform
  1082. * - fromXYZ: Matrix3 XYZ to RGB transform
  1083. * - luminanceCoefficients: RGB luminance coefficients
  1084. *
  1085. * Optional:
  1086. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  1087. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  1088. *
  1089. * Reference:
  1090. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  1091. */
  1092. spaces: {},
  1093. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1094. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1095. return color;
  1096. }
  1097. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1098. color.r = SRGBToLinear( color.r );
  1099. color.g = SRGBToLinear( color.g );
  1100. color.b = SRGBToLinear( color.b );
  1101. }
  1102. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1103. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1104. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1105. }
  1106. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1107. color.r = LinearToSRGB( color.r );
  1108. color.g = LinearToSRGB( color.g );
  1109. color.b = LinearToSRGB( color.b );
  1110. }
  1111. return color;
  1112. },
  1113. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1114. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1115. },
  1116. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1117. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1118. },
  1119. getPrimaries: function ( colorSpace ) {
  1120. return this.spaces[ colorSpace ].primaries;
  1121. },
  1122. getTransfer: function ( colorSpace ) {
  1123. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1124. return this.spaces[ colorSpace ].transfer;
  1125. },
  1126. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1127. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1128. },
  1129. define: function ( colorSpaces ) {
  1130. Object.assign( this.spaces, colorSpaces );
  1131. },
  1132. // Internal APIs
  1133. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1134. return targetMatrix
  1135. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1136. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1137. },
  1138. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1139. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1140. },
  1141. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1142. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1143. }
  1144. };
  1145. /******************************************************************************
  1146. * sRGB definitions
  1147. */
  1148. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1149. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1150. const D65 = [ 0.3127, 0.3290 ];
  1151. ColorManagement.define( {
  1152. [ LinearSRGBColorSpace ]: {
  1153. primaries: REC709_PRIMARIES,
  1154. whitePoint: D65,
  1155. transfer: LinearTransfer,
  1156. toXYZ: LINEAR_REC709_TO_XYZ,
  1157. fromXYZ: XYZ_TO_LINEAR_REC709,
  1158. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1159. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1160. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1161. },
  1162. [ SRGBColorSpace ]: {
  1163. primaries: REC709_PRIMARIES,
  1164. whitePoint: D65,
  1165. transfer: SRGBTransfer,
  1166. toXYZ: LINEAR_REC709_TO_XYZ,
  1167. fromXYZ: XYZ_TO_LINEAR_REC709,
  1168. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1169. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1170. },
  1171. } );
  1172. return ColorManagement;
  1173. }
  1174. const ColorManagement = /*@__PURE__*/ createColorManagement();
  1175. function SRGBToLinear( c ) {
  1176. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1177. }
  1178. function LinearToSRGB( c ) {
  1179. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1180. }
  1181. let _canvas;
  1182. class ImageUtils {
  1183. static getDataURL( image ) {
  1184. if ( /^data:/i.test( image.src ) ) {
  1185. return image.src;
  1186. }
  1187. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1188. return image.src;
  1189. }
  1190. let canvas;
  1191. if ( image instanceof HTMLCanvasElement ) {
  1192. canvas = image;
  1193. } else {
  1194. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1195. _canvas.width = image.width;
  1196. _canvas.height = image.height;
  1197. const context = _canvas.getContext( '2d' );
  1198. if ( image instanceof ImageData ) {
  1199. context.putImageData( image, 0, 0 );
  1200. } else {
  1201. context.drawImage( image, 0, 0, image.width, image.height );
  1202. }
  1203. canvas = _canvas;
  1204. }
  1205. return canvas.toDataURL( 'image/png' );
  1206. }
  1207. static sRGBToLinear( image ) {
  1208. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1209. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1210. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1211. const canvas = createElementNS( 'canvas' );
  1212. canvas.width = image.width;
  1213. canvas.height = image.height;
  1214. const context = canvas.getContext( '2d' );
  1215. context.drawImage( image, 0, 0, image.width, image.height );
  1216. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1217. const data = imageData.data;
  1218. for ( let i = 0; i < data.length; i ++ ) {
  1219. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1220. }
  1221. context.putImageData( imageData, 0, 0 );
  1222. return canvas;
  1223. } else if ( image.data ) {
  1224. const data = image.data.slice( 0 );
  1225. for ( let i = 0; i < data.length; i ++ ) {
  1226. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1227. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1228. } else {
  1229. // assuming float
  1230. data[ i ] = SRGBToLinear( data[ i ] );
  1231. }
  1232. }
  1233. return {
  1234. data: data,
  1235. width: image.width,
  1236. height: image.height
  1237. };
  1238. } else {
  1239. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1240. return image;
  1241. }
  1242. }
  1243. }
  1244. let _sourceId = 0;
  1245. class Source {
  1246. constructor( data = null ) {
  1247. this.isSource = true;
  1248. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1249. this.uuid = generateUUID();
  1250. this.data = data;
  1251. this.dataReady = true;
  1252. this.version = 0;
  1253. }
  1254. set needsUpdate( value ) {
  1255. if ( value === true ) this.version ++;
  1256. }
  1257. toJSON( meta ) {
  1258. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1259. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1260. return meta.images[ this.uuid ];
  1261. }
  1262. const output = {
  1263. uuid: this.uuid,
  1264. url: ''
  1265. };
  1266. const data = this.data;
  1267. if ( data !== null ) {
  1268. let url;
  1269. if ( Array.isArray( data ) ) {
  1270. // cube texture
  1271. url = [];
  1272. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1273. if ( data[ i ].isDataTexture ) {
  1274. url.push( serializeImage( data[ i ].image ) );
  1275. } else {
  1276. url.push( serializeImage( data[ i ] ) );
  1277. }
  1278. }
  1279. } else {
  1280. // texture
  1281. url = serializeImage( data );
  1282. }
  1283. output.url = url;
  1284. }
  1285. if ( ! isRootObject ) {
  1286. meta.images[ this.uuid ] = output;
  1287. }
  1288. return output;
  1289. }
  1290. }
  1291. function serializeImage( image ) {
  1292. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1293. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1294. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1295. // default images
  1296. return ImageUtils.getDataURL( image );
  1297. } else {
  1298. if ( image.data ) {
  1299. // images of DataTexture
  1300. return {
  1301. data: Array.from( image.data ),
  1302. width: image.width,
  1303. height: image.height,
  1304. type: image.data.constructor.name
  1305. };
  1306. } else {
  1307. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1308. return {};
  1309. }
  1310. }
  1311. }
  1312. let _textureId = 0;
  1313. /**
  1314. * Base class for all textures.
  1315. *
  1316. * Note: After the initial use of a texture, its dimensions, format, and type
  1317. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  1318. *
  1319. * @augments EventDispatcher
  1320. */
  1321. class Texture extends EventDispatcher {
  1322. /**
  1323. * Constructs a new texture.
  1324. *
  1325. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  1326. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  1327. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  1328. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  1329. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  1330. * @param {number} [minFilter=LinearFilter] - The min filter value.
  1331. * @param {number} [format=RGABFormat] - The min filter value.
  1332. * @param {number} [type=UnsignedByteType] - The min filter value.
  1333. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The min filter value.
  1334. * @param {string} [colorSpace=NoColorSpace] - The min filter value.
  1335. */
  1336. 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 ) {
  1337. super();
  1338. /**
  1339. * This flag can be used for type testing.
  1340. *
  1341. * @type {boolean}
  1342. * @readonly
  1343. * @default true
  1344. */
  1345. this.isTexture = true;
  1346. /**
  1347. * The ID of the texture.
  1348. *
  1349. * @name Texture#id
  1350. * @type {number}
  1351. * @readonly
  1352. */
  1353. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1354. /**
  1355. * The UUID of the material.
  1356. *
  1357. * @type {string}
  1358. * @readonly
  1359. */
  1360. this.uuid = generateUUID();
  1361. /**
  1362. * The name of the material.
  1363. *
  1364. * @type {string}
  1365. */
  1366. this.name = '';
  1367. /**
  1368. * The data definition of a texture. A reference to the data source can be
  1369. * shared across textures. This is often useful in context of spritesheets
  1370. * where multiple textures render the same data but with different texture
  1371. * transformations.
  1372. *
  1373. * @type {Source}
  1374. */
  1375. this.source = new Source( image );
  1376. /**
  1377. * An array holding user-defined mipmaps.
  1378. *
  1379. * @type {Array<Object>}
  1380. */
  1381. this.mipmaps = [];
  1382. /**
  1383. * How the texture is applied to the object. The value `UVMapping`
  1384. * is the default, where texture or uv coordinates are used to apply the map.
  1385. *
  1386. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  1387. * @default UVMapping
  1388. */
  1389. this.mapping = mapping;
  1390. /**
  1391. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  1392. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  1393. *
  1394. * @type {number}
  1395. * @default 0
  1396. */
  1397. this.channel = 0;
  1398. /**
  1399. * This defines how the texture is wrapped horizontally and corresponds to
  1400. * *U* in UV mapping.
  1401. *
  1402. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  1403. * @default ClampToEdgeWrapping
  1404. */
  1405. this.wrapS = wrapS;
  1406. /**
  1407. * This defines how the texture is wrapped horizontally and corresponds to
  1408. * *V* in UV mapping.
  1409. *
  1410. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  1411. * @default ClampToEdgeWrapping
  1412. */
  1413. this.wrapT = wrapT;
  1414. /**
  1415. * How the texture is sampled when a texel covers more than one pixel.
  1416. *
  1417. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  1418. * @default LinearFilter
  1419. */
  1420. this.magFilter = magFilter;
  1421. /**
  1422. * How the texture is sampled when a texel covers less than one pixel.
  1423. *
  1424. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  1425. * @default LinearMipmapLinearFilter
  1426. */
  1427. this.minFilter = minFilter;
  1428. /**
  1429. * The number of samples taken along the axis through the pixel that has the
  1430. * highest density of texels. By default, this value is `1`. A higher value
  1431. * gives a less blurry result than a basic mipmap, at the cost of more
  1432. * texture samples being used.
  1433. *
  1434. * @type {number}
  1435. * @default 0
  1436. */
  1437. this.anisotropy = anisotropy;
  1438. /**
  1439. * The format of the texture.
  1440. *
  1441. * @type {number}
  1442. * @default RGBAFormat
  1443. */
  1444. this.format = format;
  1445. /**
  1446. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  1447. * defines how the texture data is going to be stored on the GPU.
  1448. *
  1449. * This property allows to overwrite the default format.
  1450. *
  1451. * @type {?string}
  1452. * @default null
  1453. */
  1454. this.internalFormat = null;
  1455. /**
  1456. * The data type of the texture.
  1457. *
  1458. * @type {number}
  1459. * @default UnsignedByteType
  1460. */
  1461. this.type = type;
  1462. /**
  1463. * How much a single repetition of the texture is offset from the beginning,
  1464. * in each direction U and V. Typical range is `0.0` to `1.0`.
  1465. *
  1466. * @type {Vector2}
  1467. * @default (0,0)
  1468. */
  1469. this.offset = new Vector2( 0, 0 );
  1470. /**
  1471. * How many times the texture is repeated across the surface, in each
  1472. * direction U and V. If repeat is set greater than `1` in either direction,
  1473. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  1474. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  1475. *
  1476. * @type {Vector2}
  1477. * @default (1,1)
  1478. */
  1479. this.repeat = new Vector2( 1, 1 );
  1480. /**
  1481. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  1482. * to the center of the texture. Default is `(0, 0)`, the lower left.
  1483. *
  1484. * @type {Vector2}
  1485. * @default (0,0)
  1486. */
  1487. this.center = new Vector2( 0, 0 );
  1488. /**
  1489. * How much the texture is rotated around the center point, in radians.
  1490. * Positive values are counter-clockwise.
  1491. *
  1492. * @type {number}
  1493. * @default 0
  1494. */
  1495. this.rotation = 0;
  1496. /**
  1497. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  1498. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  1499. * {@link Texture#rotation}, and {@link Texture#center}.
  1500. *
  1501. * Set this to `false` if you are specifying the uv-transform matrix directly.
  1502. *
  1503. * @type {boolean}
  1504. * @default true
  1505. */
  1506. this.matrixAutoUpdate = true;
  1507. /**
  1508. * The uv-transformation matrix of the texture.
  1509. *
  1510. * @type {Matrix3}
  1511. */
  1512. this.matrix = new Matrix3();
  1513. /**
  1514. * Whether to generate mipmaps (if possible) for a texture.
  1515. *
  1516. * Set this to `false` if you are creating mipmaps manually.
  1517. *
  1518. * @type {boolean}
  1519. * @default true
  1520. */
  1521. this.generateMipmaps = true;
  1522. /**
  1523. * If set to `true`, the alpha channel, if present, is multiplied into the
  1524. * color channels when the texture is uploaded to the GPU.
  1525. *
  1526. * Note that this property has no effect when using `ImageBitmap`. You need to
  1527. * configure premultiply alpha on bitmap creation instead.
  1528. *
  1529. * @type {boolean}
  1530. * @default false
  1531. */
  1532. this.premultiplyAlpha = false;
  1533. /**
  1534. * If set to `true`, the texture is flipped along the vertical axis when
  1535. * uploaded to the GPU.
  1536. *
  1537. * Note that this property has no effect when using `ImageBitmap`. You need to
  1538. * configure the flip on bitmap creation instead.
  1539. *
  1540. * @type {boolean}
  1541. * @default true
  1542. */
  1543. this.flipY = true;
  1544. /**
  1545. * Specifies the alignment requirements for the start of each pixel row in memory.
  1546. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  1547. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  1548. *
  1549. * @type {number}
  1550. * @default 4
  1551. */
  1552. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1553. /**
  1554. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  1555. *
  1556. * @type {string}
  1557. * @default NoColorSpace
  1558. */
  1559. this.colorSpace = colorSpace;
  1560. /**
  1561. * An object that can be used to store custom data about the texture. It
  1562. * should not hold references to functions as these will not be cloned.
  1563. *
  1564. * @type {Object}
  1565. */
  1566. this.userData = {};
  1567. /**
  1568. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  1569. *
  1570. * @type {number}
  1571. * @readonly
  1572. * @default 0
  1573. */
  1574. this.version = 0;
  1575. /**
  1576. * A callback function, called when the texture is updated (e.g., when
  1577. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  1578. *
  1579. * @type {?Function}
  1580. * @default null
  1581. */
  1582. this.onUpdate = null;
  1583. /**
  1584. * An optional back reference to the textures render target.
  1585. *
  1586. * @type {?(RenderTarget|WebGLRenderTarget)}
  1587. * @default null
  1588. */
  1589. this.renderTarget = null;
  1590. /**
  1591. * Indicates whether a texture belongs to a render target or not.
  1592. *
  1593. * @type {boolean}
  1594. * @readonly
  1595. * @default false
  1596. */
  1597. this.isRenderTargetTexture = false;
  1598. /**
  1599. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  1600. * (only relevant for render target textures).
  1601. *
  1602. * @type {number}
  1603. * @readonly
  1604. * @default 0
  1605. */
  1606. this.pmremVersion = 0;
  1607. }
  1608. /**
  1609. * The image object holding the texture data.
  1610. *
  1611. * @type {?Object}
  1612. */
  1613. get image() {
  1614. return this.source.data;
  1615. }
  1616. set image( value = null ) {
  1617. this.source.data = value;
  1618. }
  1619. /**
  1620. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  1621. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  1622. */
  1623. updateMatrix() {
  1624. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1625. }
  1626. /**
  1627. * Returns a new texture with copied values from this instance.
  1628. *
  1629. * @return {Texture} A clone of this instance.
  1630. */
  1631. clone() {
  1632. return new this.constructor().copy( this );
  1633. }
  1634. /**
  1635. * Copies the values of the given texture to this instance.
  1636. *
  1637. * @param {Texture} source - The texture to copy.
  1638. * @return {Texture} A reference to this instance.
  1639. */
  1640. copy( source ) {
  1641. this.name = source.name;
  1642. this.source = source.source;
  1643. this.mipmaps = source.mipmaps.slice( 0 );
  1644. this.mapping = source.mapping;
  1645. this.channel = source.channel;
  1646. this.wrapS = source.wrapS;
  1647. this.wrapT = source.wrapT;
  1648. this.magFilter = source.magFilter;
  1649. this.minFilter = source.minFilter;
  1650. this.anisotropy = source.anisotropy;
  1651. this.format = source.format;
  1652. this.internalFormat = source.internalFormat;
  1653. this.type = source.type;
  1654. this.offset.copy( source.offset );
  1655. this.repeat.copy( source.repeat );
  1656. this.center.copy( source.center );
  1657. this.rotation = source.rotation;
  1658. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1659. this.matrix.copy( source.matrix );
  1660. this.generateMipmaps = source.generateMipmaps;
  1661. this.premultiplyAlpha = source.premultiplyAlpha;
  1662. this.flipY = source.flipY;
  1663. this.unpackAlignment = source.unpackAlignment;
  1664. this.colorSpace = source.colorSpace;
  1665. this.renderTarget = source.renderTarget;
  1666. this.isRenderTargetTexture = source.isRenderTargetTexture;
  1667. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1668. this.needsUpdate = true;
  1669. return this;
  1670. }
  1671. /**
  1672. * Serializes the texture into JSON.
  1673. *
  1674. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  1675. * @return {Object} A JSON object representing the serialized texture.
  1676. * @see {@link ObjectLoader#parse}
  1677. */
  1678. toJSON( meta ) {
  1679. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1680. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1681. return meta.textures[ this.uuid ];
  1682. }
  1683. const output = {
  1684. metadata: {
  1685. version: 4.6,
  1686. type: 'Texture',
  1687. generator: 'Texture.toJSON'
  1688. },
  1689. uuid: this.uuid,
  1690. name: this.name,
  1691. image: this.source.toJSON( meta ).uuid,
  1692. mapping: this.mapping,
  1693. channel: this.channel,
  1694. repeat: [ this.repeat.x, this.repeat.y ],
  1695. offset: [ this.offset.x, this.offset.y ],
  1696. center: [ this.center.x, this.center.y ],
  1697. rotation: this.rotation,
  1698. wrap: [ this.wrapS, this.wrapT ],
  1699. format: this.format,
  1700. internalFormat: this.internalFormat,
  1701. type: this.type,
  1702. colorSpace: this.colorSpace,
  1703. minFilter: this.minFilter,
  1704. magFilter: this.magFilter,
  1705. anisotropy: this.anisotropy,
  1706. flipY: this.flipY,
  1707. generateMipmaps: this.generateMipmaps,
  1708. premultiplyAlpha: this.premultiplyAlpha,
  1709. unpackAlignment: this.unpackAlignment
  1710. };
  1711. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1712. if ( ! isRootObject ) {
  1713. meta.textures[ this.uuid ] = output;
  1714. }
  1715. return output;
  1716. }
  1717. /**
  1718. * Frees the GPU-related resources allocated by this instance. Call this
  1719. * method whenever this instance is no longer used in your app.
  1720. *
  1721. * @fires Texture#dispose
  1722. */
  1723. dispose() {
  1724. /**
  1725. * Fires when the texture has been disposed of.
  1726. *
  1727. * @event Texture#dispose
  1728. * @type {Object}
  1729. */
  1730. this.dispatchEvent( { type: 'dispose' } );
  1731. }
  1732. /**
  1733. * Transforms the given uv vector with the textures uv transformation matrix.
  1734. *
  1735. * @param {Vector2} uv - The uv vector.
  1736. * @return {Vector2} The transformed uv vector.
  1737. */
  1738. transformUv( uv ) {
  1739. if ( this.mapping !== UVMapping ) return uv;
  1740. uv.applyMatrix3( this.matrix );
  1741. if ( uv.x < 0 || uv.x > 1 ) {
  1742. switch ( this.wrapS ) {
  1743. case RepeatWrapping:
  1744. uv.x = uv.x - Math.floor( uv.x );
  1745. break;
  1746. case ClampToEdgeWrapping:
  1747. uv.x = uv.x < 0 ? 0 : 1;
  1748. break;
  1749. case MirroredRepeatWrapping:
  1750. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1751. uv.x = Math.ceil( uv.x ) - uv.x;
  1752. } else {
  1753. uv.x = uv.x - Math.floor( uv.x );
  1754. }
  1755. break;
  1756. }
  1757. }
  1758. if ( uv.y < 0 || uv.y > 1 ) {
  1759. switch ( this.wrapT ) {
  1760. case RepeatWrapping:
  1761. uv.y = uv.y - Math.floor( uv.y );
  1762. break;
  1763. case ClampToEdgeWrapping:
  1764. uv.y = uv.y < 0 ? 0 : 1;
  1765. break;
  1766. case MirroredRepeatWrapping:
  1767. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1768. uv.y = Math.ceil( uv.y ) - uv.y;
  1769. } else {
  1770. uv.y = uv.y - Math.floor( uv.y );
  1771. }
  1772. break;
  1773. }
  1774. }
  1775. if ( this.flipY ) {
  1776. uv.y = 1 - uv.y;
  1777. }
  1778. return uv;
  1779. }
  1780. /**
  1781. * Setting this property to `true` indicates the engine the texture
  1782. * must be updated in the next render. This triggers a texture upload
  1783. * to the GPU and ensures correct texture parameter configuration.
  1784. *
  1785. * @type {boolean}
  1786. * @default false
  1787. * @param {boolean} value
  1788. */
  1789. set needsUpdate( value ) {
  1790. if ( value === true ) {
  1791. this.version ++;
  1792. this.source.needsUpdate = true;
  1793. }
  1794. }
  1795. /**
  1796. * Setting this property to `true` indicates the engine the PMREM
  1797. * must be regenerated.
  1798. *
  1799. * @type {boolean}
  1800. * @default false
  1801. * @param {boolean} value
  1802. */
  1803. set needsPMREMUpdate( value ) {
  1804. if ( value === true ) {
  1805. this.pmremVersion ++;
  1806. }
  1807. }
  1808. }
  1809. /**
  1810. * The default image for all textures.
  1811. *
  1812. * @static
  1813. * @type {?Image}
  1814. * @default null
  1815. */
  1816. Texture.DEFAULT_IMAGE = null;
  1817. /**
  1818. * The default mapping for all textures.
  1819. *
  1820. * @static
  1821. * @type {number}
  1822. * @default UVMapping
  1823. */
  1824. Texture.DEFAULT_MAPPING = UVMapping;
  1825. /**
  1826. * The default anisotropy value for all textures.
  1827. *
  1828. * @static
  1829. * @type {number}
  1830. * @default 1
  1831. */
  1832. Texture.DEFAULT_ANISOTROPY = 1;
  1833. class Vector4 {
  1834. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1835. Vector4.prototype.isVector4 = true;
  1836. this.x = x;
  1837. this.y = y;
  1838. this.z = z;
  1839. this.w = w;
  1840. }
  1841. get width() {
  1842. return this.z;
  1843. }
  1844. set width( value ) {
  1845. this.z = value;
  1846. }
  1847. get height() {
  1848. return this.w;
  1849. }
  1850. set height( value ) {
  1851. this.w = value;
  1852. }
  1853. set( x, y, z, w ) {
  1854. this.x = x;
  1855. this.y = y;
  1856. this.z = z;
  1857. this.w = w;
  1858. return this;
  1859. }
  1860. setScalar( scalar ) {
  1861. this.x = scalar;
  1862. this.y = scalar;
  1863. this.z = scalar;
  1864. this.w = scalar;
  1865. return this;
  1866. }
  1867. setX( x ) {
  1868. this.x = x;
  1869. return this;
  1870. }
  1871. setY( y ) {
  1872. this.y = y;
  1873. return this;
  1874. }
  1875. setZ( z ) {
  1876. this.z = z;
  1877. return this;
  1878. }
  1879. setW( w ) {
  1880. this.w = w;
  1881. return this;
  1882. }
  1883. setComponent( index, value ) {
  1884. switch ( index ) {
  1885. case 0: this.x = value; break;
  1886. case 1: this.y = value; break;
  1887. case 2: this.z = value; break;
  1888. case 3: this.w = value; break;
  1889. default: throw new Error( 'index is out of range: ' + index );
  1890. }
  1891. return this;
  1892. }
  1893. getComponent( index ) {
  1894. switch ( index ) {
  1895. case 0: return this.x;
  1896. case 1: return this.y;
  1897. case 2: return this.z;
  1898. case 3: return this.w;
  1899. default: throw new Error( 'index is out of range: ' + index );
  1900. }
  1901. }
  1902. clone() {
  1903. return new this.constructor( this.x, this.y, this.z, this.w );
  1904. }
  1905. copy( v ) {
  1906. this.x = v.x;
  1907. this.y = v.y;
  1908. this.z = v.z;
  1909. this.w = ( v.w !== undefined ) ? v.w : 1;
  1910. return this;
  1911. }
  1912. add( v ) {
  1913. this.x += v.x;
  1914. this.y += v.y;
  1915. this.z += v.z;
  1916. this.w += v.w;
  1917. return this;
  1918. }
  1919. addScalar( s ) {
  1920. this.x += s;
  1921. this.y += s;
  1922. this.z += s;
  1923. this.w += s;
  1924. return this;
  1925. }
  1926. addVectors( a, b ) {
  1927. this.x = a.x + b.x;
  1928. this.y = a.y + b.y;
  1929. this.z = a.z + b.z;
  1930. this.w = a.w + b.w;
  1931. return this;
  1932. }
  1933. addScaledVector( v, s ) {
  1934. this.x += v.x * s;
  1935. this.y += v.y * s;
  1936. this.z += v.z * s;
  1937. this.w += v.w * s;
  1938. return this;
  1939. }
  1940. sub( v ) {
  1941. this.x -= v.x;
  1942. this.y -= v.y;
  1943. this.z -= v.z;
  1944. this.w -= v.w;
  1945. return this;
  1946. }
  1947. subScalar( s ) {
  1948. this.x -= s;
  1949. this.y -= s;
  1950. this.z -= s;
  1951. this.w -= s;
  1952. return this;
  1953. }
  1954. subVectors( a, b ) {
  1955. this.x = a.x - b.x;
  1956. this.y = a.y - b.y;
  1957. this.z = a.z - b.z;
  1958. this.w = a.w - b.w;
  1959. return this;
  1960. }
  1961. multiply( v ) {
  1962. this.x *= v.x;
  1963. this.y *= v.y;
  1964. this.z *= v.z;
  1965. this.w *= v.w;
  1966. return this;
  1967. }
  1968. multiplyScalar( scalar ) {
  1969. this.x *= scalar;
  1970. this.y *= scalar;
  1971. this.z *= scalar;
  1972. this.w *= scalar;
  1973. return this;
  1974. }
  1975. applyMatrix4( m ) {
  1976. const x = this.x, y = this.y, z = this.z, w = this.w;
  1977. const e = m.elements;
  1978. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1979. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1980. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1981. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1982. return this;
  1983. }
  1984. divide( v ) {
  1985. this.x /= v.x;
  1986. this.y /= v.y;
  1987. this.z /= v.z;
  1988. this.w /= v.w;
  1989. return this;
  1990. }
  1991. divideScalar( scalar ) {
  1992. return this.multiplyScalar( 1 / scalar );
  1993. }
  1994. setAxisAngleFromQuaternion( q ) {
  1995. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1996. // q is assumed to be normalized
  1997. this.w = 2 * Math.acos( q.w );
  1998. const s = Math.sqrt( 1 - q.w * q.w );
  1999. if ( s < 0.0001 ) {
  2000. this.x = 1;
  2001. this.y = 0;
  2002. this.z = 0;
  2003. } else {
  2004. this.x = q.x / s;
  2005. this.y = q.y / s;
  2006. this.z = q.z / s;
  2007. }
  2008. return this;
  2009. }
  2010. setAxisAngleFromRotationMatrix( m ) {
  2011. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2012. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2013. let angle, x, y, z; // variables for result
  2014. const epsilon = 0.01, // margin to allow for rounding errors
  2015. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  2016. te = m.elements,
  2017. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2018. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2019. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2020. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  2021. ( Math.abs( m13 - m31 ) < epsilon ) &&
  2022. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  2023. // singularity found
  2024. // first check for identity matrix which must have +1 for all terms
  2025. // in leading diagonal and zero in other terms
  2026. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  2027. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  2028. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  2029. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  2030. // this singularity is identity matrix so angle = 0
  2031. this.set( 1, 0, 0, 0 );
  2032. return this; // zero angle, arbitrary axis
  2033. }
  2034. // otherwise this singularity is angle = 180
  2035. angle = Math.PI;
  2036. const xx = ( m11 + 1 ) / 2;
  2037. const yy = ( m22 + 1 ) / 2;
  2038. const zz = ( m33 + 1 ) / 2;
  2039. const xy = ( m12 + m21 ) / 4;
  2040. const xz = ( m13 + m31 ) / 4;
  2041. const yz = ( m23 + m32 ) / 4;
  2042. if ( ( xx > yy ) && ( xx > zz ) ) {
  2043. // m11 is the largest diagonal term
  2044. if ( xx < epsilon ) {
  2045. x = 0;
  2046. y = 0.707106781;
  2047. z = 0.707106781;
  2048. } else {
  2049. x = Math.sqrt( xx );
  2050. y = xy / x;
  2051. z = xz / x;
  2052. }
  2053. } else if ( yy > zz ) {
  2054. // m22 is the largest diagonal term
  2055. if ( yy < epsilon ) {
  2056. x = 0.707106781;
  2057. y = 0;
  2058. z = 0.707106781;
  2059. } else {
  2060. y = Math.sqrt( yy );
  2061. x = xy / y;
  2062. z = yz / y;
  2063. }
  2064. } else {
  2065. // m33 is the largest diagonal term so base result on this
  2066. if ( zz < epsilon ) {
  2067. x = 0.707106781;
  2068. y = 0.707106781;
  2069. z = 0;
  2070. } else {
  2071. z = Math.sqrt( zz );
  2072. x = xz / z;
  2073. y = yz / z;
  2074. }
  2075. }
  2076. this.set( x, y, z, angle );
  2077. return this; // return 180 deg rotation
  2078. }
  2079. // as we have reached here there are no singularities so we can handle normally
  2080. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2081. ( m13 - m31 ) * ( m13 - m31 ) +
  2082. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2083. if ( Math.abs( s ) < 0.001 ) s = 1;
  2084. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2085. // caught by singularity test above, but I've left it in just in case
  2086. this.x = ( m32 - m23 ) / s;
  2087. this.y = ( m13 - m31 ) / s;
  2088. this.z = ( m21 - m12 ) / s;
  2089. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2090. return this;
  2091. }
  2092. setFromMatrixPosition( m ) {
  2093. const e = m.elements;
  2094. this.x = e[ 12 ];
  2095. this.y = e[ 13 ];
  2096. this.z = e[ 14 ];
  2097. this.w = e[ 15 ];
  2098. return this;
  2099. }
  2100. min( v ) {
  2101. this.x = Math.min( this.x, v.x );
  2102. this.y = Math.min( this.y, v.y );
  2103. this.z = Math.min( this.z, v.z );
  2104. this.w = Math.min( this.w, v.w );
  2105. return this;
  2106. }
  2107. max( v ) {
  2108. this.x = Math.max( this.x, v.x );
  2109. this.y = Math.max( this.y, v.y );
  2110. this.z = Math.max( this.z, v.z );
  2111. this.w = Math.max( this.w, v.w );
  2112. return this;
  2113. }
  2114. clamp( min, max ) {
  2115. // assumes min < max, componentwise
  2116. this.x = clamp( this.x, min.x, max.x );
  2117. this.y = clamp( this.y, min.y, max.y );
  2118. this.z = clamp( this.z, min.z, max.z );
  2119. this.w = clamp( this.w, min.w, max.w );
  2120. return this;
  2121. }
  2122. clampScalar( minVal, maxVal ) {
  2123. this.x = clamp( this.x, minVal, maxVal );
  2124. this.y = clamp( this.y, minVal, maxVal );
  2125. this.z = clamp( this.z, minVal, maxVal );
  2126. this.w = clamp( this.w, minVal, maxVal );
  2127. return this;
  2128. }
  2129. clampLength( min, max ) {
  2130. const length = this.length();
  2131. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2132. }
  2133. floor() {
  2134. this.x = Math.floor( this.x );
  2135. this.y = Math.floor( this.y );
  2136. this.z = Math.floor( this.z );
  2137. this.w = Math.floor( this.w );
  2138. return this;
  2139. }
  2140. ceil() {
  2141. this.x = Math.ceil( this.x );
  2142. this.y = Math.ceil( this.y );
  2143. this.z = Math.ceil( this.z );
  2144. this.w = Math.ceil( this.w );
  2145. return this;
  2146. }
  2147. round() {
  2148. this.x = Math.round( this.x );
  2149. this.y = Math.round( this.y );
  2150. this.z = Math.round( this.z );
  2151. this.w = Math.round( this.w );
  2152. return this;
  2153. }
  2154. roundToZero() {
  2155. this.x = Math.trunc( this.x );
  2156. this.y = Math.trunc( this.y );
  2157. this.z = Math.trunc( this.z );
  2158. this.w = Math.trunc( this.w );
  2159. return this;
  2160. }
  2161. negate() {
  2162. this.x = - this.x;
  2163. this.y = - this.y;
  2164. this.z = - this.z;
  2165. this.w = - this.w;
  2166. return this;
  2167. }
  2168. dot( v ) {
  2169. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2170. }
  2171. lengthSq() {
  2172. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2173. }
  2174. length() {
  2175. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2176. }
  2177. manhattanLength() {
  2178. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2179. }
  2180. normalize() {
  2181. return this.divideScalar( this.length() || 1 );
  2182. }
  2183. setLength( length ) {
  2184. return this.normalize().multiplyScalar( length );
  2185. }
  2186. lerp( v, alpha ) {
  2187. this.x += ( v.x - this.x ) * alpha;
  2188. this.y += ( v.y - this.y ) * alpha;
  2189. this.z += ( v.z - this.z ) * alpha;
  2190. this.w += ( v.w - this.w ) * alpha;
  2191. return this;
  2192. }
  2193. lerpVectors( v1, v2, alpha ) {
  2194. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2195. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2196. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2197. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2198. return this;
  2199. }
  2200. equals( v ) {
  2201. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2202. }
  2203. fromArray( array, offset = 0 ) {
  2204. this.x = array[ offset ];
  2205. this.y = array[ offset + 1 ];
  2206. this.z = array[ offset + 2 ];
  2207. this.w = array[ offset + 3 ];
  2208. return this;
  2209. }
  2210. toArray( array = [], offset = 0 ) {
  2211. array[ offset ] = this.x;
  2212. array[ offset + 1 ] = this.y;
  2213. array[ offset + 2 ] = this.z;
  2214. array[ offset + 3 ] = this.w;
  2215. return array;
  2216. }
  2217. fromBufferAttribute( attribute, index ) {
  2218. this.x = attribute.getX( index );
  2219. this.y = attribute.getY( index );
  2220. this.z = attribute.getZ( index );
  2221. this.w = attribute.getW( index );
  2222. return this;
  2223. }
  2224. random() {
  2225. this.x = Math.random();
  2226. this.y = Math.random();
  2227. this.z = Math.random();
  2228. this.w = Math.random();
  2229. return this;
  2230. }
  2231. *[ Symbol.iterator ]() {
  2232. yield this.x;
  2233. yield this.y;
  2234. yield this.z;
  2235. yield this.w;
  2236. }
  2237. }
  2238. /*
  2239. In options, we can specify:
  2240. * Texture parameters for an auto-generated target texture
  2241. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2242. */
  2243. class RenderTarget extends EventDispatcher {
  2244. constructor( width = 1, height = 1, options = {} ) {
  2245. super();
  2246. this.isRenderTarget = true;
  2247. this.width = width;
  2248. this.height = height;
  2249. this.depth = 1;
  2250. this.scissor = new Vector4( 0, 0, width, height );
  2251. this.scissorTest = false;
  2252. this.viewport = new Vector4( 0, 0, width, height );
  2253. const image = { width: width, height: height, depth: 1 };
  2254. options = Object.assign( {
  2255. generateMipmaps: false,
  2256. internalFormat: null,
  2257. minFilter: LinearFilter,
  2258. depthBuffer: true,
  2259. stencilBuffer: false,
  2260. resolveDepthBuffer: true,
  2261. resolveStencilBuffer: true,
  2262. depthTexture: null,
  2263. samples: 0,
  2264. count: 1
  2265. }, options );
  2266. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  2267. texture.flipY = false;
  2268. texture.generateMipmaps = options.generateMipmaps;
  2269. texture.internalFormat = options.internalFormat;
  2270. this.textures = [];
  2271. const count = options.count;
  2272. for ( let i = 0; i < count; i ++ ) {
  2273. this.textures[ i ] = texture.clone();
  2274. this.textures[ i ].isRenderTargetTexture = true;
  2275. this.textures[ i ].renderTarget = this;
  2276. }
  2277. this.depthBuffer = options.depthBuffer;
  2278. this.stencilBuffer = options.stencilBuffer;
  2279. this.resolveDepthBuffer = options.resolveDepthBuffer;
  2280. this.resolveStencilBuffer = options.resolveStencilBuffer;
  2281. this._depthTexture = null;
  2282. this.depthTexture = options.depthTexture;
  2283. this.samples = options.samples;
  2284. }
  2285. get texture() {
  2286. return this.textures[ 0 ];
  2287. }
  2288. set texture( value ) {
  2289. this.textures[ 0 ] = value;
  2290. }
  2291. set depthTexture( current ) {
  2292. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  2293. if ( current !== null ) current.renderTarget = this;
  2294. this._depthTexture = current;
  2295. }
  2296. get depthTexture() {
  2297. return this._depthTexture;
  2298. }
  2299. setSize( width, height, depth = 1 ) {
  2300. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2301. this.width = width;
  2302. this.height = height;
  2303. this.depth = depth;
  2304. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  2305. this.textures[ i ].image.width = width;
  2306. this.textures[ i ].image.height = height;
  2307. this.textures[ i ].image.depth = depth;
  2308. }
  2309. this.dispose();
  2310. }
  2311. this.viewport.set( 0, 0, width, height );
  2312. this.scissor.set( 0, 0, width, height );
  2313. }
  2314. clone() {
  2315. return new this.constructor().copy( this );
  2316. }
  2317. copy( source ) {
  2318. this.width = source.width;
  2319. this.height = source.height;
  2320. this.depth = source.depth;
  2321. this.scissor.copy( source.scissor );
  2322. this.scissorTest = source.scissorTest;
  2323. this.viewport.copy( source.viewport );
  2324. this.textures.length = 0;
  2325. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  2326. this.textures[ i ] = source.textures[ i ].clone();
  2327. this.textures[ i ].isRenderTargetTexture = true;
  2328. this.textures[ i ].renderTarget = this;
  2329. }
  2330. // ensure image object is not shared, see #20328
  2331. const image = Object.assign( {}, source.texture.image );
  2332. this.texture.source = new Source( image );
  2333. this.depthBuffer = source.depthBuffer;
  2334. this.stencilBuffer = source.stencilBuffer;
  2335. this.resolveDepthBuffer = source.resolveDepthBuffer;
  2336. this.resolveStencilBuffer = source.resolveStencilBuffer;
  2337. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2338. this.samples = source.samples;
  2339. return this;
  2340. }
  2341. dispose() {
  2342. this.dispatchEvent( { type: 'dispose' } );
  2343. }
  2344. }
  2345. class WebGLRenderTarget extends RenderTarget {
  2346. constructor( width = 1, height = 1, options = {} ) {
  2347. super( width, height, options );
  2348. this.isWebGLRenderTarget = true;
  2349. }
  2350. }
  2351. class DataArrayTexture extends Texture {
  2352. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2353. super( null );
  2354. this.isDataArrayTexture = true;
  2355. this.image = { data, width, height, depth };
  2356. this.magFilter = NearestFilter;
  2357. this.minFilter = NearestFilter;
  2358. this.wrapR = ClampToEdgeWrapping;
  2359. this.generateMipmaps = false;
  2360. this.flipY = false;
  2361. this.unpackAlignment = 1;
  2362. this.layerUpdates = new Set();
  2363. }
  2364. addLayerUpdate( layerIndex ) {
  2365. this.layerUpdates.add( layerIndex );
  2366. }
  2367. clearLayerUpdates() {
  2368. this.layerUpdates.clear();
  2369. }
  2370. }
  2371. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2372. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  2373. super( width, height, options );
  2374. this.isWebGLArrayRenderTarget = true;
  2375. this.depth = depth;
  2376. this.texture = new DataArrayTexture( null, width, height, depth );
  2377. this.texture.isRenderTargetTexture = true;
  2378. }
  2379. }
  2380. class Data3DTexture extends Texture {
  2381. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2382. // We're going to add .setXXX() methods for setting properties later.
  2383. // Users can still set in Data3DTexture directly.
  2384. //
  2385. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  2386. // texture.anisotropy = 16;
  2387. //
  2388. // See #14839
  2389. super( null );
  2390. this.isData3DTexture = true;
  2391. this.image = { data, width, height, depth };
  2392. this.magFilter = NearestFilter;
  2393. this.minFilter = NearestFilter;
  2394. this.wrapR = ClampToEdgeWrapping;
  2395. this.generateMipmaps = false;
  2396. this.flipY = false;
  2397. this.unpackAlignment = 1;
  2398. }
  2399. }
  2400. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2401. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  2402. super( width, height, options );
  2403. this.isWebGL3DRenderTarget = true;
  2404. this.depth = depth;
  2405. this.texture = new Data3DTexture( null, width, height, depth );
  2406. this.texture.isRenderTargetTexture = true;
  2407. }
  2408. }
  2409. class Quaternion {
  2410. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2411. this.isQuaternion = true;
  2412. this._x = x;
  2413. this._y = y;
  2414. this._z = z;
  2415. this._w = w;
  2416. }
  2417. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2418. // fuzz-free, array-based Quaternion SLERP operation
  2419. let x0 = src0[ srcOffset0 + 0 ],
  2420. y0 = src0[ srcOffset0 + 1 ],
  2421. z0 = src0[ srcOffset0 + 2 ],
  2422. w0 = src0[ srcOffset0 + 3 ];
  2423. const x1 = src1[ srcOffset1 + 0 ],
  2424. y1 = src1[ srcOffset1 + 1 ],
  2425. z1 = src1[ srcOffset1 + 2 ],
  2426. w1 = src1[ srcOffset1 + 3 ];
  2427. if ( t === 0 ) {
  2428. dst[ dstOffset + 0 ] = x0;
  2429. dst[ dstOffset + 1 ] = y0;
  2430. dst[ dstOffset + 2 ] = z0;
  2431. dst[ dstOffset + 3 ] = w0;
  2432. return;
  2433. }
  2434. if ( t === 1 ) {
  2435. dst[ dstOffset + 0 ] = x1;
  2436. dst[ dstOffset + 1 ] = y1;
  2437. dst[ dstOffset + 2 ] = z1;
  2438. dst[ dstOffset + 3 ] = w1;
  2439. return;
  2440. }
  2441. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2442. let s = 1 - t;
  2443. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2444. dir = ( cos >= 0 ? 1 : -1 ),
  2445. sqrSin = 1 - cos * cos;
  2446. // Skip the Slerp for tiny steps to avoid numeric problems:
  2447. if ( sqrSin > Number.EPSILON ) {
  2448. const sin = Math.sqrt( sqrSin ),
  2449. len = Math.atan2( sin, cos * dir );
  2450. s = Math.sin( s * len ) / sin;
  2451. t = Math.sin( t * len ) / sin;
  2452. }
  2453. const tDir = t * dir;
  2454. x0 = x0 * s + x1 * tDir;
  2455. y0 = y0 * s + y1 * tDir;
  2456. z0 = z0 * s + z1 * tDir;
  2457. w0 = w0 * s + w1 * tDir;
  2458. // Normalize in case we just did a lerp:
  2459. if ( s === 1 - t ) {
  2460. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2461. x0 *= f;
  2462. y0 *= f;
  2463. z0 *= f;
  2464. w0 *= f;
  2465. }
  2466. }
  2467. dst[ dstOffset ] = x0;
  2468. dst[ dstOffset + 1 ] = y0;
  2469. dst[ dstOffset + 2 ] = z0;
  2470. dst[ dstOffset + 3 ] = w0;
  2471. }
  2472. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2473. const x0 = src0[ srcOffset0 ];
  2474. const y0 = src0[ srcOffset0 + 1 ];
  2475. const z0 = src0[ srcOffset0 + 2 ];
  2476. const w0 = src0[ srcOffset0 + 3 ];
  2477. const x1 = src1[ srcOffset1 ];
  2478. const y1 = src1[ srcOffset1 + 1 ];
  2479. const z1 = src1[ srcOffset1 + 2 ];
  2480. const w1 = src1[ srcOffset1 + 3 ];
  2481. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2482. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2483. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2484. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2485. return dst;
  2486. }
  2487. get x() {
  2488. return this._x;
  2489. }
  2490. set x( value ) {
  2491. this._x = value;
  2492. this._onChangeCallback();
  2493. }
  2494. get y() {
  2495. return this._y;
  2496. }
  2497. set y( value ) {
  2498. this._y = value;
  2499. this._onChangeCallback();
  2500. }
  2501. get z() {
  2502. return this._z;
  2503. }
  2504. set z( value ) {
  2505. this._z = value;
  2506. this._onChangeCallback();
  2507. }
  2508. get w() {
  2509. return this._w;
  2510. }
  2511. set w( value ) {
  2512. this._w = value;
  2513. this._onChangeCallback();
  2514. }
  2515. set( x, y, z, w ) {
  2516. this._x = x;
  2517. this._y = y;
  2518. this._z = z;
  2519. this._w = w;
  2520. this._onChangeCallback();
  2521. return this;
  2522. }
  2523. clone() {
  2524. return new this.constructor( this._x, this._y, this._z, this._w );
  2525. }
  2526. copy( quaternion ) {
  2527. this._x = quaternion.x;
  2528. this._y = quaternion.y;
  2529. this._z = quaternion.z;
  2530. this._w = quaternion.w;
  2531. this._onChangeCallback();
  2532. return this;
  2533. }
  2534. setFromEuler( euler, update = true ) {
  2535. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2536. // http://www.mathworks.com/matlabcentral/fileexchange/
  2537. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2538. // content/SpinCalc.m
  2539. const cos = Math.cos;
  2540. const sin = Math.sin;
  2541. const c1 = cos( x / 2 );
  2542. const c2 = cos( y / 2 );
  2543. const c3 = cos( z / 2 );
  2544. const s1 = sin( x / 2 );
  2545. const s2 = sin( y / 2 );
  2546. const s3 = sin( z / 2 );
  2547. switch ( order ) {
  2548. case 'XYZ':
  2549. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2550. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2551. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2552. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2553. break;
  2554. case 'YXZ':
  2555. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2556. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2557. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2558. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2559. break;
  2560. case 'ZXY':
  2561. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2562. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2563. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2564. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2565. break;
  2566. case 'ZYX':
  2567. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2568. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2569. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2570. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2571. break;
  2572. case 'YZX':
  2573. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2574. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2575. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2576. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2577. break;
  2578. case 'XZY':
  2579. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2580. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2581. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2582. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2583. break;
  2584. default:
  2585. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2586. }
  2587. if ( update === true ) this._onChangeCallback();
  2588. return this;
  2589. }
  2590. setFromAxisAngle( axis, angle ) {
  2591. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2592. // assumes axis is normalized
  2593. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2594. this._x = axis.x * s;
  2595. this._y = axis.y * s;
  2596. this._z = axis.z * s;
  2597. this._w = Math.cos( halfAngle );
  2598. this._onChangeCallback();
  2599. return this;
  2600. }
  2601. setFromRotationMatrix( m ) {
  2602. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2603. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2604. const te = m.elements,
  2605. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2606. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2607. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2608. trace = m11 + m22 + m33;
  2609. if ( trace > 0 ) {
  2610. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2611. this._w = 0.25 / s;
  2612. this._x = ( m32 - m23 ) * s;
  2613. this._y = ( m13 - m31 ) * s;
  2614. this._z = ( m21 - m12 ) * s;
  2615. } else if ( m11 > m22 && m11 > m33 ) {
  2616. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2617. this._w = ( m32 - m23 ) / s;
  2618. this._x = 0.25 * s;
  2619. this._y = ( m12 + m21 ) / s;
  2620. this._z = ( m13 + m31 ) / s;
  2621. } else if ( m22 > m33 ) {
  2622. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2623. this._w = ( m13 - m31 ) / s;
  2624. this._x = ( m12 + m21 ) / s;
  2625. this._y = 0.25 * s;
  2626. this._z = ( m23 + m32 ) / s;
  2627. } else {
  2628. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2629. this._w = ( m21 - m12 ) / s;
  2630. this._x = ( m13 + m31 ) / s;
  2631. this._y = ( m23 + m32 ) / s;
  2632. this._z = 0.25 * s;
  2633. }
  2634. this._onChangeCallback();
  2635. return this;
  2636. }
  2637. setFromUnitVectors( vFrom, vTo ) {
  2638. // assumes direction vectors vFrom and vTo are normalized
  2639. let r = vFrom.dot( vTo ) + 1;
  2640. if ( r < Number.EPSILON ) {
  2641. // vFrom and vTo point in opposite directions
  2642. r = 0;
  2643. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2644. this._x = - vFrom.y;
  2645. this._y = vFrom.x;
  2646. this._z = 0;
  2647. this._w = r;
  2648. } else {
  2649. this._x = 0;
  2650. this._y = - vFrom.z;
  2651. this._z = vFrom.y;
  2652. this._w = r;
  2653. }
  2654. } else {
  2655. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2656. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2657. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2658. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2659. this._w = r;
  2660. }
  2661. return this.normalize();
  2662. }
  2663. angleTo( q ) {
  2664. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  2665. }
  2666. rotateTowards( q, step ) {
  2667. const angle = this.angleTo( q );
  2668. if ( angle === 0 ) return this;
  2669. const t = Math.min( 1, step / angle );
  2670. this.slerp( q, t );
  2671. return this;
  2672. }
  2673. identity() {
  2674. return this.set( 0, 0, 0, 1 );
  2675. }
  2676. invert() {
  2677. // quaternion is assumed to have unit length
  2678. return this.conjugate();
  2679. }
  2680. conjugate() {
  2681. this._x *= -1;
  2682. this._y *= -1;
  2683. this._z *= -1;
  2684. this._onChangeCallback();
  2685. return this;
  2686. }
  2687. dot( v ) {
  2688. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2689. }
  2690. lengthSq() {
  2691. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2692. }
  2693. length() {
  2694. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2695. }
  2696. normalize() {
  2697. let l = this.length();
  2698. if ( l === 0 ) {
  2699. this._x = 0;
  2700. this._y = 0;
  2701. this._z = 0;
  2702. this._w = 1;
  2703. } else {
  2704. l = 1 / l;
  2705. this._x = this._x * l;
  2706. this._y = this._y * l;
  2707. this._z = this._z * l;
  2708. this._w = this._w * l;
  2709. }
  2710. this._onChangeCallback();
  2711. return this;
  2712. }
  2713. multiply( q ) {
  2714. return this.multiplyQuaternions( this, q );
  2715. }
  2716. premultiply( q ) {
  2717. return this.multiplyQuaternions( q, this );
  2718. }
  2719. multiplyQuaternions( a, b ) {
  2720. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2721. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2722. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2723. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2724. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2725. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2726. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2727. this._onChangeCallback();
  2728. return this;
  2729. }
  2730. slerp( qb, t ) {
  2731. if ( t === 0 ) return this;
  2732. if ( t === 1 ) return this.copy( qb );
  2733. const x = this._x, y = this._y, z = this._z, w = this._w;
  2734. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2735. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2736. if ( cosHalfTheta < 0 ) {
  2737. this._w = - qb._w;
  2738. this._x = - qb._x;
  2739. this._y = - qb._y;
  2740. this._z = - qb._z;
  2741. cosHalfTheta = - cosHalfTheta;
  2742. } else {
  2743. this.copy( qb );
  2744. }
  2745. if ( cosHalfTheta >= 1.0 ) {
  2746. this._w = w;
  2747. this._x = x;
  2748. this._y = y;
  2749. this._z = z;
  2750. return this;
  2751. }
  2752. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2753. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2754. const s = 1 - t;
  2755. this._w = s * w + t * this._w;
  2756. this._x = s * x + t * this._x;
  2757. this._y = s * y + t * this._y;
  2758. this._z = s * z + t * this._z;
  2759. this.normalize(); // normalize calls _onChangeCallback()
  2760. return this;
  2761. }
  2762. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2763. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2764. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2765. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2766. this._w = ( w * ratioA + this._w * ratioB );
  2767. this._x = ( x * ratioA + this._x * ratioB );
  2768. this._y = ( y * ratioA + this._y * ratioB );
  2769. this._z = ( z * ratioA + this._z * ratioB );
  2770. this._onChangeCallback();
  2771. return this;
  2772. }
  2773. slerpQuaternions( qa, qb, t ) {
  2774. return this.copy( qa ).slerp( qb, t );
  2775. }
  2776. random() {
  2777. // sets this quaternion to a uniform random unit quaternnion
  2778. // Ken Shoemake
  2779. // Uniform random rotations
  2780. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2781. const theta1 = 2 * Math.PI * Math.random();
  2782. const theta2 = 2 * Math.PI * Math.random();
  2783. const x0 = Math.random();
  2784. const r1 = Math.sqrt( 1 - x0 );
  2785. const r2 = Math.sqrt( x0 );
  2786. return this.set(
  2787. r1 * Math.sin( theta1 ),
  2788. r1 * Math.cos( theta1 ),
  2789. r2 * Math.sin( theta2 ),
  2790. r2 * Math.cos( theta2 ),
  2791. );
  2792. }
  2793. equals( quaternion ) {
  2794. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2795. }
  2796. fromArray( array, offset = 0 ) {
  2797. this._x = array[ offset ];
  2798. this._y = array[ offset + 1 ];
  2799. this._z = array[ offset + 2 ];
  2800. this._w = array[ offset + 3 ];
  2801. this._onChangeCallback();
  2802. return this;
  2803. }
  2804. toArray( array = [], offset = 0 ) {
  2805. array[ offset ] = this._x;
  2806. array[ offset + 1 ] = this._y;
  2807. array[ offset + 2 ] = this._z;
  2808. array[ offset + 3 ] = this._w;
  2809. return array;
  2810. }
  2811. fromBufferAttribute( attribute, index ) {
  2812. this._x = attribute.getX( index );
  2813. this._y = attribute.getY( index );
  2814. this._z = attribute.getZ( index );
  2815. this._w = attribute.getW( index );
  2816. this._onChangeCallback();
  2817. return this;
  2818. }
  2819. toJSON() {
  2820. return this.toArray();
  2821. }
  2822. _onChange( callback ) {
  2823. this._onChangeCallback = callback;
  2824. return this;
  2825. }
  2826. _onChangeCallback() {}
  2827. *[ Symbol.iterator ]() {
  2828. yield this._x;
  2829. yield this._y;
  2830. yield this._z;
  2831. yield this._w;
  2832. }
  2833. }
  2834. class Vector3 {
  2835. constructor( x = 0, y = 0, z = 0 ) {
  2836. Vector3.prototype.isVector3 = true;
  2837. this.x = x;
  2838. this.y = y;
  2839. this.z = z;
  2840. }
  2841. set( x, y, z ) {
  2842. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2843. this.x = x;
  2844. this.y = y;
  2845. this.z = z;
  2846. return this;
  2847. }
  2848. setScalar( scalar ) {
  2849. this.x = scalar;
  2850. this.y = scalar;
  2851. this.z = scalar;
  2852. return this;
  2853. }
  2854. setX( x ) {
  2855. this.x = x;
  2856. return this;
  2857. }
  2858. setY( y ) {
  2859. this.y = y;
  2860. return this;
  2861. }
  2862. setZ( z ) {
  2863. this.z = z;
  2864. return this;
  2865. }
  2866. setComponent( index, value ) {
  2867. switch ( index ) {
  2868. case 0: this.x = value; break;
  2869. case 1: this.y = value; break;
  2870. case 2: this.z = value; break;
  2871. default: throw new Error( 'index is out of range: ' + index );
  2872. }
  2873. return this;
  2874. }
  2875. getComponent( index ) {
  2876. switch ( index ) {
  2877. case 0: return this.x;
  2878. case 1: return this.y;
  2879. case 2: return this.z;
  2880. default: throw new Error( 'index is out of range: ' + index );
  2881. }
  2882. }
  2883. clone() {
  2884. return new this.constructor( this.x, this.y, this.z );
  2885. }
  2886. copy( v ) {
  2887. this.x = v.x;
  2888. this.y = v.y;
  2889. this.z = v.z;
  2890. return this;
  2891. }
  2892. add( v ) {
  2893. this.x += v.x;
  2894. this.y += v.y;
  2895. this.z += v.z;
  2896. return this;
  2897. }
  2898. addScalar( s ) {
  2899. this.x += s;
  2900. this.y += s;
  2901. this.z += s;
  2902. return this;
  2903. }
  2904. addVectors( a, b ) {
  2905. this.x = a.x + b.x;
  2906. this.y = a.y + b.y;
  2907. this.z = a.z + b.z;
  2908. return this;
  2909. }
  2910. addScaledVector( v, s ) {
  2911. this.x += v.x * s;
  2912. this.y += v.y * s;
  2913. this.z += v.z * s;
  2914. return this;
  2915. }
  2916. sub( v ) {
  2917. this.x -= v.x;
  2918. this.y -= v.y;
  2919. this.z -= v.z;
  2920. return this;
  2921. }
  2922. subScalar( s ) {
  2923. this.x -= s;
  2924. this.y -= s;
  2925. this.z -= s;
  2926. return this;
  2927. }
  2928. subVectors( a, b ) {
  2929. this.x = a.x - b.x;
  2930. this.y = a.y - b.y;
  2931. this.z = a.z - b.z;
  2932. return this;
  2933. }
  2934. multiply( v ) {
  2935. this.x *= v.x;
  2936. this.y *= v.y;
  2937. this.z *= v.z;
  2938. return this;
  2939. }
  2940. multiplyScalar( scalar ) {
  2941. this.x *= scalar;
  2942. this.y *= scalar;
  2943. this.z *= scalar;
  2944. return this;
  2945. }
  2946. multiplyVectors( a, b ) {
  2947. this.x = a.x * b.x;
  2948. this.y = a.y * b.y;
  2949. this.z = a.z * b.z;
  2950. return this;
  2951. }
  2952. applyEuler( euler ) {
  2953. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2954. }
  2955. applyAxisAngle( axis, angle ) {
  2956. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2957. }
  2958. applyMatrix3( m ) {
  2959. const x = this.x, y = this.y, z = this.z;
  2960. const e = m.elements;
  2961. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2962. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2963. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2964. return this;
  2965. }
  2966. applyNormalMatrix( m ) {
  2967. return this.applyMatrix3( m ).normalize();
  2968. }
  2969. applyMatrix4( m ) {
  2970. const x = this.x, y = this.y, z = this.z;
  2971. const e = m.elements;
  2972. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2973. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2974. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2975. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2976. return this;
  2977. }
  2978. applyQuaternion( q ) {
  2979. // quaternion q is assumed to have unit length
  2980. const vx = this.x, vy = this.y, vz = this.z;
  2981. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2982. // t = 2 * cross( q.xyz, v );
  2983. const tx = 2 * ( qy * vz - qz * vy );
  2984. const ty = 2 * ( qz * vx - qx * vz );
  2985. const tz = 2 * ( qx * vy - qy * vx );
  2986. // v + q.w * t + cross( q.xyz, t );
  2987. this.x = vx + qw * tx + qy * tz - qz * ty;
  2988. this.y = vy + qw * ty + qz * tx - qx * tz;
  2989. this.z = vz + qw * tz + qx * ty - qy * tx;
  2990. return this;
  2991. }
  2992. project( camera ) {
  2993. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2994. }
  2995. unproject( camera ) {
  2996. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2997. }
  2998. transformDirection( m ) {
  2999. // input: THREE.Matrix4 affine matrix
  3000. // vector interpreted as a direction
  3001. const x = this.x, y = this.y, z = this.z;
  3002. const e = m.elements;
  3003. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3004. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3005. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3006. return this.normalize();
  3007. }
  3008. divide( v ) {
  3009. this.x /= v.x;
  3010. this.y /= v.y;
  3011. this.z /= v.z;
  3012. return this;
  3013. }
  3014. divideScalar( scalar ) {
  3015. return this.multiplyScalar( 1 / scalar );
  3016. }
  3017. min( v ) {
  3018. this.x = Math.min( this.x, v.x );
  3019. this.y = Math.min( this.y, v.y );
  3020. this.z = Math.min( this.z, v.z );
  3021. return this;
  3022. }
  3023. max( v ) {
  3024. this.x = Math.max( this.x, v.x );
  3025. this.y = Math.max( this.y, v.y );
  3026. this.z = Math.max( this.z, v.z );
  3027. return this;
  3028. }
  3029. clamp( min, max ) {
  3030. // assumes min < max, componentwise
  3031. this.x = clamp( this.x, min.x, max.x );
  3032. this.y = clamp( this.y, min.y, max.y );
  3033. this.z = clamp( this.z, min.z, max.z );
  3034. return this;
  3035. }
  3036. clampScalar( minVal, maxVal ) {
  3037. this.x = clamp( this.x, minVal, maxVal );
  3038. this.y = clamp( this.y, minVal, maxVal );
  3039. this.z = clamp( this.z, minVal, maxVal );
  3040. return this;
  3041. }
  3042. clampLength( min, max ) {
  3043. const length = this.length();
  3044. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3045. }
  3046. floor() {
  3047. this.x = Math.floor( this.x );
  3048. this.y = Math.floor( this.y );
  3049. this.z = Math.floor( this.z );
  3050. return this;
  3051. }
  3052. ceil() {
  3053. this.x = Math.ceil( this.x );
  3054. this.y = Math.ceil( this.y );
  3055. this.z = Math.ceil( this.z );
  3056. return this;
  3057. }
  3058. round() {
  3059. this.x = Math.round( this.x );
  3060. this.y = Math.round( this.y );
  3061. this.z = Math.round( this.z );
  3062. return this;
  3063. }
  3064. roundToZero() {
  3065. this.x = Math.trunc( this.x );
  3066. this.y = Math.trunc( this.y );
  3067. this.z = Math.trunc( this.z );
  3068. return this;
  3069. }
  3070. negate() {
  3071. this.x = - this.x;
  3072. this.y = - this.y;
  3073. this.z = - this.z;
  3074. return this;
  3075. }
  3076. dot( v ) {
  3077. return this.x * v.x + this.y * v.y + this.z * v.z;
  3078. }
  3079. // TODO lengthSquared?
  3080. lengthSq() {
  3081. return this.x * this.x + this.y * this.y + this.z * this.z;
  3082. }
  3083. length() {
  3084. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  3085. }
  3086. manhattanLength() {
  3087. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  3088. }
  3089. normalize() {
  3090. return this.divideScalar( this.length() || 1 );
  3091. }
  3092. setLength( length ) {
  3093. return this.normalize().multiplyScalar( length );
  3094. }
  3095. lerp( v, alpha ) {
  3096. this.x += ( v.x - this.x ) * alpha;
  3097. this.y += ( v.y - this.y ) * alpha;
  3098. this.z += ( v.z - this.z ) * alpha;
  3099. return this;
  3100. }
  3101. lerpVectors( v1, v2, alpha ) {
  3102. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3103. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3104. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  3105. return this;
  3106. }
  3107. cross( v ) {
  3108. return this.crossVectors( this, v );
  3109. }
  3110. crossVectors( a, b ) {
  3111. const ax = a.x, ay = a.y, az = a.z;
  3112. const bx = b.x, by = b.y, bz = b.z;
  3113. this.x = ay * bz - az * by;
  3114. this.y = az * bx - ax * bz;
  3115. this.z = ax * by - ay * bx;
  3116. return this;
  3117. }
  3118. projectOnVector( v ) {
  3119. const denominator = v.lengthSq();
  3120. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  3121. const scalar = v.dot( this ) / denominator;
  3122. return this.copy( v ).multiplyScalar( scalar );
  3123. }
  3124. projectOnPlane( planeNormal ) {
  3125. _vector$c.copy( this ).projectOnVector( planeNormal );
  3126. return this.sub( _vector$c );
  3127. }
  3128. reflect( normal ) {
  3129. // reflect incident vector off plane orthogonal to normal
  3130. // normal is assumed to have unit length
  3131. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  3132. }
  3133. angleTo( v ) {
  3134. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  3135. if ( denominator === 0 ) return Math.PI / 2;
  3136. const theta = this.dot( v ) / denominator;
  3137. // clamp, to handle numerical problems
  3138. return Math.acos( clamp( theta, -1, 1 ) );
  3139. }
  3140. distanceTo( v ) {
  3141. return Math.sqrt( this.distanceToSquared( v ) );
  3142. }
  3143. distanceToSquared( v ) {
  3144. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  3145. return dx * dx + dy * dy + dz * dz;
  3146. }
  3147. manhattanDistanceTo( v ) {
  3148. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  3149. }
  3150. setFromSpherical( s ) {
  3151. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  3152. }
  3153. setFromSphericalCoords( radius, phi, theta ) {
  3154. const sinPhiRadius = Math.sin( phi ) * radius;
  3155. this.x = sinPhiRadius * Math.sin( theta );
  3156. this.y = Math.cos( phi ) * radius;
  3157. this.z = sinPhiRadius * Math.cos( theta );
  3158. return this;
  3159. }
  3160. setFromCylindrical( c ) {
  3161. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  3162. }
  3163. setFromCylindricalCoords( radius, theta, y ) {
  3164. this.x = radius * Math.sin( theta );
  3165. this.y = y;
  3166. this.z = radius * Math.cos( theta );
  3167. return this;
  3168. }
  3169. setFromMatrixPosition( m ) {
  3170. const e = m.elements;
  3171. this.x = e[ 12 ];
  3172. this.y = e[ 13 ];
  3173. this.z = e[ 14 ];
  3174. return this;
  3175. }
  3176. setFromMatrixScale( m ) {
  3177. const sx = this.setFromMatrixColumn( m, 0 ).length();
  3178. const sy = this.setFromMatrixColumn( m, 1 ).length();
  3179. const sz = this.setFromMatrixColumn( m, 2 ).length();
  3180. this.x = sx;
  3181. this.y = sy;
  3182. this.z = sz;
  3183. return this;
  3184. }
  3185. setFromMatrixColumn( m, index ) {
  3186. return this.fromArray( m.elements, index * 4 );
  3187. }
  3188. setFromMatrix3Column( m, index ) {
  3189. return this.fromArray( m.elements, index * 3 );
  3190. }
  3191. setFromEuler( e ) {
  3192. this.x = e._x;
  3193. this.y = e._y;
  3194. this.z = e._z;
  3195. return this;
  3196. }
  3197. setFromColor( c ) {
  3198. this.x = c.r;
  3199. this.y = c.g;
  3200. this.z = c.b;
  3201. return this;
  3202. }
  3203. equals( v ) {
  3204. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  3205. }
  3206. fromArray( array, offset = 0 ) {
  3207. this.x = array[ offset ];
  3208. this.y = array[ offset + 1 ];
  3209. this.z = array[ offset + 2 ];
  3210. return this;
  3211. }
  3212. toArray( array = [], offset = 0 ) {
  3213. array[ offset ] = this.x;
  3214. array[ offset + 1 ] = this.y;
  3215. array[ offset + 2 ] = this.z;
  3216. return array;
  3217. }
  3218. fromBufferAttribute( attribute, index ) {
  3219. this.x = attribute.getX( index );
  3220. this.y = attribute.getY( index );
  3221. this.z = attribute.getZ( index );
  3222. return this;
  3223. }
  3224. random() {
  3225. this.x = Math.random();
  3226. this.y = Math.random();
  3227. this.z = Math.random();
  3228. return this;
  3229. }
  3230. randomDirection() {
  3231. // https://mathworld.wolfram.com/SpherePointPicking.html
  3232. const theta = Math.random() * Math.PI * 2;
  3233. const u = Math.random() * 2 - 1;
  3234. const c = Math.sqrt( 1 - u * u );
  3235. this.x = c * Math.cos( theta );
  3236. this.y = u;
  3237. this.z = c * Math.sin( theta );
  3238. return this;
  3239. }
  3240. *[ Symbol.iterator ]() {
  3241. yield this.x;
  3242. yield this.y;
  3243. yield this.z;
  3244. }
  3245. }
  3246. const _vector$c = /*@__PURE__*/ new Vector3();
  3247. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  3248. /**
  3249. * Represents an axis-aligned bounding box (AABB) in 3D space.
  3250. */
  3251. class Box3 {
  3252. /**
  3253. * Constructs a new bounding box.
  3254. *
  3255. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  3256. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  3257. */
  3258. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  3259. /**
  3260. * This flag can be used for type testing.
  3261. *
  3262. * @type {boolean}
  3263. * @readonly
  3264. * @default true
  3265. */
  3266. this.isBox3 = true;
  3267. /**
  3268. * The lower boundary of the box.
  3269. *
  3270. * @type {Vector3}
  3271. */
  3272. this.min = min;
  3273. /**
  3274. * The upper boundary of the box.
  3275. *
  3276. * @type {Vector3}
  3277. */
  3278. this.max = max;
  3279. }
  3280. /**
  3281. * Sets the lower and upper boundaries of this box.
  3282. * Please note that this method only copies the values from the given objects.
  3283. *
  3284. * @param {Vector3} min - The lower boundary of the box.
  3285. * @param {Vector3} max - The upper boundary of the box.
  3286. * @return {Box3} A reference to this bounding box.
  3287. */
  3288. set( min, max ) {
  3289. this.min.copy( min );
  3290. this.max.copy( max );
  3291. return this;
  3292. }
  3293. /**
  3294. * Sets the upper and lower bounds of this box so it encloses the position data
  3295. * in the given array.
  3296. *
  3297. * @param {Array<number>} array - An array holding 3D position data.
  3298. * @return {Box3} A reference to this bounding box.
  3299. */
  3300. setFromArray( array ) {
  3301. this.makeEmpty();
  3302. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  3303. this.expandByPoint( _vector$b.fromArray( array, i ) );
  3304. }
  3305. return this;
  3306. }
  3307. /**
  3308. * Sets the upper and lower bounds of this box so it encloses the position data
  3309. * in the given buffer attribute.
  3310. *
  3311. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  3312. * @return {Box3} A reference to this bounding box.
  3313. */
  3314. setFromBufferAttribute( attribute ) {
  3315. this.makeEmpty();
  3316. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  3317. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  3318. }
  3319. return this;
  3320. }
  3321. /**
  3322. * Sets the upper and lower bounds of this box so it encloses the position data
  3323. * in the given array.
  3324. *
  3325. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  3326. * @return {Box3} A reference to this bounding box.
  3327. */
  3328. setFromPoints( points ) {
  3329. this.makeEmpty();
  3330. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3331. this.expandByPoint( points[ i ] );
  3332. }
  3333. return this;
  3334. }
  3335. /**
  3336. * Centers this box on the given center vector and sets this box's width, height and
  3337. * depth to the given size values.
  3338. *
  3339. * @param {Vector3} center - The center of the box.
  3340. * @param {Vector3} size - The x, y and z dimensions of the box.
  3341. * @return {Box3} A reference to this bounding box.
  3342. */
  3343. setFromCenterAndSize( center, size ) {
  3344. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3345. this.min.copy( center ).sub( halfSize );
  3346. this.max.copy( center ).add( halfSize );
  3347. return this;
  3348. }
  3349. /**
  3350. * Computes the world-axis-aligned bounding box for the given 3D object
  3351. * (including its children), accounting for the object's, and children's,
  3352. * world transforms. The function may result in a larger box than strictly necessary.
  3353. *
  3354. * @param {Object3D} object - The 3D object to compute the bounding box for.
  3355. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  3356. * world-axis-aligned bounding box at the expense of more computation.
  3357. * @return {Box3} A reference to this bounding box.
  3358. */
  3359. setFromObject( object, precise = false ) {
  3360. this.makeEmpty();
  3361. return this.expandByObject( object, precise );
  3362. }
  3363. /**
  3364. * Returns a new box with copied values from this instance.
  3365. *
  3366. * @return {Box3} A clone of this instance.
  3367. */
  3368. clone() {
  3369. return new this.constructor().copy( this );
  3370. }
  3371. /**
  3372. * Copies the values of the given box to this instance.
  3373. *
  3374. * @param {Box3} box - The box to copy.
  3375. * @return {Box3} A reference to this bounding box.
  3376. */
  3377. copy( box ) {
  3378. this.min.copy( box.min );
  3379. this.max.copy( box.max );
  3380. return this;
  3381. }
  3382. /**
  3383. * Makes this box empty which means in encloses a zero space in 3D.
  3384. *
  3385. * @return {Box3} A reference to this bounding box.
  3386. */
  3387. makeEmpty() {
  3388. this.min.x = this.min.y = this.min.z = + Infinity;
  3389. this.max.x = this.max.y = this.max.z = - Infinity;
  3390. return this;
  3391. }
  3392. /**
  3393. * Returns true if this box includes zero points within its bounds.
  3394. * Note that a box with equal lower and upper bounds still includes one
  3395. * point, the one both bounds share.
  3396. *
  3397. * @return {boolean} Whether this box is empty or not.
  3398. */
  3399. isEmpty() {
  3400. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3401. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3402. }
  3403. /**
  3404. * Returns the center point of this box.
  3405. *
  3406. * @param {Vector3} target - The target vector that is used to store the method's result.
  3407. * @return {Vector3} The center point.
  3408. */
  3409. getCenter( target ) {
  3410. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3411. }
  3412. /**
  3413. * Returns the dimensions of this box.
  3414. *
  3415. * @param {Vector3} target - The target vector that is used to store the method's result.
  3416. * @return {Vector3} The size.
  3417. */
  3418. getSize( target ) {
  3419. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3420. }
  3421. /**
  3422. * Expands the boundaries of this box to include the given point.
  3423. *
  3424. * @param {Vector3} point - The point that should be included by the bounding box.
  3425. * @return {Box3} A reference to this bounding box.
  3426. */
  3427. expandByPoint( point ) {
  3428. this.min.min( point );
  3429. this.max.max( point );
  3430. return this;
  3431. }
  3432. /**
  3433. * Expands this box equilaterally by the given vector. The width of this
  3434. * box will be expanded by the x component of the vector in both
  3435. * directions. The height of this box will be expanded by the y component of
  3436. * the vector in both directions. The depth of this box will be
  3437. * expanded by the z component of the vector in both directions.
  3438. *
  3439. * @param {Vector3} vector - The vector that should expand the bounding box.
  3440. * @return {Box3} A reference to this bounding box.
  3441. */
  3442. expandByVector( vector ) {
  3443. this.min.sub( vector );
  3444. this.max.add( vector );
  3445. return this;
  3446. }
  3447. /**
  3448. * Expands each dimension of the box by the given scalar. If negative, the
  3449. * dimensions of the box will be contracted.
  3450. *
  3451. * @param {number} scalar - The scalar value that should expand the bounding box.
  3452. * @return {Box3} A reference to this bounding box.
  3453. */
  3454. expandByScalar( scalar ) {
  3455. this.min.addScalar( - scalar );
  3456. this.max.addScalar( scalar );
  3457. return this;
  3458. }
  3459. /**
  3460. * Expands the boundaries of this box to include the given 3D object and
  3461. * its children, accounting for the object's, and children's, world
  3462. * transforms. The function may result in a larger box than strictly
  3463. * necessary (unless the precise parameter is set to true).
  3464. *
  3465. * @param {Object3D} object - The 3D object that should expand the bounding box.
  3466. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  3467. * as little as necessary at the expense of more computation.
  3468. * @return {Box3} A reference to this bounding box.
  3469. */
  3470. expandByObject( object, precise = false ) {
  3471. // Computes the world-axis-aligned bounding box of an object (including its children),
  3472. // accounting for both the object's, and children's, world transforms
  3473. object.updateWorldMatrix( false, false );
  3474. const geometry = object.geometry;
  3475. if ( geometry !== undefined ) {
  3476. const positionAttribute = geometry.getAttribute( 'position' );
  3477. // precise AABB computation based on vertex data requires at least a position attribute.
  3478. // instancing isn't supported so far and uses the normal (conservative) code path.
  3479. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  3480. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  3481. if ( object.isMesh === true ) {
  3482. object.getVertexPosition( i, _vector$b );
  3483. } else {
  3484. _vector$b.fromBufferAttribute( positionAttribute, i );
  3485. }
  3486. _vector$b.applyMatrix4( object.matrixWorld );
  3487. this.expandByPoint( _vector$b );
  3488. }
  3489. } else {
  3490. if ( object.boundingBox !== undefined ) {
  3491. // object-level bounding box
  3492. if ( object.boundingBox === null ) {
  3493. object.computeBoundingBox();
  3494. }
  3495. _box$4.copy( object.boundingBox );
  3496. } else {
  3497. // geometry-level bounding box
  3498. if ( geometry.boundingBox === null ) {
  3499. geometry.computeBoundingBox();
  3500. }
  3501. _box$4.copy( geometry.boundingBox );
  3502. }
  3503. _box$4.applyMatrix4( object.matrixWorld );
  3504. this.union( _box$4 );
  3505. }
  3506. }
  3507. const children = object.children;
  3508. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3509. this.expandByObject( children[ i ], precise );
  3510. }
  3511. return this;
  3512. }
  3513. /**
  3514. * Returns `true` if the given point lies within or on the boundaries of this box.
  3515. *
  3516. * @param {Vector3} point - The point to test.
  3517. * @return {boolean} Whether the bounding box contains the given point or not.
  3518. */
  3519. containsPoint( point ) {
  3520. return point.x >= this.min.x && point.x <= this.max.x &&
  3521. point.y >= this.min.y && point.y <= this.max.y &&
  3522. point.z >= this.min.z && point.z <= this.max.z;
  3523. }
  3524. /**
  3525. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  3526. * If this box and the given one are identical, this function also returns `true`.
  3527. *
  3528. * @param {Box3} box - The bounding box to test.
  3529. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  3530. */
  3531. containsBox( box ) {
  3532. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3533. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3534. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3535. }
  3536. /**
  3537. * Returns a point as a proportion of this box's width, height and depth.
  3538. *
  3539. * @param {Vector3} point - A point in 3D space.
  3540. * @param {Vector3} target - The target vector that is used to store the method's result.
  3541. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  3542. */
  3543. getParameter( point, target ) {
  3544. // This can potentially have a divide by zero if the box
  3545. // has a size dimension of 0.
  3546. return target.set(
  3547. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3548. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3549. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3550. );
  3551. }
  3552. /**
  3553. * Returns `true` if the given bounding box intersects with this bounding box.
  3554. *
  3555. * @param {Box3} box - The bounding box to test.
  3556. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  3557. */
  3558. intersectsBox( box ) {
  3559. // using 6 splitting planes to rule out intersections.
  3560. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  3561. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  3562. box.max.z >= this.min.z && box.min.z <= this.max.z;
  3563. }
  3564. /**
  3565. * Returns `true` if the given bounding sphere intersects with this bounding box.
  3566. *
  3567. * @param {Sphere} sphere - The bounding sphere to test.
  3568. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  3569. */
  3570. intersectsSphere( sphere ) {
  3571. // Find the point on the AABB closest to the sphere center.
  3572. this.clampPoint( sphere.center, _vector$b );
  3573. // If that point is inside the sphere, the AABB and sphere intersect.
  3574. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3575. }
  3576. /**
  3577. * Returns `true` if the given plane intersects with this bounding box.
  3578. *
  3579. * @param {Plane} plane - The plane to test.
  3580. * @return {boolean} Whether the given plane intersects with this bounding box.
  3581. */
  3582. intersectsPlane( plane ) {
  3583. // We compute the minimum and maximum dot product values. If those values
  3584. // are on the same side (back or front) of the plane, then there is no intersection.
  3585. let min, max;
  3586. if ( plane.normal.x > 0 ) {
  3587. min = plane.normal.x * this.min.x;
  3588. max = plane.normal.x * this.max.x;
  3589. } else {
  3590. min = plane.normal.x * this.max.x;
  3591. max = plane.normal.x * this.min.x;
  3592. }
  3593. if ( plane.normal.y > 0 ) {
  3594. min += plane.normal.y * this.min.y;
  3595. max += plane.normal.y * this.max.y;
  3596. } else {
  3597. min += plane.normal.y * this.max.y;
  3598. max += plane.normal.y * this.min.y;
  3599. }
  3600. if ( plane.normal.z > 0 ) {
  3601. min += plane.normal.z * this.min.z;
  3602. max += plane.normal.z * this.max.z;
  3603. } else {
  3604. min += plane.normal.z * this.max.z;
  3605. max += plane.normal.z * this.min.z;
  3606. }
  3607. return ( min <= - plane.constant && max >= - plane.constant );
  3608. }
  3609. /**
  3610. * Returns `true` if the given triangle intersects with this bounding box.
  3611. *
  3612. * @param {Triangle} triangle - The triangle to test.
  3613. * @return {boolean} Whether the given triangle intersects with this bounding box.
  3614. */
  3615. intersectsTriangle( triangle ) {
  3616. if ( this.isEmpty() ) {
  3617. return false;
  3618. }
  3619. // compute box center and extents
  3620. this.getCenter( _center );
  3621. _extents.subVectors( this.max, _center );
  3622. // translate triangle to aabb origin
  3623. _v0$3.subVectors( triangle.a, _center );
  3624. _v1$7.subVectors( triangle.b, _center );
  3625. _v2$4.subVectors( triangle.c, _center );
  3626. // compute edge vectors for triangle
  3627. _f0.subVectors( _v1$7, _v0$3 );
  3628. _f1.subVectors( _v2$4, _v1$7 );
  3629. _f2.subVectors( _v0$3, _v2$4 );
  3630. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3631. // 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
  3632. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3633. let axes = [
  3634. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3635. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3636. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3637. ];
  3638. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  3639. return false;
  3640. }
  3641. // test 3 face normals from the aabb
  3642. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3643. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  3644. return false;
  3645. }
  3646. // finally testing the face normal of the triangle
  3647. // use already existing triangle edge vectors here
  3648. _triangleNormal.crossVectors( _f0, _f1 );
  3649. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3650. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  3651. }
  3652. /**
  3653. * Clamps the given point within the bounds of this box.
  3654. *
  3655. * @param {Vector3} point - The point to clamp.
  3656. * @param {Vector3} target - The target vector that is used to store the method's result.
  3657. * @return {Vector3} The clamped point.
  3658. */
  3659. clampPoint( point, target ) {
  3660. return target.copy( point ).clamp( this.min, this.max );
  3661. }
  3662. /**
  3663. * Returns the euclidean distance from any edge of this box to the specified point. If
  3664. * the given point lies inside of this box, the distance will be `0`.
  3665. *
  3666. * @param {Vector3} point - The point to compute the distance to.
  3667. * @return {number} The euclidean distance.
  3668. */
  3669. distanceToPoint( point ) {
  3670. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3671. }
  3672. /**
  3673. * Returns a bounding sphere that encloses this bounding box.
  3674. *
  3675. * @param {Sphere} target - The target sphere that is used to store the method's result.
  3676. * @return {Sphere} The bounding sphere that encloses this bounding box.
  3677. */
  3678. getBoundingSphere( target ) {
  3679. if ( this.isEmpty() ) {
  3680. target.makeEmpty();
  3681. } else {
  3682. this.getCenter( target.center );
  3683. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3684. }
  3685. return target;
  3686. }
  3687. /**
  3688. * Computes the intersection of this bounding box and the given one, setting the upper
  3689. * bound of this box to the lesser of the two boxes' upper bounds and the
  3690. * lower bound of this box to the greater of the two boxes' lower bounds. If
  3691. * there's no overlap, makes this box empty.
  3692. *
  3693. * @param {Box3} box - The bounding box to intersect with.
  3694. * @return {Box3} A reference to this bounding box.
  3695. */
  3696. intersect( box ) {
  3697. this.min.max( box.min );
  3698. this.max.min( box.max );
  3699. // 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.
  3700. if ( this.isEmpty() ) this.makeEmpty();
  3701. return this;
  3702. }
  3703. /**
  3704. * Computes the union of this box and another and the given one, setting the upper
  3705. * bound of this box to the greater of the two boxes' upper bounds and the
  3706. * lower bound of this box to the lesser of the two boxes' lower bounds.
  3707. *
  3708. * @param {Box3} box - The bounding box that will be unioned with this instance.
  3709. * @return {Box3} A reference to this bounding box.
  3710. */
  3711. union( box ) {
  3712. this.min.min( box.min );
  3713. this.max.max( box.max );
  3714. return this;
  3715. }
  3716. /**
  3717. * Transforms this bounding box by the given 4x4 transformation matrix.
  3718. *
  3719. * @param {Matrix4} matrix - The transformation matrix.
  3720. * @return {Box3} A reference to this bounding box.
  3721. */
  3722. applyMatrix4( matrix ) {
  3723. // transform of empty box is an empty box.
  3724. if ( this.isEmpty() ) return this;
  3725. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3726. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3727. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3728. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3729. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3730. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3731. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3732. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3733. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3734. this.setFromPoints( _points );
  3735. return this;
  3736. }
  3737. /**
  3738. * Adds the given offset to both the upper and lower bounds of this bounding box,
  3739. * effectively moving it in 3D space.
  3740. *
  3741. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  3742. * @return {Box3} A reference to this bounding box.
  3743. */
  3744. translate( offset ) {
  3745. this.min.add( offset );
  3746. this.max.add( offset );
  3747. return this;
  3748. }
  3749. /**
  3750. * Returns `true` if this bounding box is equal with the given one.
  3751. *
  3752. * @param {Box3} box - The box to test for equality.
  3753. * @return {boolean} Whether this bounding box is equal with the given one.
  3754. */
  3755. equals( box ) {
  3756. return box.min.equals( this.min ) && box.max.equals( this.max );
  3757. }
  3758. }
  3759. const _points = [
  3760. /*@__PURE__*/ new Vector3(),
  3761. /*@__PURE__*/ new Vector3(),
  3762. /*@__PURE__*/ new Vector3(),
  3763. /*@__PURE__*/ new Vector3(),
  3764. /*@__PURE__*/ new Vector3(),
  3765. /*@__PURE__*/ new Vector3(),
  3766. /*@__PURE__*/ new Vector3(),
  3767. /*@__PURE__*/ new Vector3()
  3768. ];
  3769. const _vector$b = /*@__PURE__*/ new Vector3();
  3770. const _box$4 = /*@__PURE__*/ new Box3();
  3771. // triangle centered vertices
  3772. const _v0$3 = /*@__PURE__*/ new Vector3();
  3773. const _v1$7 = /*@__PURE__*/ new Vector3();
  3774. const _v2$4 = /*@__PURE__*/ new Vector3();
  3775. // triangle edge vectors
  3776. const _f0 = /*@__PURE__*/ new Vector3();
  3777. const _f1 = /*@__PURE__*/ new Vector3();
  3778. const _f2 = /*@__PURE__*/ new Vector3();
  3779. const _center = /*@__PURE__*/ new Vector3();
  3780. const _extents = /*@__PURE__*/ new Vector3();
  3781. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3782. const _testAxis = /*@__PURE__*/ new Vector3();
  3783. function satForAxes( axes, v0, v1, v2, extents ) {
  3784. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3785. _testAxis.fromArray( axes, i );
  3786. // project the aabb onto the separating axis
  3787. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3788. // project all 3 vertices of the triangle onto the separating axis
  3789. const p0 = v0.dot( _testAxis );
  3790. const p1 = v1.dot( _testAxis );
  3791. const p2 = v2.dot( _testAxis );
  3792. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3793. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3794. // points of the projected triangle are outside the projected half-length of the aabb
  3795. // the axis is separating and we can exit
  3796. return false;
  3797. }
  3798. }
  3799. return true;
  3800. }
  3801. const _box$3 = /*@__PURE__*/ new Box3();
  3802. const _v1$6 = /*@__PURE__*/ new Vector3();
  3803. const _v2$3 = /*@__PURE__*/ new Vector3();
  3804. class Sphere {
  3805. constructor( center = new Vector3(), radius = -1 ) {
  3806. this.isSphere = true;
  3807. this.center = center;
  3808. this.radius = radius;
  3809. }
  3810. set( center, radius ) {
  3811. this.center.copy( center );
  3812. this.radius = radius;
  3813. return this;
  3814. }
  3815. setFromPoints( points, optionalCenter ) {
  3816. const center = this.center;
  3817. if ( optionalCenter !== undefined ) {
  3818. center.copy( optionalCenter );
  3819. } else {
  3820. _box$3.setFromPoints( points ).getCenter( center );
  3821. }
  3822. let maxRadiusSq = 0;
  3823. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3824. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3825. }
  3826. this.radius = Math.sqrt( maxRadiusSq );
  3827. return this;
  3828. }
  3829. copy( sphere ) {
  3830. this.center.copy( sphere.center );
  3831. this.radius = sphere.radius;
  3832. return this;
  3833. }
  3834. isEmpty() {
  3835. return ( this.radius < 0 );
  3836. }
  3837. makeEmpty() {
  3838. this.center.set( 0, 0, 0 );
  3839. this.radius = -1;
  3840. return this;
  3841. }
  3842. containsPoint( point ) {
  3843. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3844. }
  3845. distanceToPoint( point ) {
  3846. return ( point.distanceTo( this.center ) - this.radius );
  3847. }
  3848. intersectsSphere( sphere ) {
  3849. const radiusSum = this.radius + sphere.radius;
  3850. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3851. }
  3852. intersectsBox( box ) {
  3853. return box.intersectsSphere( this );
  3854. }
  3855. intersectsPlane( plane ) {
  3856. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3857. }
  3858. clampPoint( point, target ) {
  3859. const deltaLengthSq = this.center.distanceToSquared( point );
  3860. target.copy( point );
  3861. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3862. target.sub( this.center ).normalize();
  3863. target.multiplyScalar( this.radius ).add( this.center );
  3864. }
  3865. return target;
  3866. }
  3867. getBoundingBox( target ) {
  3868. if ( this.isEmpty() ) {
  3869. // Empty sphere produces empty bounding box
  3870. target.makeEmpty();
  3871. return target;
  3872. }
  3873. target.set( this.center, this.center );
  3874. target.expandByScalar( this.radius );
  3875. return target;
  3876. }
  3877. applyMatrix4( matrix ) {
  3878. this.center.applyMatrix4( matrix );
  3879. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3880. return this;
  3881. }
  3882. translate( offset ) {
  3883. this.center.add( offset );
  3884. return this;
  3885. }
  3886. expandByPoint( point ) {
  3887. if ( this.isEmpty() ) {
  3888. this.center.copy( point );
  3889. this.radius = 0;
  3890. return this;
  3891. }
  3892. _v1$6.subVectors( point, this.center );
  3893. const lengthSq = _v1$6.lengthSq();
  3894. if ( lengthSq > ( this.radius * this.radius ) ) {
  3895. // calculate the minimal sphere
  3896. const length = Math.sqrt( lengthSq );
  3897. const delta = ( length - this.radius ) * 0.5;
  3898. this.center.addScaledVector( _v1$6, delta / length );
  3899. this.radius += delta;
  3900. }
  3901. return this;
  3902. }
  3903. union( sphere ) {
  3904. if ( sphere.isEmpty() ) {
  3905. return this;
  3906. }
  3907. if ( this.isEmpty() ) {
  3908. this.copy( sphere );
  3909. return this;
  3910. }
  3911. if ( this.center.equals( sphere.center ) === true ) {
  3912. this.radius = Math.max( this.radius, sphere.radius );
  3913. } else {
  3914. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3915. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3916. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3917. }
  3918. return this;
  3919. }
  3920. equals( sphere ) {
  3921. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3922. }
  3923. clone() {
  3924. return new this.constructor().copy( this );
  3925. }
  3926. }
  3927. const _vector$a = /*@__PURE__*/ new Vector3();
  3928. const _segCenter = /*@__PURE__*/ new Vector3();
  3929. const _segDir = /*@__PURE__*/ new Vector3();
  3930. const _diff = /*@__PURE__*/ new Vector3();
  3931. const _edge1 = /*@__PURE__*/ new Vector3();
  3932. const _edge2 = /*@__PURE__*/ new Vector3();
  3933. const _normal$1 = /*@__PURE__*/ new Vector3();
  3934. class Ray {
  3935. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  3936. this.origin = origin;
  3937. this.direction = direction;
  3938. }
  3939. set( origin, direction ) {
  3940. this.origin.copy( origin );
  3941. this.direction.copy( direction );
  3942. return this;
  3943. }
  3944. copy( ray ) {
  3945. this.origin.copy( ray.origin );
  3946. this.direction.copy( ray.direction );
  3947. return this;
  3948. }
  3949. at( t, target ) {
  3950. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3951. }
  3952. lookAt( v ) {
  3953. this.direction.copy( v ).sub( this.origin ).normalize();
  3954. return this;
  3955. }
  3956. recast( t ) {
  3957. this.origin.copy( this.at( t, _vector$a ) );
  3958. return this;
  3959. }
  3960. closestPointToPoint( point, target ) {
  3961. target.subVectors( point, this.origin );
  3962. const directionDistance = target.dot( this.direction );
  3963. if ( directionDistance < 0 ) {
  3964. return target.copy( this.origin );
  3965. }
  3966. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3967. }
  3968. distanceToPoint( point ) {
  3969. return Math.sqrt( this.distanceSqToPoint( point ) );
  3970. }
  3971. distanceSqToPoint( point ) {
  3972. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3973. // point behind the ray
  3974. if ( directionDistance < 0 ) {
  3975. return this.origin.distanceToSquared( point );
  3976. }
  3977. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3978. return _vector$a.distanceToSquared( point );
  3979. }
  3980. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3981. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3982. // It returns the min distance between the ray and the segment
  3983. // defined by v0 and v1
  3984. // It can also set two optional targets :
  3985. // - The closest point on the ray
  3986. // - The closest point on the segment
  3987. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3988. _segDir.copy( v1 ).sub( v0 ).normalize();
  3989. _diff.copy( this.origin ).sub( _segCenter );
  3990. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3991. const a01 = - this.direction.dot( _segDir );
  3992. const b0 = _diff.dot( this.direction );
  3993. const b1 = - _diff.dot( _segDir );
  3994. const c = _diff.lengthSq();
  3995. const det = Math.abs( 1 - a01 * a01 );
  3996. let s0, s1, sqrDist, extDet;
  3997. if ( det > 0 ) {
  3998. // The ray and segment are not parallel.
  3999. s0 = a01 * b1 - b0;
  4000. s1 = a01 * b0 - b1;
  4001. extDet = segExtent * det;
  4002. if ( s0 >= 0 ) {
  4003. if ( s1 >= - extDet ) {
  4004. if ( s1 <= extDet ) {
  4005. // region 0
  4006. // Minimum at interior points of ray and segment.
  4007. const invDet = 1 / det;
  4008. s0 *= invDet;
  4009. s1 *= invDet;
  4010. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  4011. } else {
  4012. // region 1
  4013. s1 = segExtent;
  4014. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4015. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4016. }
  4017. } else {
  4018. // region 5
  4019. s1 = - segExtent;
  4020. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4021. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4022. }
  4023. } else {
  4024. if ( s1 <= - extDet ) {
  4025. // region 4
  4026. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  4027. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4028. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4029. } else if ( s1 <= extDet ) {
  4030. // region 3
  4031. s0 = 0;
  4032. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4033. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  4034. } else {
  4035. // region 2
  4036. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  4037. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  4038. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4039. }
  4040. }
  4041. } else {
  4042. // Ray and segment are parallel.
  4043. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  4044. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  4045. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  4046. }
  4047. if ( optionalPointOnRay ) {
  4048. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  4049. }
  4050. if ( optionalPointOnSegment ) {
  4051. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  4052. }
  4053. return sqrDist;
  4054. }
  4055. intersectSphere( sphere, target ) {
  4056. _vector$a.subVectors( sphere.center, this.origin );
  4057. const tca = _vector$a.dot( this.direction );
  4058. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  4059. const radius2 = sphere.radius * sphere.radius;
  4060. if ( d2 > radius2 ) return null;
  4061. const thc = Math.sqrt( radius2 - d2 );
  4062. // t0 = first intersect point - entrance on front of sphere
  4063. const t0 = tca - thc;
  4064. // t1 = second intersect point - exit point on back of sphere
  4065. const t1 = tca + thc;
  4066. // test to see if t1 is behind the ray - if so, return null
  4067. if ( t1 < 0 ) return null;
  4068. // test to see if t0 is behind the ray:
  4069. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  4070. // in order to always return an intersect point that is in front of the ray.
  4071. if ( t0 < 0 ) return this.at( t1, target );
  4072. // else t0 is in front of the ray, so return the first collision point scaled by t0
  4073. return this.at( t0, target );
  4074. }
  4075. intersectsSphere( sphere ) {
  4076. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  4077. }
  4078. distanceToPlane( plane ) {
  4079. const denominator = plane.normal.dot( this.direction );
  4080. if ( denominator === 0 ) {
  4081. // line is coplanar, return origin
  4082. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  4083. return 0;
  4084. }
  4085. // Null is preferable to undefined since undefined means.... it is undefined
  4086. return null;
  4087. }
  4088. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  4089. // Return if the ray never intersects the plane
  4090. return t >= 0 ? t : null;
  4091. }
  4092. intersectPlane( plane, target ) {
  4093. const t = this.distanceToPlane( plane );
  4094. if ( t === null ) {
  4095. return null;
  4096. }
  4097. return this.at( t, target );
  4098. }
  4099. intersectsPlane( plane ) {
  4100. // check if the ray lies on the plane first
  4101. const distToPoint = plane.distanceToPoint( this.origin );
  4102. if ( distToPoint === 0 ) {
  4103. return true;
  4104. }
  4105. const denominator = plane.normal.dot( this.direction );
  4106. if ( denominator * distToPoint < 0 ) {
  4107. return true;
  4108. }
  4109. // ray origin is behind the plane (and is pointing behind it)
  4110. return false;
  4111. }
  4112. intersectBox( box, target ) {
  4113. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  4114. const invdirx = 1 / this.direction.x,
  4115. invdiry = 1 / this.direction.y,
  4116. invdirz = 1 / this.direction.z;
  4117. const origin = this.origin;
  4118. if ( invdirx >= 0 ) {
  4119. tmin = ( box.min.x - origin.x ) * invdirx;
  4120. tmax = ( box.max.x - origin.x ) * invdirx;
  4121. } else {
  4122. tmin = ( box.max.x - origin.x ) * invdirx;
  4123. tmax = ( box.min.x - origin.x ) * invdirx;
  4124. }
  4125. if ( invdiry >= 0 ) {
  4126. tymin = ( box.min.y - origin.y ) * invdiry;
  4127. tymax = ( box.max.y - origin.y ) * invdiry;
  4128. } else {
  4129. tymin = ( box.max.y - origin.y ) * invdiry;
  4130. tymax = ( box.min.y - origin.y ) * invdiry;
  4131. }
  4132. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  4133. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  4134. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  4135. if ( invdirz >= 0 ) {
  4136. tzmin = ( box.min.z - origin.z ) * invdirz;
  4137. tzmax = ( box.max.z - origin.z ) * invdirz;
  4138. } else {
  4139. tzmin = ( box.max.z - origin.z ) * invdirz;
  4140. tzmax = ( box.min.z - origin.z ) * invdirz;
  4141. }
  4142. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  4143. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  4144. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  4145. //return point closest to the ray (positive side)
  4146. if ( tmax < 0 ) return null;
  4147. return this.at( tmin >= 0 ? tmin : tmax, target );
  4148. }
  4149. intersectsBox( box ) {
  4150. return this.intersectBox( box, _vector$a ) !== null;
  4151. }
  4152. intersectTriangle( a, b, c, backfaceCulling, target ) {
  4153. // Compute the offset origin, edges, and normal.
  4154. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  4155. _edge1.subVectors( b, a );
  4156. _edge2.subVectors( c, a );
  4157. _normal$1.crossVectors( _edge1, _edge2 );
  4158. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  4159. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  4160. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  4161. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  4162. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  4163. let DdN = this.direction.dot( _normal$1 );
  4164. let sign;
  4165. if ( DdN > 0 ) {
  4166. if ( backfaceCulling ) return null;
  4167. sign = 1;
  4168. } else if ( DdN < 0 ) {
  4169. sign = -1;
  4170. DdN = - DdN;
  4171. } else {
  4172. return null;
  4173. }
  4174. _diff.subVectors( this.origin, a );
  4175. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  4176. // b1 < 0, no intersection
  4177. if ( DdQxE2 < 0 ) {
  4178. return null;
  4179. }
  4180. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  4181. // b2 < 0, no intersection
  4182. if ( DdE1xQ < 0 ) {
  4183. return null;
  4184. }
  4185. // b1+b2 > 1, no intersection
  4186. if ( DdQxE2 + DdE1xQ > DdN ) {
  4187. return null;
  4188. }
  4189. // Line intersects triangle, check if ray does.
  4190. const QdN = - sign * _diff.dot( _normal$1 );
  4191. // t < 0, no intersection
  4192. if ( QdN < 0 ) {
  4193. return null;
  4194. }
  4195. // Ray intersects triangle.
  4196. return this.at( QdN / DdN, target );
  4197. }
  4198. applyMatrix4( matrix4 ) {
  4199. this.origin.applyMatrix4( matrix4 );
  4200. this.direction.transformDirection( matrix4 );
  4201. return this;
  4202. }
  4203. equals( ray ) {
  4204. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  4205. }
  4206. clone() {
  4207. return new this.constructor().copy( this );
  4208. }
  4209. }
  4210. class Matrix4 {
  4211. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  4212. Matrix4.prototype.isMatrix4 = true;
  4213. this.elements = [
  4214. 1, 0, 0, 0,
  4215. 0, 1, 0, 0,
  4216. 0, 0, 1, 0,
  4217. 0, 0, 0, 1
  4218. ];
  4219. if ( n11 !== undefined ) {
  4220. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  4221. }
  4222. }
  4223. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  4224. const te = this.elements;
  4225. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  4226. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  4227. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  4228. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  4229. return this;
  4230. }
  4231. identity() {
  4232. this.set(
  4233. 1, 0, 0, 0,
  4234. 0, 1, 0, 0,
  4235. 0, 0, 1, 0,
  4236. 0, 0, 0, 1
  4237. );
  4238. return this;
  4239. }
  4240. clone() {
  4241. return new Matrix4().fromArray( this.elements );
  4242. }
  4243. copy( m ) {
  4244. const te = this.elements;
  4245. const me = m.elements;
  4246. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  4247. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  4248. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  4249. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  4250. return this;
  4251. }
  4252. copyPosition( m ) {
  4253. const te = this.elements, me = m.elements;
  4254. te[ 12 ] = me[ 12 ];
  4255. te[ 13 ] = me[ 13 ];
  4256. te[ 14 ] = me[ 14 ];
  4257. return this;
  4258. }
  4259. setFromMatrix3( m ) {
  4260. const me = m.elements;
  4261. this.set(
  4262. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  4263. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  4264. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  4265. 0, 0, 0, 1
  4266. );
  4267. return this;
  4268. }
  4269. extractBasis( xAxis, yAxis, zAxis ) {
  4270. xAxis.setFromMatrixColumn( this, 0 );
  4271. yAxis.setFromMatrixColumn( this, 1 );
  4272. zAxis.setFromMatrixColumn( this, 2 );
  4273. return this;
  4274. }
  4275. makeBasis( xAxis, yAxis, zAxis ) {
  4276. this.set(
  4277. xAxis.x, yAxis.x, zAxis.x, 0,
  4278. xAxis.y, yAxis.y, zAxis.y, 0,
  4279. xAxis.z, yAxis.z, zAxis.z, 0,
  4280. 0, 0, 0, 1
  4281. );
  4282. return this;
  4283. }
  4284. extractRotation( m ) {
  4285. // this method does not support reflection matrices
  4286. const te = this.elements;
  4287. const me = m.elements;
  4288. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  4289. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  4290. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  4291. te[ 0 ] = me[ 0 ] * scaleX;
  4292. te[ 1 ] = me[ 1 ] * scaleX;
  4293. te[ 2 ] = me[ 2 ] * scaleX;
  4294. te[ 3 ] = 0;
  4295. te[ 4 ] = me[ 4 ] * scaleY;
  4296. te[ 5 ] = me[ 5 ] * scaleY;
  4297. te[ 6 ] = me[ 6 ] * scaleY;
  4298. te[ 7 ] = 0;
  4299. te[ 8 ] = me[ 8 ] * scaleZ;
  4300. te[ 9 ] = me[ 9 ] * scaleZ;
  4301. te[ 10 ] = me[ 10 ] * scaleZ;
  4302. te[ 11 ] = 0;
  4303. te[ 12 ] = 0;
  4304. te[ 13 ] = 0;
  4305. te[ 14 ] = 0;
  4306. te[ 15 ] = 1;
  4307. return this;
  4308. }
  4309. makeRotationFromEuler( euler ) {
  4310. const te = this.elements;
  4311. const x = euler.x, y = euler.y, z = euler.z;
  4312. const a = Math.cos( x ), b = Math.sin( x );
  4313. const c = Math.cos( y ), d = Math.sin( y );
  4314. const e = Math.cos( z ), f = Math.sin( z );
  4315. if ( euler.order === 'XYZ' ) {
  4316. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  4317. te[ 0 ] = c * e;
  4318. te[ 4 ] = - c * f;
  4319. te[ 8 ] = d;
  4320. te[ 1 ] = af + be * d;
  4321. te[ 5 ] = ae - bf * d;
  4322. te[ 9 ] = - b * c;
  4323. te[ 2 ] = bf - ae * d;
  4324. te[ 6 ] = be + af * d;
  4325. te[ 10 ] = a * c;
  4326. } else if ( euler.order === 'YXZ' ) {
  4327. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  4328. te[ 0 ] = ce + df * b;
  4329. te[ 4 ] = de * b - cf;
  4330. te[ 8 ] = a * d;
  4331. te[ 1 ] = a * f;
  4332. te[ 5 ] = a * e;
  4333. te[ 9 ] = - b;
  4334. te[ 2 ] = cf * b - de;
  4335. te[ 6 ] = df + ce * b;
  4336. te[ 10 ] = a * c;
  4337. } else if ( euler.order === 'ZXY' ) {
  4338. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  4339. te[ 0 ] = ce - df * b;
  4340. te[ 4 ] = - a * f;
  4341. te[ 8 ] = de + cf * b;
  4342. te[ 1 ] = cf + de * b;
  4343. te[ 5 ] = a * e;
  4344. te[ 9 ] = df - ce * b;
  4345. te[ 2 ] = - a * d;
  4346. te[ 6 ] = b;
  4347. te[ 10 ] = a * c;
  4348. } else if ( euler.order === 'ZYX' ) {
  4349. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  4350. te[ 0 ] = c * e;
  4351. te[ 4 ] = be * d - af;
  4352. te[ 8 ] = ae * d + bf;
  4353. te[ 1 ] = c * f;
  4354. te[ 5 ] = bf * d + ae;
  4355. te[ 9 ] = af * d - be;
  4356. te[ 2 ] = - d;
  4357. te[ 6 ] = b * c;
  4358. te[ 10 ] = a * c;
  4359. } else if ( euler.order === 'YZX' ) {
  4360. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4361. te[ 0 ] = c * e;
  4362. te[ 4 ] = bd - ac * f;
  4363. te[ 8 ] = bc * f + ad;
  4364. te[ 1 ] = f;
  4365. te[ 5 ] = a * e;
  4366. te[ 9 ] = - b * e;
  4367. te[ 2 ] = - d * e;
  4368. te[ 6 ] = ad * f + bc;
  4369. te[ 10 ] = ac - bd * f;
  4370. } else if ( euler.order === 'XZY' ) {
  4371. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  4372. te[ 0 ] = c * e;
  4373. te[ 4 ] = - f;
  4374. te[ 8 ] = d * e;
  4375. te[ 1 ] = ac * f + bd;
  4376. te[ 5 ] = a * e;
  4377. te[ 9 ] = ad * f - bc;
  4378. te[ 2 ] = bc * f - ad;
  4379. te[ 6 ] = b * e;
  4380. te[ 10 ] = bd * f + ac;
  4381. }
  4382. // bottom row
  4383. te[ 3 ] = 0;
  4384. te[ 7 ] = 0;
  4385. te[ 11 ] = 0;
  4386. // last column
  4387. te[ 12 ] = 0;
  4388. te[ 13 ] = 0;
  4389. te[ 14 ] = 0;
  4390. te[ 15 ] = 1;
  4391. return this;
  4392. }
  4393. makeRotationFromQuaternion( q ) {
  4394. return this.compose( _zero, q, _one );
  4395. }
  4396. lookAt( eye, target, up ) {
  4397. const te = this.elements;
  4398. _z.subVectors( eye, target );
  4399. if ( _z.lengthSq() === 0 ) {
  4400. // eye and target are in the same position
  4401. _z.z = 1;
  4402. }
  4403. _z.normalize();
  4404. _x.crossVectors( up, _z );
  4405. if ( _x.lengthSq() === 0 ) {
  4406. // up and z are parallel
  4407. if ( Math.abs( up.z ) === 1 ) {
  4408. _z.x += 0.0001;
  4409. } else {
  4410. _z.z += 0.0001;
  4411. }
  4412. _z.normalize();
  4413. _x.crossVectors( up, _z );
  4414. }
  4415. _x.normalize();
  4416. _y.crossVectors( _z, _x );
  4417. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  4418. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  4419. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  4420. return this;
  4421. }
  4422. multiply( m ) {
  4423. return this.multiplyMatrices( this, m );
  4424. }
  4425. premultiply( m ) {
  4426. return this.multiplyMatrices( m, this );
  4427. }
  4428. multiplyMatrices( a, b ) {
  4429. const ae = a.elements;
  4430. const be = b.elements;
  4431. const te = this.elements;
  4432. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  4433. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  4434. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  4435. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  4436. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  4437. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  4438. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  4439. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  4440. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4441. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4442. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4443. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4444. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4445. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4446. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4447. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4448. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4449. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4450. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4451. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4452. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4453. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4454. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4455. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4456. return this;
  4457. }
  4458. multiplyScalar( s ) {
  4459. const te = this.elements;
  4460. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4461. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4462. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4463. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4464. return this;
  4465. }
  4466. determinant() {
  4467. const te = this.elements;
  4468. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4469. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4470. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4471. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4472. //TODO: make this more efficient
  4473. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4474. return (
  4475. n41 * (
  4476. + n14 * n23 * n32
  4477. - n13 * n24 * n32
  4478. - n14 * n22 * n33
  4479. + n12 * n24 * n33
  4480. + n13 * n22 * n34
  4481. - n12 * n23 * n34
  4482. ) +
  4483. n42 * (
  4484. + n11 * n23 * n34
  4485. - n11 * n24 * n33
  4486. + n14 * n21 * n33
  4487. - n13 * n21 * n34
  4488. + n13 * n24 * n31
  4489. - n14 * n23 * n31
  4490. ) +
  4491. n43 * (
  4492. + n11 * n24 * n32
  4493. - n11 * n22 * n34
  4494. - n14 * n21 * n32
  4495. + n12 * n21 * n34
  4496. + n14 * n22 * n31
  4497. - n12 * n24 * n31
  4498. ) +
  4499. n44 * (
  4500. - n13 * n22 * n31
  4501. - n11 * n23 * n32
  4502. + n11 * n22 * n33
  4503. + n13 * n21 * n32
  4504. - n12 * n21 * n33
  4505. + n12 * n23 * n31
  4506. )
  4507. );
  4508. }
  4509. transpose() {
  4510. const te = this.elements;
  4511. let tmp;
  4512. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4513. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4514. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4515. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4516. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4517. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4518. return this;
  4519. }
  4520. setPosition( x, y, z ) {
  4521. const te = this.elements;
  4522. if ( x.isVector3 ) {
  4523. te[ 12 ] = x.x;
  4524. te[ 13 ] = x.y;
  4525. te[ 14 ] = x.z;
  4526. } else {
  4527. te[ 12 ] = x;
  4528. te[ 13 ] = y;
  4529. te[ 14 ] = z;
  4530. }
  4531. return this;
  4532. }
  4533. invert() {
  4534. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4535. const te = this.elements,
  4536. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4537. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4538. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4539. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4540. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4541. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4542. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4543. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4544. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4545. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4546. const detInv = 1 / det;
  4547. te[ 0 ] = t11 * detInv;
  4548. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4549. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4550. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4551. te[ 4 ] = t12 * detInv;
  4552. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4553. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4554. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4555. te[ 8 ] = t13 * detInv;
  4556. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4557. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4558. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4559. te[ 12 ] = t14 * detInv;
  4560. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4561. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4562. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4563. return this;
  4564. }
  4565. scale( v ) {
  4566. const te = this.elements;
  4567. const x = v.x, y = v.y, z = v.z;
  4568. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4569. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4570. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4571. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4572. return this;
  4573. }
  4574. getMaxScaleOnAxis() {
  4575. const te = this.elements;
  4576. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4577. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4578. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4579. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4580. }
  4581. makeTranslation( x, y, z ) {
  4582. if ( x.isVector3 ) {
  4583. this.set(
  4584. 1, 0, 0, x.x,
  4585. 0, 1, 0, x.y,
  4586. 0, 0, 1, x.z,
  4587. 0, 0, 0, 1
  4588. );
  4589. } else {
  4590. this.set(
  4591. 1, 0, 0, x,
  4592. 0, 1, 0, y,
  4593. 0, 0, 1, z,
  4594. 0, 0, 0, 1
  4595. );
  4596. }
  4597. return this;
  4598. }
  4599. makeRotationX( theta ) {
  4600. const c = Math.cos( theta ), s = Math.sin( theta );
  4601. this.set(
  4602. 1, 0, 0, 0,
  4603. 0, c, - s, 0,
  4604. 0, s, c, 0,
  4605. 0, 0, 0, 1
  4606. );
  4607. return this;
  4608. }
  4609. makeRotationY( theta ) {
  4610. const c = Math.cos( theta ), s = Math.sin( theta );
  4611. this.set(
  4612. c, 0, s, 0,
  4613. 0, 1, 0, 0,
  4614. - s, 0, c, 0,
  4615. 0, 0, 0, 1
  4616. );
  4617. return this;
  4618. }
  4619. makeRotationZ( theta ) {
  4620. const c = Math.cos( theta ), s = Math.sin( theta );
  4621. this.set(
  4622. c, - s, 0, 0,
  4623. s, c, 0, 0,
  4624. 0, 0, 1, 0,
  4625. 0, 0, 0, 1
  4626. );
  4627. return this;
  4628. }
  4629. makeRotationAxis( axis, angle ) {
  4630. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4631. const c = Math.cos( angle );
  4632. const s = Math.sin( angle );
  4633. const t = 1 - c;
  4634. const x = axis.x, y = axis.y, z = axis.z;
  4635. const tx = t * x, ty = t * y;
  4636. this.set(
  4637. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4638. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4639. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4640. 0, 0, 0, 1
  4641. );
  4642. return this;
  4643. }
  4644. makeScale( x, y, z ) {
  4645. this.set(
  4646. x, 0, 0, 0,
  4647. 0, y, 0, 0,
  4648. 0, 0, z, 0,
  4649. 0, 0, 0, 1
  4650. );
  4651. return this;
  4652. }
  4653. makeShear( xy, xz, yx, yz, zx, zy ) {
  4654. this.set(
  4655. 1, yx, zx, 0,
  4656. xy, 1, zy, 0,
  4657. xz, yz, 1, 0,
  4658. 0, 0, 0, 1
  4659. );
  4660. return this;
  4661. }
  4662. compose( position, quaternion, scale ) {
  4663. const te = this.elements;
  4664. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4665. const x2 = x + x, y2 = y + y, z2 = z + z;
  4666. const xx = x * x2, xy = x * y2, xz = x * z2;
  4667. const yy = y * y2, yz = y * z2, zz = z * z2;
  4668. const wx = w * x2, wy = w * y2, wz = w * z2;
  4669. const sx = scale.x, sy = scale.y, sz = scale.z;
  4670. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4671. te[ 1 ] = ( xy + wz ) * sx;
  4672. te[ 2 ] = ( xz - wy ) * sx;
  4673. te[ 3 ] = 0;
  4674. te[ 4 ] = ( xy - wz ) * sy;
  4675. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4676. te[ 6 ] = ( yz + wx ) * sy;
  4677. te[ 7 ] = 0;
  4678. te[ 8 ] = ( xz + wy ) * sz;
  4679. te[ 9 ] = ( yz - wx ) * sz;
  4680. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4681. te[ 11 ] = 0;
  4682. te[ 12 ] = position.x;
  4683. te[ 13 ] = position.y;
  4684. te[ 14 ] = position.z;
  4685. te[ 15 ] = 1;
  4686. return this;
  4687. }
  4688. decompose( position, quaternion, scale ) {
  4689. const te = this.elements;
  4690. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4691. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4692. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4693. // if determine is negative, we need to invert one scale
  4694. const det = this.determinant();
  4695. if ( det < 0 ) sx = - sx;
  4696. position.x = te[ 12 ];
  4697. position.y = te[ 13 ];
  4698. position.z = te[ 14 ];
  4699. // scale the rotation part
  4700. _m1$4.copy( this );
  4701. const invSX = 1 / sx;
  4702. const invSY = 1 / sy;
  4703. const invSZ = 1 / sz;
  4704. _m1$4.elements[ 0 ] *= invSX;
  4705. _m1$4.elements[ 1 ] *= invSX;
  4706. _m1$4.elements[ 2 ] *= invSX;
  4707. _m1$4.elements[ 4 ] *= invSY;
  4708. _m1$4.elements[ 5 ] *= invSY;
  4709. _m1$4.elements[ 6 ] *= invSY;
  4710. _m1$4.elements[ 8 ] *= invSZ;
  4711. _m1$4.elements[ 9 ] *= invSZ;
  4712. _m1$4.elements[ 10 ] *= invSZ;
  4713. quaternion.setFromRotationMatrix( _m1$4 );
  4714. scale.x = sx;
  4715. scale.y = sy;
  4716. scale.z = sz;
  4717. return this;
  4718. }
  4719. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4720. const te = this.elements;
  4721. const x = 2 * near / ( right - left );
  4722. const y = 2 * near / ( top - bottom );
  4723. const a = ( right + left ) / ( right - left );
  4724. const b = ( top + bottom ) / ( top - bottom );
  4725. let c, d;
  4726. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4727. c = - ( far + near ) / ( far - near );
  4728. d = ( -2 * far * near ) / ( far - near );
  4729. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4730. c = - far / ( far - near );
  4731. d = ( - far * near ) / ( far - near );
  4732. } else {
  4733. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4734. }
  4735. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4736. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4737. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4738. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  4739. return this;
  4740. }
  4741. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4742. const te = this.elements;
  4743. const w = 1.0 / ( right - left );
  4744. const h = 1.0 / ( top - bottom );
  4745. const p = 1.0 / ( far - near );
  4746. const x = ( right + left ) * w;
  4747. const y = ( top + bottom ) * h;
  4748. let z, zInv;
  4749. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4750. z = ( far + near ) * p;
  4751. zInv = -2 * p;
  4752. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4753. z = near * p;
  4754. zInv = -1 * p;
  4755. } else {
  4756. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4757. }
  4758. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4759. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4760. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4761. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4762. return this;
  4763. }
  4764. equals( matrix ) {
  4765. const te = this.elements;
  4766. const me = matrix.elements;
  4767. for ( let i = 0; i < 16; i ++ ) {
  4768. if ( te[ i ] !== me[ i ] ) return false;
  4769. }
  4770. return true;
  4771. }
  4772. fromArray( array, offset = 0 ) {
  4773. for ( let i = 0; i < 16; i ++ ) {
  4774. this.elements[ i ] = array[ i + offset ];
  4775. }
  4776. return this;
  4777. }
  4778. toArray( array = [], offset = 0 ) {
  4779. const te = this.elements;
  4780. array[ offset ] = te[ 0 ];
  4781. array[ offset + 1 ] = te[ 1 ];
  4782. array[ offset + 2 ] = te[ 2 ];
  4783. array[ offset + 3 ] = te[ 3 ];
  4784. array[ offset + 4 ] = te[ 4 ];
  4785. array[ offset + 5 ] = te[ 5 ];
  4786. array[ offset + 6 ] = te[ 6 ];
  4787. array[ offset + 7 ] = te[ 7 ];
  4788. array[ offset + 8 ] = te[ 8 ];
  4789. array[ offset + 9 ] = te[ 9 ];
  4790. array[ offset + 10 ] = te[ 10 ];
  4791. array[ offset + 11 ] = te[ 11 ];
  4792. array[ offset + 12 ] = te[ 12 ];
  4793. array[ offset + 13 ] = te[ 13 ];
  4794. array[ offset + 14 ] = te[ 14 ];
  4795. array[ offset + 15 ] = te[ 15 ];
  4796. return array;
  4797. }
  4798. }
  4799. const _v1$5 = /*@__PURE__*/ new Vector3();
  4800. const _m1$4 = /*@__PURE__*/ new Matrix4();
  4801. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4802. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4803. const _x = /*@__PURE__*/ new Vector3();
  4804. const _y = /*@__PURE__*/ new Vector3();
  4805. const _z = /*@__PURE__*/ new Vector3();
  4806. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4807. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4808. class Euler {
  4809. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4810. this.isEuler = true;
  4811. this._x = x;
  4812. this._y = y;
  4813. this._z = z;
  4814. this._order = order;
  4815. }
  4816. get x() {
  4817. return this._x;
  4818. }
  4819. set x( value ) {
  4820. this._x = value;
  4821. this._onChangeCallback();
  4822. }
  4823. get y() {
  4824. return this._y;
  4825. }
  4826. set y( value ) {
  4827. this._y = value;
  4828. this._onChangeCallback();
  4829. }
  4830. get z() {
  4831. return this._z;
  4832. }
  4833. set z( value ) {
  4834. this._z = value;
  4835. this._onChangeCallback();
  4836. }
  4837. get order() {
  4838. return this._order;
  4839. }
  4840. set order( value ) {
  4841. this._order = value;
  4842. this._onChangeCallback();
  4843. }
  4844. set( x, y, z, order = this._order ) {
  4845. this._x = x;
  4846. this._y = y;
  4847. this._z = z;
  4848. this._order = order;
  4849. this._onChangeCallback();
  4850. return this;
  4851. }
  4852. clone() {
  4853. return new this.constructor( this._x, this._y, this._z, this._order );
  4854. }
  4855. copy( euler ) {
  4856. this._x = euler._x;
  4857. this._y = euler._y;
  4858. this._z = euler._z;
  4859. this._order = euler._order;
  4860. this._onChangeCallback();
  4861. return this;
  4862. }
  4863. setFromRotationMatrix( m, order = this._order, update = true ) {
  4864. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4865. const te = m.elements;
  4866. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4867. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4868. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4869. switch ( order ) {
  4870. case 'XYZ':
  4871. this._y = Math.asin( clamp( m13, -1, 1 ) );
  4872. if ( Math.abs( m13 ) < 0.9999999 ) {
  4873. this._x = Math.atan2( - m23, m33 );
  4874. this._z = Math.atan2( - m12, m11 );
  4875. } else {
  4876. this._x = Math.atan2( m32, m22 );
  4877. this._z = 0;
  4878. }
  4879. break;
  4880. case 'YXZ':
  4881. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  4882. if ( Math.abs( m23 ) < 0.9999999 ) {
  4883. this._y = Math.atan2( m13, m33 );
  4884. this._z = Math.atan2( m21, m22 );
  4885. } else {
  4886. this._y = Math.atan2( - m31, m11 );
  4887. this._z = 0;
  4888. }
  4889. break;
  4890. case 'ZXY':
  4891. this._x = Math.asin( clamp( m32, -1, 1 ) );
  4892. if ( Math.abs( m32 ) < 0.9999999 ) {
  4893. this._y = Math.atan2( - m31, m33 );
  4894. this._z = Math.atan2( - m12, m22 );
  4895. } else {
  4896. this._y = 0;
  4897. this._z = Math.atan2( m21, m11 );
  4898. }
  4899. break;
  4900. case 'ZYX':
  4901. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  4902. if ( Math.abs( m31 ) < 0.9999999 ) {
  4903. this._x = Math.atan2( m32, m33 );
  4904. this._z = Math.atan2( m21, m11 );
  4905. } else {
  4906. this._x = 0;
  4907. this._z = Math.atan2( - m12, m22 );
  4908. }
  4909. break;
  4910. case 'YZX':
  4911. this._z = Math.asin( clamp( m21, -1, 1 ) );
  4912. if ( Math.abs( m21 ) < 0.9999999 ) {
  4913. this._x = Math.atan2( - m23, m22 );
  4914. this._y = Math.atan2( - m31, m11 );
  4915. } else {
  4916. this._x = 0;
  4917. this._y = Math.atan2( m13, m33 );
  4918. }
  4919. break;
  4920. case 'XZY':
  4921. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  4922. if ( Math.abs( m12 ) < 0.9999999 ) {
  4923. this._x = Math.atan2( m32, m22 );
  4924. this._y = Math.atan2( m13, m11 );
  4925. } else {
  4926. this._x = Math.atan2( - m23, m33 );
  4927. this._y = 0;
  4928. }
  4929. break;
  4930. default:
  4931. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4932. }
  4933. this._order = order;
  4934. if ( update === true ) this._onChangeCallback();
  4935. return this;
  4936. }
  4937. setFromQuaternion( q, order, update ) {
  4938. _matrix$2.makeRotationFromQuaternion( q );
  4939. return this.setFromRotationMatrix( _matrix$2, order, update );
  4940. }
  4941. setFromVector3( v, order = this._order ) {
  4942. return this.set( v.x, v.y, v.z, order );
  4943. }
  4944. reorder( newOrder ) {
  4945. // WARNING: this discards revolution information -bhouston
  4946. _quaternion$3.setFromEuler( this );
  4947. return this.setFromQuaternion( _quaternion$3, newOrder );
  4948. }
  4949. equals( euler ) {
  4950. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4951. }
  4952. fromArray( array ) {
  4953. this._x = array[ 0 ];
  4954. this._y = array[ 1 ];
  4955. this._z = array[ 2 ];
  4956. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4957. this._onChangeCallback();
  4958. return this;
  4959. }
  4960. toArray( array = [], offset = 0 ) {
  4961. array[ offset ] = this._x;
  4962. array[ offset + 1 ] = this._y;
  4963. array[ offset + 2 ] = this._z;
  4964. array[ offset + 3 ] = this._order;
  4965. return array;
  4966. }
  4967. _onChange( callback ) {
  4968. this._onChangeCallback = callback;
  4969. return this;
  4970. }
  4971. _onChangeCallback() {}
  4972. *[ Symbol.iterator ]() {
  4973. yield this._x;
  4974. yield this._y;
  4975. yield this._z;
  4976. yield this._order;
  4977. }
  4978. }
  4979. Euler.DEFAULT_ORDER = 'XYZ';
  4980. class Layers {
  4981. constructor() {
  4982. this.mask = 1 | 0;
  4983. }
  4984. set( channel ) {
  4985. this.mask = ( 1 << channel | 0 ) >>> 0;
  4986. }
  4987. enable( channel ) {
  4988. this.mask |= 1 << channel | 0;
  4989. }
  4990. enableAll() {
  4991. this.mask = 0xffffffff | 0;
  4992. }
  4993. toggle( channel ) {
  4994. this.mask ^= 1 << channel | 0;
  4995. }
  4996. disable( channel ) {
  4997. this.mask &= ~ ( 1 << channel | 0 );
  4998. }
  4999. disableAll() {
  5000. this.mask = 0;
  5001. }
  5002. test( layers ) {
  5003. return ( this.mask & layers.mask ) !== 0;
  5004. }
  5005. isEnabled( channel ) {
  5006. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  5007. }
  5008. }
  5009. let _object3DId = 0;
  5010. const _v1$4 = /*@__PURE__*/ new Vector3();
  5011. const _q1 = /*@__PURE__*/ new Quaternion();
  5012. const _m1$3 = /*@__PURE__*/ new Matrix4();
  5013. const _target = /*@__PURE__*/ new Vector3();
  5014. const _position$3 = /*@__PURE__*/ new Vector3();
  5015. const _scale$2 = /*@__PURE__*/ new Vector3();
  5016. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  5017. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  5018. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5019. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  5020. /**
  5021. * Fires when the object has been added to its parent object.
  5022. *
  5023. * @event Object3D#added
  5024. * @type {Object}
  5025. */
  5026. const _addedEvent = { type: 'added' };
  5027. /**
  5028. * Fires when the object has been removed from its parent object.
  5029. *
  5030. * @event Object3D#removed
  5031. * @type {Object}
  5032. */
  5033. const _removedEvent = { type: 'removed' };
  5034. /**
  5035. * Fires when a new child object has been added.
  5036. *
  5037. * @event Object3D#childadded
  5038. * @type {Object}
  5039. */
  5040. const _childaddedEvent = { type: 'childadded', child: null };
  5041. /**
  5042. * Fires when a new child object has been added.
  5043. *
  5044. * @event Object3D#childremoved
  5045. * @type {Object}
  5046. */
  5047. const _childremovedEvent = { type: 'childremoved', child: null };
  5048. /**
  5049. * This is the base class for most objects in three.js and provides a set of
  5050. * properties and methods for manipulating objects in 3D space.
  5051. *
  5052. * @augments EventDispatcher
  5053. */
  5054. class Object3D extends EventDispatcher {
  5055. /**
  5056. * Constructs a new 3D object.
  5057. */
  5058. constructor() {
  5059. super();
  5060. /**
  5061. * This flag can be used for type testing.
  5062. *
  5063. * @type {boolean}
  5064. * @readonly
  5065. * @default true
  5066. */
  5067. this.isObject3D = true;
  5068. /**
  5069. * The ID of the 3D object.
  5070. *
  5071. * @name Object3D#id
  5072. * @type {number}
  5073. * @readonly
  5074. */
  5075. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  5076. /**
  5077. * The UUID of the 3D object.
  5078. *
  5079. * @type {string}
  5080. * @readonly
  5081. */
  5082. this.uuid = generateUUID();
  5083. /**
  5084. * The name of the 3D object.
  5085. *
  5086. * @type {string}
  5087. */
  5088. this.name = '';
  5089. /**
  5090. * The type property is used for detecting the object type
  5091. * in context of serialization/deserialization.
  5092. *
  5093. * @type {string}
  5094. * @readonly
  5095. */
  5096. this.type = 'Object3D';
  5097. /**
  5098. * A reference to the parent object.
  5099. *
  5100. * @type {?Object3D}
  5101. * @default null
  5102. */
  5103. this.parent = null;
  5104. /**
  5105. * An array holding the child 3D objects of this instance.
  5106. *
  5107. * @type {Array<Object3D>}
  5108. */
  5109. this.children = [];
  5110. /**
  5111. * Defines the `up` direction of the 3D object which influences
  5112. * the orientation via methods like {@link Object3D#lookAt}.
  5113. *
  5114. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  5115. *
  5116. * @type {Vector3}
  5117. */
  5118. this.up = Object3D.DEFAULT_UP.clone();
  5119. const position = new Vector3();
  5120. const rotation = new Euler();
  5121. const quaternion = new Quaternion();
  5122. const scale = new Vector3( 1, 1, 1 );
  5123. function onRotationChange() {
  5124. quaternion.setFromEuler( rotation, false );
  5125. }
  5126. function onQuaternionChange() {
  5127. rotation.setFromQuaternion( quaternion, undefined, false );
  5128. }
  5129. rotation._onChange( onRotationChange );
  5130. quaternion._onChange( onQuaternionChange );
  5131. Object.defineProperties( this, {
  5132. /**
  5133. * Represents the object's local position.
  5134. *
  5135. * @name Object3D#position
  5136. * @type {Vector3}
  5137. * @default (0,0,0)
  5138. */
  5139. position: {
  5140. configurable: true,
  5141. enumerable: true,
  5142. value: position
  5143. },
  5144. /**
  5145. * Represents the object's local rotation as Euler angles, in radians.
  5146. *
  5147. * @name Object3D#rotation
  5148. * @type {Euler}
  5149. * @default (0,0,0)
  5150. */
  5151. rotation: {
  5152. configurable: true,
  5153. enumerable: true,
  5154. value: rotation
  5155. },
  5156. /**
  5157. * Represents the object's local rotation as Quaterions.
  5158. *
  5159. * @name Object3D#quaternion
  5160. * @type {Quaternion}
  5161. */
  5162. quaternion: {
  5163. configurable: true,
  5164. enumerable: true,
  5165. value: quaternion
  5166. },
  5167. /**
  5168. * Represents the object's local scale.
  5169. *
  5170. * @name Object3D#scale
  5171. * @type {Vector3}
  5172. * @default (1,1,1)
  5173. */
  5174. scale: {
  5175. configurable: true,
  5176. enumerable: true,
  5177. value: scale
  5178. },
  5179. /**
  5180. * Represents the object's model-view matrix.
  5181. *
  5182. * @name Object3D#modelViewMatrix
  5183. * @type {Matrix4}
  5184. */
  5185. modelViewMatrix: {
  5186. value: new Matrix4()
  5187. },
  5188. /**
  5189. * Represents the object's normal matrix.
  5190. *
  5191. * @name Object3D#normalMatrix
  5192. * @type {Matrix3}
  5193. */
  5194. normalMatrix: {
  5195. value: new Matrix3()
  5196. }
  5197. } );
  5198. /**
  5199. * Represents the object's transformation matrix in local space.
  5200. *
  5201. * @type {Matrix4}
  5202. */
  5203. this.matrix = new Matrix4();
  5204. /**
  5205. * Represents the object's transformation matrix in world space.
  5206. * If the 3D object has no parent, then it's identical to the local transformation matrix
  5207. *
  5208. * @type {Matrix4}
  5209. */
  5210. this.matrixWorld = new Matrix4();
  5211. /**
  5212. * When set to `true`, the engine automatically computes the local matrix from position,
  5213. * rotation and scale every frame.
  5214. *
  5215. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  5216. *
  5217. * @type {boolean}
  5218. * @default true
  5219. */
  5220. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  5221. /**
  5222. * When set to `true`, the engine automatically computes the world matrix from the current local
  5223. * matrix and the object's transformation hierarchy.
  5224. *
  5225. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  5226. *
  5227. * @type {boolean}
  5228. * @default true
  5229. */
  5230. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  5231. /**
  5232. * When set to `true`, it calculates the world matrix in that frame and resets this property
  5233. * to `false`.
  5234. *
  5235. * @type {boolean}
  5236. * @default false
  5237. */
  5238. this.matrixWorldNeedsUpdate = false;
  5239. /**
  5240. * The layer membership of the 3D object. The 3D object is only visible if it has
  5241. * at least one layer in common with the camera in use. This property can also be
  5242. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  5243. *
  5244. * @type {Layers}
  5245. */
  5246. this.layers = new Layers();
  5247. /**
  5248. * When set to `true`, the 3D object gets rendered.
  5249. *
  5250. * @type {boolean}
  5251. * @default true
  5252. */
  5253. this.visible = true;
  5254. /**
  5255. * When set to `true`, the 3D object gets rendered into shadow maps.
  5256. *
  5257. * @type {boolean}
  5258. * @default false
  5259. */
  5260. this.castShadow = false;
  5261. /**
  5262. * When set to `true`, the 3D object is affected by shadows in the scene.
  5263. *
  5264. * @type {boolean}
  5265. * @default false
  5266. */
  5267. this.receiveShadow = false;
  5268. /**
  5269. * When set to `true`, the 3D object is honored by view frustum culling.
  5270. *
  5271. * @type {boolean}
  5272. * @default true
  5273. */
  5274. this.frustumCulled = true;
  5275. /**
  5276. * This value allows the default rendering order of scene graph objects to be
  5277. * overridden although opaque and transparent objects remain sorted independently.
  5278. * When this property is set for an instance of {@link Group},all descendants
  5279. * objects will be sorted and rendered together. Sorting is from lowest to highest
  5280. * render order.
  5281. *
  5282. * @type {number}
  5283. * @default 0
  5284. */
  5285. this.renderOrder = 0;
  5286. /**
  5287. * An array holding the animation clips of the 3D object.
  5288. *
  5289. * @type {Array<AnimationClip>}
  5290. */
  5291. this.animations = [];
  5292. /**
  5293. * An object that can be used to store custom data about the 3D object. It
  5294. * should not hold references to functions as these will not be cloned.
  5295. *
  5296. * @type {Object}
  5297. */
  5298. this.userData = {};
  5299. }
  5300. /**
  5301. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  5302. *
  5303. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  5304. * @param {Object3D} object - The 3D object.
  5305. * @param {Camera} camera - The camera that is used to render the scene.
  5306. * @param {Camera} shadowCamera - The shadow camera.
  5307. * @param {BufferGeometry} geometry - The 3D object's geometry.
  5308. * @param {Material} depthMaterial - The depth material.
  5309. * @param {Object} group - The geometry group data.
  5310. */
  5311. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  5312. /**
  5313. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  5314. *
  5315. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  5316. * @param {Object3D} object - The 3D object.
  5317. * @param {Camera} camera - The camera that is used to render the scene.
  5318. * @param {Camera} shadowCamera - The shadow camera.
  5319. * @param {BufferGeometry} geometry - The 3D object's geometry.
  5320. * @param {Material} depthMaterial - The depth material.
  5321. * @param {Object} group - The geometry group data.
  5322. */
  5323. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  5324. /**
  5325. * A callback that is executed immediately before a 3D object is rendered.
  5326. *
  5327. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  5328. * @param {Object3D} object - The 3D object.
  5329. * @param {Camera} camera - The camera that is used to render the scene.
  5330. * @param {BufferGeometry} geometry - The 3D object's geometry.
  5331. * @param {Material} material - The 3D object's material.
  5332. * @param {Object} group - The geometry group data.
  5333. */
  5334. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  5335. /**
  5336. * A callback that is executed immediately after a 3D object is rendered.
  5337. *
  5338. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  5339. * @param {Object3D} object - The 3D object.
  5340. * @param {Camera} camera - The camera that is used to render the scene.
  5341. * @param {BufferGeometry} geometry - The 3D object's geometry.
  5342. * @param {Material} material - The 3D object's material.
  5343. * @param {Object} group - The geometry group data.
  5344. */
  5345. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  5346. /**
  5347. * Applies the given transformation matrix to the object and updates the object's position,
  5348. * rotation and scale.
  5349. *
  5350. * @param {Matrix4} matrix - The transformation matrix.
  5351. */
  5352. applyMatrix4( matrix ) {
  5353. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5354. this.matrix.premultiply( matrix );
  5355. this.matrix.decompose( this.position, this.quaternion, this.scale );
  5356. }
  5357. /**
  5358. * Applies a rotation represented by given the quaternion to the 3D object.
  5359. *
  5360. * @param {Quaternion} q - The quaterion.
  5361. * @return {Object3D} A reference to this instance.
  5362. */
  5363. applyQuaternion( q ) {
  5364. this.quaternion.premultiply( q );
  5365. return this;
  5366. }
  5367. /**
  5368. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  5369. *
  5370. * @param {Vector3} axis - The (normalized) axis vector.
  5371. * @param {number} angle - The angle in radians.
  5372. */
  5373. setRotationFromAxisAngle( axis, angle ) {
  5374. // assumes axis is normalized
  5375. this.quaternion.setFromAxisAngle( axis, angle );
  5376. }
  5377. /**
  5378. * Sets the given rotation represented as Euler angles to the 3D object.
  5379. *
  5380. * @param {Euler} euler - The Euler angles.
  5381. */
  5382. setRotationFromEuler( euler ) {
  5383. this.quaternion.setFromEuler( euler, true );
  5384. }
  5385. /**
  5386. * Sets the given rotation represented as rotation matrix to the 3D object.
  5387. *
  5388. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  5389. * a pure rotation matrix (i.e, unscaled).
  5390. */
  5391. setRotationFromMatrix( m ) {
  5392. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5393. this.quaternion.setFromRotationMatrix( m );
  5394. }
  5395. /**
  5396. * Sets the given rotation represented as a Quanterion to the 3D object.
  5397. *
  5398. * @param {Quaternion} q - The Quanterion
  5399. */
  5400. setRotationFromQuaternion( q ) {
  5401. // assumes q is normalized
  5402. this.quaternion.copy( q );
  5403. }
  5404. /**
  5405. * Rotates the 3D object along an axis in local space.
  5406. *
  5407. * @param {Vector3} axis - The (normalized) axis vector.
  5408. * @param {number} angle - The angle in radians.
  5409. * @return {Object3D} A reference to this instance.
  5410. */
  5411. rotateOnAxis( axis, angle ) {
  5412. // rotate object on axis in object space
  5413. // axis is assumed to be normalized
  5414. _q1.setFromAxisAngle( axis, angle );
  5415. this.quaternion.multiply( _q1 );
  5416. return this;
  5417. }
  5418. /**
  5419. * Rotates the 3D object along an axis in world space.
  5420. *
  5421. * @param {Vector3} axis - The (normalized) axis vector.
  5422. * @param {number} angle - The angle in radians.
  5423. * @return {Object3D} A reference to this instance.
  5424. */
  5425. rotateOnWorldAxis( axis, angle ) {
  5426. // rotate object on axis in world space
  5427. // axis is assumed to be normalized
  5428. // method assumes no rotated parent
  5429. _q1.setFromAxisAngle( axis, angle );
  5430. this.quaternion.premultiply( _q1 );
  5431. return this;
  5432. }
  5433. /**
  5434. * Rotates the 3D object around its X axis in local space.
  5435. *
  5436. * @param {number} angle - The angle in radians.
  5437. * @return {Object3D} A reference to this instance.
  5438. */
  5439. rotateX( angle ) {
  5440. return this.rotateOnAxis( _xAxis, angle );
  5441. }
  5442. /**
  5443. * Rotates the 3D object around its Y axis in local space.
  5444. *
  5445. * @param {number} angle - The angle in radians.
  5446. * @return {Object3D} A reference to this instance.
  5447. */
  5448. rotateY( angle ) {
  5449. return this.rotateOnAxis( _yAxis, angle );
  5450. }
  5451. /**
  5452. * Rotates the 3D object around its Z axis in local space.
  5453. *
  5454. * @param {number} angle - The angle in radians.
  5455. * @return {Object3D} A reference to this instance.
  5456. */
  5457. rotateZ( angle ) {
  5458. return this.rotateOnAxis( _zAxis, angle );
  5459. }
  5460. /**
  5461. * Translate the 3D object by a distance along the given axis in local space.
  5462. *
  5463. * @param {Vector3} axis - The (normalized) axis vector.
  5464. * @param {number} distance - The distance in world units.
  5465. * @return {Object3D} A reference to this instance.
  5466. */
  5467. translateOnAxis( axis, distance ) {
  5468. // translate object by distance along axis in object space
  5469. // axis is assumed to be normalized
  5470. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  5471. this.position.add( _v1$4.multiplyScalar( distance ) );
  5472. return this;
  5473. }
  5474. /**
  5475. * Translate the 3D object by a distance along its X-axis in local space.
  5476. *
  5477. * @param {number} distance - The distance in world units.
  5478. * @return {Object3D} A reference to this instance.
  5479. */
  5480. translateX( distance ) {
  5481. return this.translateOnAxis( _xAxis, distance );
  5482. }
  5483. /**
  5484. * Translate the 3D object by a distance along its Y-axis in local space.
  5485. *
  5486. * @param {number} distance - The distance in world units.
  5487. * @return {Object3D} A reference to this instance.
  5488. */
  5489. translateY( distance ) {
  5490. return this.translateOnAxis( _yAxis, distance );
  5491. }
  5492. /**
  5493. * Translate the 3D object by a distance along its Z-axis in local space.
  5494. *
  5495. * @param {number} distance - The distance in world units.
  5496. * @return {Object3D} A reference to this instance.
  5497. */
  5498. translateZ( distance ) {
  5499. return this.translateOnAxis( _zAxis, distance );
  5500. }
  5501. /**
  5502. * Converts the given vector from this 3D object's local space to world space.
  5503. *
  5504. * @param {Vector3} vector - The vector to convert.
  5505. * @return {Vector3} The converted vector.
  5506. */
  5507. localToWorld( vector ) {
  5508. this.updateWorldMatrix( true, false );
  5509. return vector.applyMatrix4( this.matrixWorld );
  5510. }
  5511. /**
  5512. * Converts the given vector from this 3D object's word space to local space.
  5513. *
  5514. * @param {Vector3} vector - The vector to convert.
  5515. * @return {Vector3} The converted vector.
  5516. */
  5517. worldToLocal( vector ) {
  5518. this.updateWorldMatrix( true, false );
  5519. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  5520. }
  5521. /**
  5522. * Rotates the object to face a point in world space.
  5523. *
  5524. * This method does not support objects having non-uniformly-scaled parent(s).
  5525. *
  5526. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  5527. * @param {number} [y] - The y coordinate in world space.
  5528. * @param {number} [z] - The z coordinate in world space.
  5529. */
  5530. lookAt( x, y, z ) {
  5531. // This method does not support objects having non-uniformly-scaled parent(s)
  5532. if ( x.isVector3 ) {
  5533. _target.copy( x );
  5534. } else {
  5535. _target.set( x, y, z );
  5536. }
  5537. const parent = this.parent;
  5538. this.updateWorldMatrix( true, false );
  5539. _position$3.setFromMatrixPosition( this.matrixWorld );
  5540. if ( this.isCamera || this.isLight ) {
  5541. _m1$3.lookAt( _position$3, _target, this.up );
  5542. } else {
  5543. _m1$3.lookAt( _target, _position$3, this.up );
  5544. }
  5545. this.quaternion.setFromRotationMatrix( _m1$3 );
  5546. if ( parent ) {
  5547. _m1$3.extractRotation( parent.matrixWorld );
  5548. _q1.setFromRotationMatrix( _m1$3 );
  5549. this.quaternion.premultiply( _q1.invert() );
  5550. }
  5551. }
  5552. /**
  5553. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  5554. * objects may be added. Any current parent on an object passed in here will be
  5555. * removed, since an object can have at most one parent.
  5556. *
  5557. * @fires Object3D#added
  5558. * @fires Object3D#childadded
  5559. * @param {Object3D} object - The 3D object to add.
  5560. * @return {Object3D} A reference to this instance.
  5561. */
  5562. add( object ) {
  5563. if ( arguments.length > 1 ) {
  5564. for ( let i = 0; i < arguments.length; i ++ ) {
  5565. this.add( arguments[ i ] );
  5566. }
  5567. return this;
  5568. }
  5569. if ( object === this ) {
  5570. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  5571. return this;
  5572. }
  5573. if ( object && object.isObject3D ) {
  5574. object.removeFromParent();
  5575. object.parent = this;
  5576. this.children.push( object );
  5577. object.dispatchEvent( _addedEvent );
  5578. _childaddedEvent.child = object;
  5579. this.dispatchEvent( _childaddedEvent );
  5580. _childaddedEvent.child = null;
  5581. } else {
  5582. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  5583. }
  5584. return this;
  5585. }
  5586. /**
  5587. * Removes the given 3D object as child from this 3D object.
  5588. * An arbitrary number of objects may be removed.
  5589. *
  5590. * @fires Object3D#removed
  5591. * @fires Object3D#childremoved
  5592. * @param {Object3D} object - The 3D object to remove.
  5593. * @return {Object3D} A reference to this instance.
  5594. */
  5595. remove( object ) {
  5596. if ( arguments.length > 1 ) {
  5597. for ( let i = 0; i < arguments.length; i ++ ) {
  5598. this.remove( arguments[ i ] );
  5599. }
  5600. return this;
  5601. }
  5602. const index = this.children.indexOf( object );
  5603. if ( index !== -1 ) {
  5604. object.parent = null;
  5605. this.children.splice( index, 1 );
  5606. object.dispatchEvent( _removedEvent );
  5607. _childremovedEvent.child = object;
  5608. this.dispatchEvent( _childremovedEvent );
  5609. _childremovedEvent.child = null;
  5610. }
  5611. return this;
  5612. }
  5613. /**
  5614. * Removes this 3D object from its current parent.
  5615. *
  5616. * @fires Object3D#removed
  5617. * @fires Object3D#childremoved
  5618. * @return {Object3D} A reference to this instance.
  5619. */
  5620. removeFromParent() {
  5621. const parent = this.parent;
  5622. if ( parent !== null ) {
  5623. parent.remove( this );
  5624. }
  5625. return this;
  5626. }
  5627. /**
  5628. * Removes all child objects.
  5629. *
  5630. * @fires Object3D#removed
  5631. * @fires Object3D#childremoved
  5632. * @return {Object3D} A reference to this instance.
  5633. */
  5634. clear() {
  5635. return this.remove( ... this.children );
  5636. }
  5637. /**
  5638. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  5639. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  5640. *
  5641. * @fires Object3D#added
  5642. * @fires Object3D#childadded
  5643. * @param {Object3D} object - The 3D object to attach.
  5644. * @return {Object3D} A reference to this instance.
  5645. */
  5646. attach( object ) {
  5647. // adds object as a child of this, while maintaining the object's world transform
  5648. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  5649. this.updateWorldMatrix( true, false );
  5650. _m1$3.copy( this.matrixWorld ).invert();
  5651. if ( object.parent !== null ) {
  5652. object.parent.updateWorldMatrix( true, false );
  5653. _m1$3.multiply( object.parent.matrixWorld );
  5654. }
  5655. object.applyMatrix4( _m1$3 );
  5656. object.removeFromParent();
  5657. object.parent = this;
  5658. this.children.push( object );
  5659. object.updateWorldMatrix( false, true );
  5660. object.dispatchEvent( _addedEvent );
  5661. _childaddedEvent.child = object;
  5662. this.dispatchEvent( _childaddedEvent );
  5663. _childaddedEvent.child = null;
  5664. return this;
  5665. }
  5666. /**
  5667. * Searches through the 3D object and its children, starting with the 3D object
  5668. * itself, and returns the first with a matching ID.
  5669. *
  5670. * @param {number} id - The id.
  5671. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  5672. */
  5673. getObjectById( id ) {
  5674. return this.getObjectByProperty( 'id', id );
  5675. }
  5676. /**
  5677. * Searches through the 3D object and its children, starting with the 3D object
  5678. * itself, and returns the first with a matching name.
  5679. *
  5680. * @param {string} name - The name.
  5681. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  5682. */
  5683. getObjectByName( name ) {
  5684. return this.getObjectByProperty( 'name', name );
  5685. }
  5686. /**
  5687. * Searches through the 3D object and its children, starting with the 3D object
  5688. * itself, and returns the first with a matching property value.
  5689. *
  5690. * @param {string} name - The name of the property.
  5691. * @param {any} value - The value.
  5692. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  5693. */
  5694. getObjectByProperty( name, value ) {
  5695. if ( this[ name ] === value ) return this;
  5696. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  5697. const child = this.children[ i ];
  5698. const object = child.getObjectByProperty( name, value );
  5699. if ( object !== undefined ) {
  5700. return object;
  5701. }
  5702. }
  5703. return undefined;
  5704. }
  5705. /**
  5706. * Searches through the 3D object and its children, starting with the 3D object
  5707. * itself, and returns all 3D objects with a matching property value.
  5708. *
  5709. * @param {string} name - The name of the property.
  5710. * @param {any} value - The value.
  5711. * @param {Array<Object3D>} result - The method stores the result in this array.
  5712. * @return {Array<Object3D>} The found 3D objects.
  5713. */
  5714. getObjectsByProperty( name, value, result = [] ) {
  5715. if ( this[ name ] === value ) result.push( this );
  5716. const children = this.children;
  5717. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5718. children[ i ].getObjectsByProperty( name, value, result );
  5719. }
  5720. return result;
  5721. }
  5722. /**
  5723. * Returns a vector representing the position of the 3D object in world space.
  5724. *
  5725. * @param {Vector3} target - The target vector the result is stored to.
  5726. * @return {Vector3} The 3D object's position in world space.
  5727. */
  5728. getWorldPosition( target ) {
  5729. this.updateWorldMatrix( true, false );
  5730. return target.setFromMatrixPosition( this.matrixWorld );
  5731. }
  5732. /**
  5733. * Returns a Quaternion representing the position of the 3D object in world space.
  5734. *
  5735. * @param {Quaternion} target - The target Quaternion the result is stored to.
  5736. * @return {Quaternion} The 3D object's rotation in world space.
  5737. */
  5738. getWorldQuaternion( target ) {
  5739. this.updateWorldMatrix( true, false );
  5740. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  5741. return target;
  5742. }
  5743. /**
  5744. * Returns a vector representing the scale of the 3D object in world space.
  5745. *
  5746. * @param {Vector3} target - The target vector the result is stored to.
  5747. * @return {Vector3} The 3D object's scale in world space.
  5748. */
  5749. getWorldScale( target ) {
  5750. this.updateWorldMatrix( true, false );
  5751. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  5752. return target;
  5753. }
  5754. /**
  5755. * Returns a vector representing the ("look") direction of the 3D object in world space.
  5756. *
  5757. * @param {Vector3} target - The target vector the result is stored to.
  5758. * @return {Vector3} The 3D object's direction in world space.
  5759. */
  5760. getWorldDirection( target ) {
  5761. this.updateWorldMatrix( true, false );
  5762. const e = this.matrixWorld.elements;
  5763. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  5764. }
  5765. /**
  5766. * Abstract method to get intersections between a casted ray and this
  5767. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  5768. * implement this method in order to use raycasting.
  5769. *
  5770. * @abstract
  5771. * @param {Raycaster} raycaster - The raycaster.
  5772. * @param {Array<Object>} intersects - An array holding the result of the method.
  5773. */
  5774. raycast( /* raycaster, intersects */ ) {}
  5775. /**
  5776. * Executes the callback on this 3D object and all descendants.
  5777. *
  5778. * Note: Modifying the scene graph inside the callback is discouraged.
  5779. *
  5780. * @param {Function} callback - A callback function that allows to process the current 3D object.
  5781. */
  5782. traverse( callback ) {
  5783. callback( this );
  5784. const children = this.children;
  5785. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5786. children[ i ].traverse( callback );
  5787. }
  5788. }
  5789. /**
  5790. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  5791. * Descendants of invisible 3D objects are not traversed.
  5792. *
  5793. * Note: Modifying the scene graph inside the callback is discouraged.
  5794. *
  5795. * @param {Function} callback - A callback function that allows to process the current 3D object.
  5796. */
  5797. traverseVisible( callback ) {
  5798. if ( this.visible === false ) return;
  5799. callback( this );
  5800. const children = this.children;
  5801. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5802. children[ i ].traverseVisible( callback );
  5803. }
  5804. }
  5805. /**
  5806. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  5807. *
  5808. * Note: Modifying the scene graph inside the callback is discouraged.
  5809. *
  5810. * @param {Function} callback - A callback function that allows to process the current 3D object.
  5811. */
  5812. traverseAncestors( callback ) {
  5813. const parent = this.parent;
  5814. if ( parent !== null ) {
  5815. callback( parent );
  5816. parent.traverseAncestors( callback );
  5817. }
  5818. }
  5819. /**
  5820. * Updates the transformation matrix in local space by computing it from the current
  5821. * positon, rotation and scale values.
  5822. */
  5823. updateMatrix() {
  5824. this.matrix.compose( this.position, this.quaternion, this.scale );
  5825. this.matrixWorldNeedsUpdate = true;
  5826. }
  5827. /**
  5828. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  5829. *
  5830. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  5831. * local space. The computation of the local and world matrix can be controlled with the
  5832. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  5833. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  5834. *
  5835. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  5836. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  5837. */
  5838. updateMatrixWorld( force ) {
  5839. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5840. if ( this.matrixWorldNeedsUpdate || force ) {
  5841. if ( this.matrixWorldAutoUpdate === true ) {
  5842. if ( this.parent === null ) {
  5843. this.matrixWorld.copy( this.matrix );
  5844. } else {
  5845. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5846. }
  5847. }
  5848. this.matrixWorldNeedsUpdate = false;
  5849. force = true;
  5850. }
  5851. // make sure descendants are updated if required
  5852. const children = this.children;
  5853. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5854. const child = children[ i ];
  5855. child.updateMatrixWorld( force );
  5856. }
  5857. }
  5858. /**
  5859. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  5860. * update of ancestor and descendant nodes.
  5861. *
  5862. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  5863. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  5864. */
  5865. updateWorldMatrix( updateParents, updateChildren ) {
  5866. const parent = this.parent;
  5867. if ( updateParents === true && parent !== null ) {
  5868. parent.updateWorldMatrix( true, false );
  5869. }
  5870. if ( this.matrixAutoUpdate ) this.updateMatrix();
  5871. if ( this.matrixWorldAutoUpdate === true ) {
  5872. if ( this.parent === null ) {
  5873. this.matrixWorld.copy( this.matrix );
  5874. } else {
  5875. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5876. }
  5877. }
  5878. // make sure descendants are updated
  5879. if ( updateChildren === true ) {
  5880. const children = this.children;
  5881. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5882. const child = children[ i ];
  5883. child.updateWorldMatrix( false, true );
  5884. }
  5885. }
  5886. }
  5887. /**
  5888. * Serializes the 3D object into JSON.
  5889. *
  5890. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5891. * @return {Object} A JSON object representing the serialized 3D object.
  5892. * @see {@link ObjectLoader#parse}
  5893. */
  5894. toJSON( meta ) {
  5895. // meta is a string when called from JSON.stringify
  5896. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5897. const output = {};
  5898. // meta is a hash used to collect geometries, materials.
  5899. // not providing it implies that this is the root object
  5900. // being serialized.
  5901. if ( isRootObject ) {
  5902. // initialize meta obj
  5903. meta = {
  5904. geometries: {},
  5905. materials: {},
  5906. textures: {},
  5907. images: {},
  5908. shapes: {},
  5909. skeletons: {},
  5910. animations: {},
  5911. nodes: {}
  5912. };
  5913. output.metadata = {
  5914. version: 4.6,
  5915. type: 'Object',
  5916. generator: 'Object3D.toJSON'
  5917. };
  5918. }
  5919. // standard Object3D serialization
  5920. const object = {};
  5921. object.uuid = this.uuid;
  5922. object.type = this.type;
  5923. if ( this.name !== '' ) object.name = this.name;
  5924. if ( this.castShadow === true ) object.castShadow = true;
  5925. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5926. if ( this.visible === false ) object.visible = false;
  5927. if ( this.frustumCulled === false ) object.frustumCulled = false;
  5928. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  5929. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  5930. object.layers = this.layers.mask;
  5931. object.matrix = this.matrix.toArray();
  5932. object.up = this.up.toArray();
  5933. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  5934. // object specific properties
  5935. if ( this.isInstancedMesh ) {
  5936. object.type = 'InstancedMesh';
  5937. object.count = this.count;
  5938. object.instanceMatrix = this.instanceMatrix.toJSON();
  5939. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  5940. }
  5941. if ( this.isBatchedMesh ) {
  5942. object.type = 'BatchedMesh';
  5943. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  5944. object.sortObjects = this.sortObjects;
  5945. object.drawRanges = this._drawRanges;
  5946. object.reservedRanges = this._reservedRanges;
  5947. object.visibility = this._visibility;
  5948. object.active = this._active;
  5949. object.bounds = this._bounds.map( bound => ( {
  5950. boxInitialized: bound.boxInitialized,
  5951. boxMin: bound.box.min.toArray(),
  5952. boxMax: bound.box.max.toArray(),
  5953. sphereInitialized: bound.sphereInitialized,
  5954. sphereRadius: bound.sphere.radius,
  5955. sphereCenter: bound.sphere.center.toArray()
  5956. } ) );
  5957. object.maxInstanceCount = this._maxInstanceCount;
  5958. object.maxVertexCount = this._maxVertexCount;
  5959. object.maxIndexCount = this._maxIndexCount;
  5960. object.geometryInitialized = this._geometryInitialized;
  5961. object.geometryCount = this._geometryCount;
  5962. object.matricesTexture = this._matricesTexture.toJSON( meta );
  5963. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  5964. if ( this.boundingSphere !== null ) {
  5965. object.boundingSphere = {
  5966. center: object.boundingSphere.center.toArray(),
  5967. radius: object.boundingSphere.radius
  5968. };
  5969. }
  5970. if ( this.boundingBox !== null ) {
  5971. object.boundingBox = {
  5972. min: object.boundingBox.min.toArray(),
  5973. max: object.boundingBox.max.toArray()
  5974. };
  5975. }
  5976. }
  5977. //
  5978. function serialize( library, element ) {
  5979. if ( library[ element.uuid ] === undefined ) {
  5980. library[ element.uuid ] = element.toJSON( meta );
  5981. }
  5982. return element.uuid;
  5983. }
  5984. if ( this.isScene ) {
  5985. if ( this.background ) {
  5986. if ( this.background.isColor ) {
  5987. object.background = this.background.toJSON();
  5988. } else if ( this.background.isTexture ) {
  5989. object.background = this.background.toJSON( meta ).uuid;
  5990. }
  5991. }
  5992. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  5993. object.environment = this.environment.toJSON( meta ).uuid;
  5994. }
  5995. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  5996. object.geometry = serialize( meta.geometries, this.geometry );
  5997. const parameters = this.geometry.parameters;
  5998. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  5999. const shapes = parameters.shapes;
  6000. if ( Array.isArray( shapes ) ) {
  6001. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  6002. const shape = shapes[ i ];
  6003. serialize( meta.shapes, shape );
  6004. }
  6005. } else {
  6006. serialize( meta.shapes, shapes );
  6007. }
  6008. }
  6009. }
  6010. if ( this.isSkinnedMesh ) {
  6011. object.bindMode = this.bindMode;
  6012. object.bindMatrix = this.bindMatrix.toArray();
  6013. if ( this.skeleton !== undefined ) {
  6014. serialize( meta.skeletons, this.skeleton );
  6015. object.skeleton = this.skeleton.uuid;
  6016. }
  6017. }
  6018. if ( this.material !== undefined ) {
  6019. if ( Array.isArray( this.material ) ) {
  6020. const uuids = [];
  6021. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  6022. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  6023. }
  6024. object.material = uuids;
  6025. } else {
  6026. object.material = serialize( meta.materials, this.material );
  6027. }
  6028. }
  6029. //
  6030. if ( this.children.length > 0 ) {
  6031. object.children = [];
  6032. for ( let i = 0; i < this.children.length; i ++ ) {
  6033. object.children.push( this.children[ i ].toJSON( meta ).object );
  6034. }
  6035. }
  6036. //
  6037. if ( this.animations.length > 0 ) {
  6038. object.animations = [];
  6039. for ( let i = 0; i < this.animations.length; i ++ ) {
  6040. const animation = this.animations[ i ];
  6041. object.animations.push( serialize( meta.animations, animation ) );
  6042. }
  6043. }
  6044. if ( isRootObject ) {
  6045. const geometries = extractFromCache( meta.geometries );
  6046. const materials = extractFromCache( meta.materials );
  6047. const textures = extractFromCache( meta.textures );
  6048. const images = extractFromCache( meta.images );
  6049. const shapes = extractFromCache( meta.shapes );
  6050. const skeletons = extractFromCache( meta.skeletons );
  6051. const animations = extractFromCache( meta.animations );
  6052. const nodes = extractFromCache( meta.nodes );
  6053. if ( geometries.length > 0 ) output.geometries = geometries;
  6054. if ( materials.length > 0 ) output.materials = materials;
  6055. if ( textures.length > 0 ) output.textures = textures;
  6056. if ( images.length > 0 ) output.images = images;
  6057. if ( shapes.length > 0 ) output.shapes = shapes;
  6058. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  6059. if ( animations.length > 0 ) output.animations = animations;
  6060. if ( nodes.length > 0 ) output.nodes = nodes;
  6061. }
  6062. output.object = object;
  6063. return output;
  6064. // extract data from the cache hash
  6065. // remove metadata on each item
  6066. // and return as array
  6067. function extractFromCache( cache ) {
  6068. const values = [];
  6069. for ( const key in cache ) {
  6070. const data = cache[ key ];
  6071. delete data.metadata;
  6072. values.push( data );
  6073. }
  6074. return values;
  6075. }
  6076. }
  6077. /**
  6078. * Returns a new 3D object with copied values from this instance.
  6079. *
  6080. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  6081. * @return {Object3D} A clone of this instance.
  6082. */
  6083. clone( recursive ) {
  6084. return new this.constructor().copy( this, recursive );
  6085. }
  6086. /**
  6087. * Copies the values of the given 3D object to this instance.
  6088. *
  6089. * @param {Object3D} source - The 3D object to copy.
  6090. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  6091. * @return {Object3D} A reference to this instance.
  6092. */
  6093. copy( source, recursive = true ) {
  6094. this.name = source.name;
  6095. this.up.copy( source.up );
  6096. this.position.copy( source.position );
  6097. this.rotation.order = source.rotation.order;
  6098. this.quaternion.copy( source.quaternion );
  6099. this.scale.copy( source.scale );
  6100. this.matrix.copy( source.matrix );
  6101. this.matrixWorld.copy( source.matrixWorld );
  6102. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6103. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  6104. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  6105. this.layers.mask = source.layers.mask;
  6106. this.visible = source.visible;
  6107. this.castShadow = source.castShadow;
  6108. this.receiveShadow = source.receiveShadow;
  6109. this.frustumCulled = source.frustumCulled;
  6110. this.renderOrder = source.renderOrder;
  6111. this.animations = source.animations.slice();
  6112. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6113. if ( recursive === true ) {
  6114. for ( let i = 0; i < source.children.length; i ++ ) {
  6115. const child = source.children[ i ];
  6116. this.add( child.clone() );
  6117. }
  6118. }
  6119. return this;
  6120. }
  6121. }
  6122. /**
  6123. * The default up direction for objects, also used as the default
  6124. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  6125. *
  6126. * @static
  6127. * @type {Vector3}
  6128. * @default (0,1,0)
  6129. */
  6130. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  6131. /**
  6132. * The default setting for {@link Object3D#matrixAutoUpdate} for
  6133. * newly created 3D objects.
  6134. *
  6135. * @static
  6136. * @type {boolean}
  6137. * @default true
  6138. */
  6139. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  6140. /**
  6141. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  6142. * newly created 3D objects.
  6143. *
  6144. * @static
  6145. * @type {boolean}
  6146. * @default true
  6147. */
  6148. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  6149. const _v0$2 = /*@__PURE__*/ new Vector3();
  6150. const _v1$3 = /*@__PURE__*/ new Vector3();
  6151. const _v2$2 = /*@__PURE__*/ new Vector3();
  6152. const _v3$2 = /*@__PURE__*/ new Vector3();
  6153. const _vab = /*@__PURE__*/ new Vector3();
  6154. const _vac = /*@__PURE__*/ new Vector3();
  6155. const _vbc = /*@__PURE__*/ new Vector3();
  6156. const _vap = /*@__PURE__*/ new Vector3();
  6157. const _vbp = /*@__PURE__*/ new Vector3();
  6158. const _vcp = /*@__PURE__*/ new Vector3();
  6159. const _v40 = /*@__PURE__*/ new Vector4();
  6160. const _v41 = /*@__PURE__*/ new Vector4();
  6161. const _v42 = /*@__PURE__*/ new Vector4();
  6162. class Triangle {
  6163. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  6164. this.a = a;
  6165. this.b = b;
  6166. this.c = c;
  6167. }
  6168. static getNormal( a, b, c, target ) {
  6169. target.subVectors( c, b );
  6170. _v0$2.subVectors( a, b );
  6171. target.cross( _v0$2 );
  6172. const targetLengthSq = target.lengthSq();
  6173. if ( targetLengthSq > 0 ) {
  6174. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  6175. }
  6176. return target.set( 0, 0, 0 );
  6177. }
  6178. // static/instance method to calculate barycentric coordinates
  6179. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  6180. static getBarycoord( point, a, b, c, target ) {
  6181. _v0$2.subVectors( c, a );
  6182. _v1$3.subVectors( b, a );
  6183. _v2$2.subVectors( point, a );
  6184. const dot00 = _v0$2.dot( _v0$2 );
  6185. const dot01 = _v0$2.dot( _v1$3 );
  6186. const dot02 = _v0$2.dot( _v2$2 );
  6187. const dot11 = _v1$3.dot( _v1$3 );
  6188. const dot12 = _v1$3.dot( _v2$2 );
  6189. const denom = ( dot00 * dot11 - dot01 * dot01 );
  6190. // collinear or singular triangle
  6191. if ( denom === 0 ) {
  6192. target.set( 0, 0, 0 );
  6193. return null;
  6194. }
  6195. const invDenom = 1 / denom;
  6196. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  6197. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  6198. // barycentric coordinates must always sum to 1
  6199. return target.set( 1 - u - v, v, u );
  6200. }
  6201. static containsPoint( point, a, b, c ) {
  6202. // if the triangle is degenerate then we can't contain a point
  6203. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  6204. return false;
  6205. }
  6206. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  6207. }
  6208. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  6209. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  6210. target.x = 0;
  6211. target.y = 0;
  6212. if ( 'z' in target ) target.z = 0;
  6213. if ( 'w' in target ) target.w = 0;
  6214. return null;
  6215. }
  6216. target.setScalar( 0 );
  6217. target.addScaledVector( v1, _v3$2.x );
  6218. target.addScaledVector( v2, _v3$2.y );
  6219. target.addScaledVector( v3, _v3$2.z );
  6220. return target;
  6221. }
  6222. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  6223. _v40.setScalar( 0 );
  6224. _v41.setScalar( 0 );
  6225. _v42.setScalar( 0 );
  6226. _v40.fromBufferAttribute( attr, i1 );
  6227. _v41.fromBufferAttribute( attr, i2 );
  6228. _v42.fromBufferAttribute( attr, i3 );
  6229. target.setScalar( 0 );
  6230. target.addScaledVector( _v40, barycoord.x );
  6231. target.addScaledVector( _v41, barycoord.y );
  6232. target.addScaledVector( _v42, barycoord.z );
  6233. return target;
  6234. }
  6235. static isFrontFacing( a, b, c, direction ) {
  6236. _v0$2.subVectors( c, b );
  6237. _v1$3.subVectors( a, b );
  6238. // strictly front facing
  6239. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  6240. }
  6241. set( a, b, c ) {
  6242. this.a.copy( a );
  6243. this.b.copy( b );
  6244. this.c.copy( c );
  6245. return this;
  6246. }
  6247. setFromPointsAndIndices( points, i0, i1, i2 ) {
  6248. this.a.copy( points[ i0 ] );
  6249. this.b.copy( points[ i1 ] );
  6250. this.c.copy( points[ i2 ] );
  6251. return this;
  6252. }
  6253. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  6254. this.a.fromBufferAttribute( attribute, i0 );
  6255. this.b.fromBufferAttribute( attribute, i1 );
  6256. this.c.fromBufferAttribute( attribute, i2 );
  6257. return this;
  6258. }
  6259. clone() {
  6260. return new this.constructor().copy( this );
  6261. }
  6262. copy( triangle ) {
  6263. this.a.copy( triangle.a );
  6264. this.b.copy( triangle.b );
  6265. this.c.copy( triangle.c );
  6266. return this;
  6267. }
  6268. getArea() {
  6269. _v0$2.subVectors( this.c, this.b );
  6270. _v1$3.subVectors( this.a, this.b );
  6271. return _v0$2.cross( _v1$3 ).length() * 0.5;
  6272. }
  6273. getMidpoint( target ) {
  6274. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  6275. }
  6276. getNormal( target ) {
  6277. return Triangle.getNormal( this.a, this.b, this.c, target );
  6278. }
  6279. getPlane( target ) {
  6280. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  6281. }
  6282. getBarycoord( point, target ) {
  6283. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  6284. }
  6285. getInterpolation( point, v1, v2, v3, target ) {
  6286. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  6287. }
  6288. containsPoint( point ) {
  6289. return Triangle.containsPoint( point, this.a, this.b, this.c );
  6290. }
  6291. isFrontFacing( direction ) {
  6292. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  6293. }
  6294. intersectsBox( box ) {
  6295. return box.intersectsTriangle( this );
  6296. }
  6297. closestPointToPoint( p, target ) {
  6298. const a = this.a, b = this.b, c = this.c;
  6299. let v, w;
  6300. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  6301. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  6302. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  6303. // basically, we're distinguishing which of the voronoi regions of the triangle
  6304. // the point lies in with the minimum amount of redundant computation.
  6305. _vab.subVectors( b, a );
  6306. _vac.subVectors( c, a );
  6307. _vap.subVectors( p, a );
  6308. const d1 = _vab.dot( _vap );
  6309. const d2 = _vac.dot( _vap );
  6310. if ( d1 <= 0 && d2 <= 0 ) {
  6311. // vertex region of A; barycentric coords (1, 0, 0)
  6312. return target.copy( a );
  6313. }
  6314. _vbp.subVectors( p, b );
  6315. const d3 = _vab.dot( _vbp );
  6316. const d4 = _vac.dot( _vbp );
  6317. if ( d3 >= 0 && d4 <= d3 ) {
  6318. // vertex region of B; barycentric coords (0, 1, 0)
  6319. return target.copy( b );
  6320. }
  6321. const vc = d1 * d4 - d3 * d2;
  6322. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  6323. v = d1 / ( d1 - d3 );
  6324. // edge region of AB; barycentric coords (1-v, v, 0)
  6325. return target.copy( a ).addScaledVector( _vab, v );
  6326. }
  6327. _vcp.subVectors( p, c );
  6328. const d5 = _vab.dot( _vcp );
  6329. const d6 = _vac.dot( _vcp );
  6330. if ( d6 >= 0 && d5 <= d6 ) {
  6331. // vertex region of C; barycentric coords (0, 0, 1)
  6332. return target.copy( c );
  6333. }
  6334. const vb = d5 * d2 - d1 * d6;
  6335. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  6336. w = d2 / ( d2 - d6 );
  6337. // edge region of AC; barycentric coords (1-w, 0, w)
  6338. return target.copy( a ).addScaledVector( _vac, w );
  6339. }
  6340. const va = d3 * d6 - d5 * d4;
  6341. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  6342. _vbc.subVectors( c, b );
  6343. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  6344. // edge region of BC; barycentric coords (0, 1-w, w)
  6345. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  6346. }
  6347. // face region
  6348. const denom = 1 / ( va + vb + vc );
  6349. // u = va * denom
  6350. v = vb * denom;
  6351. w = vc * denom;
  6352. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  6353. }
  6354. equals( triangle ) {
  6355. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  6356. }
  6357. }
  6358. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  6359. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  6360. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  6361. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  6362. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  6363. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  6364. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  6365. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  6366. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  6367. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  6368. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  6369. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  6370. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  6371. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  6372. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  6373. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  6374. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  6375. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  6376. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  6377. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  6378. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  6379. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  6380. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  6381. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  6382. const _hslA = { h: 0, s: 0, l: 0 };
  6383. const _hslB = { h: 0, s: 0, l: 0 };
  6384. function hue2rgb( p, q, t ) {
  6385. if ( t < 0 ) t += 1;
  6386. if ( t > 1 ) t -= 1;
  6387. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  6388. if ( t < 1 / 2 ) return q;
  6389. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  6390. return p;
  6391. }
  6392. class Color {
  6393. constructor( r, g, b ) {
  6394. this.isColor = true;
  6395. this.r = 1;
  6396. this.g = 1;
  6397. this.b = 1;
  6398. return this.set( r, g, b );
  6399. }
  6400. set( r, g, b ) {
  6401. if ( g === undefined && b === undefined ) {
  6402. // r is THREE.Color, hex or string
  6403. const value = r;
  6404. if ( value && value.isColor ) {
  6405. this.copy( value );
  6406. } else if ( typeof value === 'number' ) {
  6407. this.setHex( value );
  6408. } else if ( typeof value === 'string' ) {
  6409. this.setStyle( value );
  6410. }
  6411. } else {
  6412. this.setRGB( r, g, b );
  6413. }
  6414. return this;
  6415. }
  6416. setScalar( scalar ) {
  6417. this.r = scalar;
  6418. this.g = scalar;
  6419. this.b = scalar;
  6420. return this;
  6421. }
  6422. setHex( hex, colorSpace = SRGBColorSpace ) {
  6423. hex = Math.floor( hex );
  6424. this.r = ( hex >> 16 & 255 ) / 255;
  6425. this.g = ( hex >> 8 & 255 ) / 255;
  6426. this.b = ( hex & 255 ) / 255;
  6427. ColorManagement.toWorkingColorSpace( this, colorSpace );
  6428. return this;
  6429. }
  6430. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  6431. this.r = r;
  6432. this.g = g;
  6433. this.b = b;
  6434. ColorManagement.toWorkingColorSpace( this, colorSpace );
  6435. return this;
  6436. }
  6437. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  6438. // h,s,l ranges are in 0.0 - 1.0
  6439. h = euclideanModulo( h, 1 );
  6440. s = clamp( s, 0, 1 );
  6441. l = clamp( l, 0, 1 );
  6442. if ( s === 0 ) {
  6443. this.r = this.g = this.b = l;
  6444. } else {
  6445. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  6446. const q = ( 2 * l ) - p;
  6447. this.r = hue2rgb( q, p, h + 1 / 3 );
  6448. this.g = hue2rgb( q, p, h );
  6449. this.b = hue2rgb( q, p, h - 1 / 3 );
  6450. }
  6451. ColorManagement.toWorkingColorSpace( this, colorSpace );
  6452. return this;
  6453. }
  6454. setStyle( style, colorSpace = SRGBColorSpace ) {
  6455. function handleAlpha( string ) {
  6456. if ( string === undefined ) return;
  6457. if ( parseFloat( string ) < 1 ) {
  6458. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  6459. }
  6460. }
  6461. let m;
  6462. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  6463. // rgb / hsl
  6464. let color;
  6465. const name = m[ 1 ];
  6466. const components = m[ 2 ];
  6467. switch ( name ) {
  6468. case 'rgb':
  6469. case 'rgba':
  6470. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6471. // rgb(255,0,0) rgba(255,0,0,0.5)
  6472. handleAlpha( color[ 4 ] );
  6473. return this.setRGB(
  6474. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  6475. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  6476. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  6477. colorSpace
  6478. );
  6479. }
  6480. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6481. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  6482. handleAlpha( color[ 4 ] );
  6483. return this.setRGB(
  6484. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  6485. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  6486. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  6487. colorSpace
  6488. );
  6489. }
  6490. break;
  6491. case 'hsl':
  6492. case 'hsla':
  6493. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  6494. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  6495. handleAlpha( color[ 4 ] );
  6496. return this.setHSL(
  6497. parseFloat( color[ 1 ] ) / 360,
  6498. parseFloat( color[ 2 ] ) / 100,
  6499. parseFloat( color[ 3 ] ) / 100,
  6500. colorSpace
  6501. );
  6502. }
  6503. break;
  6504. default:
  6505. console.warn( 'THREE.Color: Unknown color model ' + style );
  6506. }
  6507. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  6508. // hex color
  6509. const hex = m[ 1 ];
  6510. const size = hex.length;
  6511. if ( size === 3 ) {
  6512. // #ff0
  6513. return this.setRGB(
  6514. parseInt( hex.charAt( 0 ), 16 ) / 15,
  6515. parseInt( hex.charAt( 1 ), 16 ) / 15,
  6516. parseInt( hex.charAt( 2 ), 16 ) / 15,
  6517. colorSpace
  6518. );
  6519. } else if ( size === 6 ) {
  6520. // #ff0000
  6521. return this.setHex( parseInt( hex, 16 ), colorSpace );
  6522. } else {
  6523. console.warn( 'THREE.Color: Invalid hex color ' + style );
  6524. }
  6525. } else if ( style && style.length > 0 ) {
  6526. return this.setColorName( style, colorSpace );
  6527. }
  6528. return this;
  6529. }
  6530. setColorName( style, colorSpace = SRGBColorSpace ) {
  6531. // color keywords
  6532. const hex = _colorKeywords[ style.toLowerCase() ];
  6533. if ( hex !== undefined ) {
  6534. // red
  6535. this.setHex( hex, colorSpace );
  6536. } else {
  6537. // unknown color
  6538. console.warn( 'THREE.Color: Unknown color ' + style );
  6539. }
  6540. return this;
  6541. }
  6542. clone() {
  6543. return new this.constructor( this.r, this.g, this.b );
  6544. }
  6545. copy( color ) {
  6546. this.r = color.r;
  6547. this.g = color.g;
  6548. this.b = color.b;
  6549. return this;
  6550. }
  6551. copySRGBToLinear( color ) {
  6552. this.r = SRGBToLinear( color.r );
  6553. this.g = SRGBToLinear( color.g );
  6554. this.b = SRGBToLinear( color.b );
  6555. return this;
  6556. }
  6557. copyLinearToSRGB( color ) {
  6558. this.r = LinearToSRGB( color.r );
  6559. this.g = LinearToSRGB( color.g );
  6560. this.b = LinearToSRGB( color.b );
  6561. return this;
  6562. }
  6563. convertSRGBToLinear() {
  6564. this.copySRGBToLinear( this );
  6565. return this;
  6566. }
  6567. convertLinearToSRGB() {
  6568. this.copyLinearToSRGB( this );
  6569. return this;
  6570. }
  6571. getHex( colorSpace = SRGBColorSpace ) {
  6572. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  6573. 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 ) );
  6574. }
  6575. getHexString( colorSpace = SRGBColorSpace ) {
  6576. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  6577. }
  6578. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  6579. // h,s,l ranges are in 0.0 - 1.0
  6580. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  6581. const r = _color.r, g = _color.g, b = _color.b;
  6582. const max = Math.max( r, g, b );
  6583. const min = Math.min( r, g, b );
  6584. let hue, saturation;
  6585. const lightness = ( min + max ) / 2.0;
  6586. if ( min === max ) {
  6587. hue = 0;
  6588. saturation = 0;
  6589. } else {
  6590. const delta = max - min;
  6591. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  6592. switch ( max ) {
  6593. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  6594. case g: hue = ( b - r ) / delta + 2; break;
  6595. case b: hue = ( r - g ) / delta + 4; break;
  6596. }
  6597. hue /= 6;
  6598. }
  6599. target.h = hue;
  6600. target.s = saturation;
  6601. target.l = lightness;
  6602. return target;
  6603. }
  6604. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  6605. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  6606. target.r = _color.r;
  6607. target.g = _color.g;
  6608. target.b = _color.b;
  6609. return target;
  6610. }
  6611. getStyle( colorSpace = SRGBColorSpace ) {
  6612. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  6613. const r = _color.r, g = _color.g, b = _color.b;
  6614. if ( colorSpace !== SRGBColorSpace ) {
  6615. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  6616. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  6617. }
  6618. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  6619. }
  6620. offsetHSL( h, s, l ) {
  6621. this.getHSL( _hslA );
  6622. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  6623. }
  6624. add( color ) {
  6625. this.r += color.r;
  6626. this.g += color.g;
  6627. this.b += color.b;
  6628. return this;
  6629. }
  6630. addColors( color1, color2 ) {
  6631. this.r = color1.r + color2.r;
  6632. this.g = color1.g + color2.g;
  6633. this.b = color1.b + color2.b;
  6634. return this;
  6635. }
  6636. addScalar( s ) {
  6637. this.r += s;
  6638. this.g += s;
  6639. this.b += s;
  6640. return this;
  6641. }
  6642. sub( color ) {
  6643. this.r = Math.max( 0, this.r - color.r );
  6644. this.g = Math.max( 0, this.g - color.g );
  6645. this.b = Math.max( 0, this.b - color.b );
  6646. return this;
  6647. }
  6648. multiply( color ) {
  6649. this.r *= color.r;
  6650. this.g *= color.g;
  6651. this.b *= color.b;
  6652. return this;
  6653. }
  6654. multiplyScalar( s ) {
  6655. this.r *= s;
  6656. this.g *= s;
  6657. this.b *= s;
  6658. return this;
  6659. }
  6660. lerp( color, alpha ) {
  6661. this.r += ( color.r - this.r ) * alpha;
  6662. this.g += ( color.g - this.g ) * alpha;
  6663. this.b += ( color.b - this.b ) * alpha;
  6664. return this;
  6665. }
  6666. lerpColors( color1, color2, alpha ) {
  6667. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  6668. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  6669. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  6670. return this;
  6671. }
  6672. lerpHSL( color, alpha ) {
  6673. this.getHSL( _hslA );
  6674. color.getHSL( _hslB );
  6675. const h = lerp( _hslA.h, _hslB.h, alpha );
  6676. const s = lerp( _hslA.s, _hslB.s, alpha );
  6677. const l = lerp( _hslA.l, _hslB.l, alpha );
  6678. this.setHSL( h, s, l );
  6679. return this;
  6680. }
  6681. setFromVector3( v ) {
  6682. this.r = v.x;
  6683. this.g = v.y;
  6684. this.b = v.z;
  6685. return this;
  6686. }
  6687. applyMatrix3( m ) {
  6688. const r = this.r, g = this.g, b = this.b;
  6689. const e = m.elements;
  6690. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  6691. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  6692. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  6693. return this;
  6694. }
  6695. equals( c ) {
  6696. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  6697. }
  6698. fromArray( array, offset = 0 ) {
  6699. this.r = array[ offset ];
  6700. this.g = array[ offset + 1 ];
  6701. this.b = array[ offset + 2 ];
  6702. return this;
  6703. }
  6704. toArray( array = [], offset = 0 ) {
  6705. array[ offset ] = this.r;
  6706. array[ offset + 1 ] = this.g;
  6707. array[ offset + 2 ] = this.b;
  6708. return array;
  6709. }
  6710. fromBufferAttribute( attribute, index ) {
  6711. this.r = attribute.getX( index );
  6712. this.g = attribute.getY( index );
  6713. this.b = attribute.getZ( index );
  6714. return this;
  6715. }
  6716. toJSON() {
  6717. return this.getHex();
  6718. }
  6719. *[ Symbol.iterator ]() {
  6720. yield this.r;
  6721. yield this.g;
  6722. yield this.b;
  6723. }
  6724. }
  6725. const _color = /*@__PURE__*/ new Color();
  6726. Color.NAMES = _colorKeywords;
  6727. let _materialId = 0;
  6728. /**
  6729. * Abstract base class for materials.
  6730. *
  6731. * Materials define the appearance of renderable 3D objects.
  6732. *
  6733. * @abstract
  6734. * @augments EventDispatcher
  6735. */
  6736. class Material extends EventDispatcher {
  6737. /**
  6738. * Constructs a new material.
  6739. */
  6740. constructor() {
  6741. super();
  6742. /**
  6743. * This flag can be used for type testing.
  6744. *
  6745. * @type {boolean}
  6746. * @readonly
  6747. * @default true
  6748. */
  6749. this.isMaterial = true;
  6750. /**
  6751. * The ID of the material.
  6752. *
  6753. * @name Material#id
  6754. * @type {number}
  6755. * @readonly
  6756. */
  6757. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  6758. /**
  6759. * The UUID of the material.
  6760. *
  6761. * @type {string}
  6762. * @readonly
  6763. */
  6764. this.uuid = generateUUID();
  6765. /**
  6766. * The name of the material.
  6767. *
  6768. * @type {string}
  6769. */
  6770. this.name = '';
  6771. /**
  6772. * The type property is used for detecting the object type
  6773. * in context of serialization/deserialization.
  6774. *
  6775. * @type {string}
  6776. * @readonly
  6777. */
  6778. this.type = 'Material';
  6779. /**
  6780. * Defines the blending type of the material.
  6781. *
  6782. * It must be set to `CustomBlending` if custom blending properties like
  6783. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  6784. * should have any effect.
  6785. *
  6786. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  6787. * @default NormalBlending
  6788. */
  6789. this.blending = NormalBlending;
  6790. /**
  6791. * Defines which side of faces will be rendered - front, back or both.
  6792. *
  6793. * @type {(FrontSide|BackSide|DoubleSide)}
  6794. * @default FrontSide
  6795. */
  6796. this.side = FrontSide;
  6797. /**
  6798. * If set to `true`, vertex colors should be used.
  6799. *
  6800. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  6801. * four (RGBA) component color buffer attribute is used.
  6802. *
  6803. * @type {boolean}
  6804. * @default false
  6805. */
  6806. this.vertexColors = false;
  6807. /**
  6808. * Defines how transparent the material is.
  6809. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  6810. *
  6811. * If the {@link Material#transparent} is not set to `true`,
  6812. * the material will remain fully opaque and this value will only affect its color.
  6813. *
  6814. * @type {number}
  6815. * @default 1
  6816. */
  6817. this.opacity = 1;
  6818. /**
  6819. * Defines whether this material is transparent. This has an effect on
  6820. * rendering as transparent objects need special treatment and are rendered
  6821. * after non-transparent objects.
  6822. *
  6823. * When set to true, the extent to which the material is transparent is
  6824. * controlled by {@link Material#opacity}.
  6825. *
  6826. * @type {boolean}
  6827. * @default false
  6828. */
  6829. this.transparent = false;
  6830. /**
  6831. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  6832. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  6833. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  6834. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  6835. *
  6836. * @type {boolean}
  6837. * @default false
  6838. */
  6839. this.alphaHash = false;
  6840. /**
  6841. * Defines the blending source factor.
  6842. *
  6843. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  6844. * @default SrcAlphaFactor
  6845. */
  6846. this.blendSrc = SrcAlphaFactor;
  6847. /**
  6848. * Defines the blending destination factor.
  6849. *
  6850. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  6851. * @default OneMinusSrcAlphaFactor
  6852. */
  6853. this.blendDst = OneMinusSrcAlphaFactor;
  6854. /**
  6855. * Defines the blending equation.
  6856. *
  6857. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  6858. * @default OneMinusSrcAlphaFactor
  6859. */
  6860. this.blendEquation = AddEquation;
  6861. /**
  6862. * Defines the blending source alpha factor.
  6863. *
  6864. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  6865. * @default null
  6866. */
  6867. this.blendSrcAlpha = null;
  6868. /**
  6869. * Defines the blending destination alpha factor.
  6870. *
  6871. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  6872. * @default null
  6873. */
  6874. this.blendDstAlpha = null;
  6875. /**
  6876. * Defines the blending equation of the alpha channel.
  6877. *
  6878. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  6879. * @default OneMinusSrcAlphaFactor
  6880. */
  6881. this.blendEquationAlpha = null;
  6882. /**
  6883. * Represents the RGB values of the constant blend color.
  6884. *
  6885. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  6886. *
  6887. * @type {Color}
  6888. * @default (0,0,0)
  6889. */
  6890. this.blendColor = new Color( 0, 0, 0 );
  6891. /**
  6892. * Represents the alpha value of the constant blend color.
  6893. *
  6894. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  6895. *
  6896. * @type {number}
  6897. * @default 0
  6898. */
  6899. this.blendAlpha = 0;
  6900. /**
  6901. * Defines the depth function.
  6902. *
  6903. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  6904. * @default LessEqualDepth
  6905. */
  6906. this.depthFunc = LessEqualDepth;
  6907. /**
  6908. * Whether to have depth test enabled when rendering this material.
  6909. * When the depth test is disabled, the depth write will also be implicitly disabled.
  6910. *
  6911. * @type {boolean}
  6912. * @default true
  6913. */
  6914. this.depthTest = true;
  6915. /**
  6916. * Whether rendering this material has any effect on the depth buffer.
  6917. *
  6918. * When drawing 2D overlays it can be useful to disable the depth writing in
  6919. * order to layer several things together without creating z-index artifacts.
  6920. *
  6921. * @type {boolean}
  6922. * @default true
  6923. */
  6924. this.depthWrite = true;
  6925. /**
  6926. * The bit mask to use when writing to the stencil buffer.
  6927. *
  6928. * @type {number}
  6929. * @default 0xff
  6930. */
  6931. this.stencilWriteMask = 0xff;
  6932. /**
  6933. * The stencil comparison function to use.
  6934. *
  6935. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  6936. * @default AlwaysStencilFunc
  6937. */
  6938. this.stencilFunc = AlwaysStencilFunc;
  6939. /**
  6940. * The value to use when performing stencil comparisons or stencil operations.
  6941. *
  6942. * @type {number}
  6943. * @default 0
  6944. */
  6945. this.stencilRef = 0;
  6946. /**
  6947. * The bit mask to use when comparing against the stencil buffer.
  6948. *
  6949. * @type {number}
  6950. * @default 0xff
  6951. */
  6952. this.stencilFuncMask = 0xff;
  6953. /**
  6954. * Which stencil operation to perform when the comparison function returns `false`.
  6955. *
  6956. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  6957. * @default KeepStencilOp
  6958. */
  6959. this.stencilFail = KeepStencilOp;
  6960. /**
  6961. * Which stencil operation to perform when the comparison function returns
  6962. * `true` but the depth test fails.
  6963. *
  6964. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  6965. * @default KeepStencilOp
  6966. */
  6967. this.stencilZFail = KeepStencilOp;
  6968. /**
  6969. * Which stencil operation to perform when the comparison function returns
  6970. * `true` and the depth test passes.
  6971. *
  6972. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  6973. * @default KeepStencilOp
  6974. */
  6975. this.stencilZPass = KeepStencilOp;
  6976. /**
  6977. * Whether stencil operations are performed against the stencil buffer. In
  6978. * order to perform writes or comparisons against the stencil buffer this
  6979. * value must be `true`.
  6980. *
  6981. * @type {boolean}
  6982. * @default false
  6983. */
  6984. this.stencilWrite = false;
  6985. /**
  6986. * User-defined clipping planes specified as THREE.Plane objects in world
  6987. * space. These planes apply to the objects this material is attached to.
  6988. * Points in space whose signed distance to the plane is negative are clipped
  6989. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  6990. * be `true`.
  6991. *
  6992. * @type {?Array<Plane>}
  6993. * @default null
  6994. */
  6995. this.clippingPlanes = null;
  6996. /**
  6997. * Changes the behavior of clipping planes so that only their intersection is
  6998. * clipped, rather than their union.
  6999. *
  7000. * @type {boolean}
  7001. * @default false
  7002. */
  7003. this.clipIntersection = false;
  7004. /**
  7005. * Defines whether to clip shadows according to the clipping planes specified
  7006. * on this material.
  7007. *
  7008. * @type {boolean}
  7009. * @default false
  7010. */
  7011. this.clipShadows = false;
  7012. /**
  7013. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  7014. * is determined as follows:
  7015. *
  7016. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  7017. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  7018. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  7019. *
  7020. * @type {?(FrontSide|BackSide|DoubleSide)}
  7021. * @default null
  7022. */
  7023. this.shadowSide = null;
  7024. /**
  7025. * Whether to render the material's color.
  7026. *
  7027. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  7028. * objects that occlude other objects.
  7029. *
  7030. * @type {boolean}
  7031. * @default true
  7032. */
  7033. this.colorWrite = true;
  7034. /**
  7035. * Override the renderer's default precision for this material.
  7036. *
  7037. * @type {?('highp'|'mediump'|'lowp')}
  7038. * @default null
  7039. */
  7040. this.precision = null;
  7041. /**
  7042. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  7043. * be offset after it is interpolated from the depth values of the appropriate vertices.
  7044. * The offset is added before the depth test is performed and before the value is written
  7045. * into the depth buffer.
  7046. *
  7047. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  7048. * rendering solids with highlighted edges.
  7049. *
  7050. * @type {boolean}
  7051. * @default false
  7052. */
  7053. this.polygonOffset = false;
  7054. /**
  7055. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  7056. *
  7057. * @type {number}
  7058. * @default 0
  7059. */
  7060. this.polygonOffsetFactor = 0;
  7061. /**
  7062. * Is multiplied by an implementation-specific value to create a constant depth offset.
  7063. *
  7064. * @type {number}
  7065. * @default 0
  7066. */
  7067. this.polygonOffsetUnits = 0;
  7068. /**
  7069. * Whether to apply dithering to the color to remove the appearance of banding.
  7070. *
  7071. * @type {boolean}
  7072. * @default false
  7073. */
  7074. this.dithering = false;
  7075. /**
  7076. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  7077. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  7078. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  7079. *
  7080. * @type {boolean}
  7081. * @default false
  7082. */
  7083. this.alphaToCoverage = false;
  7084. /**
  7085. * Whether to premultiply the alpha (transparency) value.
  7086. *
  7087. * @type {boolean}
  7088. * @default false
  7089. */
  7090. this.premultipliedAlpha = false;
  7091. /**
  7092. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  7093. *
  7094. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  7095. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  7096. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  7097. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  7098. * disable the two pass rendering to avoid performance issues.
  7099. *
  7100. * @type {boolean}
  7101. * @default false
  7102. */
  7103. this.forceSinglePass = false;
  7104. /**
  7105. * Defines whether 3D objects using this material are visible.
  7106. *
  7107. * @type {boolean}
  7108. * @default true
  7109. */
  7110. this.visible = true;
  7111. /**
  7112. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  7113. *
  7114. * It is ignored when rendering to a render target or using post processing or when using
  7115. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  7116. *
  7117. * @type {boolean}
  7118. * @default true
  7119. */
  7120. this.toneMapped = true;
  7121. /**
  7122. * An object that can be used to store custom data about the Material. It
  7123. * should not hold references to functions as these will not be cloned.
  7124. *
  7125. * @type {Object}
  7126. */
  7127. this.userData = {};
  7128. /**
  7129. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  7130. *
  7131. * @type {number}
  7132. * @readonly
  7133. * @default 0
  7134. */
  7135. this.version = 0;
  7136. this._alphaTest = 0;
  7137. }
  7138. /**
  7139. * Sets the alpha value to be used when running an alpha test. The material
  7140. * will not be rendered if the opacity is lower than this value.
  7141. *
  7142. * @type {number}
  7143. * @readonly
  7144. * @default 0
  7145. */
  7146. get alphaTest() {
  7147. return this._alphaTest;
  7148. }
  7149. set alphaTest( value ) {
  7150. if ( this._alphaTest > 0 !== value > 0 ) {
  7151. this.version ++;
  7152. }
  7153. this._alphaTest = value;
  7154. }
  7155. /**
  7156. * An optional callback that is executed immediately before the material is used to render a 3D object.
  7157. *
  7158. * This method can only be used when rendering with {@link WebGLRenderer}.
  7159. *
  7160. * @param {WebGLRenderer} renderer - The renderer.
  7161. * @param {Scene} scene - The scene.
  7162. * @param {Camera} camera - The camera that is used to render the scene.
  7163. * @param {BufferGeometry} geometry - The 3D object's geometry.
  7164. * @param {Object3D} object - The 3D object.
  7165. * @param {Object} group - The geometry group data.
  7166. */
  7167. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  7168. /**
  7169. * An optional callback that is executed immediately before the shader
  7170. * program is compiled. This function is called with the shader source code
  7171. * as a parameter. Useful for the modification of built-in materials.
  7172. *
  7173. * This method can only be used when rendering with {@link WebGLRenderer}. The
  7174. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  7175. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  7176. *
  7177. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  7178. * @param {WebGLRenderer} renderer - A reference to the renderer.
  7179. */
  7180. onBeforeCompile( /* shaderobject, renderer */ ) {}
  7181. /**
  7182. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  7183. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  7184. * shader or recompile the shader for this material as needed.
  7185. *
  7186. * This method can only be used when rendering with {@link WebGLRenderer}.
  7187. *
  7188. * @return {string} The custom program cache key.
  7189. */
  7190. customProgramCacheKey() {
  7191. return this.onBeforeCompile.toString();
  7192. }
  7193. setValues( values ) {
  7194. if ( values === undefined ) return;
  7195. for ( const key in values ) {
  7196. const newValue = values[ key ];
  7197. if ( newValue === undefined ) {
  7198. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  7199. continue;
  7200. }
  7201. const currentValue = this[ key ];
  7202. if ( currentValue === undefined ) {
  7203. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  7204. continue;
  7205. }
  7206. if ( currentValue && currentValue.isColor ) {
  7207. currentValue.set( newValue );
  7208. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  7209. currentValue.copy( newValue );
  7210. } else {
  7211. this[ key ] = newValue;
  7212. }
  7213. }
  7214. }
  7215. /**
  7216. * Serializes the material into JSON.
  7217. *
  7218. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  7219. * @return {Object} A JSON object representing the serialized material.
  7220. * @see {@link ObjectLoader#parse}
  7221. */
  7222. toJSON( meta ) {
  7223. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  7224. if ( isRootObject ) {
  7225. meta = {
  7226. textures: {},
  7227. images: {}
  7228. };
  7229. }
  7230. const data = {
  7231. metadata: {
  7232. version: 4.6,
  7233. type: 'Material',
  7234. generator: 'Material.toJSON'
  7235. }
  7236. };
  7237. // standard Material serialization
  7238. data.uuid = this.uuid;
  7239. data.type = this.type;
  7240. if ( this.name !== '' ) data.name = this.name;
  7241. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  7242. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  7243. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  7244. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  7245. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  7246. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  7247. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  7248. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  7249. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  7250. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  7251. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  7252. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  7253. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  7254. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  7255. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  7256. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  7257. }
  7258. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  7259. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  7260. }
  7261. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  7262. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  7263. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  7264. }
  7265. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  7266. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  7267. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  7268. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  7269. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  7270. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  7271. }
  7272. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  7273. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  7274. }
  7275. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  7276. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  7277. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  7278. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  7279. }
  7280. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  7281. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  7282. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  7283. if ( this.lightMap && this.lightMap.isTexture ) {
  7284. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  7285. data.lightMapIntensity = this.lightMapIntensity;
  7286. }
  7287. if ( this.aoMap && this.aoMap.isTexture ) {
  7288. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  7289. data.aoMapIntensity = this.aoMapIntensity;
  7290. }
  7291. if ( this.bumpMap && this.bumpMap.isTexture ) {
  7292. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  7293. data.bumpScale = this.bumpScale;
  7294. }
  7295. if ( this.normalMap && this.normalMap.isTexture ) {
  7296. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  7297. data.normalMapType = this.normalMapType;
  7298. data.normalScale = this.normalScale.toArray();
  7299. }
  7300. if ( this.displacementMap && this.displacementMap.isTexture ) {
  7301. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  7302. data.displacementScale = this.displacementScale;
  7303. data.displacementBias = this.displacementBias;
  7304. }
  7305. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  7306. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  7307. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  7308. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  7309. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  7310. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  7311. if ( this.envMap && this.envMap.isTexture ) {
  7312. data.envMap = this.envMap.toJSON( meta ).uuid;
  7313. if ( this.combine !== undefined ) data.combine = this.combine;
  7314. }
  7315. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  7316. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  7317. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  7318. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  7319. if ( this.gradientMap && this.gradientMap.isTexture ) {
  7320. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  7321. }
  7322. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  7323. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  7324. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  7325. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  7326. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  7327. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  7328. if ( this.size !== undefined ) data.size = this.size;
  7329. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  7330. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  7331. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  7332. if ( this.side !== FrontSide ) data.side = this.side;
  7333. if ( this.vertexColors === true ) data.vertexColors = true;
  7334. if ( this.opacity < 1 ) data.opacity = this.opacity;
  7335. if ( this.transparent === true ) data.transparent = true;
  7336. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  7337. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  7338. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  7339. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  7340. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  7341. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  7342. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  7343. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  7344. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  7345. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  7346. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  7347. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  7348. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  7349. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  7350. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  7351. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  7352. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  7353. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  7354. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  7355. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  7356. // rotation (SpriteMaterial)
  7357. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  7358. if ( this.polygonOffset === true ) data.polygonOffset = true;
  7359. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  7360. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  7361. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  7362. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  7363. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  7364. if ( this.scale !== undefined ) data.scale = this.scale;
  7365. if ( this.dithering === true ) data.dithering = true;
  7366. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  7367. if ( this.alphaHash === true ) data.alphaHash = true;
  7368. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  7369. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  7370. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  7371. if ( this.wireframe === true ) data.wireframe = true;
  7372. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  7373. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  7374. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  7375. if ( this.flatShading === true ) data.flatShading = true;
  7376. if ( this.visible === false ) data.visible = false;
  7377. if ( this.toneMapped === false ) data.toneMapped = false;
  7378. if ( this.fog === false ) data.fog = false;
  7379. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  7380. // TODO: Copied from Object3D.toJSON
  7381. function extractFromCache( cache ) {
  7382. const values = [];
  7383. for ( const key in cache ) {
  7384. const data = cache[ key ];
  7385. delete data.metadata;
  7386. values.push( data );
  7387. }
  7388. return values;
  7389. }
  7390. if ( isRootObject ) {
  7391. const textures = extractFromCache( meta.textures );
  7392. const images = extractFromCache( meta.images );
  7393. if ( textures.length > 0 ) data.textures = textures;
  7394. if ( images.length > 0 ) data.images = images;
  7395. }
  7396. return data;
  7397. }
  7398. /**
  7399. * Returns a new material with copied values from this instance.
  7400. *
  7401. * @return {Material} A clone of this instance.
  7402. */
  7403. clone() {
  7404. return new this.constructor().copy( this );
  7405. }
  7406. /**
  7407. * Copies the values of the given material to this instance.
  7408. *
  7409. * @param {Material} source - The material to copy.
  7410. * @return {Material} A reference to this instance.
  7411. */
  7412. copy( source ) {
  7413. this.name = source.name;
  7414. this.blending = source.blending;
  7415. this.side = source.side;
  7416. this.vertexColors = source.vertexColors;
  7417. this.opacity = source.opacity;
  7418. this.transparent = source.transparent;
  7419. this.blendSrc = source.blendSrc;
  7420. this.blendDst = source.blendDst;
  7421. this.blendEquation = source.blendEquation;
  7422. this.blendSrcAlpha = source.blendSrcAlpha;
  7423. this.blendDstAlpha = source.blendDstAlpha;
  7424. this.blendEquationAlpha = source.blendEquationAlpha;
  7425. this.blendColor.copy( source.blendColor );
  7426. this.blendAlpha = source.blendAlpha;
  7427. this.depthFunc = source.depthFunc;
  7428. this.depthTest = source.depthTest;
  7429. this.depthWrite = source.depthWrite;
  7430. this.stencilWriteMask = source.stencilWriteMask;
  7431. this.stencilFunc = source.stencilFunc;
  7432. this.stencilRef = source.stencilRef;
  7433. this.stencilFuncMask = source.stencilFuncMask;
  7434. this.stencilFail = source.stencilFail;
  7435. this.stencilZFail = source.stencilZFail;
  7436. this.stencilZPass = source.stencilZPass;
  7437. this.stencilWrite = source.stencilWrite;
  7438. const srcPlanes = source.clippingPlanes;
  7439. let dstPlanes = null;
  7440. if ( srcPlanes !== null ) {
  7441. const n = srcPlanes.length;
  7442. dstPlanes = new Array( n );
  7443. for ( let i = 0; i !== n; ++ i ) {
  7444. dstPlanes[ i ] = srcPlanes[ i ].clone();
  7445. }
  7446. }
  7447. this.clippingPlanes = dstPlanes;
  7448. this.clipIntersection = source.clipIntersection;
  7449. this.clipShadows = source.clipShadows;
  7450. this.shadowSide = source.shadowSide;
  7451. this.colorWrite = source.colorWrite;
  7452. this.precision = source.precision;
  7453. this.polygonOffset = source.polygonOffset;
  7454. this.polygonOffsetFactor = source.polygonOffsetFactor;
  7455. this.polygonOffsetUnits = source.polygonOffsetUnits;
  7456. this.dithering = source.dithering;
  7457. this.alphaTest = source.alphaTest;
  7458. this.alphaHash = source.alphaHash;
  7459. this.alphaToCoverage = source.alphaToCoverage;
  7460. this.premultipliedAlpha = source.premultipliedAlpha;
  7461. this.forceSinglePass = source.forceSinglePass;
  7462. this.visible = source.visible;
  7463. this.toneMapped = source.toneMapped;
  7464. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  7465. return this;
  7466. }
  7467. /**
  7468. * Frees the GPU-related resources allocated by this instance. Call this
  7469. * method whenever this instance is no longer used in your app.
  7470. *
  7471. * @fires Material#dispose
  7472. */
  7473. dispose() {
  7474. /**
  7475. * Fires when the material has been disposed of.
  7476. *
  7477. * @event Material#dispose
  7478. * @type {Object}
  7479. */
  7480. this.dispatchEvent( { type: 'dispose' } );
  7481. }
  7482. /**
  7483. * Setting this property to `true` indicates the engine the material
  7484. * needs to be recompiled.
  7485. *
  7486. * @type {boolean}
  7487. * @default false
  7488. * @param {boolean} value
  7489. */
  7490. set needsUpdate( value ) {
  7491. if ( value === true ) this.version ++;
  7492. }
  7493. onBuild( /* shaderobject, renderer */ ) {
  7494. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  7495. }
  7496. }
  7497. class MeshBasicMaterial extends Material {
  7498. constructor( parameters ) {
  7499. super();
  7500. this.isMeshBasicMaterial = true;
  7501. this.type = 'MeshBasicMaterial';
  7502. this.color = new Color( 0xffffff ); // emissive
  7503. this.map = null;
  7504. this.lightMap = null;
  7505. this.lightMapIntensity = 1.0;
  7506. this.aoMap = null;
  7507. this.aoMapIntensity = 1.0;
  7508. this.specularMap = null;
  7509. this.alphaMap = null;
  7510. this.envMap = null;
  7511. this.envMapRotation = new Euler();
  7512. this.combine = MultiplyOperation;
  7513. this.reflectivity = 1;
  7514. this.refractionRatio = 0.98;
  7515. this.wireframe = false;
  7516. this.wireframeLinewidth = 1;
  7517. this.wireframeLinecap = 'round';
  7518. this.wireframeLinejoin = 'round';
  7519. this.fog = true;
  7520. this.setValues( parameters );
  7521. }
  7522. copy( source ) {
  7523. super.copy( source );
  7524. this.color.copy( source.color );
  7525. this.map = source.map;
  7526. this.lightMap = source.lightMap;
  7527. this.lightMapIntensity = source.lightMapIntensity;
  7528. this.aoMap = source.aoMap;
  7529. this.aoMapIntensity = source.aoMapIntensity;
  7530. this.specularMap = source.specularMap;
  7531. this.alphaMap = source.alphaMap;
  7532. this.envMap = source.envMap;
  7533. this.envMapRotation.copy( source.envMapRotation );
  7534. this.combine = source.combine;
  7535. this.reflectivity = source.reflectivity;
  7536. this.refractionRatio = source.refractionRatio;
  7537. this.wireframe = source.wireframe;
  7538. this.wireframeLinewidth = source.wireframeLinewidth;
  7539. this.wireframeLinecap = source.wireframeLinecap;
  7540. this.wireframeLinejoin = source.wireframeLinejoin;
  7541. this.fog = source.fog;
  7542. return this;
  7543. }
  7544. }
  7545. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  7546. const _tables = /*@__PURE__*/ _generateTables();
  7547. function _generateTables() {
  7548. // float32 to float16 helpers
  7549. const buffer = new ArrayBuffer( 4 );
  7550. const floatView = new Float32Array( buffer );
  7551. const uint32View = new Uint32Array( buffer );
  7552. const baseTable = new Uint32Array( 512 );
  7553. const shiftTable = new Uint32Array( 512 );
  7554. for ( let i = 0; i < 256; ++ i ) {
  7555. const e = i - 127;
  7556. // very small number (0, -0)
  7557. if ( e < -27 ) {
  7558. baseTable[ i ] = 0x0000;
  7559. baseTable[ i | 0x100 ] = 0x8000;
  7560. shiftTable[ i ] = 24;
  7561. shiftTable[ i | 0x100 ] = 24;
  7562. // small number (denorm)
  7563. } else if ( e < -14 ) {
  7564. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  7565. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  7566. shiftTable[ i ] = - e - 1;
  7567. shiftTable[ i | 0x100 ] = - e - 1;
  7568. // normal number
  7569. } else if ( e <= 15 ) {
  7570. baseTable[ i ] = ( e + 15 ) << 10;
  7571. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  7572. shiftTable[ i ] = 13;
  7573. shiftTable[ i | 0x100 ] = 13;
  7574. // large number (Infinity, -Infinity)
  7575. } else if ( e < 128 ) {
  7576. baseTable[ i ] = 0x7c00;
  7577. baseTable[ i | 0x100 ] = 0xfc00;
  7578. shiftTable[ i ] = 24;
  7579. shiftTable[ i | 0x100 ] = 24;
  7580. // stay (NaN, Infinity, -Infinity)
  7581. } else {
  7582. baseTable[ i ] = 0x7c00;
  7583. baseTable[ i | 0x100 ] = 0xfc00;
  7584. shiftTable[ i ] = 13;
  7585. shiftTable[ i | 0x100 ] = 13;
  7586. }
  7587. }
  7588. // float16 to float32 helpers
  7589. const mantissaTable = new Uint32Array( 2048 );
  7590. const exponentTable = new Uint32Array( 64 );
  7591. const offsetTable = new Uint32Array( 64 );
  7592. for ( let i = 1; i < 1024; ++ i ) {
  7593. let m = i << 13; // zero pad mantissa bits
  7594. let e = 0; // zero exponent
  7595. // normalized
  7596. while ( ( m & 0x00800000 ) === 0 ) {
  7597. m <<= 1;
  7598. e -= 0x00800000; // decrement exponent
  7599. }
  7600. m &= -8388609; // clear leading 1 bit
  7601. e += 0x38800000; // adjust bias
  7602. mantissaTable[ i ] = m | e;
  7603. }
  7604. for ( let i = 1024; i < 2048; ++ i ) {
  7605. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  7606. }
  7607. for ( let i = 1; i < 31; ++ i ) {
  7608. exponentTable[ i ] = i << 23;
  7609. }
  7610. exponentTable[ 31 ] = 0x47800000;
  7611. exponentTable[ 32 ] = 0x80000000;
  7612. for ( let i = 33; i < 63; ++ i ) {
  7613. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  7614. }
  7615. exponentTable[ 63 ] = 0xc7800000;
  7616. for ( let i = 1; i < 64; ++ i ) {
  7617. if ( i !== 32 ) {
  7618. offsetTable[ i ] = 1024;
  7619. }
  7620. }
  7621. return {
  7622. floatView: floatView,
  7623. uint32View: uint32View,
  7624. baseTable: baseTable,
  7625. shiftTable: shiftTable,
  7626. mantissaTable: mantissaTable,
  7627. exponentTable: exponentTable,
  7628. offsetTable: offsetTable
  7629. };
  7630. }
  7631. // float32 to float16
  7632. function toHalfFloat( val ) {
  7633. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  7634. val = clamp( val, -65504, 65504 );
  7635. _tables.floatView[ 0 ] = val;
  7636. const f = _tables.uint32View[ 0 ];
  7637. const e = ( f >> 23 ) & 0x1ff;
  7638. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  7639. }
  7640. // float16 to float32
  7641. function fromHalfFloat( val ) {
  7642. const m = val >> 10;
  7643. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  7644. return _tables.floatView[ 0 ];
  7645. }
  7646. const DataUtils = {
  7647. toHalfFloat: toHalfFloat,
  7648. fromHalfFloat: fromHalfFloat,
  7649. };
  7650. const _vector$9 = /*@__PURE__*/ new Vector3();
  7651. const _vector2$1 = /*@__PURE__*/ new Vector2();
  7652. let _id$3 = 0;
  7653. class BufferAttribute {
  7654. constructor( array, itemSize, normalized = false ) {
  7655. if ( Array.isArray( array ) ) {
  7656. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  7657. }
  7658. this.isBufferAttribute = true;
  7659. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  7660. this.name = '';
  7661. this.array = array;
  7662. this.itemSize = itemSize;
  7663. this.count = array !== undefined ? array.length / itemSize : 0;
  7664. this.normalized = normalized;
  7665. this.usage = StaticDrawUsage;
  7666. this.updateRanges = [];
  7667. this.gpuType = FloatType;
  7668. this.version = 0;
  7669. }
  7670. onUploadCallback() {}
  7671. set needsUpdate( value ) {
  7672. if ( value === true ) this.version ++;
  7673. }
  7674. setUsage( value ) {
  7675. this.usage = value;
  7676. return this;
  7677. }
  7678. addUpdateRange( start, count ) {
  7679. this.updateRanges.push( { start, count } );
  7680. }
  7681. clearUpdateRanges() {
  7682. this.updateRanges.length = 0;
  7683. }
  7684. copy( source ) {
  7685. this.name = source.name;
  7686. this.array = new source.array.constructor( source.array );
  7687. this.itemSize = source.itemSize;
  7688. this.count = source.count;
  7689. this.normalized = source.normalized;
  7690. this.usage = source.usage;
  7691. this.gpuType = source.gpuType;
  7692. return this;
  7693. }
  7694. copyAt( index1, attribute, index2 ) {
  7695. index1 *= this.itemSize;
  7696. index2 *= attribute.itemSize;
  7697. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  7698. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7699. }
  7700. return this;
  7701. }
  7702. copyArray( array ) {
  7703. this.array.set( array );
  7704. return this;
  7705. }
  7706. applyMatrix3( m ) {
  7707. if ( this.itemSize === 2 ) {
  7708. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7709. _vector2$1.fromBufferAttribute( this, i );
  7710. _vector2$1.applyMatrix3( m );
  7711. this.setXY( i, _vector2$1.x, _vector2$1.y );
  7712. }
  7713. } else if ( this.itemSize === 3 ) {
  7714. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7715. _vector$9.fromBufferAttribute( this, i );
  7716. _vector$9.applyMatrix3( m );
  7717. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  7718. }
  7719. }
  7720. return this;
  7721. }
  7722. applyMatrix4( m ) {
  7723. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7724. _vector$9.fromBufferAttribute( this, i );
  7725. _vector$9.applyMatrix4( m );
  7726. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  7727. }
  7728. return this;
  7729. }
  7730. applyNormalMatrix( m ) {
  7731. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7732. _vector$9.fromBufferAttribute( this, i );
  7733. _vector$9.applyNormalMatrix( m );
  7734. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  7735. }
  7736. return this;
  7737. }
  7738. transformDirection( m ) {
  7739. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7740. _vector$9.fromBufferAttribute( this, i );
  7741. _vector$9.transformDirection( m );
  7742. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  7743. }
  7744. return this;
  7745. }
  7746. set( value, offset = 0 ) {
  7747. // Matching BufferAttribute constructor, do not normalize the array.
  7748. this.array.set( value, offset );
  7749. return this;
  7750. }
  7751. getComponent( index, component ) {
  7752. let value = this.array[ index * this.itemSize + component ];
  7753. if ( this.normalized ) value = denormalize( value, this.array );
  7754. return value;
  7755. }
  7756. setComponent( index, component, value ) {
  7757. if ( this.normalized ) value = normalize( value, this.array );
  7758. this.array[ index * this.itemSize + component ] = value;
  7759. return this;
  7760. }
  7761. getX( index ) {
  7762. let x = this.array[ index * this.itemSize ];
  7763. if ( this.normalized ) x = denormalize( x, this.array );
  7764. return x;
  7765. }
  7766. setX( index, x ) {
  7767. if ( this.normalized ) x = normalize( x, this.array );
  7768. this.array[ index * this.itemSize ] = x;
  7769. return this;
  7770. }
  7771. getY( index ) {
  7772. let y = this.array[ index * this.itemSize + 1 ];
  7773. if ( this.normalized ) y = denormalize( y, this.array );
  7774. return y;
  7775. }
  7776. setY( index, y ) {
  7777. if ( this.normalized ) y = normalize( y, this.array );
  7778. this.array[ index * this.itemSize + 1 ] = y;
  7779. return this;
  7780. }
  7781. getZ( index ) {
  7782. let z = this.array[ index * this.itemSize + 2 ];
  7783. if ( this.normalized ) z = denormalize( z, this.array );
  7784. return z;
  7785. }
  7786. setZ( index, z ) {
  7787. if ( this.normalized ) z = normalize( z, this.array );
  7788. this.array[ index * this.itemSize + 2 ] = z;
  7789. return this;
  7790. }
  7791. getW( index ) {
  7792. let w = this.array[ index * this.itemSize + 3 ];
  7793. if ( this.normalized ) w = denormalize( w, this.array );
  7794. return w;
  7795. }
  7796. setW( index, w ) {
  7797. if ( this.normalized ) w = normalize( w, this.array );
  7798. this.array[ index * this.itemSize + 3 ] = w;
  7799. return this;
  7800. }
  7801. setXY( index, x, y ) {
  7802. index *= this.itemSize;
  7803. if ( this.normalized ) {
  7804. x = normalize( x, this.array );
  7805. y = normalize( y, this.array );
  7806. }
  7807. this.array[ index + 0 ] = x;
  7808. this.array[ index + 1 ] = y;
  7809. return this;
  7810. }
  7811. setXYZ( index, x, y, z ) {
  7812. index *= this.itemSize;
  7813. if ( this.normalized ) {
  7814. x = normalize( x, this.array );
  7815. y = normalize( y, this.array );
  7816. z = normalize( z, this.array );
  7817. }
  7818. this.array[ index + 0 ] = x;
  7819. this.array[ index + 1 ] = y;
  7820. this.array[ index + 2 ] = z;
  7821. return this;
  7822. }
  7823. setXYZW( index, x, y, z, w ) {
  7824. index *= this.itemSize;
  7825. if ( this.normalized ) {
  7826. x = normalize( x, this.array );
  7827. y = normalize( y, this.array );
  7828. z = normalize( z, this.array );
  7829. w = normalize( w, this.array );
  7830. }
  7831. this.array[ index + 0 ] = x;
  7832. this.array[ index + 1 ] = y;
  7833. this.array[ index + 2 ] = z;
  7834. this.array[ index + 3 ] = w;
  7835. return this;
  7836. }
  7837. onUpload( callback ) {
  7838. this.onUploadCallback = callback;
  7839. return this;
  7840. }
  7841. clone() {
  7842. return new this.constructor( this.array, this.itemSize ).copy( this );
  7843. }
  7844. toJSON() {
  7845. const data = {
  7846. itemSize: this.itemSize,
  7847. type: this.array.constructor.name,
  7848. array: Array.from( this.array ),
  7849. normalized: this.normalized
  7850. };
  7851. if ( this.name !== '' ) data.name = this.name;
  7852. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  7853. return data;
  7854. }
  7855. }
  7856. //
  7857. class Int8BufferAttribute extends BufferAttribute {
  7858. constructor( array, itemSize, normalized ) {
  7859. super( new Int8Array( array ), itemSize, normalized );
  7860. }
  7861. }
  7862. class Uint8BufferAttribute extends BufferAttribute {
  7863. constructor( array, itemSize, normalized ) {
  7864. super( new Uint8Array( array ), itemSize, normalized );
  7865. }
  7866. }
  7867. class Uint8ClampedBufferAttribute extends BufferAttribute {
  7868. constructor( array, itemSize, normalized ) {
  7869. super( new Uint8ClampedArray( array ), itemSize, normalized );
  7870. }
  7871. }
  7872. class Int16BufferAttribute extends BufferAttribute {
  7873. constructor( array, itemSize, normalized ) {
  7874. super( new Int16Array( array ), itemSize, normalized );
  7875. }
  7876. }
  7877. class Uint16BufferAttribute extends BufferAttribute {
  7878. constructor( array, itemSize, normalized ) {
  7879. super( new Uint16Array( array ), itemSize, normalized );
  7880. }
  7881. }
  7882. class Int32BufferAttribute extends BufferAttribute {
  7883. constructor( array, itemSize, normalized ) {
  7884. super( new Int32Array( array ), itemSize, normalized );
  7885. }
  7886. }
  7887. class Uint32BufferAttribute extends BufferAttribute {
  7888. constructor( array, itemSize, normalized ) {
  7889. super( new Uint32Array( array ), itemSize, normalized );
  7890. }
  7891. }
  7892. class Float16BufferAttribute extends BufferAttribute {
  7893. constructor( array, itemSize, normalized ) {
  7894. super( new Uint16Array( array ), itemSize, normalized );
  7895. this.isFloat16BufferAttribute = true;
  7896. }
  7897. getX( index ) {
  7898. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  7899. if ( this.normalized ) x = denormalize( x, this.array );
  7900. return x;
  7901. }
  7902. setX( index, x ) {
  7903. if ( this.normalized ) x = normalize( x, this.array );
  7904. this.array[ index * this.itemSize ] = toHalfFloat( x );
  7905. return this;
  7906. }
  7907. getY( index ) {
  7908. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  7909. if ( this.normalized ) y = denormalize( y, this.array );
  7910. return y;
  7911. }
  7912. setY( index, y ) {
  7913. if ( this.normalized ) y = normalize( y, this.array );
  7914. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  7915. return this;
  7916. }
  7917. getZ( index ) {
  7918. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  7919. if ( this.normalized ) z = denormalize( z, this.array );
  7920. return z;
  7921. }
  7922. setZ( index, z ) {
  7923. if ( this.normalized ) z = normalize( z, this.array );
  7924. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  7925. return this;
  7926. }
  7927. getW( index ) {
  7928. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  7929. if ( this.normalized ) w = denormalize( w, this.array );
  7930. return w;
  7931. }
  7932. setW( index, w ) {
  7933. if ( this.normalized ) w = normalize( w, this.array );
  7934. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  7935. return this;
  7936. }
  7937. setXY( index, x, y ) {
  7938. index *= this.itemSize;
  7939. if ( this.normalized ) {
  7940. x = normalize( x, this.array );
  7941. y = normalize( y, this.array );
  7942. }
  7943. this.array[ index + 0 ] = toHalfFloat( x );
  7944. this.array[ index + 1 ] = toHalfFloat( y );
  7945. return this;
  7946. }
  7947. setXYZ( index, x, y, z ) {
  7948. index *= this.itemSize;
  7949. if ( this.normalized ) {
  7950. x = normalize( x, this.array );
  7951. y = normalize( y, this.array );
  7952. z = normalize( z, this.array );
  7953. }
  7954. this.array[ index + 0 ] = toHalfFloat( x );
  7955. this.array[ index + 1 ] = toHalfFloat( y );
  7956. this.array[ index + 2 ] = toHalfFloat( z );
  7957. return this;
  7958. }
  7959. setXYZW( index, x, y, z, w ) {
  7960. index *= this.itemSize;
  7961. if ( this.normalized ) {
  7962. x = normalize( x, this.array );
  7963. y = normalize( y, this.array );
  7964. z = normalize( z, this.array );
  7965. w = normalize( w, this.array );
  7966. }
  7967. this.array[ index + 0 ] = toHalfFloat( x );
  7968. this.array[ index + 1 ] = toHalfFloat( y );
  7969. this.array[ index + 2 ] = toHalfFloat( z );
  7970. this.array[ index + 3 ] = toHalfFloat( w );
  7971. return this;
  7972. }
  7973. }
  7974. class Float32BufferAttribute extends BufferAttribute {
  7975. constructor( array, itemSize, normalized ) {
  7976. super( new Float32Array( array ), itemSize, normalized );
  7977. }
  7978. }
  7979. let _id$2 = 0;
  7980. const _m1$2 = /*@__PURE__*/ new Matrix4();
  7981. const _obj = /*@__PURE__*/ new Object3D();
  7982. const _offset = /*@__PURE__*/ new Vector3();
  7983. const _box$2 = /*@__PURE__*/ new Box3();
  7984. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  7985. const _vector$8 = /*@__PURE__*/ new Vector3();
  7986. class BufferGeometry extends EventDispatcher {
  7987. constructor() {
  7988. super();
  7989. this.isBufferGeometry = true;
  7990. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  7991. this.uuid = generateUUID();
  7992. this.name = '';
  7993. this.type = 'BufferGeometry';
  7994. this.index = null;
  7995. this.indirect = null;
  7996. this.attributes = {};
  7997. this.morphAttributes = {};
  7998. this.morphTargetsRelative = false;
  7999. this.groups = [];
  8000. this.boundingBox = null;
  8001. this.boundingSphere = null;
  8002. this.drawRange = { start: 0, count: Infinity };
  8003. this.userData = {};
  8004. }
  8005. getIndex() {
  8006. return this.index;
  8007. }
  8008. setIndex( index ) {
  8009. if ( Array.isArray( index ) ) {
  8010. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  8011. } else {
  8012. this.index = index;
  8013. }
  8014. return this;
  8015. }
  8016. setIndirect( indirect ) {
  8017. this.indirect = indirect;
  8018. return this;
  8019. }
  8020. getIndirect() {
  8021. return this.indirect;
  8022. }
  8023. getAttribute( name ) {
  8024. return this.attributes[ name ];
  8025. }
  8026. setAttribute( name, attribute ) {
  8027. this.attributes[ name ] = attribute;
  8028. return this;
  8029. }
  8030. deleteAttribute( name ) {
  8031. delete this.attributes[ name ];
  8032. return this;
  8033. }
  8034. hasAttribute( name ) {
  8035. return this.attributes[ name ] !== undefined;
  8036. }
  8037. addGroup( start, count, materialIndex = 0 ) {
  8038. this.groups.push( {
  8039. start: start,
  8040. count: count,
  8041. materialIndex: materialIndex
  8042. } );
  8043. }
  8044. clearGroups() {
  8045. this.groups = [];
  8046. }
  8047. setDrawRange( start, count ) {
  8048. this.drawRange.start = start;
  8049. this.drawRange.count = count;
  8050. }
  8051. applyMatrix4( matrix ) {
  8052. const position = this.attributes.position;
  8053. if ( position !== undefined ) {
  8054. position.applyMatrix4( matrix );
  8055. position.needsUpdate = true;
  8056. }
  8057. const normal = this.attributes.normal;
  8058. if ( normal !== undefined ) {
  8059. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8060. normal.applyNormalMatrix( normalMatrix );
  8061. normal.needsUpdate = true;
  8062. }
  8063. const tangent = this.attributes.tangent;
  8064. if ( tangent !== undefined ) {
  8065. tangent.transformDirection( matrix );
  8066. tangent.needsUpdate = true;
  8067. }
  8068. if ( this.boundingBox !== null ) {
  8069. this.computeBoundingBox();
  8070. }
  8071. if ( this.boundingSphere !== null ) {
  8072. this.computeBoundingSphere();
  8073. }
  8074. return this;
  8075. }
  8076. applyQuaternion( q ) {
  8077. _m1$2.makeRotationFromQuaternion( q );
  8078. this.applyMatrix4( _m1$2 );
  8079. return this;
  8080. }
  8081. rotateX( angle ) {
  8082. // rotate geometry around world x-axis
  8083. _m1$2.makeRotationX( angle );
  8084. this.applyMatrix4( _m1$2 );
  8085. return this;
  8086. }
  8087. rotateY( angle ) {
  8088. // rotate geometry around world y-axis
  8089. _m1$2.makeRotationY( angle );
  8090. this.applyMatrix4( _m1$2 );
  8091. return this;
  8092. }
  8093. rotateZ( angle ) {
  8094. // rotate geometry around world z-axis
  8095. _m1$2.makeRotationZ( angle );
  8096. this.applyMatrix4( _m1$2 );
  8097. return this;
  8098. }
  8099. translate( x, y, z ) {
  8100. // translate geometry
  8101. _m1$2.makeTranslation( x, y, z );
  8102. this.applyMatrix4( _m1$2 );
  8103. return this;
  8104. }
  8105. scale( x, y, z ) {
  8106. // scale geometry
  8107. _m1$2.makeScale( x, y, z );
  8108. this.applyMatrix4( _m1$2 );
  8109. return this;
  8110. }
  8111. lookAt( vector ) {
  8112. _obj.lookAt( vector );
  8113. _obj.updateMatrix();
  8114. this.applyMatrix4( _obj.matrix );
  8115. return this;
  8116. }
  8117. center() {
  8118. this.computeBoundingBox();
  8119. this.boundingBox.getCenter( _offset ).negate();
  8120. this.translate( _offset.x, _offset.y, _offset.z );
  8121. return this;
  8122. }
  8123. setFromPoints( points ) {
  8124. const positionAttribute = this.getAttribute( 'position' );
  8125. if ( positionAttribute === undefined ) {
  8126. const position = [];
  8127. for ( let i = 0, l = points.length; i < l; i ++ ) {
  8128. const point = points[ i ];
  8129. position.push( point.x, point.y, point.z || 0 );
  8130. }
  8131. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  8132. } else {
  8133. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  8134. for ( let i = 0; i < l; i ++ ) {
  8135. const point = points[ i ];
  8136. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  8137. }
  8138. if ( points.length > positionAttribute.count ) {
  8139. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  8140. }
  8141. positionAttribute.needsUpdate = true;
  8142. }
  8143. return this;
  8144. }
  8145. computeBoundingBox() {
  8146. if ( this.boundingBox === null ) {
  8147. this.boundingBox = new Box3();
  8148. }
  8149. const position = this.attributes.position;
  8150. const morphAttributesPosition = this.morphAttributes.position;
  8151. if ( position && position.isGLBufferAttribute ) {
  8152. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  8153. this.boundingBox.set(
  8154. new Vector3( - Infinity, - Infinity, - Infinity ),
  8155. new Vector3( + Infinity, + Infinity, + Infinity )
  8156. );
  8157. return;
  8158. }
  8159. if ( position !== undefined ) {
  8160. this.boundingBox.setFromBufferAttribute( position );
  8161. // process morph attributes if present
  8162. if ( morphAttributesPosition ) {
  8163. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  8164. const morphAttribute = morphAttributesPosition[ i ];
  8165. _box$2.setFromBufferAttribute( morphAttribute );
  8166. if ( this.morphTargetsRelative ) {
  8167. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  8168. this.boundingBox.expandByPoint( _vector$8 );
  8169. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  8170. this.boundingBox.expandByPoint( _vector$8 );
  8171. } else {
  8172. this.boundingBox.expandByPoint( _box$2.min );
  8173. this.boundingBox.expandByPoint( _box$2.max );
  8174. }
  8175. }
  8176. }
  8177. } else {
  8178. this.boundingBox.makeEmpty();
  8179. }
  8180. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  8181. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  8182. }
  8183. }
  8184. computeBoundingSphere() {
  8185. if ( this.boundingSphere === null ) {
  8186. this.boundingSphere = new Sphere();
  8187. }
  8188. const position = this.attributes.position;
  8189. const morphAttributesPosition = this.morphAttributes.position;
  8190. if ( position && position.isGLBufferAttribute ) {
  8191. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  8192. this.boundingSphere.set( new Vector3(), Infinity );
  8193. return;
  8194. }
  8195. if ( position ) {
  8196. // first, find the center of the bounding sphere
  8197. const center = this.boundingSphere.center;
  8198. _box$2.setFromBufferAttribute( position );
  8199. // process morph attributes if present
  8200. if ( morphAttributesPosition ) {
  8201. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  8202. const morphAttribute = morphAttributesPosition[ i ];
  8203. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  8204. if ( this.morphTargetsRelative ) {
  8205. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  8206. _box$2.expandByPoint( _vector$8 );
  8207. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  8208. _box$2.expandByPoint( _vector$8 );
  8209. } else {
  8210. _box$2.expandByPoint( _boxMorphTargets.min );
  8211. _box$2.expandByPoint( _boxMorphTargets.max );
  8212. }
  8213. }
  8214. }
  8215. _box$2.getCenter( center );
  8216. // second, try to find a boundingSphere with a radius smaller than the
  8217. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  8218. let maxRadiusSq = 0;
  8219. for ( let i = 0, il = position.count; i < il; i ++ ) {
  8220. _vector$8.fromBufferAttribute( position, i );
  8221. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  8222. }
  8223. // process morph attributes if present
  8224. if ( morphAttributesPosition ) {
  8225. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  8226. const morphAttribute = morphAttributesPosition[ i ];
  8227. const morphTargetsRelative = this.morphTargetsRelative;
  8228. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  8229. _vector$8.fromBufferAttribute( morphAttribute, j );
  8230. if ( morphTargetsRelative ) {
  8231. _offset.fromBufferAttribute( position, j );
  8232. _vector$8.add( _offset );
  8233. }
  8234. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  8235. }
  8236. }
  8237. }
  8238. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  8239. if ( isNaN( this.boundingSphere.radius ) ) {
  8240. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  8241. }
  8242. }
  8243. }
  8244. computeTangents() {
  8245. const index = this.index;
  8246. const attributes = this.attributes;
  8247. // based on http://www.terathon.com/code/tangent.html
  8248. // (per vertex tangents)
  8249. if ( index === null ||
  8250. attributes.position === undefined ||
  8251. attributes.normal === undefined ||
  8252. attributes.uv === undefined ) {
  8253. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  8254. return;
  8255. }
  8256. const positionAttribute = attributes.position;
  8257. const normalAttribute = attributes.normal;
  8258. const uvAttribute = attributes.uv;
  8259. if ( this.hasAttribute( 'tangent' ) === false ) {
  8260. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  8261. }
  8262. const tangentAttribute = this.getAttribute( 'tangent' );
  8263. const tan1 = [], tan2 = [];
  8264. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8265. tan1[ i ] = new Vector3();
  8266. tan2[ i ] = new Vector3();
  8267. }
  8268. const vA = new Vector3(),
  8269. vB = new Vector3(),
  8270. vC = new Vector3(),
  8271. uvA = new Vector2(),
  8272. uvB = new Vector2(),
  8273. uvC = new Vector2(),
  8274. sdir = new Vector3(),
  8275. tdir = new Vector3();
  8276. function handleTriangle( a, b, c ) {
  8277. vA.fromBufferAttribute( positionAttribute, a );
  8278. vB.fromBufferAttribute( positionAttribute, b );
  8279. vC.fromBufferAttribute( positionAttribute, c );
  8280. uvA.fromBufferAttribute( uvAttribute, a );
  8281. uvB.fromBufferAttribute( uvAttribute, b );
  8282. uvC.fromBufferAttribute( uvAttribute, c );
  8283. vB.sub( vA );
  8284. vC.sub( vA );
  8285. uvB.sub( uvA );
  8286. uvC.sub( uvA );
  8287. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  8288. // silently ignore degenerate uv triangles having coincident or colinear vertices
  8289. if ( ! isFinite( r ) ) return;
  8290. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  8291. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  8292. tan1[ a ].add( sdir );
  8293. tan1[ b ].add( sdir );
  8294. tan1[ c ].add( sdir );
  8295. tan2[ a ].add( tdir );
  8296. tan2[ b ].add( tdir );
  8297. tan2[ c ].add( tdir );
  8298. }
  8299. let groups = this.groups;
  8300. if ( groups.length === 0 ) {
  8301. groups = [ {
  8302. start: 0,
  8303. count: index.count
  8304. } ];
  8305. }
  8306. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  8307. const group = groups[ i ];
  8308. const start = group.start;
  8309. const count = group.count;
  8310. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  8311. handleTriangle(
  8312. index.getX( j + 0 ),
  8313. index.getX( j + 1 ),
  8314. index.getX( j + 2 )
  8315. );
  8316. }
  8317. }
  8318. const tmp = new Vector3(), tmp2 = new Vector3();
  8319. const n = new Vector3(), n2 = new Vector3();
  8320. function handleVertex( v ) {
  8321. n.fromBufferAttribute( normalAttribute, v );
  8322. n2.copy( n );
  8323. const t = tan1[ v ];
  8324. // Gram-Schmidt orthogonalize
  8325. tmp.copy( t );
  8326. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  8327. // Calculate handedness
  8328. tmp2.crossVectors( n2, t );
  8329. const test = tmp2.dot( tan2[ v ] );
  8330. const w = ( test < 0.0 ) ? -1 : 1.0;
  8331. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  8332. }
  8333. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  8334. const group = groups[ i ];
  8335. const start = group.start;
  8336. const count = group.count;
  8337. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  8338. handleVertex( index.getX( j + 0 ) );
  8339. handleVertex( index.getX( j + 1 ) );
  8340. handleVertex( index.getX( j + 2 ) );
  8341. }
  8342. }
  8343. }
  8344. computeVertexNormals() {
  8345. const index = this.index;
  8346. const positionAttribute = this.getAttribute( 'position' );
  8347. if ( positionAttribute !== undefined ) {
  8348. let normalAttribute = this.getAttribute( 'normal' );
  8349. if ( normalAttribute === undefined ) {
  8350. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  8351. this.setAttribute( 'normal', normalAttribute );
  8352. } else {
  8353. // reset existing normals to zero
  8354. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  8355. normalAttribute.setXYZ( i, 0, 0, 0 );
  8356. }
  8357. }
  8358. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  8359. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  8360. const cb = new Vector3(), ab = new Vector3();
  8361. // indexed elements
  8362. if ( index ) {
  8363. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  8364. const vA = index.getX( i + 0 );
  8365. const vB = index.getX( i + 1 );
  8366. const vC = index.getX( i + 2 );
  8367. pA.fromBufferAttribute( positionAttribute, vA );
  8368. pB.fromBufferAttribute( positionAttribute, vB );
  8369. pC.fromBufferAttribute( positionAttribute, vC );
  8370. cb.subVectors( pC, pB );
  8371. ab.subVectors( pA, pB );
  8372. cb.cross( ab );
  8373. nA.fromBufferAttribute( normalAttribute, vA );
  8374. nB.fromBufferAttribute( normalAttribute, vB );
  8375. nC.fromBufferAttribute( normalAttribute, vC );
  8376. nA.add( cb );
  8377. nB.add( cb );
  8378. nC.add( cb );
  8379. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  8380. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  8381. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  8382. }
  8383. } else {
  8384. // non-indexed elements (unconnected triangle soup)
  8385. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  8386. pA.fromBufferAttribute( positionAttribute, i + 0 );
  8387. pB.fromBufferAttribute( positionAttribute, i + 1 );
  8388. pC.fromBufferAttribute( positionAttribute, i + 2 );
  8389. cb.subVectors( pC, pB );
  8390. ab.subVectors( pA, pB );
  8391. cb.cross( ab );
  8392. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  8393. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  8394. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  8395. }
  8396. }
  8397. this.normalizeNormals();
  8398. normalAttribute.needsUpdate = true;
  8399. }
  8400. }
  8401. normalizeNormals() {
  8402. const normals = this.attributes.normal;
  8403. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  8404. _vector$8.fromBufferAttribute( normals, i );
  8405. _vector$8.normalize();
  8406. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  8407. }
  8408. }
  8409. toNonIndexed() {
  8410. function convertBufferAttribute( attribute, indices ) {
  8411. const array = attribute.array;
  8412. const itemSize = attribute.itemSize;
  8413. const normalized = attribute.normalized;
  8414. const array2 = new array.constructor( indices.length * itemSize );
  8415. let index = 0, index2 = 0;
  8416. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  8417. if ( attribute.isInterleavedBufferAttribute ) {
  8418. index = indices[ i ] * attribute.data.stride + attribute.offset;
  8419. } else {
  8420. index = indices[ i ] * itemSize;
  8421. }
  8422. for ( let j = 0; j < itemSize; j ++ ) {
  8423. array2[ index2 ++ ] = array[ index ++ ];
  8424. }
  8425. }
  8426. return new BufferAttribute( array2, itemSize, normalized );
  8427. }
  8428. //
  8429. if ( this.index === null ) {
  8430. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  8431. return this;
  8432. }
  8433. const geometry2 = new BufferGeometry();
  8434. const indices = this.index.array;
  8435. const attributes = this.attributes;
  8436. // attributes
  8437. for ( const name in attributes ) {
  8438. const attribute = attributes[ name ];
  8439. const newAttribute = convertBufferAttribute( attribute, indices );
  8440. geometry2.setAttribute( name, newAttribute );
  8441. }
  8442. // morph attributes
  8443. const morphAttributes = this.morphAttributes;
  8444. for ( const name in morphAttributes ) {
  8445. const morphArray = [];
  8446. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8447. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  8448. const attribute = morphAttribute[ i ];
  8449. const newAttribute = convertBufferAttribute( attribute, indices );
  8450. morphArray.push( newAttribute );
  8451. }
  8452. geometry2.morphAttributes[ name ] = morphArray;
  8453. }
  8454. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  8455. // groups
  8456. const groups = this.groups;
  8457. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  8458. const group = groups[ i ];
  8459. geometry2.addGroup( group.start, group.count, group.materialIndex );
  8460. }
  8461. return geometry2;
  8462. }
  8463. toJSON() {
  8464. const data = {
  8465. metadata: {
  8466. version: 4.6,
  8467. type: 'BufferGeometry',
  8468. generator: 'BufferGeometry.toJSON'
  8469. }
  8470. };
  8471. // standard BufferGeometry serialization
  8472. data.uuid = this.uuid;
  8473. data.type = this.type;
  8474. if ( this.name !== '' ) data.name = this.name;
  8475. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  8476. if ( this.parameters !== undefined ) {
  8477. const parameters = this.parameters;
  8478. for ( const key in parameters ) {
  8479. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8480. }
  8481. return data;
  8482. }
  8483. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  8484. data.data = { attributes: {} };
  8485. const index = this.index;
  8486. if ( index !== null ) {
  8487. data.data.index = {
  8488. type: index.array.constructor.name,
  8489. array: Array.prototype.slice.call( index.array )
  8490. };
  8491. }
  8492. const attributes = this.attributes;
  8493. for ( const key in attributes ) {
  8494. const attribute = attributes[ key ];
  8495. data.data.attributes[ key ] = attribute.toJSON( data.data );
  8496. }
  8497. const morphAttributes = {};
  8498. let hasMorphAttributes = false;
  8499. for ( const key in this.morphAttributes ) {
  8500. const attributeArray = this.morphAttributes[ key ];
  8501. const array = [];
  8502. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  8503. const attribute = attributeArray[ i ];
  8504. array.push( attribute.toJSON( data.data ) );
  8505. }
  8506. if ( array.length > 0 ) {
  8507. morphAttributes[ key ] = array;
  8508. hasMorphAttributes = true;
  8509. }
  8510. }
  8511. if ( hasMorphAttributes ) {
  8512. data.data.morphAttributes = morphAttributes;
  8513. data.data.morphTargetsRelative = this.morphTargetsRelative;
  8514. }
  8515. const groups = this.groups;
  8516. if ( groups.length > 0 ) {
  8517. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  8518. }
  8519. const boundingSphere = this.boundingSphere;
  8520. if ( boundingSphere !== null ) {
  8521. data.data.boundingSphere = {
  8522. center: boundingSphere.center.toArray(),
  8523. radius: boundingSphere.radius
  8524. };
  8525. }
  8526. return data;
  8527. }
  8528. clone() {
  8529. return new this.constructor().copy( this );
  8530. }
  8531. copy( source ) {
  8532. // reset
  8533. this.index = null;
  8534. this.attributes = {};
  8535. this.morphAttributes = {};
  8536. this.groups = [];
  8537. this.boundingBox = null;
  8538. this.boundingSphere = null;
  8539. // used for storing cloned, shared data
  8540. const data = {};
  8541. // name
  8542. this.name = source.name;
  8543. // index
  8544. const index = source.index;
  8545. if ( index !== null ) {
  8546. this.setIndex( index.clone( data ) );
  8547. }
  8548. // attributes
  8549. const attributes = source.attributes;
  8550. for ( const name in attributes ) {
  8551. const attribute = attributes[ name ];
  8552. this.setAttribute( name, attribute.clone( data ) );
  8553. }
  8554. // morph attributes
  8555. const morphAttributes = source.morphAttributes;
  8556. for ( const name in morphAttributes ) {
  8557. const array = [];
  8558. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  8559. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  8560. array.push( morphAttribute[ i ].clone( data ) );
  8561. }
  8562. this.morphAttributes[ name ] = array;
  8563. }
  8564. this.morphTargetsRelative = source.morphTargetsRelative;
  8565. // groups
  8566. const groups = source.groups;
  8567. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  8568. const group = groups[ i ];
  8569. this.addGroup( group.start, group.count, group.materialIndex );
  8570. }
  8571. // bounding box
  8572. const boundingBox = source.boundingBox;
  8573. if ( boundingBox !== null ) {
  8574. this.boundingBox = boundingBox.clone();
  8575. }
  8576. // bounding sphere
  8577. const boundingSphere = source.boundingSphere;
  8578. if ( boundingSphere !== null ) {
  8579. this.boundingSphere = boundingSphere.clone();
  8580. }
  8581. // draw range
  8582. this.drawRange.start = source.drawRange.start;
  8583. this.drawRange.count = source.drawRange.count;
  8584. // user data
  8585. this.userData = source.userData;
  8586. return this;
  8587. }
  8588. dispose() {
  8589. this.dispatchEvent( { type: 'dispose' } );
  8590. }
  8591. }
  8592. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  8593. const _ray$3 = /*@__PURE__*/ new Ray();
  8594. const _sphere$6 = /*@__PURE__*/ new Sphere();
  8595. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  8596. const _vA$1 = /*@__PURE__*/ new Vector3();
  8597. const _vB$1 = /*@__PURE__*/ new Vector3();
  8598. const _vC$1 = /*@__PURE__*/ new Vector3();
  8599. const _tempA = /*@__PURE__*/ new Vector3();
  8600. const _morphA = /*@__PURE__*/ new Vector3();
  8601. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  8602. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  8603. class Mesh extends Object3D {
  8604. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  8605. super();
  8606. this.isMesh = true;
  8607. this.type = 'Mesh';
  8608. this.geometry = geometry;
  8609. this.material = material;
  8610. this.updateMorphTargets();
  8611. }
  8612. copy( source, recursive ) {
  8613. super.copy( source, recursive );
  8614. if ( source.morphTargetInfluences !== undefined ) {
  8615. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  8616. }
  8617. if ( source.morphTargetDictionary !== undefined ) {
  8618. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  8619. }
  8620. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  8621. this.geometry = source.geometry;
  8622. return this;
  8623. }
  8624. updateMorphTargets() {
  8625. const geometry = this.geometry;
  8626. const morphAttributes = geometry.morphAttributes;
  8627. const keys = Object.keys( morphAttributes );
  8628. if ( keys.length > 0 ) {
  8629. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  8630. if ( morphAttribute !== undefined ) {
  8631. this.morphTargetInfluences = [];
  8632. this.morphTargetDictionary = {};
  8633. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  8634. const name = morphAttribute[ m ].name || String( m );
  8635. this.morphTargetInfluences.push( 0 );
  8636. this.morphTargetDictionary[ name ] = m;
  8637. }
  8638. }
  8639. }
  8640. }
  8641. getVertexPosition( index, target ) {
  8642. const geometry = this.geometry;
  8643. const position = geometry.attributes.position;
  8644. const morphPosition = geometry.morphAttributes.position;
  8645. const morphTargetsRelative = geometry.morphTargetsRelative;
  8646. target.fromBufferAttribute( position, index );
  8647. const morphInfluences = this.morphTargetInfluences;
  8648. if ( morphPosition && morphInfluences ) {
  8649. _morphA.set( 0, 0, 0 );
  8650. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  8651. const influence = morphInfluences[ i ];
  8652. const morphAttribute = morphPosition[ i ];
  8653. if ( influence === 0 ) continue;
  8654. _tempA.fromBufferAttribute( morphAttribute, index );
  8655. if ( morphTargetsRelative ) {
  8656. _morphA.addScaledVector( _tempA, influence );
  8657. } else {
  8658. _morphA.addScaledVector( _tempA.sub( target ), influence );
  8659. }
  8660. }
  8661. target.add( _morphA );
  8662. }
  8663. return target;
  8664. }
  8665. raycast( raycaster, intersects ) {
  8666. const geometry = this.geometry;
  8667. const material = this.material;
  8668. const matrixWorld = this.matrixWorld;
  8669. if ( material === undefined ) return;
  8670. // test with bounding sphere in world space
  8671. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8672. _sphere$6.copy( geometry.boundingSphere );
  8673. _sphere$6.applyMatrix4( matrixWorld );
  8674. // check distance from ray origin to bounding sphere
  8675. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  8676. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  8677. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  8678. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  8679. }
  8680. // convert ray to local space of mesh
  8681. _inverseMatrix$3.copy( matrixWorld ).invert();
  8682. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  8683. // test with bounding box in local space
  8684. if ( geometry.boundingBox !== null ) {
  8685. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  8686. }
  8687. // test for intersections with geometry
  8688. this._computeIntersections( raycaster, intersects, _ray$3 );
  8689. }
  8690. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  8691. let intersection;
  8692. const geometry = this.geometry;
  8693. const material = this.material;
  8694. const index = geometry.index;
  8695. const position = geometry.attributes.position;
  8696. const uv = geometry.attributes.uv;
  8697. const uv1 = geometry.attributes.uv1;
  8698. const normal = geometry.attributes.normal;
  8699. const groups = geometry.groups;
  8700. const drawRange = geometry.drawRange;
  8701. if ( index !== null ) {
  8702. // indexed buffer geometry
  8703. if ( Array.isArray( material ) ) {
  8704. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  8705. const group = groups[ i ];
  8706. const groupMaterial = material[ group.materialIndex ];
  8707. const start = Math.max( group.start, drawRange.start );
  8708. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  8709. for ( let j = start, jl = end; j < jl; j += 3 ) {
  8710. const a = index.getX( j );
  8711. const b = index.getX( j + 1 );
  8712. const c = index.getX( j + 2 );
  8713. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  8714. if ( intersection ) {
  8715. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  8716. intersection.face.materialIndex = group.materialIndex;
  8717. intersects.push( intersection );
  8718. }
  8719. }
  8720. }
  8721. } else {
  8722. const start = Math.max( 0, drawRange.start );
  8723. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  8724. for ( let i = start, il = end; i < il; i += 3 ) {
  8725. const a = index.getX( i );
  8726. const b = index.getX( i + 1 );
  8727. const c = index.getX( i + 2 );
  8728. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  8729. if ( intersection ) {
  8730. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  8731. intersects.push( intersection );
  8732. }
  8733. }
  8734. }
  8735. } else if ( position !== undefined ) {
  8736. // non-indexed buffer geometry
  8737. if ( Array.isArray( material ) ) {
  8738. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  8739. const group = groups[ i ];
  8740. const groupMaterial = material[ group.materialIndex ];
  8741. const start = Math.max( group.start, drawRange.start );
  8742. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  8743. for ( let j = start, jl = end; j < jl; j += 3 ) {
  8744. const a = j;
  8745. const b = j + 1;
  8746. const c = j + 2;
  8747. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  8748. if ( intersection ) {
  8749. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  8750. intersection.face.materialIndex = group.materialIndex;
  8751. intersects.push( intersection );
  8752. }
  8753. }
  8754. }
  8755. } else {
  8756. const start = Math.max( 0, drawRange.start );
  8757. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  8758. for ( let i = start, il = end; i < il; i += 3 ) {
  8759. const a = i;
  8760. const b = i + 1;
  8761. const c = i + 2;
  8762. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  8763. if ( intersection ) {
  8764. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  8765. intersects.push( intersection );
  8766. }
  8767. }
  8768. }
  8769. }
  8770. }
  8771. }
  8772. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  8773. let intersect;
  8774. if ( material.side === BackSide ) {
  8775. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  8776. } else {
  8777. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  8778. }
  8779. if ( intersect === null ) return null;
  8780. _intersectionPointWorld.copy( point );
  8781. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  8782. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  8783. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  8784. return {
  8785. distance: distance,
  8786. point: _intersectionPointWorld.clone(),
  8787. object: object
  8788. };
  8789. }
  8790. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  8791. object.getVertexPosition( a, _vA$1 );
  8792. object.getVertexPosition( b, _vB$1 );
  8793. object.getVertexPosition( c, _vC$1 );
  8794. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  8795. if ( intersection ) {
  8796. const barycoord = new Vector3();
  8797. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  8798. if ( uv ) {
  8799. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  8800. }
  8801. if ( uv1 ) {
  8802. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  8803. }
  8804. if ( normal ) {
  8805. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  8806. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  8807. intersection.normal.multiplyScalar( -1 );
  8808. }
  8809. }
  8810. const face = {
  8811. a: a,
  8812. b: b,
  8813. c: c,
  8814. normal: new Vector3(),
  8815. materialIndex: 0
  8816. };
  8817. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  8818. intersection.face = face;
  8819. intersection.barycoord = barycoord;
  8820. }
  8821. return intersection;
  8822. }
  8823. class BoxGeometry extends BufferGeometry {
  8824. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  8825. super();
  8826. this.type = 'BoxGeometry';
  8827. this.parameters = {
  8828. width: width,
  8829. height: height,
  8830. depth: depth,
  8831. widthSegments: widthSegments,
  8832. heightSegments: heightSegments,
  8833. depthSegments: depthSegments
  8834. };
  8835. const scope = this;
  8836. // segments
  8837. widthSegments = Math.floor( widthSegments );
  8838. heightSegments = Math.floor( heightSegments );
  8839. depthSegments = Math.floor( depthSegments );
  8840. // buffers
  8841. const indices = [];
  8842. const vertices = [];
  8843. const normals = [];
  8844. const uvs = [];
  8845. // helper variables
  8846. let numberOfVertices = 0;
  8847. let groupStart = 0;
  8848. // build each side of the box geometry
  8849. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  8850. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  8851. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  8852. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  8853. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  8854. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  8855. // build geometry
  8856. this.setIndex( indices );
  8857. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8858. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8859. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8860. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  8861. const segmentWidth = width / gridX;
  8862. const segmentHeight = height / gridY;
  8863. const widthHalf = width / 2;
  8864. const heightHalf = height / 2;
  8865. const depthHalf = depth / 2;
  8866. const gridX1 = gridX + 1;
  8867. const gridY1 = gridY + 1;
  8868. let vertexCounter = 0;
  8869. let groupCount = 0;
  8870. const vector = new Vector3();
  8871. // generate vertices, normals and uvs
  8872. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8873. const y = iy * segmentHeight - heightHalf;
  8874. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8875. const x = ix * segmentWidth - widthHalf;
  8876. // set values to correct vector component
  8877. vector[ u ] = x * udir;
  8878. vector[ v ] = y * vdir;
  8879. vector[ w ] = depthHalf;
  8880. // now apply vector to vertex buffer
  8881. vertices.push( vector.x, vector.y, vector.z );
  8882. // set values to correct vector component
  8883. vector[ u ] = 0;
  8884. vector[ v ] = 0;
  8885. vector[ w ] = depth > 0 ? 1 : -1;
  8886. // now apply vector to normal buffer
  8887. normals.push( vector.x, vector.y, vector.z );
  8888. // uvs
  8889. uvs.push( ix / gridX );
  8890. uvs.push( 1 - ( iy / gridY ) );
  8891. // counters
  8892. vertexCounter += 1;
  8893. }
  8894. }
  8895. // indices
  8896. // 1. you need three indices to draw a single face
  8897. // 2. a single segment consists of two faces
  8898. // 3. so we need to generate six (2*3) indices per segment
  8899. for ( let iy = 0; iy < gridY; iy ++ ) {
  8900. for ( let ix = 0; ix < gridX; ix ++ ) {
  8901. const a = numberOfVertices + ix + gridX1 * iy;
  8902. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  8903. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  8904. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  8905. // faces
  8906. indices.push( a, b, d );
  8907. indices.push( b, c, d );
  8908. // increase counter
  8909. groupCount += 6;
  8910. }
  8911. }
  8912. // add a group to the geometry. this will ensure multi material support
  8913. scope.addGroup( groupStart, groupCount, materialIndex );
  8914. // calculate new start value for groups
  8915. groupStart += groupCount;
  8916. // update total number of vertices
  8917. numberOfVertices += vertexCounter;
  8918. }
  8919. }
  8920. copy( source ) {
  8921. super.copy( source );
  8922. this.parameters = Object.assign( {}, source.parameters );
  8923. return this;
  8924. }
  8925. static fromJSON( data ) {
  8926. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  8927. }
  8928. }
  8929. /**
  8930. * Uniform Utilities
  8931. */
  8932. function cloneUniforms( src ) {
  8933. const dst = {};
  8934. for ( const u in src ) {
  8935. dst[ u ] = {};
  8936. for ( const p in src[ u ] ) {
  8937. const property = src[ u ][ p ];
  8938. if ( property && ( property.isColor ||
  8939. property.isMatrix3 || property.isMatrix4 ||
  8940. property.isVector2 || property.isVector3 || property.isVector4 ||
  8941. property.isTexture || property.isQuaternion ) ) {
  8942. if ( property.isRenderTargetTexture ) {
  8943. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  8944. dst[ u ][ p ] = null;
  8945. } else {
  8946. dst[ u ][ p ] = property.clone();
  8947. }
  8948. } else if ( Array.isArray( property ) ) {
  8949. dst[ u ][ p ] = property.slice();
  8950. } else {
  8951. dst[ u ][ p ] = property;
  8952. }
  8953. }
  8954. }
  8955. return dst;
  8956. }
  8957. function mergeUniforms( uniforms ) {
  8958. const merged = {};
  8959. for ( let u = 0; u < uniforms.length; u ++ ) {
  8960. const tmp = cloneUniforms( uniforms[ u ] );
  8961. for ( const p in tmp ) {
  8962. merged[ p ] = tmp[ p ];
  8963. }
  8964. }
  8965. return merged;
  8966. }
  8967. function cloneUniformsGroups( src ) {
  8968. const dst = [];
  8969. for ( let u = 0; u < src.length; u ++ ) {
  8970. dst.push( src[ u ].clone() );
  8971. }
  8972. return dst;
  8973. }
  8974. function getUnlitUniformColorSpace( renderer ) {
  8975. const currentRenderTarget = renderer.getRenderTarget();
  8976. if ( currentRenderTarget === null ) {
  8977. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  8978. return renderer.outputColorSpace;
  8979. }
  8980. // https://github.com/mrdoob/three.js/issues/27868
  8981. if ( currentRenderTarget.isXRRenderTarget === true ) {
  8982. return currentRenderTarget.texture.colorSpace;
  8983. }
  8984. return ColorManagement.workingColorSpace;
  8985. }
  8986. // Legacy
  8987. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  8988. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  8989. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  8990. class ShaderMaterial extends Material {
  8991. constructor( parameters ) {
  8992. super();
  8993. this.isShaderMaterial = true;
  8994. this.type = 'ShaderMaterial';
  8995. this.defines = {};
  8996. this.uniforms = {};
  8997. this.uniformsGroups = [];
  8998. this.vertexShader = default_vertex;
  8999. this.fragmentShader = default_fragment;
  9000. this.linewidth = 1;
  9001. this.wireframe = false;
  9002. this.wireframeLinewidth = 1;
  9003. this.fog = false; // set to use scene fog
  9004. this.lights = false; // set to use scene lights
  9005. this.clipping = false; // set to use user-defined clipping planes
  9006. this.forceSinglePass = true;
  9007. this.extensions = {
  9008. clipCullDistance: false, // set to use vertex shader clipping
  9009. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  9010. };
  9011. // When rendered geometry doesn't include these attributes but the material does,
  9012. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9013. this.defaultAttributeValues = {
  9014. 'color': [ 1, 1, 1 ],
  9015. 'uv': [ 0, 0 ],
  9016. 'uv1': [ 0, 0 ]
  9017. };
  9018. this.index0AttributeName = undefined;
  9019. this.uniformsNeedUpdate = false;
  9020. this.glslVersion = null;
  9021. if ( parameters !== undefined ) {
  9022. this.setValues( parameters );
  9023. }
  9024. }
  9025. copy( source ) {
  9026. super.copy( source );
  9027. this.fragmentShader = source.fragmentShader;
  9028. this.vertexShader = source.vertexShader;
  9029. this.uniforms = cloneUniforms( source.uniforms );
  9030. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  9031. this.defines = Object.assign( {}, source.defines );
  9032. this.wireframe = source.wireframe;
  9033. this.wireframeLinewidth = source.wireframeLinewidth;
  9034. this.fog = source.fog;
  9035. this.lights = source.lights;
  9036. this.clipping = source.clipping;
  9037. this.extensions = Object.assign( {}, source.extensions );
  9038. this.glslVersion = source.glslVersion;
  9039. return this;
  9040. }
  9041. toJSON( meta ) {
  9042. const data = super.toJSON( meta );
  9043. data.glslVersion = this.glslVersion;
  9044. data.uniforms = {};
  9045. for ( const name in this.uniforms ) {
  9046. const uniform = this.uniforms[ name ];
  9047. const value = uniform.value;
  9048. if ( value && value.isTexture ) {
  9049. data.uniforms[ name ] = {
  9050. type: 't',
  9051. value: value.toJSON( meta ).uuid
  9052. };
  9053. } else if ( value && value.isColor ) {
  9054. data.uniforms[ name ] = {
  9055. type: 'c',
  9056. value: value.getHex()
  9057. };
  9058. } else if ( value && value.isVector2 ) {
  9059. data.uniforms[ name ] = {
  9060. type: 'v2',
  9061. value: value.toArray()
  9062. };
  9063. } else if ( value && value.isVector3 ) {
  9064. data.uniforms[ name ] = {
  9065. type: 'v3',
  9066. value: value.toArray()
  9067. };
  9068. } else if ( value && value.isVector4 ) {
  9069. data.uniforms[ name ] = {
  9070. type: 'v4',
  9071. value: value.toArray()
  9072. };
  9073. } else if ( value && value.isMatrix3 ) {
  9074. data.uniforms[ name ] = {
  9075. type: 'm3',
  9076. value: value.toArray()
  9077. };
  9078. } else if ( value && value.isMatrix4 ) {
  9079. data.uniforms[ name ] = {
  9080. type: 'm4',
  9081. value: value.toArray()
  9082. };
  9083. } else {
  9084. data.uniforms[ name ] = {
  9085. value: value
  9086. };
  9087. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  9088. }
  9089. }
  9090. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  9091. data.vertexShader = this.vertexShader;
  9092. data.fragmentShader = this.fragmentShader;
  9093. data.lights = this.lights;
  9094. data.clipping = this.clipping;
  9095. const extensions = {};
  9096. for ( const key in this.extensions ) {
  9097. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  9098. }
  9099. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  9100. return data;
  9101. }
  9102. }
  9103. class Camera extends Object3D {
  9104. constructor() {
  9105. super();
  9106. this.isCamera = true;
  9107. this.type = 'Camera';
  9108. this.matrixWorldInverse = new Matrix4();
  9109. this.projectionMatrix = new Matrix4();
  9110. this.projectionMatrixInverse = new Matrix4();
  9111. this.coordinateSystem = WebGLCoordinateSystem;
  9112. }
  9113. copy( source, recursive ) {
  9114. super.copy( source, recursive );
  9115. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9116. this.projectionMatrix.copy( source.projectionMatrix );
  9117. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  9118. this.coordinateSystem = source.coordinateSystem;
  9119. return this;
  9120. }
  9121. getWorldDirection( target ) {
  9122. return super.getWorldDirection( target ).negate();
  9123. }
  9124. updateMatrixWorld( force ) {
  9125. super.updateMatrixWorld( force );
  9126. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  9127. }
  9128. updateWorldMatrix( updateParents, updateChildren ) {
  9129. super.updateWorldMatrix( updateParents, updateChildren );
  9130. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  9131. }
  9132. clone() {
  9133. return new this.constructor().copy( this );
  9134. }
  9135. }
  9136. const _v3$1 = /*@__PURE__*/ new Vector3();
  9137. const _minTarget = /*@__PURE__*/ new Vector2();
  9138. const _maxTarget = /*@__PURE__*/ new Vector2();
  9139. class PerspectiveCamera extends Camera {
  9140. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  9141. super();
  9142. this.isPerspectiveCamera = true;
  9143. this.type = 'PerspectiveCamera';
  9144. this.fov = fov;
  9145. this.zoom = 1;
  9146. this.near = near;
  9147. this.far = far;
  9148. this.focus = 10;
  9149. this.aspect = aspect;
  9150. this.view = null;
  9151. this.filmGauge = 35; // width of the film (default in millimeters)
  9152. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  9153. this.updateProjectionMatrix();
  9154. }
  9155. copy( source, recursive ) {
  9156. super.copy( source, recursive );
  9157. this.fov = source.fov;
  9158. this.zoom = source.zoom;
  9159. this.near = source.near;
  9160. this.far = source.far;
  9161. this.focus = source.focus;
  9162. this.aspect = source.aspect;
  9163. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9164. this.filmGauge = source.filmGauge;
  9165. this.filmOffset = source.filmOffset;
  9166. return this;
  9167. }
  9168. /**
  9169. * Sets the FOV by focal length in respect to the current .filmGauge.
  9170. *
  9171. * The default film gauge is 35, so that the focal length can be specified for
  9172. * a 35mm (full frame) camera.
  9173. *
  9174. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  9175. */
  9176. setFocalLength( focalLength ) {
  9177. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  9178. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  9179. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  9180. this.updateProjectionMatrix();
  9181. }
  9182. /**
  9183. * Calculates the focal length from the current .fov and .filmGauge.
  9184. *
  9185. * @returns {number}
  9186. */
  9187. getFocalLength() {
  9188. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  9189. return 0.5 * this.getFilmHeight() / vExtentSlope;
  9190. }
  9191. getEffectiveFOV() {
  9192. return RAD2DEG * 2 * Math.atan(
  9193. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  9194. }
  9195. getFilmWidth() {
  9196. // film not completely covered in portrait format (aspect < 1)
  9197. return this.filmGauge * Math.min( this.aspect, 1 );
  9198. }
  9199. getFilmHeight() {
  9200. // film not completely covered in landscape format (aspect > 1)
  9201. return this.filmGauge / Math.max( this.aspect, 1 );
  9202. }
  9203. /**
  9204. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  9205. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  9206. *
  9207. * @param {number} distance
  9208. * @param {Vector2} minTarget
  9209. * @param {Vector2} maxTarget
  9210. */
  9211. getViewBounds( distance, minTarget, maxTarget ) {
  9212. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  9213. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  9214. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  9215. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  9216. }
  9217. /**
  9218. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  9219. *
  9220. * @param {number} distance
  9221. * @param {Vector2} target - Vector2 target used to store result where x is width and y is height.
  9222. * @returns {Vector2}
  9223. */
  9224. getViewSize( distance, target ) {
  9225. this.getViewBounds( distance, _minTarget, _maxTarget );
  9226. return target.subVectors( _maxTarget, _minTarget );
  9227. }
  9228. /**
  9229. * Sets an offset in a larger frustum. This is useful for multi-window or
  9230. * multi-monitor/multi-machine setups.
  9231. *
  9232. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9233. * the monitors are in grid like this
  9234. *
  9235. * +---+---+---+
  9236. * | A | B | C |
  9237. * +---+---+---+
  9238. * | D | E | F |
  9239. * +---+---+---+
  9240. *
  9241. * then for each monitor you would call it like this
  9242. *
  9243. * const w = 1920;
  9244. * const h = 1080;
  9245. * const fullWidth = w * 3;
  9246. * const fullHeight = h * 2;
  9247. *
  9248. * --A--
  9249. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9250. * --B--
  9251. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9252. * --C--
  9253. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9254. * --D--
  9255. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9256. * --E--
  9257. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9258. * --F--
  9259. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9260. *
  9261. * Note there is no reason monitors have to be the same size or in a grid.
  9262. *
  9263. * @param {number} fullWidth
  9264. * @param {number} fullHeight
  9265. * @param {number} x
  9266. * @param {number} y
  9267. * @param {number} width
  9268. * @param {number} height
  9269. */
  9270. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9271. this.aspect = fullWidth / fullHeight;
  9272. if ( this.view === null ) {
  9273. this.view = {
  9274. enabled: true,
  9275. fullWidth: 1,
  9276. fullHeight: 1,
  9277. offsetX: 0,
  9278. offsetY: 0,
  9279. width: 1,
  9280. height: 1
  9281. };
  9282. }
  9283. this.view.enabled = true;
  9284. this.view.fullWidth = fullWidth;
  9285. this.view.fullHeight = fullHeight;
  9286. this.view.offsetX = x;
  9287. this.view.offsetY = y;
  9288. this.view.width = width;
  9289. this.view.height = height;
  9290. this.updateProjectionMatrix();
  9291. }
  9292. clearViewOffset() {
  9293. if ( this.view !== null ) {
  9294. this.view.enabled = false;
  9295. }
  9296. this.updateProjectionMatrix();
  9297. }
  9298. updateProjectionMatrix() {
  9299. const near = this.near;
  9300. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  9301. let height = 2 * top;
  9302. let width = this.aspect * height;
  9303. let left = -0.5 * width;
  9304. const view = this.view;
  9305. if ( this.view !== null && this.view.enabled ) {
  9306. const fullWidth = view.fullWidth,
  9307. fullHeight = view.fullHeight;
  9308. left += view.offsetX * width / fullWidth;
  9309. top -= view.offsetY * height / fullHeight;
  9310. width *= view.width / fullWidth;
  9311. height *= view.height / fullHeight;
  9312. }
  9313. const skew = this.filmOffset;
  9314. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  9315. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  9316. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9317. }
  9318. toJSON( meta ) {
  9319. const data = super.toJSON( meta );
  9320. data.object.fov = this.fov;
  9321. data.object.zoom = this.zoom;
  9322. data.object.near = this.near;
  9323. data.object.far = this.far;
  9324. data.object.focus = this.focus;
  9325. data.object.aspect = this.aspect;
  9326. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9327. data.object.filmGauge = this.filmGauge;
  9328. data.object.filmOffset = this.filmOffset;
  9329. return data;
  9330. }
  9331. }
  9332. const fov = -90; // negative fov is not an error
  9333. const aspect = 1;
  9334. class CubeCamera extends Object3D {
  9335. constructor( near, far, renderTarget ) {
  9336. super();
  9337. this.type = 'CubeCamera';
  9338. this.renderTarget = renderTarget;
  9339. this.coordinateSystem = null;
  9340. this.activeMipmapLevel = 0;
  9341. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  9342. cameraPX.layers = this.layers;
  9343. this.add( cameraPX );
  9344. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  9345. cameraNX.layers = this.layers;
  9346. this.add( cameraNX );
  9347. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  9348. cameraPY.layers = this.layers;
  9349. this.add( cameraPY );
  9350. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  9351. cameraNY.layers = this.layers;
  9352. this.add( cameraNY );
  9353. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  9354. cameraPZ.layers = this.layers;
  9355. this.add( cameraPZ );
  9356. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  9357. cameraNZ.layers = this.layers;
  9358. this.add( cameraNZ );
  9359. }
  9360. updateCoordinateSystem() {
  9361. const coordinateSystem = this.coordinateSystem;
  9362. const cameras = this.children.concat();
  9363. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  9364. for ( const camera of cameras ) this.remove( camera );
  9365. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9366. cameraPX.up.set( 0, 1, 0 );
  9367. cameraPX.lookAt( 1, 0, 0 );
  9368. cameraNX.up.set( 0, 1, 0 );
  9369. cameraNX.lookAt( -1, 0, 0 );
  9370. cameraPY.up.set( 0, 0, -1 );
  9371. cameraPY.lookAt( 0, 1, 0 );
  9372. cameraNY.up.set( 0, 0, 1 );
  9373. cameraNY.lookAt( 0, -1, 0 );
  9374. cameraPZ.up.set( 0, 1, 0 );
  9375. cameraPZ.lookAt( 0, 0, 1 );
  9376. cameraNZ.up.set( 0, 1, 0 );
  9377. cameraNZ.lookAt( 0, 0, -1 );
  9378. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9379. cameraPX.up.set( 0, -1, 0 );
  9380. cameraPX.lookAt( -1, 0, 0 );
  9381. cameraNX.up.set( 0, -1, 0 );
  9382. cameraNX.lookAt( 1, 0, 0 );
  9383. cameraPY.up.set( 0, 0, 1 );
  9384. cameraPY.lookAt( 0, 1, 0 );
  9385. cameraNY.up.set( 0, 0, -1 );
  9386. cameraNY.lookAt( 0, -1, 0 );
  9387. cameraPZ.up.set( 0, -1, 0 );
  9388. cameraPZ.lookAt( 0, 0, 1 );
  9389. cameraNZ.up.set( 0, -1, 0 );
  9390. cameraNZ.lookAt( 0, 0, -1 );
  9391. } else {
  9392. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  9393. }
  9394. for ( const camera of cameras ) {
  9395. this.add( camera );
  9396. camera.updateMatrixWorld();
  9397. }
  9398. }
  9399. update( renderer, scene ) {
  9400. if ( this.parent === null ) this.updateMatrixWorld();
  9401. const { renderTarget, activeMipmapLevel } = this;
  9402. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  9403. this.coordinateSystem = renderer.coordinateSystem;
  9404. this.updateCoordinateSystem();
  9405. }
  9406. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  9407. const currentRenderTarget = renderer.getRenderTarget();
  9408. const currentActiveCubeFace = renderer.getActiveCubeFace();
  9409. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  9410. const currentXrEnabled = renderer.xr.enabled;
  9411. renderer.xr.enabled = false;
  9412. const generateMipmaps = renderTarget.texture.generateMipmaps;
  9413. renderTarget.texture.generateMipmaps = false;
  9414. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  9415. renderer.render( scene, cameraPX );
  9416. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  9417. renderer.render( scene, cameraNX );
  9418. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  9419. renderer.render( scene, cameraPY );
  9420. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  9421. renderer.render( scene, cameraNY );
  9422. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  9423. renderer.render( scene, cameraPZ );
  9424. // mipmaps are generated during the last call of render()
  9425. // at this point, all sides of the cube render target are defined
  9426. renderTarget.texture.generateMipmaps = generateMipmaps;
  9427. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  9428. renderer.render( scene, cameraNZ );
  9429. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  9430. renderer.xr.enabled = currentXrEnabled;
  9431. renderTarget.texture.needsPMREMUpdate = true;
  9432. }
  9433. }
  9434. class CubeTexture extends Texture {
  9435. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  9436. images = images !== undefined ? images : [];
  9437. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  9438. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  9439. this.isCubeTexture = true;
  9440. this.flipY = false;
  9441. }
  9442. get images() {
  9443. return this.image;
  9444. }
  9445. set images( value ) {
  9446. this.image = value;
  9447. }
  9448. }
  9449. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  9450. constructor( size = 1, options = {} ) {
  9451. super( size, size, options );
  9452. this.isWebGLCubeRenderTarget = true;
  9453. const image = { width: size, height: size, depth: 1 };
  9454. const images = [ image, image, image, image, image, image ];
  9455. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  9456. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  9457. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  9458. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  9459. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  9460. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  9461. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  9462. this.texture.isRenderTargetTexture = true;
  9463. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  9464. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  9465. }
  9466. fromEquirectangularTexture( renderer, texture ) {
  9467. this.texture.type = texture.type;
  9468. this.texture.colorSpace = texture.colorSpace;
  9469. this.texture.generateMipmaps = texture.generateMipmaps;
  9470. this.texture.minFilter = texture.minFilter;
  9471. this.texture.magFilter = texture.magFilter;
  9472. const shader = {
  9473. uniforms: {
  9474. tEquirect: { value: null },
  9475. },
  9476. vertexShader: /* glsl */`
  9477. varying vec3 vWorldDirection;
  9478. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  9479. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  9480. }
  9481. void main() {
  9482. vWorldDirection = transformDirection( position, modelMatrix );
  9483. #include <begin_vertex>
  9484. #include <project_vertex>
  9485. }
  9486. `,
  9487. fragmentShader: /* glsl */`
  9488. uniform sampler2D tEquirect;
  9489. varying vec3 vWorldDirection;
  9490. #include <common>
  9491. void main() {
  9492. vec3 direction = normalize( vWorldDirection );
  9493. vec2 sampleUV = equirectUv( direction );
  9494. gl_FragColor = texture2D( tEquirect, sampleUV );
  9495. }
  9496. `
  9497. };
  9498. const geometry = new BoxGeometry( 5, 5, 5 );
  9499. const material = new ShaderMaterial( {
  9500. name: 'CubemapFromEquirect',
  9501. uniforms: cloneUniforms( shader.uniforms ),
  9502. vertexShader: shader.vertexShader,
  9503. fragmentShader: shader.fragmentShader,
  9504. side: BackSide,
  9505. blending: NoBlending
  9506. } );
  9507. material.uniforms.tEquirect.value = texture;
  9508. const mesh = new Mesh( geometry, material );
  9509. const currentMinFilter = texture.minFilter;
  9510. // Avoid blurred poles
  9511. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  9512. const camera = new CubeCamera( 1, 10, this );
  9513. camera.update( renderer, mesh );
  9514. texture.minFilter = currentMinFilter;
  9515. mesh.geometry.dispose();
  9516. mesh.material.dispose();
  9517. return this;
  9518. }
  9519. clear( renderer, color, depth, stencil ) {
  9520. const currentRenderTarget = renderer.getRenderTarget();
  9521. for ( let i = 0; i < 6; i ++ ) {
  9522. renderer.setRenderTarget( this, i );
  9523. renderer.clear( color, depth, stencil );
  9524. }
  9525. renderer.setRenderTarget( currentRenderTarget );
  9526. }
  9527. }
  9528. class Group extends Object3D {
  9529. constructor() {
  9530. super();
  9531. this.isGroup = true;
  9532. this.type = 'Group';
  9533. }
  9534. }
  9535. const _moveEvent = { type: 'move' };
  9536. class WebXRController {
  9537. constructor() {
  9538. this._targetRay = null;
  9539. this._grip = null;
  9540. this._hand = null;
  9541. }
  9542. getHandSpace() {
  9543. if ( this._hand === null ) {
  9544. this._hand = new Group();
  9545. this._hand.matrixAutoUpdate = false;
  9546. this._hand.visible = false;
  9547. this._hand.joints = {};
  9548. this._hand.inputState = { pinching: false };
  9549. }
  9550. return this._hand;
  9551. }
  9552. getTargetRaySpace() {
  9553. if ( this._targetRay === null ) {
  9554. this._targetRay = new Group();
  9555. this._targetRay.matrixAutoUpdate = false;
  9556. this._targetRay.visible = false;
  9557. this._targetRay.hasLinearVelocity = false;
  9558. this._targetRay.linearVelocity = new Vector3();
  9559. this._targetRay.hasAngularVelocity = false;
  9560. this._targetRay.angularVelocity = new Vector3();
  9561. }
  9562. return this._targetRay;
  9563. }
  9564. getGripSpace() {
  9565. if ( this._grip === null ) {
  9566. this._grip = new Group();
  9567. this._grip.matrixAutoUpdate = false;
  9568. this._grip.visible = false;
  9569. this._grip.hasLinearVelocity = false;
  9570. this._grip.linearVelocity = new Vector3();
  9571. this._grip.hasAngularVelocity = false;
  9572. this._grip.angularVelocity = new Vector3();
  9573. }
  9574. return this._grip;
  9575. }
  9576. dispatchEvent( event ) {
  9577. if ( this._targetRay !== null ) {
  9578. this._targetRay.dispatchEvent( event );
  9579. }
  9580. if ( this._grip !== null ) {
  9581. this._grip.dispatchEvent( event );
  9582. }
  9583. if ( this._hand !== null ) {
  9584. this._hand.dispatchEvent( event );
  9585. }
  9586. return this;
  9587. }
  9588. connect( inputSource ) {
  9589. if ( inputSource && inputSource.hand ) {
  9590. const hand = this._hand;
  9591. if ( hand ) {
  9592. for ( const inputjoint of inputSource.hand.values() ) {
  9593. // Initialize hand with joints when connected
  9594. this._getHandJoint( hand, inputjoint );
  9595. }
  9596. }
  9597. }
  9598. this.dispatchEvent( { type: 'connected', data: inputSource } );
  9599. return this;
  9600. }
  9601. disconnect( inputSource ) {
  9602. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  9603. if ( this._targetRay !== null ) {
  9604. this._targetRay.visible = false;
  9605. }
  9606. if ( this._grip !== null ) {
  9607. this._grip.visible = false;
  9608. }
  9609. if ( this._hand !== null ) {
  9610. this._hand.visible = false;
  9611. }
  9612. return this;
  9613. }
  9614. update( inputSource, frame, referenceSpace ) {
  9615. let inputPose = null;
  9616. let gripPose = null;
  9617. let handPose = null;
  9618. const targetRay = this._targetRay;
  9619. const grip = this._grip;
  9620. const hand = this._hand;
  9621. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  9622. if ( hand && inputSource.hand ) {
  9623. handPose = true;
  9624. for ( const inputjoint of inputSource.hand.values() ) {
  9625. // Update the joints groups with the XRJoint poses
  9626. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  9627. // The transform of this joint will be updated with the joint pose on each frame
  9628. const joint = this._getHandJoint( hand, inputjoint );
  9629. if ( jointPose !== null ) {
  9630. joint.matrix.fromArray( jointPose.transform.matrix );
  9631. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  9632. joint.matrixWorldNeedsUpdate = true;
  9633. joint.jointRadius = jointPose.radius;
  9634. }
  9635. joint.visible = jointPose !== null;
  9636. }
  9637. // Custom events
  9638. // Check pinchz
  9639. const indexTip = hand.joints[ 'index-finger-tip' ];
  9640. const thumbTip = hand.joints[ 'thumb-tip' ];
  9641. const distance = indexTip.position.distanceTo( thumbTip.position );
  9642. const distanceToPinch = 0.02;
  9643. const threshold = 0.005;
  9644. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  9645. hand.inputState.pinching = false;
  9646. this.dispatchEvent( {
  9647. type: 'pinchend',
  9648. handedness: inputSource.handedness,
  9649. target: this
  9650. } );
  9651. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  9652. hand.inputState.pinching = true;
  9653. this.dispatchEvent( {
  9654. type: 'pinchstart',
  9655. handedness: inputSource.handedness,
  9656. target: this
  9657. } );
  9658. }
  9659. } else {
  9660. if ( grip !== null && inputSource.gripSpace ) {
  9661. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  9662. if ( gripPose !== null ) {
  9663. grip.matrix.fromArray( gripPose.transform.matrix );
  9664. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  9665. grip.matrixWorldNeedsUpdate = true;
  9666. if ( gripPose.linearVelocity ) {
  9667. grip.hasLinearVelocity = true;
  9668. grip.linearVelocity.copy( gripPose.linearVelocity );
  9669. } else {
  9670. grip.hasLinearVelocity = false;
  9671. }
  9672. if ( gripPose.angularVelocity ) {
  9673. grip.hasAngularVelocity = true;
  9674. grip.angularVelocity.copy( gripPose.angularVelocity );
  9675. } else {
  9676. grip.hasAngularVelocity = false;
  9677. }
  9678. }
  9679. }
  9680. }
  9681. if ( targetRay !== null ) {
  9682. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  9683. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  9684. if ( inputPose === null && gripPose !== null ) {
  9685. inputPose = gripPose;
  9686. }
  9687. if ( inputPose !== null ) {
  9688. targetRay.matrix.fromArray( inputPose.transform.matrix );
  9689. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  9690. targetRay.matrixWorldNeedsUpdate = true;
  9691. if ( inputPose.linearVelocity ) {
  9692. targetRay.hasLinearVelocity = true;
  9693. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  9694. } else {
  9695. targetRay.hasLinearVelocity = false;
  9696. }
  9697. if ( inputPose.angularVelocity ) {
  9698. targetRay.hasAngularVelocity = true;
  9699. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  9700. } else {
  9701. targetRay.hasAngularVelocity = false;
  9702. }
  9703. this.dispatchEvent( _moveEvent );
  9704. }
  9705. }
  9706. }
  9707. if ( targetRay !== null ) {
  9708. targetRay.visible = ( inputPose !== null );
  9709. }
  9710. if ( grip !== null ) {
  9711. grip.visible = ( gripPose !== null );
  9712. }
  9713. if ( hand !== null ) {
  9714. hand.visible = ( handPose !== null );
  9715. }
  9716. return this;
  9717. }
  9718. // private method
  9719. _getHandJoint( hand, inputjoint ) {
  9720. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  9721. const joint = new Group();
  9722. joint.matrixAutoUpdate = false;
  9723. joint.visible = false;
  9724. hand.joints[ inputjoint.jointName ] = joint;
  9725. hand.add( joint );
  9726. }
  9727. return hand.joints[ inputjoint.jointName ];
  9728. }
  9729. }
  9730. class FogExp2 {
  9731. constructor( color, density = 0.00025 ) {
  9732. this.isFogExp2 = true;
  9733. this.name = '';
  9734. this.color = new Color( color );
  9735. this.density = density;
  9736. }
  9737. clone() {
  9738. return new FogExp2( this.color, this.density );
  9739. }
  9740. toJSON( /* meta */ ) {
  9741. return {
  9742. type: 'FogExp2',
  9743. name: this.name,
  9744. color: this.color.getHex(),
  9745. density: this.density
  9746. };
  9747. }
  9748. }
  9749. class Fog {
  9750. constructor( color, near = 1, far = 1000 ) {
  9751. this.isFog = true;
  9752. this.name = '';
  9753. this.color = new Color( color );
  9754. this.near = near;
  9755. this.far = far;
  9756. }
  9757. clone() {
  9758. return new Fog( this.color, this.near, this.far );
  9759. }
  9760. toJSON( /* meta */ ) {
  9761. return {
  9762. type: 'Fog',
  9763. name: this.name,
  9764. color: this.color.getHex(),
  9765. near: this.near,
  9766. far: this.far
  9767. };
  9768. }
  9769. }
  9770. class Scene extends Object3D {
  9771. constructor() {
  9772. super();
  9773. this.isScene = true;
  9774. this.type = 'Scene';
  9775. this.background = null;
  9776. this.environment = null;
  9777. this.fog = null;
  9778. this.backgroundBlurriness = 0;
  9779. this.backgroundIntensity = 1;
  9780. this.backgroundRotation = new Euler();
  9781. this.environmentIntensity = 1;
  9782. this.environmentRotation = new Euler();
  9783. this.overrideMaterial = null;
  9784. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  9785. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  9786. }
  9787. }
  9788. copy( source, recursive ) {
  9789. super.copy( source, recursive );
  9790. if ( source.background !== null ) this.background = source.background.clone();
  9791. if ( source.environment !== null ) this.environment = source.environment.clone();
  9792. if ( source.fog !== null ) this.fog = source.fog.clone();
  9793. this.backgroundBlurriness = source.backgroundBlurriness;
  9794. this.backgroundIntensity = source.backgroundIntensity;
  9795. this.backgroundRotation.copy( source.backgroundRotation );
  9796. this.environmentIntensity = source.environmentIntensity;
  9797. this.environmentRotation.copy( source.environmentRotation );
  9798. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  9799. this.matrixAutoUpdate = source.matrixAutoUpdate;
  9800. return this;
  9801. }
  9802. toJSON( meta ) {
  9803. const data = super.toJSON( meta );
  9804. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  9805. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  9806. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  9807. data.object.backgroundRotation = this.backgroundRotation.toArray();
  9808. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  9809. data.object.environmentRotation = this.environmentRotation.toArray();
  9810. return data;
  9811. }
  9812. }
  9813. class InterleavedBuffer {
  9814. constructor( array, stride ) {
  9815. this.isInterleavedBuffer = true;
  9816. this.array = array;
  9817. this.stride = stride;
  9818. this.count = array !== undefined ? array.length / stride : 0;
  9819. this.usage = StaticDrawUsage;
  9820. this.updateRanges = [];
  9821. this.version = 0;
  9822. this.uuid = generateUUID();
  9823. }
  9824. onUploadCallback() {}
  9825. set needsUpdate( value ) {
  9826. if ( value === true ) this.version ++;
  9827. }
  9828. setUsage( value ) {
  9829. this.usage = value;
  9830. return this;
  9831. }
  9832. addUpdateRange( start, count ) {
  9833. this.updateRanges.push( { start, count } );
  9834. }
  9835. clearUpdateRanges() {
  9836. this.updateRanges.length = 0;
  9837. }
  9838. copy( source ) {
  9839. this.array = new source.array.constructor( source.array );
  9840. this.count = source.count;
  9841. this.stride = source.stride;
  9842. this.usage = source.usage;
  9843. return this;
  9844. }
  9845. copyAt( index1, attribute, index2 ) {
  9846. index1 *= this.stride;
  9847. index2 *= attribute.stride;
  9848. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  9849. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  9850. }
  9851. return this;
  9852. }
  9853. set( value, offset = 0 ) {
  9854. this.array.set( value, offset );
  9855. return this;
  9856. }
  9857. clone( data ) {
  9858. if ( data.arrayBuffers === undefined ) {
  9859. data.arrayBuffers = {};
  9860. }
  9861. if ( this.array.buffer._uuid === undefined ) {
  9862. this.array.buffer._uuid = generateUUID();
  9863. }
  9864. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  9865. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  9866. }
  9867. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  9868. const ib = new this.constructor( array, this.stride );
  9869. ib.setUsage( this.usage );
  9870. return ib;
  9871. }
  9872. onUpload( callback ) {
  9873. this.onUploadCallback = callback;
  9874. return this;
  9875. }
  9876. toJSON( data ) {
  9877. if ( data.arrayBuffers === undefined ) {
  9878. data.arrayBuffers = {};
  9879. }
  9880. // generate UUID for array buffer if necessary
  9881. if ( this.array.buffer._uuid === undefined ) {
  9882. this.array.buffer._uuid = generateUUID();
  9883. }
  9884. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  9885. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  9886. }
  9887. //
  9888. return {
  9889. uuid: this.uuid,
  9890. buffer: this.array.buffer._uuid,
  9891. type: this.array.constructor.name,
  9892. stride: this.stride
  9893. };
  9894. }
  9895. }
  9896. const _vector$7 = /*@__PURE__*/ new Vector3();
  9897. class InterleavedBufferAttribute {
  9898. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  9899. this.isInterleavedBufferAttribute = true;
  9900. this.name = '';
  9901. this.data = interleavedBuffer;
  9902. this.itemSize = itemSize;
  9903. this.offset = offset;
  9904. this.normalized = normalized;
  9905. }
  9906. get count() {
  9907. return this.data.count;
  9908. }
  9909. get array() {
  9910. return this.data.array;
  9911. }
  9912. set needsUpdate( value ) {
  9913. this.data.needsUpdate = value;
  9914. }
  9915. applyMatrix4( m ) {
  9916. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  9917. _vector$7.fromBufferAttribute( this, i );
  9918. _vector$7.applyMatrix4( m );
  9919. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  9920. }
  9921. return this;
  9922. }
  9923. applyNormalMatrix( m ) {
  9924. for ( let i = 0, l = this.count; i < l; i ++ ) {
  9925. _vector$7.fromBufferAttribute( this, i );
  9926. _vector$7.applyNormalMatrix( m );
  9927. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  9928. }
  9929. return this;
  9930. }
  9931. transformDirection( m ) {
  9932. for ( let i = 0, l = this.count; i < l; i ++ ) {
  9933. _vector$7.fromBufferAttribute( this, i );
  9934. _vector$7.transformDirection( m );
  9935. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  9936. }
  9937. return this;
  9938. }
  9939. getComponent( index, component ) {
  9940. let value = this.array[ index * this.data.stride + this.offset + component ];
  9941. if ( this.normalized ) value = denormalize( value, this.array );
  9942. return value;
  9943. }
  9944. setComponent( index, component, value ) {
  9945. if ( this.normalized ) value = normalize( value, this.array );
  9946. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  9947. return this;
  9948. }
  9949. setX( index, x ) {
  9950. if ( this.normalized ) x = normalize( x, this.array );
  9951. this.data.array[ index * this.data.stride + this.offset ] = x;
  9952. return this;
  9953. }
  9954. setY( index, y ) {
  9955. if ( this.normalized ) y = normalize( y, this.array );
  9956. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  9957. return this;
  9958. }
  9959. setZ( index, z ) {
  9960. if ( this.normalized ) z = normalize( z, this.array );
  9961. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  9962. return this;
  9963. }
  9964. setW( index, w ) {
  9965. if ( this.normalized ) w = normalize( w, this.array );
  9966. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  9967. return this;
  9968. }
  9969. getX( index ) {
  9970. let x = this.data.array[ index * this.data.stride + this.offset ];
  9971. if ( this.normalized ) x = denormalize( x, this.array );
  9972. return x;
  9973. }
  9974. getY( index ) {
  9975. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  9976. if ( this.normalized ) y = denormalize( y, this.array );
  9977. return y;
  9978. }
  9979. getZ( index ) {
  9980. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  9981. if ( this.normalized ) z = denormalize( z, this.array );
  9982. return z;
  9983. }
  9984. getW( index ) {
  9985. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  9986. if ( this.normalized ) w = denormalize( w, this.array );
  9987. return w;
  9988. }
  9989. setXY( index, x, y ) {
  9990. index = index * this.data.stride + this.offset;
  9991. if ( this.normalized ) {
  9992. x = normalize( x, this.array );
  9993. y = normalize( y, this.array );
  9994. }
  9995. this.data.array[ index + 0 ] = x;
  9996. this.data.array[ index + 1 ] = y;
  9997. return this;
  9998. }
  9999. setXYZ( index, x, y, z ) {
  10000. index = index * this.data.stride + this.offset;
  10001. if ( this.normalized ) {
  10002. x = normalize( x, this.array );
  10003. y = normalize( y, this.array );
  10004. z = normalize( z, this.array );
  10005. }
  10006. this.data.array[ index + 0 ] = x;
  10007. this.data.array[ index + 1 ] = y;
  10008. this.data.array[ index + 2 ] = z;
  10009. return this;
  10010. }
  10011. setXYZW( index, x, y, z, w ) {
  10012. index = index * this.data.stride + this.offset;
  10013. if ( this.normalized ) {
  10014. x = normalize( x, this.array );
  10015. y = normalize( y, this.array );
  10016. z = normalize( z, this.array );
  10017. w = normalize( w, this.array );
  10018. }
  10019. this.data.array[ index + 0 ] = x;
  10020. this.data.array[ index + 1 ] = y;
  10021. this.data.array[ index + 2 ] = z;
  10022. this.data.array[ index + 3 ] = w;
  10023. return this;
  10024. }
  10025. clone( data ) {
  10026. if ( data === undefined ) {
  10027. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  10028. const array = [];
  10029. for ( let i = 0; i < this.count; i ++ ) {
  10030. const index = i * this.data.stride + this.offset;
  10031. for ( let j = 0; j < this.itemSize; j ++ ) {
  10032. array.push( this.data.array[ index + j ] );
  10033. }
  10034. }
  10035. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  10036. } else {
  10037. if ( data.interleavedBuffers === undefined ) {
  10038. data.interleavedBuffers = {};
  10039. }
  10040. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  10041. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  10042. }
  10043. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  10044. }
  10045. }
  10046. toJSON( data ) {
  10047. if ( data === undefined ) {
  10048. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  10049. const array = [];
  10050. for ( let i = 0; i < this.count; i ++ ) {
  10051. const index = i * this.data.stride + this.offset;
  10052. for ( let j = 0; j < this.itemSize; j ++ ) {
  10053. array.push( this.data.array[ index + j ] );
  10054. }
  10055. }
  10056. // de-interleave data and save it as an ordinary buffer attribute for now
  10057. return {
  10058. itemSize: this.itemSize,
  10059. type: this.array.constructor.name,
  10060. array: array,
  10061. normalized: this.normalized
  10062. };
  10063. } else {
  10064. // save as true interleaved attribute
  10065. if ( data.interleavedBuffers === undefined ) {
  10066. data.interleavedBuffers = {};
  10067. }
  10068. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  10069. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  10070. }
  10071. return {
  10072. isInterleavedBufferAttribute: true,
  10073. itemSize: this.itemSize,
  10074. data: this.data.uuid,
  10075. offset: this.offset,
  10076. normalized: this.normalized
  10077. };
  10078. }
  10079. }
  10080. }
  10081. class SpriteMaterial extends Material {
  10082. constructor( parameters ) {
  10083. super();
  10084. this.isSpriteMaterial = true;
  10085. this.type = 'SpriteMaterial';
  10086. this.color = new Color( 0xffffff );
  10087. this.map = null;
  10088. this.alphaMap = null;
  10089. this.rotation = 0;
  10090. this.sizeAttenuation = true;
  10091. this.transparent = true;
  10092. this.fog = true;
  10093. this.setValues( parameters );
  10094. }
  10095. copy( source ) {
  10096. super.copy( source );
  10097. this.color.copy( source.color );
  10098. this.map = source.map;
  10099. this.alphaMap = source.alphaMap;
  10100. this.rotation = source.rotation;
  10101. this.sizeAttenuation = source.sizeAttenuation;
  10102. this.fog = source.fog;
  10103. return this;
  10104. }
  10105. }
  10106. let _geometry;
  10107. const _intersectPoint = /*@__PURE__*/ new Vector3();
  10108. const _worldScale = /*@__PURE__*/ new Vector3();
  10109. const _mvPosition = /*@__PURE__*/ new Vector3();
  10110. const _alignedPosition = /*@__PURE__*/ new Vector2();
  10111. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  10112. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  10113. const _vA = /*@__PURE__*/ new Vector3();
  10114. const _vB = /*@__PURE__*/ new Vector3();
  10115. const _vC = /*@__PURE__*/ new Vector3();
  10116. const _uvA = /*@__PURE__*/ new Vector2();
  10117. const _uvB = /*@__PURE__*/ new Vector2();
  10118. const _uvC = /*@__PURE__*/ new Vector2();
  10119. class Sprite extends Object3D {
  10120. constructor( material = new SpriteMaterial() ) {
  10121. super();
  10122. this.isSprite = true;
  10123. this.type = 'Sprite';
  10124. if ( _geometry === undefined ) {
  10125. _geometry = new BufferGeometry();
  10126. const float32Array = new Float32Array( [
  10127. -0.5, -0.5, 0, 0, 0,
  10128. 0.5, -0.5, 0, 1, 0,
  10129. 0.5, 0.5, 0, 1, 1,
  10130. -0.5, 0.5, 0, 0, 1
  10131. ] );
  10132. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  10133. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  10134. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  10135. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  10136. }
  10137. this.geometry = _geometry;
  10138. this.material = material;
  10139. this.center = new Vector2( 0.5, 0.5 );
  10140. }
  10141. raycast( raycaster, intersects ) {
  10142. if ( raycaster.camera === null ) {
  10143. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  10144. }
  10145. _worldScale.setFromMatrixScale( this.matrixWorld );
  10146. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  10147. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  10148. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  10149. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  10150. _worldScale.multiplyScalar( - _mvPosition.z );
  10151. }
  10152. const rotation = this.material.rotation;
  10153. let sin, cos;
  10154. if ( rotation !== 0 ) {
  10155. cos = Math.cos( rotation );
  10156. sin = Math.sin( rotation );
  10157. }
  10158. const center = this.center;
  10159. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  10160. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  10161. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  10162. _uvA.set( 0, 0 );
  10163. _uvB.set( 1, 0 );
  10164. _uvC.set( 1, 1 );
  10165. // check first triangle
  10166. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  10167. if ( intersect === null ) {
  10168. // check second triangle
  10169. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  10170. _uvB.set( 0, 1 );
  10171. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  10172. if ( intersect === null ) {
  10173. return;
  10174. }
  10175. }
  10176. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  10177. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10178. intersects.push( {
  10179. distance: distance,
  10180. point: _intersectPoint.clone(),
  10181. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  10182. face: null,
  10183. object: this
  10184. } );
  10185. }
  10186. copy( source, recursive ) {
  10187. super.copy( source, recursive );
  10188. if ( source.center !== undefined ) this.center.copy( source.center );
  10189. this.material = source.material;
  10190. return this;
  10191. }
  10192. }
  10193. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  10194. // compute position in camera space
  10195. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  10196. // to check if rotation is not zero
  10197. if ( sin !== undefined ) {
  10198. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  10199. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  10200. } else {
  10201. _rotatedPosition.copy( _alignedPosition );
  10202. }
  10203. vertexPosition.copy( mvPosition );
  10204. vertexPosition.x += _rotatedPosition.x;
  10205. vertexPosition.y += _rotatedPosition.y;
  10206. // transform to world space
  10207. vertexPosition.applyMatrix4( _viewWorldMatrix );
  10208. }
  10209. const _v1$2 = /*@__PURE__*/ new Vector3();
  10210. const _v2$1 = /*@__PURE__*/ new Vector3();
  10211. class LOD extends Object3D {
  10212. constructor() {
  10213. super();
  10214. this._currentLevel = 0;
  10215. this.type = 'LOD';
  10216. Object.defineProperties( this, {
  10217. levels: {
  10218. enumerable: true,
  10219. value: []
  10220. },
  10221. isLOD: {
  10222. value: true,
  10223. }
  10224. } );
  10225. this.autoUpdate = true;
  10226. }
  10227. copy( source ) {
  10228. super.copy( source, false );
  10229. const levels = source.levels;
  10230. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  10231. const level = levels[ i ];
  10232. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  10233. }
  10234. this.autoUpdate = source.autoUpdate;
  10235. return this;
  10236. }
  10237. addLevel( object, distance = 0, hysteresis = 0 ) {
  10238. distance = Math.abs( distance );
  10239. const levels = this.levels;
  10240. let l;
  10241. for ( l = 0; l < levels.length; l ++ ) {
  10242. if ( distance < levels[ l ].distance ) {
  10243. break;
  10244. }
  10245. }
  10246. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  10247. this.add( object );
  10248. return this;
  10249. }
  10250. removeLevel( distance ) {
  10251. const levels = this.levels;
  10252. for ( let i = 0; i < levels.length; i ++ ) {
  10253. if ( levels[ i ].distance === distance ) {
  10254. const removedElements = levels.splice( i, 1 );
  10255. this.remove( removedElements[ 0 ].object );
  10256. return true;
  10257. }
  10258. }
  10259. return false;
  10260. }
  10261. getCurrentLevel() {
  10262. return this._currentLevel;
  10263. }
  10264. getObjectForDistance( distance ) {
  10265. const levels = this.levels;
  10266. if ( levels.length > 0 ) {
  10267. let i, l;
  10268. for ( i = 1, l = levels.length; i < l; i ++ ) {
  10269. let levelDistance = levels[ i ].distance;
  10270. if ( levels[ i ].object.visible ) {
  10271. levelDistance -= levelDistance * levels[ i ].hysteresis;
  10272. }
  10273. if ( distance < levelDistance ) {
  10274. break;
  10275. }
  10276. }
  10277. return levels[ i - 1 ].object;
  10278. }
  10279. return null;
  10280. }
  10281. raycast( raycaster, intersects ) {
  10282. const levels = this.levels;
  10283. if ( levels.length > 0 ) {
  10284. _v1$2.setFromMatrixPosition( this.matrixWorld );
  10285. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  10286. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  10287. }
  10288. }
  10289. update( camera ) {
  10290. const levels = this.levels;
  10291. if ( levels.length > 1 ) {
  10292. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  10293. _v2$1.setFromMatrixPosition( this.matrixWorld );
  10294. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  10295. levels[ 0 ].object.visible = true;
  10296. let i, l;
  10297. for ( i = 1, l = levels.length; i < l; i ++ ) {
  10298. let levelDistance = levels[ i ].distance;
  10299. if ( levels[ i ].object.visible ) {
  10300. levelDistance -= levelDistance * levels[ i ].hysteresis;
  10301. }
  10302. if ( distance >= levelDistance ) {
  10303. levels[ i - 1 ].object.visible = false;
  10304. levels[ i ].object.visible = true;
  10305. } else {
  10306. break;
  10307. }
  10308. }
  10309. this._currentLevel = i - 1;
  10310. for ( ; i < l; i ++ ) {
  10311. levels[ i ].object.visible = false;
  10312. }
  10313. }
  10314. }
  10315. toJSON( meta ) {
  10316. const data = super.toJSON( meta );
  10317. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  10318. data.object.levels = [];
  10319. const levels = this.levels;
  10320. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  10321. const level = levels[ i ];
  10322. data.object.levels.push( {
  10323. object: level.object.uuid,
  10324. distance: level.distance,
  10325. hysteresis: level.hysteresis
  10326. } );
  10327. }
  10328. return data;
  10329. }
  10330. }
  10331. const _basePosition = /*@__PURE__*/ new Vector3();
  10332. const _skinIndex = /*@__PURE__*/ new Vector4();
  10333. const _skinWeight = /*@__PURE__*/ new Vector4();
  10334. const _vector3 = /*@__PURE__*/ new Vector3();
  10335. const _matrix4 = /*@__PURE__*/ new Matrix4();
  10336. const _vertex = /*@__PURE__*/ new Vector3();
  10337. const _sphere$5 = /*@__PURE__*/ new Sphere();
  10338. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  10339. const _ray$2 = /*@__PURE__*/ new Ray();
  10340. class SkinnedMesh extends Mesh {
  10341. constructor( geometry, material ) {
  10342. super( geometry, material );
  10343. this.isSkinnedMesh = true;
  10344. this.type = 'SkinnedMesh';
  10345. this.bindMode = AttachedBindMode;
  10346. this.bindMatrix = new Matrix4();
  10347. this.bindMatrixInverse = new Matrix4();
  10348. this.boundingBox = null;
  10349. this.boundingSphere = null;
  10350. }
  10351. computeBoundingBox() {
  10352. const geometry = this.geometry;
  10353. if ( this.boundingBox === null ) {
  10354. this.boundingBox = new Box3();
  10355. }
  10356. this.boundingBox.makeEmpty();
  10357. const positionAttribute = geometry.getAttribute( 'position' );
  10358. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  10359. this.getVertexPosition( i, _vertex );
  10360. this.boundingBox.expandByPoint( _vertex );
  10361. }
  10362. }
  10363. computeBoundingSphere() {
  10364. const geometry = this.geometry;
  10365. if ( this.boundingSphere === null ) {
  10366. this.boundingSphere = new Sphere();
  10367. }
  10368. this.boundingSphere.makeEmpty();
  10369. const positionAttribute = geometry.getAttribute( 'position' );
  10370. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  10371. this.getVertexPosition( i, _vertex );
  10372. this.boundingSphere.expandByPoint( _vertex );
  10373. }
  10374. }
  10375. copy( source, recursive ) {
  10376. super.copy( source, recursive );
  10377. this.bindMode = source.bindMode;
  10378. this.bindMatrix.copy( source.bindMatrix );
  10379. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  10380. this.skeleton = source.skeleton;
  10381. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  10382. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  10383. return this;
  10384. }
  10385. raycast( raycaster, intersects ) {
  10386. const material = this.material;
  10387. const matrixWorld = this.matrixWorld;
  10388. if ( material === undefined ) return;
  10389. // test with bounding sphere in world space
  10390. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  10391. _sphere$5.copy( this.boundingSphere );
  10392. _sphere$5.applyMatrix4( matrixWorld );
  10393. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  10394. // convert ray to local space of skinned mesh
  10395. _inverseMatrix$2.copy( matrixWorld ).invert();
  10396. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  10397. // test with bounding box in local space
  10398. if ( this.boundingBox !== null ) {
  10399. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  10400. }
  10401. // test for intersections with geometry
  10402. this._computeIntersections( raycaster, intersects, _ray$2 );
  10403. }
  10404. getVertexPosition( index, target ) {
  10405. super.getVertexPosition( index, target );
  10406. this.applyBoneTransform( index, target );
  10407. return target;
  10408. }
  10409. bind( skeleton, bindMatrix ) {
  10410. this.skeleton = skeleton;
  10411. if ( bindMatrix === undefined ) {
  10412. this.updateMatrixWorld( true );
  10413. this.skeleton.calculateInverses();
  10414. bindMatrix = this.matrixWorld;
  10415. }
  10416. this.bindMatrix.copy( bindMatrix );
  10417. this.bindMatrixInverse.copy( bindMatrix ).invert();
  10418. }
  10419. pose() {
  10420. this.skeleton.pose();
  10421. }
  10422. normalizeSkinWeights() {
  10423. const vector = new Vector4();
  10424. const skinWeight = this.geometry.attributes.skinWeight;
  10425. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  10426. vector.fromBufferAttribute( skinWeight, i );
  10427. const scale = 1.0 / vector.manhattanLength();
  10428. if ( scale !== Infinity ) {
  10429. vector.multiplyScalar( scale );
  10430. } else {
  10431. vector.set( 1, 0, 0, 0 ); // do something reasonable
  10432. }
  10433. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  10434. }
  10435. }
  10436. updateMatrixWorld( force ) {
  10437. super.updateMatrixWorld( force );
  10438. if ( this.bindMode === AttachedBindMode ) {
  10439. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  10440. } else if ( this.bindMode === DetachedBindMode ) {
  10441. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  10442. } else {
  10443. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  10444. }
  10445. }
  10446. applyBoneTransform( index, vector ) {
  10447. const skeleton = this.skeleton;
  10448. const geometry = this.geometry;
  10449. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  10450. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  10451. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  10452. vector.set( 0, 0, 0 );
  10453. for ( let i = 0; i < 4; i ++ ) {
  10454. const weight = _skinWeight.getComponent( i );
  10455. if ( weight !== 0 ) {
  10456. const boneIndex = _skinIndex.getComponent( i );
  10457. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  10458. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  10459. }
  10460. }
  10461. return vector.applyMatrix4( this.bindMatrixInverse );
  10462. }
  10463. }
  10464. class Bone extends Object3D {
  10465. constructor() {
  10466. super();
  10467. this.isBone = true;
  10468. this.type = 'Bone';
  10469. }
  10470. }
  10471. class DataTexture extends Texture {
  10472. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  10473. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10474. this.isDataTexture = true;
  10475. this.image = { data: data, width: width, height: height };
  10476. this.generateMipmaps = false;
  10477. this.flipY = false;
  10478. this.unpackAlignment = 1;
  10479. }
  10480. }
  10481. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  10482. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  10483. class Skeleton {
  10484. constructor( bones = [], boneInverses = [] ) {
  10485. this.uuid = generateUUID();
  10486. this.bones = bones.slice( 0 );
  10487. this.boneInverses = boneInverses;
  10488. this.boneMatrices = null;
  10489. this.boneTexture = null;
  10490. this.init();
  10491. }
  10492. init() {
  10493. const bones = this.bones;
  10494. const boneInverses = this.boneInverses;
  10495. this.boneMatrices = new Float32Array( bones.length * 16 );
  10496. // calculate inverse bone matrices if necessary
  10497. if ( boneInverses.length === 0 ) {
  10498. this.calculateInverses();
  10499. } else {
  10500. // handle special case
  10501. if ( bones.length !== boneInverses.length ) {
  10502. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  10503. this.boneInverses = [];
  10504. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10505. this.boneInverses.push( new Matrix4() );
  10506. }
  10507. }
  10508. }
  10509. }
  10510. calculateInverses() {
  10511. this.boneInverses.length = 0;
  10512. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10513. const inverse = new Matrix4();
  10514. if ( this.bones[ i ] ) {
  10515. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  10516. }
  10517. this.boneInverses.push( inverse );
  10518. }
  10519. }
  10520. pose() {
  10521. // recover the bind-time world matrices
  10522. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10523. const bone = this.bones[ i ];
  10524. if ( bone ) {
  10525. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  10526. }
  10527. }
  10528. // compute the local matrices, positions, rotations and scales
  10529. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10530. const bone = this.bones[ i ];
  10531. if ( bone ) {
  10532. if ( bone.parent && bone.parent.isBone ) {
  10533. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  10534. bone.matrix.multiply( bone.matrixWorld );
  10535. } else {
  10536. bone.matrix.copy( bone.matrixWorld );
  10537. }
  10538. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  10539. }
  10540. }
  10541. }
  10542. update() {
  10543. const bones = this.bones;
  10544. const boneInverses = this.boneInverses;
  10545. const boneMatrices = this.boneMatrices;
  10546. const boneTexture = this.boneTexture;
  10547. // flatten bone matrices to array
  10548. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  10549. // compute the offset between the current and the original transform
  10550. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  10551. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  10552. _offsetMatrix.toArray( boneMatrices, i * 16 );
  10553. }
  10554. if ( boneTexture !== null ) {
  10555. boneTexture.needsUpdate = true;
  10556. }
  10557. }
  10558. clone() {
  10559. return new Skeleton( this.bones, this.boneInverses );
  10560. }
  10561. computeBoneTexture() {
  10562. // layout (1 matrix = 4 pixels)
  10563. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  10564. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  10565. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  10566. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  10567. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  10568. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  10569. size = Math.ceil( size / 4 ) * 4;
  10570. size = Math.max( size, 4 );
  10571. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  10572. boneMatrices.set( this.boneMatrices ); // copy current values
  10573. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  10574. boneTexture.needsUpdate = true;
  10575. this.boneMatrices = boneMatrices;
  10576. this.boneTexture = boneTexture;
  10577. return this;
  10578. }
  10579. getBoneByName( name ) {
  10580. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  10581. const bone = this.bones[ i ];
  10582. if ( bone.name === name ) {
  10583. return bone;
  10584. }
  10585. }
  10586. return undefined;
  10587. }
  10588. dispose( ) {
  10589. if ( this.boneTexture !== null ) {
  10590. this.boneTexture.dispose();
  10591. this.boneTexture = null;
  10592. }
  10593. }
  10594. fromJSON( json, bones ) {
  10595. this.uuid = json.uuid;
  10596. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  10597. const uuid = json.bones[ i ];
  10598. let bone = bones[ uuid ];
  10599. if ( bone === undefined ) {
  10600. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  10601. bone = new Bone();
  10602. }
  10603. this.bones.push( bone );
  10604. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  10605. }
  10606. this.init();
  10607. return this;
  10608. }
  10609. toJSON() {
  10610. const data = {
  10611. metadata: {
  10612. version: 4.6,
  10613. type: 'Skeleton',
  10614. generator: 'Skeleton.toJSON'
  10615. },
  10616. bones: [],
  10617. boneInverses: []
  10618. };
  10619. data.uuid = this.uuid;
  10620. const bones = this.bones;
  10621. const boneInverses = this.boneInverses;
  10622. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  10623. const bone = bones[ i ];
  10624. data.bones.push( bone.uuid );
  10625. const boneInverse = boneInverses[ i ];
  10626. data.boneInverses.push( boneInverse.toArray() );
  10627. }
  10628. return data;
  10629. }
  10630. }
  10631. class InstancedBufferAttribute extends BufferAttribute {
  10632. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  10633. super( array, itemSize, normalized );
  10634. this.isInstancedBufferAttribute = true;
  10635. this.meshPerAttribute = meshPerAttribute;
  10636. }
  10637. copy( source ) {
  10638. super.copy( source );
  10639. this.meshPerAttribute = source.meshPerAttribute;
  10640. return this;
  10641. }
  10642. toJSON() {
  10643. const data = super.toJSON();
  10644. data.meshPerAttribute = this.meshPerAttribute;
  10645. data.isInstancedBufferAttribute = true;
  10646. return data;
  10647. }
  10648. }
  10649. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  10650. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  10651. const _instanceIntersects = [];
  10652. const _box3 = /*@__PURE__*/ new Box3();
  10653. const _identity = /*@__PURE__*/ new Matrix4();
  10654. const _mesh$1 = /*@__PURE__*/ new Mesh();
  10655. const _sphere$4 = /*@__PURE__*/ new Sphere();
  10656. class InstancedMesh extends Mesh {
  10657. constructor( geometry, material, count ) {
  10658. super( geometry, material );
  10659. this.isInstancedMesh = true;
  10660. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  10661. this.instanceColor = null;
  10662. this.morphTexture = null;
  10663. this.count = count;
  10664. this.boundingBox = null;
  10665. this.boundingSphere = null;
  10666. for ( let i = 0; i < count; i ++ ) {
  10667. this.setMatrixAt( i, _identity );
  10668. }
  10669. }
  10670. computeBoundingBox() {
  10671. const geometry = this.geometry;
  10672. const count = this.count;
  10673. if ( this.boundingBox === null ) {
  10674. this.boundingBox = new Box3();
  10675. }
  10676. if ( geometry.boundingBox === null ) {
  10677. geometry.computeBoundingBox();
  10678. }
  10679. this.boundingBox.makeEmpty();
  10680. for ( let i = 0; i < count; i ++ ) {
  10681. this.getMatrixAt( i, _instanceLocalMatrix );
  10682. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  10683. this.boundingBox.union( _box3 );
  10684. }
  10685. }
  10686. computeBoundingSphere() {
  10687. const geometry = this.geometry;
  10688. const count = this.count;
  10689. if ( this.boundingSphere === null ) {
  10690. this.boundingSphere = new Sphere();
  10691. }
  10692. if ( geometry.boundingSphere === null ) {
  10693. geometry.computeBoundingSphere();
  10694. }
  10695. this.boundingSphere.makeEmpty();
  10696. for ( let i = 0; i < count; i ++ ) {
  10697. this.getMatrixAt( i, _instanceLocalMatrix );
  10698. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  10699. this.boundingSphere.union( _sphere$4 );
  10700. }
  10701. }
  10702. copy( source, recursive ) {
  10703. super.copy( source, recursive );
  10704. this.instanceMatrix.copy( source.instanceMatrix );
  10705. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  10706. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  10707. this.count = source.count;
  10708. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  10709. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  10710. return this;
  10711. }
  10712. getColorAt( index, color ) {
  10713. color.fromArray( this.instanceColor.array, index * 3 );
  10714. }
  10715. getMatrixAt( index, matrix ) {
  10716. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  10717. }
  10718. getMorphAt( index, object ) {
  10719. const objectInfluences = object.morphTargetInfluences;
  10720. const array = this.morphTexture.source.data.data;
  10721. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  10722. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  10723. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10724. objectInfluences[ i ] = array[ dataIndex + i ];
  10725. }
  10726. }
  10727. raycast( raycaster, intersects ) {
  10728. const matrixWorld = this.matrixWorld;
  10729. const raycastTimes = this.count;
  10730. _mesh$1.geometry = this.geometry;
  10731. _mesh$1.material = this.material;
  10732. if ( _mesh$1.material === undefined ) return;
  10733. // test with bounding sphere first
  10734. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  10735. _sphere$4.copy( this.boundingSphere );
  10736. _sphere$4.applyMatrix4( matrixWorld );
  10737. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  10738. // now test each instance
  10739. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  10740. // calculate the world matrix for each instance
  10741. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  10742. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  10743. // the mesh represents this single instance
  10744. _mesh$1.matrixWorld = _instanceWorldMatrix;
  10745. _mesh$1.raycast( raycaster, _instanceIntersects );
  10746. // process the result of raycast
  10747. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  10748. const intersect = _instanceIntersects[ i ];
  10749. intersect.instanceId = instanceId;
  10750. intersect.object = this;
  10751. intersects.push( intersect );
  10752. }
  10753. _instanceIntersects.length = 0;
  10754. }
  10755. }
  10756. setColorAt( index, color ) {
  10757. if ( this.instanceColor === null ) {
  10758. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  10759. }
  10760. color.toArray( this.instanceColor.array, index * 3 );
  10761. }
  10762. setMatrixAt( index, matrix ) {
  10763. matrix.toArray( this.instanceMatrix.array, index * 16 );
  10764. }
  10765. setMorphAt( index, object ) {
  10766. const objectInfluences = object.morphTargetInfluences;
  10767. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  10768. if ( this.morphTexture === null ) {
  10769. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  10770. }
  10771. const array = this.morphTexture.source.data.data;
  10772. let morphInfluencesSum = 0;
  10773. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10774. morphInfluencesSum += objectInfluences[ i ];
  10775. }
  10776. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10777. const dataIndex = len * index;
  10778. array[ dataIndex ] = morphBaseInfluence;
  10779. array.set( objectInfluences, dataIndex + 1 );
  10780. }
  10781. updateMorphTargets() {
  10782. }
  10783. dispose() {
  10784. this.dispatchEvent( { type: 'dispose' } );
  10785. if ( this.morphTexture !== null ) {
  10786. this.morphTexture.dispose();
  10787. this.morphTexture = null;
  10788. }
  10789. return this;
  10790. }
  10791. }
  10792. const _vector1 = /*@__PURE__*/ new Vector3();
  10793. const _vector2 = /*@__PURE__*/ new Vector3();
  10794. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  10795. class Plane {
  10796. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  10797. this.isPlane = true;
  10798. // normal is assumed to be normalized
  10799. this.normal = normal;
  10800. this.constant = constant;
  10801. }
  10802. set( normal, constant ) {
  10803. this.normal.copy( normal );
  10804. this.constant = constant;
  10805. return this;
  10806. }
  10807. setComponents( x, y, z, w ) {
  10808. this.normal.set( x, y, z );
  10809. this.constant = w;
  10810. return this;
  10811. }
  10812. setFromNormalAndCoplanarPoint( normal, point ) {
  10813. this.normal.copy( normal );
  10814. this.constant = - point.dot( this.normal );
  10815. return this;
  10816. }
  10817. setFromCoplanarPoints( a, b, c ) {
  10818. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  10819. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  10820. this.setFromNormalAndCoplanarPoint( normal, a );
  10821. return this;
  10822. }
  10823. copy( plane ) {
  10824. this.normal.copy( plane.normal );
  10825. this.constant = plane.constant;
  10826. return this;
  10827. }
  10828. normalize() {
  10829. // Note: will lead to a divide by zero if the plane is invalid.
  10830. const inverseNormalLength = 1.0 / this.normal.length();
  10831. this.normal.multiplyScalar( inverseNormalLength );
  10832. this.constant *= inverseNormalLength;
  10833. return this;
  10834. }
  10835. negate() {
  10836. this.constant *= -1;
  10837. this.normal.negate();
  10838. return this;
  10839. }
  10840. distanceToPoint( point ) {
  10841. return this.normal.dot( point ) + this.constant;
  10842. }
  10843. distanceToSphere( sphere ) {
  10844. return this.distanceToPoint( sphere.center ) - sphere.radius;
  10845. }
  10846. projectPoint( point, target ) {
  10847. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  10848. }
  10849. intersectLine( line, target ) {
  10850. const direction = line.delta( _vector1 );
  10851. const denominator = this.normal.dot( direction );
  10852. if ( denominator === 0 ) {
  10853. // line is coplanar, return origin
  10854. if ( this.distanceToPoint( line.start ) === 0 ) {
  10855. return target.copy( line.start );
  10856. }
  10857. // Unsure if this is the correct method to handle this case.
  10858. return null;
  10859. }
  10860. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  10861. if ( t < 0 || t > 1 ) {
  10862. return null;
  10863. }
  10864. return target.copy( line.start ).addScaledVector( direction, t );
  10865. }
  10866. intersectsLine( line ) {
  10867. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  10868. const startSign = this.distanceToPoint( line.start );
  10869. const endSign = this.distanceToPoint( line.end );
  10870. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  10871. }
  10872. intersectsBox( box ) {
  10873. return box.intersectsPlane( this );
  10874. }
  10875. intersectsSphere( sphere ) {
  10876. return sphere.intersectsPlane( this );
  10877. }
  10878. coplanarPoint( target ) {
  10879. return target.copy( this.normal ).multiplyScalar( - this.constant );
  10880. }
  10881. applyMatrix4( matrix, optionalNormalMatrix ) {
  10882. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  10883. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  10884. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  10885. this.constant = - referencePoint.dot( normal );
  10886. return this;
  10887. }
  10888. translate( offset ) {
  10889. this.constant -= offset.dot( this.normal );
  10890. return this;
  10891. }
  10892. equals( plane ) {
  10893. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  10894. }
  10895. clone() {
  10896. return new this.constructor().copy( this );
  10897. }
  10898. }
  10899. const _sphere$3 = /*@__PURE__*/ new Sphere();
  10900. const _vector$6 = /*@__PURE__*/ new Vector3();
  10901. class Frustum {
  10902. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  10903. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  10904. }
  10905. set( p0, p1, p2, p3, p4, p5 ) {
  10906. const planes = this.planes;
  10907. planes[ 0 ].copy( p0 );
  10908. planes[ 1 ].copy( p1 );
  10909. planes[ 2 ].copy( p2 );
  10910. planes[ 3 ].copy( p3 );
  10911. planes[ 4 ].copy( p4 );
  10912. planes[ 5 ].copy( p5 );
  10913. return this;
  10914. }
  10915. copy( frustum ) {
  10916. const planes = this.planes;
  10917. for ( let i = 0; i < 6; i ++ ) {
  10918. planes[ i ].copy( frustum.planes[ i ] );
  10919. }
  10920. return this;
  10921. }
  10922. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  10923. const planes = this.planes;
  10924. const me = m.elements;
  10925. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  10926. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  10927. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  10928. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  10929. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  10930. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  10931. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  10932. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  10933. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  10934. if ( coordinateSystem === WebGLCoordinateSystem ) {
  10935. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  10936. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  10937. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  10938. } else {
  10939. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  10940. }
  10941. return this;
  10942. }
  10943. intersectsObject( object ) {
  10944. if ( object.boundingSphere !== undefined ) {
  10945. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  10946. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  10947. } else {
  10948. const geometry = object.geometry;
  10949. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10950. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  10951. }
  10952. return this.intersectsSphere( _sphere$3 );
  10953. }
  10954. intersectsSprite( sprite ) {
  10955. _sphere$3.center.set( 0, 0, 0 );
  10956. _sphere$3.radius = 0.7071067811865476;
  10957. _sphere$3.applyMatrix4( sprite.matrixWorld );
  10958. return this.intersectsSphere( _sphere$3 );
  10959. }
  10960. intersectsSphere( sphere ) {
  10961. const planes = this.planes;
  10962. const center = sphere.center;
  10963. const negRadius = - sphere.radius;
  10964. for ( let i = 0; i < 6; i ++ ) {
  10965. const distance = planes[ i ].distanceToPoint( center );
  10966. if ( distance < negRadius ) {
  10967. return false;
  10968. }
  10969. }
  10970. return true;
  10971. }
  10972. intersectsBox( box ) {
  10973. const planes = this.planes;
  10974. for ( let i = 0; i < 6; i ++ ) {
  10975. const plane = planes[ i ];
  10976. // corner at max distance
  10977. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10978. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10979. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10980. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  10981. return false;
  10982. }
  10983. }
  10984. return true;
  10985. }
  10986. containsPoint( point ) {
  10987. const planes = this.planes;
  10988. for ( let i = 0; i < 6; i ++ ) {
  10989. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  10990. return false;
  10991. }
  10992. }
  10993. return true;
  10994. }
  10995. clone() {
  10996. return new this.constructor().copy( this );
  10997. }
  10998. }
  10999. function ascIdSort( a, b ) {
  11000. return a - b;
  11001. }
  11002. function sortOpaque( a, b ) {
  11003. return a.z - b.z;
  11004. }
  11005. function sortTransparent( a, b ) {
  11006. return b.z - a.z;
  11007. }
  11008. class MultiDrawRenderList {
  11009. constructor() {
  11010. this.index = 0;
  11011. this.pool = [];
  11012. this.list = [];
  11013. }
  11014. push( start, count, z, index ) {
  11015. const pool = this.pool;
  11016. const list = this.list;
  11017. if ( this.index >= pool.length ) {
  11018. pool.push( {
  11019. start: -1,
  11020. count: -1,
  11021. z: -1,
  11022. index: -1,
  11023. } );
  11024. }
  11025. const item = pool[ this.index ];
  11026. list.push( item );
  11027. this.index ++;
  11028. item.start = start;
  11029. item.count = count;
  11030. item.z = z;
  11031. item.index = index;
  11032. }
  11033. reset() {
  11034. this.list.length = 0;
  11035. this.index = 0;
  11036. }
  11037. }
  11038. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  11039. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  11040. const _frustum = /*@__PURE__*/ new Frustum();
  11041. const _box$1 = /*@__PURE__*/ new Box3();
  11042. const _sphere$2 = /*@__PURE__*/ new Sphere();
  11043. const _vector$5 = /*@__PURE__*/ new Vector3();
  11044. const _forward = /*@__PURE__*/ new Vector3();
  11045. const _temp = /*@__PURE__*/ new Vector3();
  11046. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  11047. const _mesh = /*@__PURE__*/ new Mesh();
  11048. const _batchIntersects = [];
  11049. // copies data from attribute "src" into "target" starting at "targetOffset"
  11050. function copyAttributeData( src, target, targetOffset = 0 ) {
  11051. const itemSize = target.itemSize;
  11052. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  11053. // use the component getters and setters if the array data cannot
  11054. // be copied directly
  11055. const vertexCount = src.count;
  11056. for ( let i = 0; i < vertexCount; i ++ ) {
  11057. for ( let c = 0; c < itemSize; c ++ ) {
  11058. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  11059. }
  11060. }
  11061. } else {
  11062. // faster copy approach using typed array set function
  11063. target.array.set( src.array, targetOffset * itemSize );
  11064. }
  11065. target.needsUpdate = true;
  11066. }
  11067. // safely copies array contents to a potentially smaller array
  11068. function copyArrayContents( src, target ) {
  11069. if ( src.constructor !== target.constructor ) {
  11070. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  11071. const len = Math.min( src.length, target.length );
  11072. for ( let i = 0; i < len; i ++ ) {
  11073. target[ i ] = src[ i ];
  11074. }
  11075. } else {
  11076. // if the arrays use the same data layout we can use a fast block copy
  11077. const len = Math.min( src.length, target.length );
  11078. target.set( new src.constructor( src.buffer, 0, len ) );
  11079. }
  11080. }
  11081. class BatchedMesh extends Mesh {
  11082. get maxInstanceCount() {
  11083. return this._maxInstanceCount;
  11084. }
  11085. get instanceCount() {
  11086. return this._instanceInfo.length - this._availableInstanceIds.length;
  11087. }
  11088. get unusedVertexCount() {
  11089. return this._maxVertexCount - this._nextVertexStart;
  11090. }
  11091. get unusedIndexCount() {
  11092. return this._maxIndexCount - this._nextIndexStart;
  11093. }
  11094. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  11095. super( new BufferGeometry(), material );
  11096. this.isBatchedMesh = true;
  11097. this.perObjectFrustumCulled = true;
  11098. this.sortObjects = true;
  11099. this.boundingBox = null;
  11100. this.boundingSphere = null;
  11101. this.customSort = null;
  11102. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  11103. this._instanceInfo = [];
  11104. this._geometryInfo = [];
  11105. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  11106. this._availableInstanceIds = [];
  11107. this._availableGeometryIds = [];
  11108. // used to track where the next point is that geometry should be inserted
  11109. this._nextIndexStart = 0;
  11110. this._nextVertexStart = 0;
  11111. this._geometryCount = 0;
  11112. // flags
  11113. this._visibilityChanged = true;
  11114. this._geometryInitialized = false;
  11115. // cached user options
  11116. this._maxInstanceCount = maxInstanceCount;
  11117. this._maxVertexCount = maxVertexCount;
  11118. this._maxIndexCount = maxIndexCount;
  11119. // buffers for multi draw
  11120. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  11121. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  11122. this._multiDrawCount = 0;
  11123. this._multiDrawInstances = null;
  11124. // Local matrix per geometry by using data texture
  11125. this._matricesTexture = null;
  11126. this._indirectTexture = null;
  11127. this._colorsTexture = null;
  11128. this._initMatricesTexture();
  11129. this._initIndirectTexture();
  11130. }
  11131. _initMatricesTexture() {
  11132. // layout (1 matrix = 4 pixels)
  11133. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  11134. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  11135. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  11136. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  11137. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  11138. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  11139. size = Math.ceil( size / 4 ) * 4;
  11140. size = Math.max( size, 4 );
  11141. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  11142. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  11143. this._matricesTexture = matricesTexture;
  11144. }
  11145. _initIndirectTexture() {
  11146. let size = Math.sqrt( this._maxInstanceCount );
  11147. size = Math.ceil( size );
  11148. const indirectArray = new Uint32Array( size * size );
  11149. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  11150. this._indirectTexture = indirectTexture;
  11151. }
  11152. _initColorsTexture() {
  11153. let size = Math.sqrt( this._maxInstanceCount );
  11154. size = Math.ceil( size );
  11155. // 4 floats per RGBA pixel initialized to white
  11156. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  11157. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  11158. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  11159. this._colorsTexture = colorsTexture;
  11160. }
  11161. _initializeGeometry( reference ) {
  11162. const geometry = this.geometry;
  11163. const maxVertexCount = this._maxVertexCount;
  11164. const maxIndexCount = this._maxIndexCount;
  11165. if ( this._geometryInitialized === false ) {
  11166. for ( const attributeName in reference.attributes ) {
  11167. const srcAttribute = reference.getAttribute( attributeName );
  11168. const { array, itemSize, normalized } = srcAttribute;
  11169. const dstArray = new array.constructor( maxVertexCount * itemSize );
  11170. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  11171. geometry.setAttribute( attributeName, dstAttribute );
  11172. }
  11173. if ( reference.getIndex() !== null ) {
  11174. // Reserve last u16 index for primitive restart.
  11175. const indexArray = maxVertexCount > 65535
  11176. ? new Uint32Array( maxIndexCount )
  11177. : new Uint16Array( maxIndexCount );
  11178. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  11179. }
  11180. this._geometryInitialized = true;
  11181. }
  11182. }
  11183. // Make sure the geometry is compatible with the existing combined geometry attributes
  11184. _validateGeometry( geometry ) {
  11185. // check to ensure the geometries are using consistent attributes and indices
  11186. const batchGeometry = this.geometry;
  11187. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  11188. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  11189. }
  11190. for ( const attributeName in batchGeometry.attributes ) {
  11191. if ( ! geometry.hasAttribute( attributeName ) ) {
  11192. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  11193. }
  11194. const srcAttribute = geometry.getAttribute( attributeName );
  11195. const dstAttribute = batchGeometry.getAttribute( attributeName );
  11196. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  11197. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  11198. }
  11199. }
  11200. }
  11201. validateInstanceId( instanceId ) {
  11202. const instanceInfo = this._instanceInfo;
  11203. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  11204. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  11205. }
  11206. }
  11207. validateGeometryId( geometryId ) {
  11208. const geometryInfoList = this._geometryInfo;
  11209. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  11210. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  11211. }
  11212. }
  11213. setCustomSort( func ) {
  11214. this.customSort = func;
  11215. return this;
  11216. }
  11217. computeBoundingBox() {
  11218. if ( this.boundingBox === null ) {
  11219. this.boundingBox = new Box3();
  11220. }
  11221. const boundingBox = this.boundingBox;
  11222. const instanceInfo = this._instanceInfo;
  11223. boundingBox.makeEmpty();
  11224. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11225. if ( instanceInfo[ i ].active === false ) continue;
  11226. const geometryId = instanceInfo[ i ].geometryIndex;
  11227. this.getMatrixAt( i, _matrix$1 );
  11228. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  11229. boundingBox.union( _box$1 );
  11230. }
  11231. }
  11232. computeBoundingSphere() {
  11233. if ( this.boundingSphere === null ) {
  11234. this.boundingSphere = new Sphere();
  11235. }
  11236. const boundingSphere = this.boundingSphere;
  11237. const instanceInfo = this._instanceInfo;
  11238. boundingSphere.makeEmpty();
  11239. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11240. if ( instanceInfo[ i ].active === false ) continue;
  11241. const geometryId = instanceInfo[ i ].geometryIndex;
  11242. this.getMatrixAt( i, _matrix$1 );
  11243. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  11244. boundingSphere.union( _sphere$2 );
  11245. }
  11246. }
  11247. addInstance( geometryId ) {
  11248. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  11249. // ensure we're not over geometry
  11250. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  11251. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  11252. }
  11253. const instanceInfo = {
  11254. visible: true,
  11255. active: true,
  11256. geometryIndex: geometryId,
  11257. };
  11258. let drawId = null;
  11259. // Prioritize using previously freed instance ids
  11260. if ( this._availableInstanceIds.length > 0 ) {
  11261. this._availableInstanceIds.sort( ascIdSort );
  11262. drawId = this._availableInstanceIds.shift();
  11263. this._instanceInfo[ drawId ] = instanceInfo;
  11264. } else {
  11265. drawId = this._instanceInfo.length;
  11266. this._instanceInfo.push( instanceInfo );
  11267. }
  11268. const matricesTexture = this._matricesTexture;
  11269. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  11270. matricesTexture.needsUpdate = true;
  11271. const colorsTexture = this._colorsTexture;
  11272. if ( colorsTexture ) {
  11273. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  11274. colorsTexture.needsUpdate = true;
  11275. }
  11276. this._visibilityChanged = true;
  11277. return drawId;
  11278. }
  11279. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  11280. this._initializeGeometry( geometry );
  11281. this._validateGeometry( geometry );
  11282. const geometryInfo = {
  11283. // geometry information
  11284. vertexStart: -1,
  11285. vertexCount: -1,
  11286. reservedVertexCount: -1,
  11287. indexStart: -1,
  11288. indexCount: -1,
  11289. reservedIndexCount: -1,
  11290. // draw range information
  11291. start: -1,
  11292. count: -1,
  11293. // state
  11294. boundingBox: null,
  11295. boundingSphere: null,
  11296. active: true,
  11297. };
  11298. const geometryInfoList = this._geometryInfo;
  11299. geometryInfo.vertexStart = this._nextVertexStart;
  11300. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  11301. const index = geometry.getIndex();
  11302. const hasIndex = index !== null;
  11303. if ( hasIndex ) {
  11304. geometryInfo.indexStart = this._nextIndexStart;
  11305. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  11306. }
  11307. if (
  11308. geometryInfo.indexStart !== -1 &&
  11309. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  11310. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  11311. ) {
  11312. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  11313. }
  11314. // update id
  11315. let geometryId;
  11316. if ( this._availableGeometryIds.length > 0 ) {
  11317. this._availableGeometryIds.sort( ascIdSort );
  11318. geometryId = this._availableGeometryIds.shift();
  11319. geometryInfoList[ geometryId ] = geometryInfo;
  11320. } else {
  11321. geometryId = this._geometryCount;
  11322. this._geometryCount ++;
  11323. geometryInfoList.push( geometryInfo );
  11324. }
  11325. // update the geometry
  11326. this.setGeometryAt( geometryId, geometry );
  11327. // increment the next geometry position
  11328. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  11329. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  11330. return geometryId;
  11331. }
  11332. setGeometryAt( geometryId, geometry ) {
  11333. if ( geometryId >= this._geometryCount ) {
  11334. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  11335. }
  11336. this._validateGeometry( geometry );
  11337. const batchGeometry = this.geometry;
  11338. const hasIndex = batchGeometry.getIndex() !== null;
  11339. const dstIndex = batchGeometry.getIndex();
  11340. const srcIndex = geometry.getIndex();
  11341. const geometryInfo = this._geometryInfo[ geometryId ];
  11342. if (
  11343. hasIndex &&
  11344. srcIndex.count > geometryInfo.reservedIndexCount ||
  11345. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  11346. ) {
  11347. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  11348. }
  11349. // copy geometry buffer data over
  11350. const vertexStart = geometryInfo.vertexStart;
  11351. const reservedVertexCount = geometryInfo.reservedVertexCount;
  11352. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  11353. for ( const attributeName in batchGeometry.attributes ) {
  11354. // copy attribute data
  11355. const srcAttribute = geometry.getAttribute( attributeName );
  11356. const dstAttribute = batchGeometry.getAttribute( attributeName );
  11357. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  11358. // fill the rest in with zeroes
  11359. const itemSize = srcAttribute.itemSize;
  11360. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  11361. const index = vertexStart + i;
  11362. for ( let c = 0; c < itemSize; c ++ ) {
  11363. dstAttribute.setComponent( index, c, 0 );
  11364. }
  11365. }
  11366. dstAttribute.needsUpdate = true;
  11367. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  11368. }
  11369. // copy index
  11370. if ( hasIndex ) {
  11371. const indexStart = geometryInfo.indexStart;
  11372. const reservedIndexCount = geometryInfo.reservedIndexCount;
  11373. geometryInfo.indexCount = geometry.getIndex().count;
  11374. // copy index data over
  11375. for ( let i = 0; i < srcIndex.count; i ++ ) {
  11376. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  11377. }
  11378. // fill the rest in with zeroes
  11379. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  11380. dstIndex.setX( indexStart + i, vertexStart );
  11381. }
  11382. dstIndex.needsUpdate = true;
  11383. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  11384. }
  11385. // update the draw range
  11386. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  11387. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  11388. // store the bounding boxes
  11389. geometryInfo.boundingBox = null;
  11390. if ( geometry.boundingBox !== null ) {
  11391. geometryInfo.boundingBox = geometry.boundingBox.clone();
  11392. }
  11393. geometryInfo.boundingSphere = null;
  11394. if ( geometry.boundingSphere !== null ) {
  11395. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  11396. }
  11397. this._visibilityChanged = true;
  11398. return geometryId;
  11399. }
  11400. deleteGeometry( geometryId ) {
  11401. const geometryInfoList = this._geometryInfo;
  11402. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  11403. return this;
  11404. }
  11405. // delete any instances associated with this geometry
  11406. const instanceInfo = this._instanceInfo;
  11407. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11408. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  11409. this.deleteInstance( i );
  11410. }
  11411. }
  11412. geometryInfoList[ geometryId ].active = false;
  11413. this._availableGeometryIds.push( geometryId );
  11414. this._visibilityChanged = true;
  11415. return this;
  11416. }
  11417. deleteInstance( instanceId ) {
  11418. this.validateInstanceId( instanceId );
  11419. this._instanceInfo[ instanceId ].active = false;
  11420. this._availableInstanceIds.push( instanceId );
  11421. this._visibilityChanged = true;
  11422. return this;
  11423. }
  11424. optimize() {
  11425. // track the next indices to copy data to
  11426. let nextVertexStart = 0;
  11427. let nextIndexStart = 0;
  11428. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  11429. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  11430. const geometryInfoList = this._geometryInfo;
  11431. const indices = geometryInfoList
  11432. .map( ( e, i ) => i )
  11433. .sort( ( a, b ) => {
  11434. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  11435. } );
  11436. const geometry = this.geometry;
  11437. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  11438. // if a geometry range is inactive then don't copy anything
  11439. const index = indices[ i ];
  11440. const geometryInfo = geometryInfoList[ index ];
  11441. if ( geometryInfo.active === false ) {
  11442. continue;
  11443. }
  11444. // if a geometry contains an index buffer then shift it, as well
  11445. if ( geometry.index !== null ) {
  11446. if ( geometryInfo.indexStart !== nextIndexStart ) {
  11447. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  11448. const index = geometry.index;
  11449. const array = index.array;
  11450. // shift the index pointers based on how the vertex data will shift
  11451. // adjusting the index must happen first so the original vertex start value is available
  11452. const elementDelta = nextVertexStart - vertexStart;
  11453. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  11454. array[ j ] = array[ j ] + elementDelta;
  11455. }
  11456. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  11457. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  11458. geometryInfo.indexStart = nextIndexStart;
  11459. }
  11460. nextIndexStart += geometryInfo.reservedIndexCount;
  11461. }
  11462. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  11463. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  11464. const { vertexStart, reservedVertexCount } = geometryInfo;
  11465. const attributes = geometry.attributes;
  11466. for ( const key in attributes ) {
  11467. const attribute = attributes[ key ];
  11468. const { array, itemSize } = attribute;
  11469. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  11470. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  11471. }
  11472. geometryInfo.vertexStart = nextVertexStart;
  11473. }
  11474. nextVertexStart += geometryInfo.reservedVertexCount;
  11475. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  11476. // step the next geometry points to the shifted position
  11477. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  11478. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  11479. }
  11480. return this;
  11481. }
  11482. // get bounding box and compute it if it doesn't exist
  11483. getBoundingBoxAt( geometryId, target ) {
  11484. if ( geometryId >= this._geometryCount ) {
  11485. return null;
  11486. }
  11487. // compute bounding box
  11488. const geometry = this.geometry;
  11489. const geometryInfo = this._geometryInfo[ geometryId ];
  11490. if ( geometryInfo.boundingBox === null ) {
  11491. const box = new Box3();
  11492. const index = geometry.index;
  11493. const position = geometry.attributes.position;
  11494. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  11495. let iv = i;
  11496. if ( index ) {
  11497. iv = index.getX( iv );
  11498. }
  11499. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  11500. }
  11501. geometryInfo.boundingBox = box;
  11502. }
  11503. target.copy( geometryInfo.boundingBox );
  11504. return target;
  11505. }
  11506. // get bounding sphere and compute it if it doesn't exist
  11507. getBoundingSphereAt( geometryId, target ) {
  11508. if ( geometryId >= this._geometryCount ) {
  11509. return null;
  11510. }
  11511. // compute bounding sphere
  11512. const geometry = this.geometry;
  11513. const geometryInfo = this._geometryInfo[ geometryId ];
  11514. if ( geometryInfo.boundingSphere === null ) {
  11515. const sphere = new Sphere();
  11516. this.getBoundingBoxAt( geometryId, _box$1 );
  11517. _box$1.getCenter( sphere.center );
  11518. const index = geometry.index;
  11519. const position = geometry.attributes.position;
  11520. let maxRadiusSq = 0;
  11521. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  11522. let iv = i;
  11523. if ( index ) {
  11524. iv = index.getX( iv );
  11525. }
  11526. _vector$5.fromBufferAttribute( position, iv );
  11527. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  11528. }
  11529. sphere.radius = Math.sqrt( maxRadiusSq );
  11530. geometryInfo.boundingSphere = sphere;
  11531. }
  11532. target.copy( geometryInfo.boundingSphere );
  11533. return target;
  11534. }
  11535. setMatrixAt( instanceId, matrix ) {
  11536. this.validateInstanceId( instanceId );
  11537. const matricesTexture = this._matricesTexture;
  11538. const matricesArray = this._matricesTexture.image.data;
  11539. matrix.toArray( matricesArray, instanceId * 16 );
  11540. matricesTexture.needsUpdate = true;
  11541. return this;
  11542. }
  11543. getMatrixAt( instanceId, matrix ) {
  11544. this.validateInstanceId( instanceId );
  11545. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  11546. }
  11547. setColorAt( instanceId, color ) {
  11548. this.validateInstanceId( instanceId );
  11549. if ( this._colorsTexture === null ) {
  11550. this._initColorsTexture();
  11551. }
  11552. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  11553. this._colorsTexture.needsUpdate = true;
  11554. return this;
  11555. }
  11556. getColorAt( instanceId, color ) {
  11557. this.validateInstanceId( instanceId );
  11558. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  11559. }
  11560. setVisibleAt( instanceId, value ) {
  11561. this.validateInstanceId( instanceId );
  11562. if ( this._instanceInfo[ instanceId ].visible === value ) {
  11563. return this;
  11564. }
  11565. this._instanceInfo[ instanceId ].visible = value;
  11566. this._visibilityChanged = true;
  11567. return this;
  11568. }
  11569. getVisibleAt( instanceId ) {
  11570. this.validateInstanceId( instanceId );
  11571. return this._instanceInfo[ instanceId ].visible;
  11572. }
  11573. setGeometryIdAt( instanceId, geometryId ) {
  11574. this.validateInstanceId( instanceId );
  11575. this.validateGeometryId( geometryId );
  11576. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  11577. return this;
  11578. }
  11579. getGeometryIdAt( instanceId ) {
  11580. this.validateInstanceId( instanceId );
  11581. return this._instanceInfo[ instanceId ].geometryIndex;
  11582. }
  11583. getGeometryRangeAt( geometryId, target = {} ) {
  11584. this.validateGeometryId( geometryId );
  11585. const geometryInfo = this._geometryInfo[ geometryId ];
  11586. target.vertexStart = geometryInfo.vertexStart;
  11587. target.vertexCount = geometryInfo.vertexCount;
  11588. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  11589. target.indexStart = geometryInfo.indexStart;
  11590. target.indexCount = geometryInfo.indexCount;
  11591. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  11592. target.start = geometryInfo.start;
  11593. target.count = geometryInfo.count;
  11594. return target;
  11595. }
  11596. setInstanceCount( maxInstanceCount ) {
  11597. // shrink the available instances as much as possible
  11598. const availableInstanceIds = this._availableInstanceIds;
  11599. const instanceInfo = this._instanceInfo;
  11600. availableInstanceIds.sort( ascIdSort );
  11601. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  11602. instanceInfo.pop();
  11603. availableInstanceIds.pop();
  11604. }
  11605. // throw an error if it can't be shrunk to the desired size
  11606. if ( maxInstanceCount < instanceInfo.length ) {
  11607. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  11608. }
  11609. // copy the multi draw counts
  11610. const multiDrawCounts = new Int32Array( maxInstanceCount );
  11611. const multiDrawStarts = new Int32Array( maxInstanceCount );
  11612. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  11613. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  11614. this._multiDrawCounts = multiDrawCounts;
  11615. this._multiDrawStarts = multiDrawStarts;
  11616. this._maxInstanceCount = maxInstanceCount;
  11617. // update texture data for instance sampling
  11618. const indirectTexture = this._indirectTexture;
  11619. const matricesTexture = this._matricesTexture;
  11620. const colorsTexture = this._colorsTexture;
  11621. indirectTexture.dispose();
  11622. this._initIndirectTexture();
  11623. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  11624. matricesTexture.dispose();
  11625. this._initMatricesTexture();
  11626. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  11627. if ( colorsTexture ) {
  11628. colorsTexture.dispose();
  11629. this._initColorsTexture();
  11630. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  11631. }
  11632. }
  11633. setGeometrySize( maxVertexCount, maxIndexCount ) {
  11634. // Check if we can shrink to the requested vertex attribute size
  11635. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  11636. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  11637. if ( requiredVertexLength > maxVertexCount ) {
  11638. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  11639. }
  11640. // Check if we can shrink to the requested index attribute size
  11641. if ( this.geometry.index ) {
  11642. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  11643. if ( requiredIndexLength > maxIndexCount ) {
  11644. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  11645. }
  11646. }
  11647. //
  11648. // dispose of the previous geometry
  11649. const oldGeometry = this.geometry;
  11650. oldGeometry.dispose();
  11651. // recreate the geometry needed based on the previous variant
  11652. this._maxVertexCount = maxVertexCount;
  11653. this._maxIndexCount = maxIndexCount;
  11654. if ( this._geometryInitialized ) {
  11655. this._geometryInitialized = false;
  11656. this.geometry = new BufferGeometry();
  11657. this._initializeGeometry( oldGeometry );
  11658. }
  11659. // copy data from the previous geometry
  11660. const geometry = this.geometry;
  11661. if ( oldGeometry.index ) {
  11662. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  11663. }
  11664. for ( const key in oldGeometry.attributes ) {
  11665. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  11666. }
  11667. }
  11668. raycast( raycaster, intersects ) {
  11669. const instanceInfo = this._instanceInfo;
  11670. const geometryInfoList = this._geometryInfo;
  11671. const matrixWorld = this.matrixWorld;
  11672. const batchGeometry = this.geometry;
  11673. // iterate over each geometry
  11674. _mesh.material = this.material;
  11675. _mesh.geometry.index = batchGeometry.index;
  11676. _mesh.geometry.attributes = batchGeometry.attributes;
  11677. if ( _mesh.geometry.boundingBox === null ) {
  11678. _mesh.geometry.boundingBox = new Box3();
  11679. }
  11680. if ( _mesh.geometry.boundingSphere === null ) {
  11681. _mesh.geometry.boundingSphere = new Sphere();
  11682. }
  11683. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11684. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  11685. continue;
  11686. }
  11687. const geometryId = instanceInfo[ i ].geometryIndex;
  11688. const geometryInfo = geometryInfoList[ geometryId ];
  11689. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  11690. // get the intersects
  11691. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  11692. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  11693. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  11694. _mesh.raycast( raycaster, _batchIntersects );
  11695. // add batch id to the intersects
  11696. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  11697. const intersect = _batchIntersects[ j ];
  11698. intersect.object = this;
  11699. intersect.batchId = i;
  11700. intersects.push( intersect );
  11701. }
  11702. _batchIntersects.length = 0;
  11703. }
  11704. _mesh.material = null;
  11705. _mesh.geometry.index = null;
  11706. _mesh.geometry.attributes = {};
  11707. _mesh.geometry.setDrawRange( 0, Infinity );
  11708. }
  11709. copy( source ) {
  11710. super.copy( source );
  11711. this.geometry = source.geometry.clone();
  11712. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  11713. this.sortObjects = source.sortObjects;
  11714. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  11715. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  11716. this._geometryInfo = source._geometryInfo.map( info => ( {
  11717. ...info,
  11718. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  11719. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  11720. } ) );
  11721. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  11722. this._maxInstanceCount = source._maxInstanceCount;
  11723. this._maxVertexCount = source._maxVertexCount;
  11724. this._maxIndexCount = source._maxIndexCount;
  11725. this._geometryInitialized = source._geometryInitialized;
  11726. this._geometryCount = source._geometryCount;
  11727. this._multiDrawCounts = source._multiDrawCounts.slice();
  11728. this._multiDrawStarts = source._multiDrawStarts.slice();
  11729. this._matricesTexture = source._matricesTexture.clone();
  11730. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  11731. if ( this._colorsTexture !== null ) {
  11732. this._colorsTexture = source._colorsTexture.clone();
  11733. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  11734. }
  11735. return this;
  11736. }
  11737. dispose() {
  11738. // Assuming the geometry is not shared with other meshes
  11739. this.geometry.dispose();
  11740. this._matricesTexture.dispose();
  11741. this._matricesTexture = null;
  11742. this._indirectTexture.dispose();
  11743. this._indirectTexture = null;
  11744. if ( this._colorsTexture !== null ) {
  11745. this._colorsTexture.dispose();
  11746. this._colorsTexture = null;
  11747. }
  11748. return this;
  11749. }
  11750. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  11751. // if visibility has not changed and frustum culling and object sorting is not required
  11752. // then skip iterating over all items
  11753. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  11754. return;
  11755. }
  11756. // the indexed version of the multi draw function requires specifying the start
  11757. // offset in bytes.
  11758. const index = geometry.getIndex();
  11759. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  11760. const instanceInfo = this._instanceInfo;
  11761. const multiDrawStarts = this._multiDrawStarts;
  11762. const multiDrawCounts = this._multiDrawCounts;
  11763. const geometryInfoList = this._geometryInfo;
  11764. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  11765. const indirectTexture = this._indirectTexture;
  11766. const indirectArray = indirectTexture.image.data;
  11767. // prepare the frustum in the local frame
  11768. if ( perObjectFrustumCulled ) {
  11769. _matrix$1
  11770. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  11771. .multiply( this.matrixWorld );
  11772. _frustum.setFromProjectionMatrix(
  11773. _matrix$1,
  11774. renderer.coordinateSystem
  11775. );
  11776. }
  11777. let multiDrawCount = 0;
  11778. if ( this.sortObjects ) {
  11779. // get the camera position in the local frame
  11780. _matrix$1.copy( this.matrixWorld ).invert();
  11781. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  11782. _forward.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  11783. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11784. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  11785. const geometryId = instanceInfo[ i ].geometryIndex;
  11786. // get the bounds in world space
  11787. this.getMatrixAt( i, _matrix$1 );
  11788. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  11789. // determine whether the batched geometry is within the frustum
  11790. let culled = false;
  11791. if ( perObjectFrustumCulled ) {
  11792. culled = ! _frustum.intersectsSphere( _sphere$2 );
  11793. }
  11794. if ( ! culled ) {
  11795. // get the distance from camera used for sorting
  11796. const geometryInfo = geometryInfoList[ geometryId ];
  11797. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  11798. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  11799. }
  11800. }
  11801. }
  11802. // Sort the draw ranges and prep for rendering
  11803. const list = _renderList.list;
  11804. const customSort = this.customSort;
  11805. if ( customSort === null ) {
  11806. list.sort( material.transparent ? sortTransparent : sortOpaque );
  11807. } else {
  11808. customSort.call( this, list, camera );
  11809. }
  11810. for ( let i = 0, l = list.length; i < l; i ++ ) {
  11811. const item = list[ i ];
  11812. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  11813. multiDrawCounts[ multiDrawCount ] = item.count;
  11814. indirectArray[ multiDrawCount ] = item.index;
  11815. multiDrawCount ++;
  11816. }
  11817. _renderList.reset();
  11818. } else {
  11819. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  11820. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  11821. const geometryId = instanceInfo[ i ].geometryIndex;
  11822. // determine whether the batched geometry is within the frustum
  11823. let culled = false;
  11824. if ( perObjectFrustumCulled ) {
  11825. // get the bounds in world space
  11826. this.getMatrixAt( i, _matrix$1 );
  11827. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  11828. culled = ! _frustum.intersectsSphere( _sphere$2 );
  11829. }
  11830. if ( ! culled ) {
  11831. const geometryInfo = geometryInfoList[ geometryId ];
  11832. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  11833. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  11834. indirectArray[ multiDrawCount ] = i;
  11835. multiDrawCount ++;
  11836. }
  11837. }
  11838. }
  11839. }
  11840. indirectTexture.needsUpdate = true;
  11841. this._multiDrawCount = multiDrawCount;
  11842. this._visibilityChanged = false;
  11843. }
  11844. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  11845. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  11846. }
  11847. }
  11848. class LineBasicMaterial extends Material {
  11849. constructor( parameters ) {
  11850. super();
  11851. this.isLineBasicMaterial = true;
  11852. this.type = 'LineBasicMaterial';
  11853. this.color = new Color( 0xffffff );
  11854. this.map = null;
  11855. this.linewidth = 1;
  11856. this.linecap = 'round';
  11857. this.linejoin = 'round';
  11858. this.fog = true;
  11859. this.setValues( parameters );
  11860. }
  11861. copy( source ) {
  11862. super.copy( source );
  11863. this.color.copy( source.color );
  11864. this.map = source.map;
  11865. this.linewidth = source.linewidth;
  11866. this.linecap = source.linecap;
  11867. this.linejoin = source.linejoin;
  11868. this.fog = source.fog;
  11869. return this;
  11870. }
  11871. }
  11872. const _vStart = /*@__PURE__*/ new Vector3();
  11873. const _vEnd = /*@__PURE__*/ new Vector3();
  11874. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  11875. const _ray$1 = /*@__PURE__*/ new Ray();
  11876. const _sphere$1 = /*@__PURE__*/ new Sphere();
  11877. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  11878. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  11879. class Line extends Object3D {
  11880. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  11881. super();
  11882. this.isLine = true;
  11883. this.type = 'Line';
  11884. this.geometry = geometry;
  11885. this.material = material;
  11886. this.updateMorphTargets();
  11887. }
  11888. copy( source, recursive ) {
  11889. super.copy( source, recursive );
  11890. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  11891. this.geometry = source.geometry;
  11892. return this;
  11893. }
  11894. computeLineDistances() {
  11895. const geometry = this.geometry;
  11896. // we assume non-indexed geometry
  11897. if ( geometry.index === null ) {
  11898. const positionAttribute = geometry.attributes.position;
  11899. const lineDistances = [ 0 ];
  11900. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  11901. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  11902. _vEnd.fromBufferAttribute( positionAttribute, i );
  11903. lineDistances[ i ] = lineDistances[ i - 1 ];
  11904. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  11905. }
  11906. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  11907. } else {
  11908. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  11909. }
  11910. return this;
  11911. }
  11912. raycast( raycaster, intersects ) {
  11913. const geometry = this.geometry;
  11914. const matrixWorld = this.matrixWorld;
  11915. const threshold = raycaster.params.Line.threshold;
  11916. const drawRange = geometry.drawRange;
  11917. // Checking boundingSphere distance to ray
  11918. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  11919. _sphere$1.copy( geometry.boundingSphere );
  11920. _sphere$1.applyMatrix4( matrixWorld );
  11921. _sphere$1.radius += threshold;
  11922. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  11923. //
  11924. _inverseMatrix$1.copy( matrixWorld ).invert();
  11925. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  11926. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  11927. const localThresholdSq = localThreshold * localThreshold;
  11928. const step = this.isLineSegments ? 2 : 1;
  11929. const index = geometry.index;
  11930. const attributes = geometry.attributes;
  11931. const positionAttribute = attributes.position;
  11932. if ( index !== null ) {
  11933. const start = Math.max( 0, drawRange.start );
  11934. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  11935. for ( let i = start, l = end - 1; i < l; i += step ) {
  11936. const a = index.getX( i );
  11937. const b = index.getX( i + 1 );
  11938. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  11939. if ( intersect ) {
  11940. intersects.push( intersect );
  11941. }
  11942. }
  11943. if ( this.isLineLoop ) {
  11944. const a = index.getX( end - 1 );
  11945. const b = index.getX( start );
  11946. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  11947. if ( intersect ) {
  11948. intersects.push( intersect );
  11949. }
  11950. }
  11951. } else {
  11952. const start = Math.max( 0, drawRange.start );
  11953. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  11954. for ( let i = start, l = end - 1; i < l; i += step ) {
  11955. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  11956. if ( intersect ) {
  11957. intersects.push( intersect );
  11958. }
  11959. }
  11960. if ( this.isLineLoop ) {
  11961. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  11962. if ( intersect ) {
  11963. intersects.push( intersect );
  11964. }
  11965. }
  11966. }
  11967. }
  11968. updateMorphTargets() {
  11969. const geometry = this.geometry;
  11970. const morphAttributes = geometry.morphAttributes;
  11971. const keys = Object.keys( morphAttributes );
  11972. if ( keys.length > 0 ) {
  11973. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  11974. if ( morphAttribute !== undefined ) {
  11975. this.morphTargetInfluences = [];
  11976. this.morphTargetDictionary = {};
  11977. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  11978. const name = morphAttribute[ m ].name || String( m );
  11979. this.morphTargetInfluences.push( 0 );
  11980. this.morphTargetDictionary[ name ] = m;
  11981. }
  11982. }
  11983. }
  11984. }
  11985. }
  11986. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  11987. const positionAttribute = object.geometry.attributes.position;
  11988. _vStart.fromBufferAttribute( positionAttribute, a );
  11989. _vEnd.fromBufferAttribute( positionAttribute, b );
  11990. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  11991. if ( distSq > thresholdSq ) return;
  11992. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  11993. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  11994. if ( distance < raycaster.near || distance > raycaster.far ) return;
  11995. return {
  11996. distance: distance,
  11997. // What do we want? intersection point on the ray or on the segment??
  11998. // point: raycaster.ray.at( distance ),
  11999. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  12000. index: i,
  12001. face: null,
  12002. faceIndex: null,
  12003. barycoord: null,
  12004. object: object
  12005. };
  12006. }
  12007. const _start = /*@__PURE__*/ new Vector3();
  12008. const _end = /*@__PURE__*/ new Vector3();
  12009. class LineSegments extends Line {
  12010. constructor( geometry, material ) {
  12011. super( geometry, material );
  12012. this.isLineSegments = true;
  12013. this.type = 'LineSegments';
  12014. }
  12015. computeLineDistances() {
  12016. const geometry = this.geometry;
  12017. // we assume non-indexed geometry
  12018. if ( geometry.index === null ) {
  12019. const positionAttribute = geometry.attributes.position;
  12020. const lineDistances = [];
  12021. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  12022. _start.fromBufferAttribute( positionAttribute, i );
  12023. _end.fromBufferAttribute( positionAttribute, i + 1 );
  12024. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  12025. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  12026. }
  12027. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  12028. } else {
  12029. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  12030. }
  12031. return this;
  12032. }
  12033. }
  12034. class LineLoop extends Line {
  12035. constructor( geometry, material ) {
  12036. super( geometry, material );
  12037. this.isLineLoop = true;
  12038. this.type = 'LineLoop';
  12039. }
  12040. }
  12041. class PointsMaterial extends Material {
  12042. constructor( parameters ) {
  12043. super();
  12044. this.isPointsMaterial = true;
  12045. this.type = 'PointsMaterial';
  12046. this.color = new Color( 0xffffff );
  12047. this.map = null;
  12048. this.alphaMap = null;
  12049. this.size = 1;
  12050. this.sizeAttenuation = true;
  12051. this.fog = true;
  12052. this.setValues( parameters );
  12053. }
  12054. copy( source ) {
  12055. super.copy( source );
  12056. this.color.copy( source.color );
  12057. this.map = source.map;
  12058. this.alphaMap = source.alphaMap;
  12059. this.size = source.size;
  12060. this.sizeAttenuation = source.sizeAttenuation;
  12061. this.fog = source.fog;
  12062. return this;
  12063. }
  12064. }
  12065. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  12066. const _ray = /*@__PURE__*/ new Ray();
  12067. const _sphere = /*@__PURE__*/ new Sphere();
  12068. const _position$2 = /*@__PURE__*/ new Vector3();
  12069. class Points extends Object3D {
  12070. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  12071. super();
  12072. this.isPoints = true;
  12073. this.type = 'Points';
  12074. this.geometry = geometry;
  12075. this.material = material;
  12076. this.updateMorphTargets();
  12077. }
  12078. copy( source, recursive ) {
  12079. super.copy( source, recursive );
  12080. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  12081. this.geometry = source.geometry;
  12082. return this;
  12083. }
  12084. raycast( raycaster, intersects ) {
  12085. const geometry = this.geometry;
  12086. const matrixWorld = this.matrixWorld;
  12087. const threshold = raycaster.params.Points.threshold;
  12088. const drawRange = geometry.drawRange;
  12089. // Checking boundingSphere distance to ray
  12090. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12091. _sphere.copy( geometry.boundingSphere );
  12092. _sphere.applyMatrix4( matrixWorld );
  12093. _sphere.radius += threshold;
  12094. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  12095. //
  12096. _inverseMatrix.copy( matrixWorld ).invert();
  12097. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  12098. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  12099. const localThresholdSq = localThreshold * localThreshold;
  12100. const index = geometry.index;
  12101. const attributes = geometry.attributes;
  12102. const positionAttribute = attributes.position;
  12103. if ( index !== null ) {
  12104. const start = Math.max( 0, drawRange.start );
  12105. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12106. for ( let i = start, il = end; i < il; i ++ ) {
  12107. const a = index.getX( i );
  12108. _position$2.fromBufferAttribute( positionAttribute, a );
  12109. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  12110. }
  12111. } else {
  12112. const start = Math.max( 0, drawRange.start );
  12113. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  12114. for ( let i = start, l = end; i < l; i ++ ) {
  12115. _position$2.fromBufferAttribute( positionAttribute, i );
  12116. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  12117. }
  12118. }
  12119. }
  12120. updateMorphTargets() {
  12121. const geometry = this.geometry;
  12122. const morphAttributes = geometry.morphAttributes;
  12123. const keys = Object.keys( morphAttributes );
  12124. if ( keys.length > 0 ) {
  12125. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  12126. if ( morphAttribute !== undefined ) {
  12127. this.morphTargetInfluences = [];
  12128. this.morphTargetDictionary = {};
  12129. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12130. const name = morphAttribute[ m ].name || String( m );
  12131. this.morphTargetInfluences.push( 0 );
  12132. this.morphTargetDictionary[ name ] = m;
  12133. }
  12134. }
  12135. }
  12136. }
  12137. }
  12138. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  12139. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  12140. if ( rayPointDistanceSq < localThresholdSq ) {
  12141. const intersectPoint = new Vector3();
  12142. _ray.closestPointToPoint( point, intersectPoint );
  12143. intersectPoint.applyMatrix4( matrixWorld );
  12144. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  12145. if ( distance < raycaster.near || distance > raycaster.far ) return;
  12146. intersects.push( {
  12147. distance: distance,
  12148. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  12149. point: intersectPoint,
  12150. index: index,
  12151. face: null,
  12152. faceIndex: null,
  12153. barycoord: null,
  12154. object: object
  12155. } );
  12156. }
  12157. }
  12158. class VideoTexture extends Texture {
  12159. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12160. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12161. this.isVideoTexture = true;
  12162. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  12163. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  12164. this.generateMipmaps = false;
  12165. const scope = this;
  12166. function updateVideo() {
  12167. scope.needsUpdate = true;
  12168. video.requestVideoFrameCallback( updateVideo );
  12169. }
  12170. if ( 'requestVideoFrameCallback' in video ) {
  12171. video.requestVideoFrameCallback( updateVideo );
  12172. }
  12173. }
  12174. clone() {
  12175. return new this.constructor( this.image ).copy( this );
  12176. }
  12177. update() {
  12178. const video = this.image;
  12179. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  12180. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  12181. this.needsUpdate = true;
  12182. }
  12183. }
  12184. }
  12185. class VideoFrameTexture extends VideoTexture {
  12186. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12187. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12188. this.isVideoFrameTexture = true;
  12189. }
  12190. update() {
  12191. // overwrites `VideoTexture.update()` with an empty method since
  12192. // this type of texture is updated via `setFrame()`.
  12193. }
  12194. clone() {
  12195. return new this.constructor().copy( this ); // restoring Texture.clone()
  12196. }
  12197. setFrame( frame ) {
  12198. this.image = frame;
  12199. this.needsUpdate = true;
  12200. }
  12201. }
  12202. class FramebufferTexture extends Texture {
  12203. constructor( width, height ) {
  12204. super( { width, height } );
  12205. this.isFramebufferTexture = true;
  12206. this.magFilter = NearestFilter;
  12207. this.minFilter = NearestFilter;
  12208. this.generateMipmaps = false;
  12209. this.needsUpdate = true;
  12210. }
  12211. }
  12212. class CompressedTexture extends Texture {
  12213. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  12214. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  12215. this.isCompressedTexture = true;
  12216. this.image = { width: width, height: height };
  12217. this.mipmaps = mipmaps;
  12218. // no flipping for cube textures
  12219. // (also flipping doesn't work for compressed textures )
  12220. this.flipY = false;
  12221. // can't generate mipmaps for compressed textures
  12222. // mips must be embedded in DDS files
  12223. this.generateMipmaps = false;
  12224. }
  12225. }
  12226. class CompressedArrayTexture extends CompressedTexture {
  12227. constructor( mipmaps, width, height, depth, format, type ) {
  12228. super( mipmaps, width, height, format, type );
  12229. this.isCompressedArrayTexture = true;
  12230. this.image.depth = depth;
  12231. this.wrapR = ClampToEdgeWrapping;
  12232. this.layerUpdates = new Set();
  12233. }
  12234. addLayerUpdate( layerIndex ) {
  12235. this.layerUpdates.add( layerIndex );
  12236. }
  12237. clearLayerUpdates() {
  12238. this.layerUpdates.clear();
  12239. }
  12240. }
  12241. class CompressedCubeTexture extends CompressedTexture {
  12242. constructor( images, format, type ) {
  12243. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  12244. this.isCompressedCubeTexture = true;
  12245. this.isCubeTexture = true;
  12246. this.image = images;
  12247. }
  12248. }
  12249. class CanvasTexture extends Texture {
  12250. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12251. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12252. this.isCanvasTexture = true;
  12253. this.needsUpdate = true;
  12254. }
  12255. }
  12256. class DepthTexture extends Texture {
  12257. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  12258. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  12259. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  12260. }
  12261. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  12262. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  12263. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12264. this.isDepthTexture = true;
  12265. this.image = { width: width, height: height };
  12266. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  12267. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  12268. this.flipY = false;
  12269. this.generateMipmaps = false;
  12270. this.compareFunction = null;
  12271. }
  12272. copy( source ) {
  12273. super.copy( source );
  12274. this.compareFunction = source.compareFunction;
  12275. return this;
  12276. }
  12277. toJSON( meta ) {
  12278. const data = super.toJSON( meta );
  12279. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  12280. return data;
  12281. }
  12282. }
  12283. /**
  12284. * Extensible curve object.
  12285. *
  12286. * Some common of curve methods:
  12287. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  12288. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  12289. * .getPoints(), .getSpacedPoints()
  12290. * .getLength()
  12291. * .updateArcLengths()
  12292. *
  12293. * This following curves inherit from THREE.Curve:
  12294. *
  12295. * -- 2D curves --
  12296. * THREE.ArcCurve
  12297. * THREE.CubicBezierCurve
  12298. * THREE.EllipseCurve
  12299. * THREE.LineCurve
  12300. * THREE.QuadraticBezierCurve
  12301. * THREE.SplineCurve
  12302. *
  12303. * -- 3D curves --
  12304. * THREE.CatmullRomCurve3
  12305. * THREE.CubicBezierCurve3
  12306. * THREE.LineCurve3
  12307. * THREE.QuadraticBezierCurve3
  12308. *
  12309. * A series of curves can be represented as a THREE.CurvePath.
  12310. *
  12311. **/
  12312. class Curve {
  12313. constructor() {
  12314. this.type = 'Curve';
  12315. this.arcLengthDivisions = 200;
  12316. }
  12317. // Virtual base class method to overwrite and implement in subclasses
  12318. // - t [0 .. 1]
  12319. getPoint( /* t, optionalTarget */ ) {
  12320. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  12321. return null;
  12322. }
  12323. // Get point at relative position in curve according to arc length
  12324. // - u [0 .. 1]
  12325. getPointAt( u, optionalTarget ) {
  12326. const t = this.getUtoTmapping( u );
  12327. return this.getPoint( t, optionalTarget );
  12328. }
  12329. // Get sequence of points using getPoint( t )
  12330. getPoints( divisions = 5 ) {
  12331. const points = [];
  12332. for ( let d = 0; d <= divisions; d ++ ) {
  12333. points.push( this.getPoint( d / divisions ) );
  12334. }
  12335. return points;
  12336. }
  12337. // Get sequence of points using getPointAt( u )
  12338. getSpacedPoints( divisions = 5 ) {
  12339. const points = [];
  12340. for ( let d = 0; d <= divisions; d ++ ) {
  12341. points.push( this.getPointAt( d / divisions ) );
  12342. }
  12343. return points;
  12344. }
  12345. // Get total curve arc length
  12346. getLength() {
  12347. const lengths = this.getLengths();
  12348. return lengths[ lengths.length - 1 ];
  12349. }
  12350. // Get list of cumulative segment lengths
  12351. getLengths( divisions = this.arcLengthDivisions ) {
  12352. if ( this.cacheArcLengths &&
  12353. ( this.cacheArcLengths.length === divisions + 1 ) &&
  12354. ! this.needsUpdate ) {
  12355. return this.cacheArcLengths;
  12356. }
  12357. this.needsUpdate = false;
  12358. const cache = [];
  12359. let current, last = this.getPoint( 0 );
  12360. let sum = 0;
  12361. cache.push( 0 );
  12362. for ( let p = 1; p <= divisions; p ++ ) {
  12363. current = this.getPoint( p / divisions );
  12364. sum += current.distanceTo( last );
  12365. cache.push( sum );
  12366. last = current;
  12367. }
  12368. this.cacheArcLengths = cache;
  12369. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  12370. }
  12371. updateArcLengths() {
  12372. this.needsUpdate = true;
  12373. this.getLengths();
  12374. }
  12375. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  12376. getUtoTmapping( u, distance ) {
  12377. const arcLengths = this.getLengths();
  12378. let i = 0;
  12379. const il = arcLengths.length;
  12380. let targetArcLength; // The targeted u distance value to get
  12381. if ( distance ) {
  12382. targetArcLength = distance;
  12383. } else {
  12384. targetArcLength = u * arcLengths[ il - 1 ];
  12385. }
  12386. // binary search for the index with largest value smaller than target u distance
  12387. let low = 0, high = il - 1, comparison;
  12388. while ( low <= high ) {
  12389. 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
  12390. comparison = arcLengths[ i ] - targetArcLength;
  12391. if ( comparison < 0 ) {
  12392. low = i + 1;
  12393. } else if ( comparison > 0 ) {
  12394. high = i - 1;
  12395. } else {
  12396. high = i;
  12397. break;
  12398. // DONE
  12399. }
  12400. }
  12401. i = high;
  12402. if ( arcLengths[ i ] === targetArcLength ) {
  12403. return i / ( il - 1 );
  12404. }
  12405. // we could get finer grain at lengths, or use simple interpolation between two points
  12406. const lengthBefore = arcLengths[ i ];
  12407. const lengthAfter = arcLengths[ i + 1 ];
  12408. const segmentLength = lengthAfter - lengthBefore;
  12409. // determine where we are between the 'before' and 'after' points
  12410. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  12411. // add that fractional amount to t
  12412. const t = ( i + segmentFraction ) / ( il - 1 );
  12413. return t;
  12414. }
  12415. // Returns a unit vector tangent at t
  12416. // In case any sub curve does not implement its tangent derivation,
  12417. // 2 points a small delta apart will be used to find its gradient
  12418. // which seems to give a reasonable approximation
  12419. getTangent( t, optionalTarget ) {
  12420. const delta = 0.0001;
  12421. let t1 = t - delta;
  12422. let t2 = t + delta;
  12423. // Capping in case of danger
  12424. if ( t1 < 0 ) t1 = 0;
  12425. if ( t2 > 1 ) t2 = 1;
  12426. const pt1 = this.getPoint( t1 );
  12427. const pt2 = this.getPoint( t2 );
  12428. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  12429. tangent.copy( pt2 ).sub( pt1 ).normalize();
  12430. return tangent;
  12431. }
  12432. getTangentAt( u, optionalTarget ) {
  12433. const t = this.getUtoTmapping( u );
  12434. return this.getTangent( t, optionalTarget );
  12435. }
  12436. computeFrenetFrames( segments, closed ) {
  12437. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  12438. const normal = new Vector3();
  12439. const tangents = [];
  12440. const normals = [];
  12441. const binormals = [];
  12442. const vec = new Vector3();
  12443. const mat = new Matrix4();
  12444. // compute the tangent vectors for each segment on the curve
  12445. for ( let i = 0; i <= segments; i ++ ) {
  12446. const u = i / segments;
  12447. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  12448. }
  12449. // select an initial normal vector perpendicular to the first tangent vector,
  12450. // and in the direction of the minimum tangent xyz component
  12451. normals[ 0 ] = new Vector3();
  12452. binormals[ 0 ] = new Vector3();
  12453. let min = Number.MAX_VALUE;
  12454. const tx = Math.abs( tangents[ 0 ].x );
  12455. const ty = Math.abs( tangents[ 0 ].y );
  12456. const tz = Math.abs( tangents[ 0 ].z );
  12457. if ( tx <= min ) {
  12458. min = tx;
  12459. normal.set( 1, 0, 0 );
  12460. }
  12461. if ( ty <= min ) {
  12462. min = ty;
  12463. normal.set( 0, 1, 0 );
  12464. }
  12465. if ( tz <= min ) {
  12466. normal.set( 0, 0, 1 );
  12467. }
  12468. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  12469. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  12470. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  12471. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  12472. for ( let i = 1; i <= segments; i ++ ) {
  12473. normals[ i ] = normals[ i - 1 ].clone();
  12474. binormals[ i ] = binormals[ i - 1 ].clone();
  12475. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  12476. if ( vec.length() > Number.EPSILON ) {
  12477. vec.normalize();
  12478. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  12479. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  12480. }
  12481. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  12482. }
  12483. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  12484. if ( closed === true ) {
  12485. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  12486. theta /= segments;
  12487. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  12488. theta = - theta;
  12489. }
  12490. for ( let i = 1; i <= segments; i ++ ) {
  12491. // twist a little...
  12492. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  12493. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  12494. }
  12495. }
  12496. return {
  12497. tangents: tangents,
  12498. normals: normals,
  12499. binormals: binormals
  12500. };
  12501. }
  12502. clone() {
  12503. return new this.constructor().copy( this );
  12504. }
  12505. copy( source ) {
  12506. this.arcLengthDivisions = source.arcLengthDivisions;
  12507. return this;
  12508. }
  12509. toJSON() {
  12510. const data = {
  12511. metadata: {
  12512. version: 4.6,
  12513. type: 'Curve',
  12514. generator: 'Curve.toJSON'
  12515. }
  12516. };
  12517. data.arcLengthDivisions = this.arcLengthDivisions;
  12518. data.type = this.type;
  12519. return data;
  12520. }
  12521. fromJSON( json ) {
  12522. this.arcLengthDivisions = json.arcLengthDivisions;
  12523. return this;
  12524. }
  12525. }
  12526. class EllipseCurve extends Curve {
  12527. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  12528. super();
  12529. this.isEllipseCurve = true;
  12530. this.type = 'EllipseCurve';
  12531. this.aX = aX;
  12532. this.aY = aY;
  12533. this.xRadius = xRadius;
  12534. this.yRadius = yRadius;
  12535. this.aStartAngle = aStartAngle;
  12536. this.aEndAngle = aEndAngle;
  12537. this.aClockwise = aClockwise;
  12538. this.aRotation = aRotation;
  12539. }
  12540. getPoint( t, optionalTarget = new Vector2() ) {
  12541. const point = optionalTarget;
  12542. const twoPi = Math.PI * 2;
  12543. let deltaAngle = this.aEndAngle - this.aStartAngle;
  12544. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  12545. // ensures that deltaAngle is 0 .. 2 PI
  12546. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  12547. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  12548. if ( deltaAngle < Number.EPSILON ) {
  12549. if ( samePoints ) {
  12550. deltaAngle = 0;
  12551. } else {
  12552. deltaAngle = twoPi;
  12553. }
  12554. }
  12555. if ( this.aClockwise === true && ! samePoints ) {
  12556. if ( deltaAngle === twoPi ) {
  12557. deltaAngle = - twoPi;
  12558. } else {
  12559. deltaAngle = deltaAngle - twoPi;
  12560. }
  12561. }
  12562. const angle = this.aStartAngle + t * deltaAngle;
  12563. let x = this.aX + this.xRadius * Math.cos( angle );
  12564. let y = this.aY + this.yRadius * Math.sin( angle );
  12565. if ( this.aRotation !== 0 ) {
  12566. const cos = Math.cos( this.aRotation );
  12567. const sin = Math.sin( this.aRotation );
  12568. const tx = x - this.aX;
  12569. const ty = y - this.aY;
  12570. // Rotate the point about the center of the ellipse.
  12571. x = tx * cos - ty * sin + this.aX;
  12572. y = tx * sin + ty * cos + this.aY;
  12573. }
  12574. return point.set( x, y );
  12575. }
  12576. copy( source ) {
  12577. super.copy( source );
  12578. this.aX = source.aX;
  12579. this.aY = source.aY;
  12580. this.xRadius = source.xRadius;
  12581. this.yRadius = source.yRadius;
  12582. this.aStartAngle = source.aStartAngle;
  12583. this.aEndAngle = source.aEndAngle;
  12584. this.aClockwise = source.aClockwise;
  12585. this.aRotation = source.aRotation;
  12586. return this;
  12587. }
  12588. toJSON() {
  12589. const data = super.toJSON();
  12590. data.aX = this.aX;
  12591. data.aY = this.aY;
  12592. data.xRadius = this.xRadius;
  12593. data.yRadius = this.yRadius;
  12594. data.aStartAngle = this.aStartAngle;
  12595. data.aEndAngle = this.aEndAngle;
  12596. data.aClockwise = this.aClockwise;
  12597. data.aRotation = this.aRotation;
  12598. return data;
  12599. }
  12600. fromJSON( json ) {
  12601. super.fromJSON( json );
  12602. this.aX = json.aX;
  12603. this.aY = json.aY;
  12604. this.xRadius = json.xRadius;
  12605. this.yRadius = json.yRadius;
  12606. this.aStartAngle = json.aStartAngle;
  12607. this.aEndAngle = json.aEndAngle;
  12608. this.aClockwise = json.aClockwise;
  12609. this.aRotation = json.aRotation;
  12610. return this;
  12611. }
  12612. }
  12613. class ArcCurve extends EllipseCurve {
  12614. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  12615. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  12616. this.isArcCurve = true;
  12617. this.type = 'ArcCurve';
  12618. }
  12619. }
  12620. /**
  12621. * Centripetal CatmullRom Curve - which is useful for avoiding
  12622. * cusps and self-intersections in non-uniform catmull rom curves.
  12623. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  12624. *
  12625. * curve.type accepts centripetal(default), chordal and catmullrom
  12626. * curve.tension is used for catmullrom which defaults to 0.5
  12627. */
  12628. /*
  12629. Based on an optimized c++ solution in
  12630. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  12631. - http://ideone.com/NoEbVM
  12632. This CubicPoly class could be used for reusing some variables and calculations,
  12633. but for three.js curve use, it could be possible inlined and flatten into a single function call
  12634. which can be placed in CurveUtils.
  12635. */
  12636. function CubicPoly() {
  12637. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  12638. /*
  12639. * Compute coefficients for a cubic polynomial
  12640. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  12641. * such that
  12642. * p(0) = x0, p(1) = x1
  12643. * and
  12644. * p'(0) = t0, p'(1) = t1.
  12645. */
  12646. function init( x0, x1, t0, t1 ) {
  12647. c0 = x0;
  12648. c1 = t0;
  12649. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  12650. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  12651. }
  12652. return {
  12653. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  12654. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  12655. },
  12656. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  12657. // compute tangents when parameterized in [t1,t2]
  12658. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  12659. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  12660. // rescale tangents for parametrization in [0,1]
  12661. t1 *= dt1;
  12662. t2 *= dt1;
  12663. init( x1, x2, t1, t2 );
  12664. },
  12665. calc: function ( t ) {
  12666. const t2 = t * t;
  12667. const t3 = t2 * t;
  12668. return c0 + c1 * t + c2 * t2 + c3 * t3;
  12669. }
  12670. };
  12671. }
  12672. //
  12673. const tmp = /*@__PURE__*/ new Vector3();
  12674. const px = /*@__PURE__*/ new CubicPoly();
  12675. const py = /*@__PURE__*/ new CubicPoly();
  12676. const pz = /*@__PURE__*/ new CubicPoly();
  12677. class CatmullRomCurve3 extends Curve {
  12678. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  12679. super();
  12680. this.isCatmullRomCurve3 = true;
  12681. this.type = 'CatmullRomCurve3';
  12682. this.points = points;
  12683. this.closed = closed;
  12684. this.curveType = curveType;
  12685. this.tension = tension;
  12686. }
  12687. getPoint( t, optionalTarget = new Vector3() ) {
  12688. const point = optionalTarget;
  12689. const points = this.points;
  12690. const l = points.length;
  12691. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  12692. let intPoint = Math.floor( p );
  12693. let weight = p - intPoint;
  12694. if ( this.closed ) {
  12695. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  12696. } else if ( weight === 0 && intPoint === l - 1 ) {
  12697. intPoint = l - 2;
  12698. weight = 1;
  12699. }
  12700. let p0, p3; // 4 points (p1 & p2 defined below)
  12701. if ( this.closed || intPoint > 0 ) {
  12702. p0 = points[ ( intPoint - 1 ) % l ];
  12703. } else {
  12704. // extrapolate first point
  12705. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  12706. p0 = tmp;
  12707. }
  12708. const p1 = points[ intPoint % l ];
  12709. const p2 = points[ ( intPoint + 1 ) % l ];
  12710. if ( this.closed || intPoint + 2 < l ) {
  12711. p3 = points[ ( intPoint + 2 ) % l ];
  12712. } else {
  12713. // extrapolate last point
  12714. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  12715. p3 = tmp;
  12716. }
  12717. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  12718. // init Centripetal / Chordal Catmull-Rom
  12719. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  12720. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  12721. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  12722. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  12723. // safety check for repeated points
  12724. if ( dt1 < 1e-4 ) dt1 = 1.0;
  12725. if ( dt0 < 1e-4 ) dt0 = dt1;
  12726. if ( dt2 < 1e-4 ) dt2 = dt1;
  12727. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  12728. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  12729. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  12730. } else if ( this.curveType === 'catmullrom' ) {
  12731. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  12732. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  12733. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  12734. }
  12735. point.set(
  12736. px.calc( weight ),
  12737. py.calc( weight ),
  12738. pz.calc( weight )
  12739. );
  12740. return point;
  12741. }
  12742. copy( source ) {
  12743. super.copy( source );
  12744. this.points = [];
  12745. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  12746. const point = source.points[ i ];
  12747. this.points.push( point.clone() );
  12748. }
  12749. this.closed = source.closed;
  12750. this.curveType = source.curveType;
  12751. this.tension = source.tension;
  12752. return this;
  12753. }
  12754. toJSON() {
  12755. const data = super.toJSON();
  12756. data.points = [];
  12757. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  12758. const point = this.points[ i ];
  12759. data.points.push( point.toArray() );
  12760. }
  12761. data.closed = this.closed;
  12762. data.curveType = this.curveType;
  12763. data.tension = this.tension;
  12764. return data;
  12765. }
  12766. fromJSON( json ) {
  12767. super.fromJSON( json );
  12768. this.points = [];
  12769. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  12770. const point = json.points[ i ];
  12771. this.points.push( new Vector3().fromArray( point ) );
  12772. }
  12773. this.closed = json.closed;
  12774. this.curveType = json.curveType;
  12775. this.tension = json.tension;
  12776. return this;
  12777. }
  12778. }
  12779. /**
  12780. * Bezier Curves formulas obtained from
  12781. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  12782. */
  12783. function CatmullRom( t, p0, p1, p2, p3 ) {
  12784. const v0 = ( p2 - p0 ) * 0.5;
  12785. const v1 = ( p3 - p1 ) * 0.5;
  12786. const t2 = t * t;
  12787. const t3 = t * t2;
  12788. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  12789. }
  12790. //
  12791. function QuadraticBezierP0( t, p ) {
  12792. const k = 1 - t;
  12793. return k * k * p;
  12794. }
  12795. function QuadraticBezierP1( t, p ) {
  12796. return 2 * ( 1 - t ) * t * p;
  12797. }
  12798. function QuadraticBezierP2( t, p ) {
  12799. return t * t * p;
  12800. }
  12801. function QuadraticBezier( t, p0, p1, p2 ) {
  12802. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  12803. QuadraticBezierP2( t, p2 );
  12804. }
  12805. //
  12806. function CubicBezierP0( t, p ) {
  12807. const k = 1 - t;
  12808. return k * k * k * p;
  12809. }
  12810. function CubicBezierP1( t, p ) {
  12811. const k = 1 - t;
  12812. return 3 * k * k * t * p;
  12813. }
  12814. function CubicBezierP2( t, p ) {
  12815. return 3 * ( 1 - t ) * t * t * p;
  12816. }
  12817. function CubicBezierP3( t, p ) {
  12818. return t * t * t * p;
  12819. }
  12820. function CubicBezier( t, p0, p1, p2, p3 ) {
  12821. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  12822. CubicBezierP3( t, p3 );
  12823. }
  12824. class CubicBezierCurve extends Curve {
  12825. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  12826. super();
  12827. this.isCubicBezierCurve = true;
  12828. this.type = 'CubicBezierCurve';
  12829. this.v0 = v0;
  12830. this.v1 = v1;
  12831. this.v2 = v2;
  12832. this.v3 = v3;
  12833. }
  12834. getPoint( t, optionalTarget = new Vector2() ) {
  12835. const point = optionalTarget;
  12836. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  12837. point.set(
  12838. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  12839. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  12840. );
  12841. return point;
  12842. }
  12843. copy( source ) {
  12844. super.copy( source );
  12845. this.v0.copy( source.v0 );
  12846. this.v1.copy( source.v1 );
  12847. this.v2.copy( source.v2 );
  12848. this.v3.copy( source.v3 );
  12849. return this;
  12850. }
  12851. toJSON() {
  12852. const data = super.toJSON();
  12853. data.v0 = this.v0.toArray();
  12854. data.v1 = this.v1.toArray();
  12855. data.v2 = this.v2.toArray();
  12856. data.v3 = this.v3.toArray();
  12857. return data;
  12858. }
  12859. fromJSON( json ) {
  12860. super.fromJSON( json );
  12861. this.v0.fromArray( json.v0 );
  12862. this.v1.fromArray( json.v1 );
  12863. this.v2.fromArray( json.v2 );
  12864. this.v3.fromArray( json.v3 );
  12865. return this;
  12866. }
  12867. }
  12868. class CubicBezierCurve3 extends Curve {
  12869. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  12870. super();
  12871. this.isCubicBezierCurve3 = true;
  12872. this.type = 'CubicBezierCurve3';
  12873. this.v0 = v0;
  12874. this.v1 = v1;
  12875. this.v2 = v2;
  12876. this.v3 = v3;
  12877. }
  12878. getPoint( t, optionalTarget = new Vector3() ) {
  12879. const point = optionalTarget;
  12880. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  12881. point.set(
  12882. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  12883. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  12884. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  12885. );
  12886. return point;
  12887. }
  12888. copy( source ) {
  12889. super.copy( source );
  12890. this.v0.copy( source.v0 );
  12891. this.v1.copy( source.v1 );
  12892. this.v2.copy( source.v2 );
  12893. this.v3.copy( source.v3 );
  12894. return this;
  12895. }
  12896. toJSON() {
  12897. const data = super.toJSON();
  12898. data.v0 = this.v0.toArray();
  12899. data.v1 = this.v1.toArray();
  12900. data.v2 = this.v2.toArray();
  12901. data.v3 = this.v3.toArray();
  12902. return data;
  12903. }
  12904. fromJSON( json ) {
  12905. super.fromJSON( json );
  12906. this.v0.fromArray( json.v0 );
  12907. this.v1.fromArray( json.v1 );
  12908. this.v2.fromArray( json.v2 );
  12909. this.v3.fromArray( json.v3 );
  12910. return this;
  12911. }
  12912. }
  12913. class LineCurve extends Curve {
  12914. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  12915. super();
  12916. this.isLineCurve = true;
  12917. this.type = 'LineCurve';
  12918. this.v1 = v1;
  12919. this.v2 = v2;
  12920. }
  12921. getPoint( t, optionalTarget = new Vector2() ) {
  12922. const point = optionalTarget;
  12923. if ( t === 1 ) {
  12924. point.copy( this.v2 );
  12925. } else {
  12926. point.copy( this.v2 ).sub( this.v1 );
  12927. point.multiplyScalar( t ).add( this.v1 );
  12928. }
  12929. return point;
  12930. }
  12931. // Line curve is linear, so we can overwrite default getPointAt
  12932. getPointAt( u, optionalTarget ) {
  12933. return this.getPoint( u, optionalTarget );
  12934. }
  12935. getTangent( t, optionalTarget = new Vector2() ) {
  12936. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  12937. }
  12938. getTangentAt( u, optionalTarget ) {
  12939. return this.getTangent( u, optionalTarget );
  12940. }
  12941. copy( source ) {
  12942. super.copy( source );
  12943. this.v1.copy( source.v1 );
  12944. this.v2.copy( source.v2 );
  12945. return this;
  12946. }
  12947. toJSON() {
  12948. const data = super.toJSON();
  12949. data.v1 = this.v1.toArray();
  12950. data.v2 = this.v2.toArray();
  12951. return data;
  12952. }
  12953. fromJSON( json ) {
  12954. super.fromJSON( json );
  12955. this.v1.fromArray( json.v1 );
  12956. this.v2.fromArray( json.v2 );
  12957. return this;
  12958. }
  12959. }
  12960. class LineCurve3 extends Curve {
  12961. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  12962. super();
  12963. this.isLineCurve3 = true;
  12964. this.type = 'LineCurve3';
  12965. this.v1 = v1;
  12966. this.v2 = v2;
  12967. }
  12968. getPoint( t, optionalTarget = new Vector3() ) {
  12969. const point = optionalTarget;
  12970. if ( t === 1 ) {
  12971. point.copy( this.v2 );
  12972. } else {
  12973. point.copy( this.v2 ).sub( this.v1 );
  12974. point.multiplyScalar( t ).add( this.v1 );
  12975. }
  12976. return point;
  12977. }
  12978. // Line curve is linear, so we can overwrite default getPointAt
  12979. getPointAt( u, optionalTarget ) {
  12980. return this.getPoint( u, optionalTarget );
  12981. }
  12982. getTangent( t, optionalTarget = new Vector3() ) {
  12983. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  12984. }
  12985. getTangentAt( u, optionalTarget ) {
  12986. return this.getTangent( u, optionalTarget );
  12987. }
  12988. copy( source ) {
  12989. super.copy( source );
  12990. this.v1.copy( source.v1 );
  12991. this.v2.copy( source.v2 );
  12992. return this;
  12993. }
  12994. toJSON() {
  12995. const data = super.toJSON();
  12996. data.v1 = this.v1.toArray();
  12997. data.v2 = this.v2.toArray();
  12998. return data;
  12999. }
  13000. fromJSON( json ) {
  13001. super.fromJSON( json );
  13002. this.v1.fromArray( json.v1 );
  13003. this.v2.fromArray( json.v2 );
  13004. return this;
  13005. }
  13006. }
  13007. class QuadraticBezierCurve extends Curve {
  13008. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  13009. super();
  13010. this.isQuadraticBezierCurve = true;
  13011. this.type = 'QuadraticBezierCurve';
  13012. this.v0 = v0;
  13013. this.v1 = v1;
  13014. this.v2 = v2;
  13015. }
  13016. getPoint( t, optionalTarget = new Vector2() ) {
  13017. const point = optionalTarget;
  13018. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  13019. point.set(
  13020. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  13021. QuadraticBezier( t, v0.y, v1.y, v2.y )
  13022. );
  13023. return point;
  13024. }
  13025. copy( source ) {
  13026. super.copy( source );
  13027. this.v0.copy( source.v0 );
  13028. this.v1.copy( source.v1 );
  13029. this.v2.copy( source.v2 );
  13030. return this;
  13031. }
  13032. toJSON() {
  13033. const data = super.toJSON();
  13034. data.v0 = this.v0.toArray();
  13035. data.v1 = this.v1.toArray();
  13036. data.v2 = this.v2.toArray();
  13037. return data;
  13038. }
  13039. fromJSON( json ) {
  13040. super.fromJSON( json );
  13041. this.v0.fromArray( json.v0 );
  13042. this.v1.fromArray( json.v1 );
  13043. this.v2.fromArray( json.v2 );
  13044. return this;
  13045. }
  13046. }
  13047. class QuadraticBezierCurve3 extends Curve {
  13048. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  13049. super();
  13050. this.isQuadraticBezierCurve3 = true;
  13051. this.type = 'QuadraticBezierCurve3';
  13052. this.v0 = v0;
  13053. this.v1 = v1;
  13054. this.v2 = v2;
  13055. }
  13056. getPoint( t, optionalTarget = new Vector3() ) {
  13057. const point = optionalTarget;
  13058. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  13059. point.set(
  13060. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  13061. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  13062. QuadraticBezier( t, v0.z, v1.z, v2.z )
  13063. );
  13064. return point;
  13065. }
  13066. copy( source ) {
  13067. super.copy( source );
  13068. this.v0.copy( source.v0 );
  13069. this.v1.copy( source.v1 );
  13070. this.v2.copy( source.v2 );
  13071. return this;
  13072. }
  13073. toJSON() {
  13074. const data = super.toJSON();
  13075. data.v0 = this.v0.toArray();
  13076. data.v1 = this.v1.toArray();
  13077. data.v2 = this.v2.toArray();
  13078. return data;
  13079. }
  13080. fromJSON( json ) {
  13081. super.fromJSON( json );
  13082. this.v0.fromArray( json.v0 );
  13083. this.v1.fromArray( json.v1 );
  13084. this.v2.fromArray( json.v2 );
  13085. return this;
  13086. }
  13087. }
  13088. class SplineCurve extends Curve {
  13089. constructor( points = [] ) {
  13090. super();
  13091. this.isSplineCurve = true;
  13092. this.type = 'SplineCurve';
  13093. this.points = points;
  13094. }
  13095. getPoint( t, optionalTarget = new Vector2() ) {
  13096. const point = optionalTarget;
  13097. const points = this.points;
  13098. const p = ( points.length - 1 ) * t;
  13099. const intPoint = Math.floor( p );
  13100. const weight = p - intPoint;
  13101. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  13102. const p1 = points[ intPoint ];
  13103. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  13104. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  13105. point.set(
  13106. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  13107. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  13108. );
  13109. return point;
  13110. }
  13111. copy( source ) {
  13112. super.copy( source );
  13113. this.points = [];
  13114. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  13115. const point = source.points[ i ];
  13116. this.points.push( point.clone() );
  13117. }
  13118. return this;
  13119. }
  13120. toJSON() {
  13121. const data = super.toJSON();
  13122. data.points = [];
  13123. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  13124. const point = this.points[ i ];
  13125. data.points.push( point.toArray() );
  13126. }
  13127. return data;
  13128. }
  13129. fromJSON( json ) {
  13130. super.fromJSON( json );
  13131. this.points = [];
  13132. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  13133. const point = json.points[ i ];
  13134. this.points.push( new Vector2().fromArray( point ) );
  13135. }
  13136. return this;
  13137. }
  13138. }
  13139. var Curves = /*#__PURE__*/Object.freeze({
  13140. __proto__: null,
  13141. ArcCurve: ArcCurve,
  13142. CatmullRomCurve3: CatmullRomCurve3,
  13143. CubicBezierCurve: CubicBezierCurve,
  13144. CubicBezierCurve3: CubicBezierCurve3,
  13145. EllipseCurve: EllipseCurve,
  13146. LineCurve: LineCurve,
  13147. LineCurve3: LineCurve3,
  13148. QuadraticBezierCurve: QuadraticBezierCurve,
  13149. QuadraticBezierCurve3: QuadraticBezierCurve3,
  13150. SplineCurve: SplineCurve
  13151. });
  13152. /**************************************************************
  13153. * Curved Path - a curve path is simply a array of connected
  13154. * curves, but retains the api of a curve
  13155. **************************************************************/
  13156. class CurvePath extends Curve {
  13157. constructor() {
  13158. super();
  13159. this.type = 'CurvePath';
  13160. this.curves = [];
  13161. this.autoClose = false; // Automatically closes the path
  13162. }
  13163. add( curve ) {
  13164. this.curves.push( curve );
  13165. }
  13166. closePath() {
  13167. // Add a line curve if start and end of lines are not connected
  13168. const startPoint = this.curves[ 0 ].getPoint( 0 );
  13169. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  13170. if ( ! startPoint.equals( endPoint ) ) {
  13171. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  13172. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  13173. }
  13174. return this;
  13175. }
  13176. // To get accurate point with reference to
  13177. // entire path distance at time t,
  13178. // following has to be done:
  13179. // 1. Length of each sub path have to be known
  13180. // 2. Locate and identify type of curve
  13181. // 3. Get t for the curve
  13182. // 4. Return curve.getPointAt(t')
  13183. getPoint( t, optionalTarget ) {
  13184. const d = t * this.getLength();
  13185. const curveLengths = this.getCurveLengths();
  13186. let i = 0;
  13187. // To think about boundaries points.
  13188. while ( i < curveLengths.length ) {
  13189. if ( curveLengths[ i ] >= d ) {
  13190. const diff = curveLengths[ i ] - d;
  13191. const curve = this.curves[ i ];
  13192. const segmentLength = curve.getLength();
  13193. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  13194. return curve.getPointAt( u, optionalTarget );
  13195. }
  13196. i ++;
  13197. }
  13198. return null;
  13199. // loop where sum != 0, sum > d , sum+1 <d
  13200. }
  13201. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  13202. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  13203. // getPoint() depends on getLength
  13204. getLength() {
  13205. const lens = this.getCurveLengths();
  13206. return lens[ lens.length - 1 ];
  13207. }
  13208. // cacheLengths must be recalculated.
  13209. updateArcLengths() {
  13210. this.needsUpdate = true;
  13211. this.cacheLengths = null;
  13212. this.getCurveLengths();
  13213. }
  13214. // Compute lengths and cache them
  13215. // We cannot overwrite getLengths() because UtoT mapping uses it.
  13216. getCurveLengths() {
  13217. // We use cache values if curves and cache array are same length
  13218. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  13219. return this.cacheLengths;
  13220. }
  13221. // Get length of sub-curve
  13222. // Push sums into cached array
  13223. const lengths = [];
  13224. let sums = 0;
  13225. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  13226. sums += this.curves[ i ].getLength();
  13227. lengths.push( sums );
  13228. }
  13229. this.cacheLengths = lengths;
  13230. return lengths;
  13231. }
  13232. getSpacedPoints( divisions = 40 ) {
  13233. const points = [];
  13234. for ( let i = 0; i <= divisions; i ++ ) {
  13235. points.push( this.getPoint( i / divisions ) );
  13236. }
  13237. if ( this.autoClose ) {
  13238. points.push( points[ 0 ] );
  13239. }
  13240. return points;
  13241. }
  13242. getPoints( divisions = 12 ) {
  13243. const points = [];
  13244. let last;
  13245. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  13246. const curve = curves[ i ];
  13247. const resolution = curve.isEllipseCurve ? divisions * 2
  13248. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  13249. : curve.isSplineCurve ? divisions * curve.points.length
  13250. : divisions;
  13251. const pts = curve.getPoints( resolution );
  13252. for ( let j = 0; j < pts.length; j ++ ) {
  13253. const point = pts[ j ];
  13254. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  13255. points.push( point );
  13256. last = point;
  13257. }
  13258. }
  13259. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  13260. points.push( points[ 0 ] );
  13261. }
  13262. return points;
  13263. }
  13264. copy( source ) {
  13265. super.copy( source );
  13266. this.curves = [];
  13267. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  13268. const curve = source.curves[ i ];
  13269. this.curves.push( curve.clone() );
  13270. }
  13271. this.autoClose = source.autoClose;
  13272. return this;
  13273. }
  13274. toJSON() {
  13275. const data = super.toJSON();
  13276. data.autoClose = this.autoClose;
  13277. data.curves = [];
  13278. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  13279. const curve = this.curves[ i ];
  13280. data.curves.push( curve.toJSON() );
  13281. }
  13282. return data;
  13283. }
  13284. fromJSON( json ) {
  13285. super.fromJSON( json );
  13286. this.autoClose = json.autoClose;
  13287. this.curves = [];
  13288. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  13289. const curve = json.curves[ i ];
  13290. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  13291. }
  13292. return this;
  13293. }
  13294. }
  13295. class Path extends CurvePath {
  13296. constructor( points ) {
  13297. super();
  13298. this.type = 'Path';
  13299. this.currentPoint = new Vector2();
  13300. if ( points ) {
  13301. this.setFromPoints( points );
  13302. }
  13303. }
  13304. setFromPoints( points ) {
  13305. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  13306. for ( let i = 1, l = points.length; i < l; i ++ ) {
  13307. this.lineTo( points[ i ].x, points[ i ].y );
  13308. }
  13309. return this;
  13310. }
  13311. moveTo( x, y ) {
  13312. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  13313. return this;
  13314. }
  13315. lineTo( x, y ) {
  13316. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  13317. this.curves.push( curve );
  13318. this.currentPoint.set( x, y );
  13319. return this;
  13320. }
  13321. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  13322. const curve = new QuadraticBezierCurve(
  13323. this.currentPoint.clone(),
  13324. new Vector2( aCPx, aCPy ),
  13325. new Vector2( aX, aY )
  13326. );
  13327. this.curves.push( curve );
  13328. this.currentPoint.set( aX, aY );
  13329. return this;
  13330. }
  13331. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  13332. const curve = new CubicBezierCurve(
  13333. this.currentPoint.clone(),
  13334. new Vector2( aCP1x, aCP1y ),
  13335. new Vector2( aCP2x, aCP2y ),
  13336. new Vector2( aX, aY )
  13337. );
  13338. this.curves.push( curve );
  13339. this.currentPoint.set( aX, aY );
  13340. return this;
  13341. }
  13342. splineThru( pts /*Array of Vector*/ ) {
  13343. const npts = [ this.currentPoint.clone() ].concat( pts );
  13344. const curve = new SplineCurve( npts );
  13345. this.curves.push( curve );
  13346. this.currentPoint.copy( pts[ pts.length - 1 ] );
  13347. return this;
  13348. }
  13349. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  13350. const x0 = this.currentPoint.x;
  13351. const y0 = this.currentPoint.y;
  13352. this.absarc( aX + x0, aY + y0, aRadius,
  13353. aStartAngle, aEndAngle, aClockwise );
  13354. return this;
  13355. }
  13356. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  13357. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  13358. return this;
  13359. }
  13360. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  13361. const x0 = this.currentPoint.x;
  13362. const y0 = this.currentPoint.y;
  13363. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  13364. return this;
  13365. }
  13366. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  13367. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  13368. if ( this.curves.length > 0 ) {
  13369. // if a previous curve is present, attempt to join
  13370. const firstPoint = curve.getPoint( 0 );
  13371. if ( ! firstPoint.equals( this.currentPoint ) ) {
  13372. this.lineTo( firstPoint.x, firstPoint.y );
  13373. }
  13374. }
  13375. this.curves.push( curve );
  13376. const lastPoint = curve.getPoint( 1 );
  13377. this.currentPoint.copy( lastPoint );
  13378. return this;
  13379. }
  13380. copy( source ) {
  13381. super.copy( source );
  13382. this.currentPoint.copy( source.currentPoint );
  13383. return this;
  13384. }
  13385. toJSON() {
  13386. const data = super.toJSON();
  13387. data.currentPoint = this.currentPoint.toArray();
  13388. return data;
  13389. }
  13390. fromJSON( json ) {
  13391. super.fromJSON( json );
  13392. this.currentPoint.fromArray( json.currentPoint );
  13393. return this;
  13394. }
  13395. }
  13396. class LatheGeometry extends BufferGeometry {
  13397. 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 ) {
  13398. super();
  13399. this.type = 'LatheGeometry';
  13400. this.parameters = {
  13401. points: points,
  13402. segments: segments,
  13403. phiStart: phiStart,
  13404. phiLength: phiLength
  13405. };
  13406. segments = Math.floor( segments );
  13407. // clamp phiLength so it's in range of [ 0, 2PI ]
  13408. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  13409. // buffers
  13410. const indices = [];
  13411. const vertices = [];
  13412. const uvs = [];
  13413. const initNormals = [];
  13414. const normals = [];
  13415. // helper variables
  13416. const inverseSegments = 1.0 / segments;
  13417. const vertex = new Vector3();
  13418. const uv = new Vector2();
  13419. const normal = new Vector3();
  13420. const curNormal = new Vector3();
  13421. const prevNormal = new Vector3();
  13422. let dx = 0;
  13423. let dy = 0;
  13424. // pre-compute normals for initial "meridian"
  13425. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  13426. switch ( j ) {
  13427. case 0: // special handling for 1st vertex on path
  13428. dx = points[ j + 1 ].x - points[ j ].x;
  13429. dy = points[ j + 1 ].y - points[ j ].y;
  13430. normal.x = dy * 1.0;
  13431. normal.y = - dx;
  13432. normal.z = dy * 0.0;
  13433. prevNormal.copy( normal );
  13434. normal.normalize();
  13435. initNormals.push( normal.x, normal.y, normal.z );
  13436. break;
  13437. case ( points.length - 1 ): // special handling for last Vertex on path
  13438. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  13439. break;
  13440. default: // default handling for all vertices in between
  13441. dx = points[ j + 1 ].x - points[ j ].x;
  13442. dy = points[ j + 1 ].y - points[ j ].y;
  13443. normal.x = dy * 1.0;
  13444. normal.y = - dx;
  13445. normal.z = dy * 0.0;
  13446. curNormal.copy( normal );
  13447. normal.x += prevNormal.x;
  13448. normal.y += prevNormal.y;
  13449. normal.z += prevNormal.z;
  13450. normal.normalize();
  13451. initNormals.push( normal.x, normal.y, normal.z );
  13452. prevNormal.copy( curNormal );
  13453. }
  13454. }
  13455. // generate vertices, uvs and normals
  13456. for ( let i = 0; i <= segments; i ++ ) {
  13457. const phi = phiStart + i * inverseSegments * phiLength;
  13458. const sin = Math.sin( phi );
  13459. const cos = Math.cos( phi );
  13460. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  13461. // vertex
  13462. vertex.x = points[ j ].x * sin;
  13463. vertex.y = points[ j ].y;
  13464. vertex.z = points[ j ].x * cos;
  13465. vertices.push( vertex.x, vertex.y, vertex.z );
  13466. // uv
  13467. uv.x = i / segments;
  13468. uv.y = j / ( points.length - 1 );
  13469. uvs.push( uv.x, uv.y );
  13470. // normal
  13471. const x = initNormals[ 3 * j + 0 ] * sin;
  13472. const y = initNormals[ 3 * j + 1 ];
  13473. const z = initNormals[ 3 * j + 0 ] * cos;
  13474. normals.push( x, y, z );
  13475. }
  13476. }
  13477. // indices
  13478. for ( let i = 0; i < segments; i ++ ) {
  13479. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  13480. const base = j + i * points.length;
  13481. const a = base;
  13482. const b = base + points.length;
  13483. const c = base + points.length + 1;
  13484. const d = base + 1;
  13485. // faces
  13486. indices.push( a, b, d );
  13487. indices.push( c, d, b );
  13488. }
  13489. }
  13490. // build geometry
  13491. this.setIndex( indices );
  13492. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13493. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13494. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13495. }
  13496. copy( source ) {
  13497. super.copy( source );
  13498. this.parameters = Object.assign( {}, source.parameters );
  13499. return this;
  13500. }
  13501. static fromJSON( data ) {
  13502. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  13503. }
  13504. }
  13505. class CapsuleGeometry extends LatheGeometry {
  13506. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  13507. const path = new Path();
  13508. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  13509. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  13510. super( path.getPoints( capSegments ), radialSegments );
  13511. this.type = 'CapsuleGeometry';
  13512. this.parameters = {
  13513. radius: radius,
  13514. length: length,
  13515. capSegments: capSegments,
  13516. radialSegments: radialSegments,
  13517. };
  13518. }
  13519. static fromJSON( data ) {
  13520. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  13521. }
  13522. }
  13523. class CircleGeometry extends BufferGeometry {
  13524. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13525. super();
  13526. this.type = 'CircleGeometry';
  13527. this.parameters = {
  13528. radius: radius,
  13529. segments: segments,
  13530. thetaStart: thetaStart,
  13531. thetaLength: thetaLength
  13532. };
  13533. segments = Math.max( 3, segments );
  13534. // buffers
  13535. const indices = [];
  13536. const vertices = [];
  13537. const normals = [];
  13538. const uvs = [];
  13539. // helper variables
  13540. const vertex = new Vector3();
  13541. const uv = new Vector2();
  13542. // center point
  13543. vertices.push( 0, 0, 0 );
  13544. normals.push( 0, 0, 1 );
  13545. uvs.push( 0.5, 0.5 );
  13546. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  13547. const segment = thetaStart + s / segments * thetaLength;
  13548. // vertex
  13549. vertex.x = radius * Math.cos( segment );
  13550. vertex.y = radius * Math.sin( segment );
  13551. vertices.push( vertex.x, vertex.y, vertex.z );
  13552. // normal
  13553. normals.push( 0, 0, 1 );
  13554. // uvs
  13555. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  13556. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  13557. uvs.push( uv.x, uv.y );
  13558. }
  13559. // indices
  13560. for ( let i = 1; i <= segments; i ++ ) {
  13561. indices.push( i, i + 1, 0 );
  13562. }
  13563. // build geometry
  13564. this.setIndex( indices );
  13565. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13566. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13567. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13568. }
  13569. copy( source ) {
  13570. super.copy( source );
  13571. this.parameters = Object.assign( {}, source.parameters );
  13572. return this;
  13573. }
  13574. static fromJSON( data ) {
  13575. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  13576. }
  13577. }
  13578. class CylinderGeometry extends BufferGeometry {
  13579. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13580. super();
  13581. this.type = 'CylinderGeometry';
  13582. this.parameters = {
  13583. radiusTop: radiusTop,
  13584. radiusBottom: radiusBottom,
  13585. height: height,
  13586. radialSegments: radialSegments,
  13587. heightSegments: heightSegments,
  13588. openEnded: openEnded,
  13589. thetaStart: thetaStart,
  13590. thetaLength: thetaLength
  13591. };
  13592. const scope = this;
  13593. radialSegments = Math.floor( radialSegments );
  13594. heightSegments = Math.floor( heightSegments );
  13595. // buffers
  13596. const indices = [];
  13597. const vertices = [];
  13598. const normals = [];
  13599. const uvs = [];
  13600. // helper variables
  13601. let index = 0;
  13602. const indexArray = [];
  13603. const halfHeight = height / 2;
  13604. let groupStart = 0;
  13605. // generate geometry
  13606. generateTorso();
  13607. if ( openEnded === false ) {
  13608. if ( radiusTop > 0 ) generateCap( true );
  13609. if ( radiusBottom > 0 ) generateCap( false );
  13610. }
  13611. // build geometry
  13612. this.setIndex( indices );
  13613. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13614. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13615. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13616. function generateTorso() {
  13617. const normal = new Vector3();
  13618. const vertex = new Vector3();
  13619. let groupCount = 0;
  13620. // this will be used to calculate the normal
  13621. const slope = ( radiusBottom - radiusTop ) / height;
  13622. // generate vertices, normals and uvs
  13623. for ( let y = 0; y <= heightSegments; y ++ ) {
  13624. const indexRow = [];
  13625. const v = y / heightSegments;
  13626. // calculate the radius of the current row
  13627. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  13628. for ( let x = 0; x <= radialSegments; x ++ ) {
  13629. const u = x / radialSegments;
  13630. const theta = u * thetaLength + thetaStart;
  13631. const sinTheta = Math.sin( theta );
  13632. const cosTheta = Math.cos( theta );
  13633. // vertex
  13634. vertex.x = radius * sinTheta;
  13635. vertex.y = - v * height + halfHeight;
  13636. vertex.z = radius * cosTheta;
  13637. vertices.push( vertex.x, vertex.y, vertex.z );
  13638. // normal
  13639. normal.set( sinTheta, slope, cosTheta ).normalize();
  13640. normals.push( normal.x, normal.y, normal.z );
  13641. // uv
  13642. uvs.push( u, 1 - v );
  13643. // save index of vertex in respective row
  13644. indexRow.push( index ++ );
  13645. }
  13646. // now save vertices of the row in our index array
  13647. indexArray.push( indexRow );
  13648. }
  13649. // generate indices
  13650. for ( let x = 0; x < radialSegments; x ++ ) {
  13651. for ( let y = 0; y < heightSegments; y ++ ) {
  13652. // we use the index array to access the correct indices
  13653. const a = indexArray[ y ][ x ];
  13654. const b = indexArray[ y + 1 ][ x ];
  13655. const c = indexArray[ y + 1 ][ x + 1 ];
  13656. const d = indexArray[ y ][ x + 1 ];
  13657. // faces
  13658. if ( radiusTop > 0 || y !== 0 ) {
  13659. indices.push( a, b, d );
  13660. groupCount += 3;
  13661. }
  13662. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  13663. indices.push( b, c, d );
  13664. groupCount += 3;
  13665. }
  13666. }
  13667. }
  13668. // add a group to the geometry. this will ensure multi material support
  13669. scope.addGroup( groupStart, groupCount, 0 );
  13670. // calculate new start value for groups
  13671. groupStart += groupCount;
  13672. }
  13673. function generateCap( top ) {
  13674. // save the index of the first center vertex
  13675. const centerIndexStart = index;
  13676. const uv = new Vector2();
  13677. const vertex = new Vector3();
  13678. let groupCount = 0;
  13679. const radius = ( top === true ) ? radiusTop : radiusBottom;
  13680. const sign = ( top === true ) ? 1 : -1;
  13681. // first we generate the center vertex data of the cap.
  13682. // because the geometry needs one set of uvs per face,
  13683. // we must generate a center vertex per face/segment
  13684. for ( let x = 1; x <= radialSegments; x ++ ) {
  13685. // vertex
  13686. vertices.push( 0, halfHeight * sign, 0 );
  13687. // normal
  13688. normals.push( 0, sign, 0 );
  13689. // uv
  13690. uvs.push( 0.5, 0.5 );
  13691. // increase index
  13692. index ++;
  13693. }
  13694. // save the index of the last center vertex
  13695. const centerIndexEnd = index;
  13696. // now we generate the surrounding vertices, normals and uvs
  13697. for ( let x = 0; x <= radialSegments; x ++ ) {
  13698. const u = x / radialSegments;
  13699. const theta = u * thetaLength + thetaStart;
  13700. const cosTheta = Math.cos( theta );
  13701. const sinTheta = Math.sin( theta );
  13702. // vertex
  13703. vertex.x = radius * sinTheta;
  13704. vertex.y = halfHeight * sign;
  13705. vertex.z = radius * cosTheta;
  13706. vertices.push( vertex.x, vertex.y, vertex.z );
  13707. // normal
  13708. normals.push( 0, sign, 0 );
  13709. // uv
  13710. uv.x = ( cosTheta * 0.5 ) + 0.5;
  13711. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  13712. uvs.push( uv.x, uv.y );
  13713. // increase index
  13714. index ++;
  13715. }
  13716. // generate indices
  13717. for ( let x = 0; x < radialSegments; x ++ ) {
  13718. const c = centerIndexStart + x;
  13719. const i = centerIndexEnd + x;
  13720. if ( top === true ) {
  13721. // face top
  13722. indices.push( i, i + 1, c );
  13723. } else {
  13724. // face bottom
  13725. indices.push( i + 1, i, c );
  13726. }
  13727. groupCount += 3;
  13728. }
  13729. // add a group to the geometry. this will ensure multi material support
  13730. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  13731. // calculate new start value for groups
  13732. groupStart += groupCount;
  13733. }
  13734. }
  13735. copy( source ) {
  13736. super.copy( source );
  13737. this.parameters = Object.assign( {}, source.parameters );
  13738. return this;
  13739. }
  13740. static fromJSON( data ) {
  13741. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  13742. }
  13743. }
  13744. class ConeGeometry extends CylinderGeometry {
  13745. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13746. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  13747. this.type = 'ConeGeometry';
  13748. this.parameters = {
  13749. radius: radius,
  13750. height: height,
  13751. radialSegments: radialSegments,
  13752. heightSegments: heightSegments,
  13753. openEnded: openEnded,
  13754. thetaStart: thetaStart,
  13755. thetaLength: thetaLength
  13756. };
  13757. }
  13758. static fromJSON( data ) {
  13759. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  13760. }
  13761. }
  13762. class PolyhedronGeometry extends BufferGeometry {
  13763. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  13764. super();
  13765. this.type = 'PolyhedronGeometry';
  13766. this.parameters = {
  13767. vertices: vertices,
  13768. indices: indices,
  13769. radius: radius,
  13770. detail: detail
  13771. };
  13772. // default buffer data
  13773. const vertexBuffer = [];
  13774. const uvBuffer = [];
  13775. // the subdivision creates the vertex buffer data
  13776. subdivide( detail );
  13777. // all vertices should lie on a conceptual sphere with a given radius
  13778. applyRadius( radius );
  13779. // finally, create the uv data
  13780. generateUVs();
  13781. // build non-indexed geometry
  13782. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  13783. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  13784. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  13785. if ( detail === 0 ) {
  13786. this.computeVertexNormals(); // flat normals
  13787. } else {
  13788. this.normalizeNormals(); // smooth normals
  13789. }
  13790. // helper functions
  13791. function subdivide( detail ) {
  13792. const a = new Vector3();
  13793. const b = new Vector3();
  13794. const c = new Vector3();
  13795. // iterate over all faces and apply a subdivision with the given detail value
  13796. for ( let i = 0; i < indices.length; i += 3 ) {
  13797. // get the vertices of the face
  13798. getVertexByIndex( indices[ i + 0 ], a );
  13799. getVertexByIndex( indices[ i + 1 ], b );
  13800. getVertexByIndex( indices[ i + 2 ], c );
  13801. // perform subdivision
  13802. subdivideFace( a, b, c, detail );
  13803. }
  13804. }
  13805. function subdivideFace( a, b, c, detail ) {
  13806. const cols = detail + 1;
  13807. // we use this multidimensional array as a data structure for creating the subdivision
  13808. const v = [];
  13809. // construct all of the vertices for this subdivision
  13810. for ( let i = 0; i <= cols; i ++ ) {
  13811. v[ i ] = [];
  13812. const aj = a.clone().lerp( c, i / cols );
  13813. const bj = b.clone().lerp( c, i / cols );
  13814. const rows = cols - i;
  13815. for ( let j = 0; j <= rows; j ++ ) {
  13816. if ( j === 0 && i === cols ) {
  13817. v[ i ][ j ] = aj;
  13818. } else {
  13819. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  13820. }
  13821. }
  13822. }
  13823. // construct all of the faces
  13824. for ( let i = 0; i < cols; i ++ ) {
  13825. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  13826. const k = Math.floor( j / 2 );
  13827. if ( j % 2 === 0 ) {
  13828. pushVertex( v[ i ][ k + 1 ] );
  13829. pushVertex( v[ i + 1 ][ k ] );
  13830. pushVertex( v[ i ][ k ] );
  13831. } else {
  13832. pushVertex( v[ i ][ k + 1 ] );
  13833. pushVertex( v[ i + 1 ][ k + 1 ] );
  13834. pushVertex( v[ i + 1 ][ k ] );
  13835. }
  13836. }
  13837. }
  13838. }
  13839. function applyRadius( radius ) {
  13840. const vertex = new Vector3();
  13841. // iterate over the entire buffer and apply the radius to each vertex
  13842. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  13843. vertex.x = vertexBuffer[ i + 0 ];
  13844. vertex.y = vertexBuffer[ i + 1 ];
  13845. vertex.z = vertexBuffer[ i + 2 ];
  13846. vertex.normalize().multiplyScalar( radius );
  13847. vertexBuffer[ i + 0 ] = vertex.x;
  13848. vertexBuffer[ i + 1 ] = vertex.y;
  13849. vertexBuffer[ i + 2 ] = vertex.z;
  13850. }
  13851. }
  13852. function generateUVs() {
  13853. const vertex = new Vector3();
  13854. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  13855. vertex.x = vertexBuffer[ i + 0 ];
  13856. vertex.y = vertexBuffer[ i + 1 ];
  13857. vertex.z = vertexBuffer[ i + 2 ];
  13858. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  13859. const v = inclination( vertex ) / Math.PI + 0.5;
  13860. uvBuffer.push( u, 1 - v );
  13861. }
  13862. correctUVs();
  13863. correctSeam();
  13864. }
  13865. function correctSeam() {
  13866. // handle case when face straddles the seam, see #3269
  13867. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  13868. // uv data of a single face
  13869. const x0 = uvBuffer[ i + 0 ];
  13870. const x1 = uvBuffer[ i + 2 ];
  13871. const x2 = uvBuffer[ i + 4 ];
  13872. const max = Math.max( x0, x1, x2 );
  13873. const min = Math.min( x0, x1, x2 );
  13874. // 0.9 is somewhat arbitrary
  13875. if ( max > 0.9 && min < 0.1 ) {
  13876. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  13877. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  13878. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  13879. }
  13880. }
  13881. }
  13882. function pushVertex( vertex ) {
  13883. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  13884. }
  13885. function getVertexByIndex( index, vertex ) {
  13886. const stride = index * 3;
  13887. vertex.x = vertices[ stride + 0 ];
  13888. vertex.y = vertices[ stride + 1 ];
  13889. vertex.z = vertices[ stride + 2 ];
  13890. }
  13891. function correctUVs() {
  13892. const a = new Vector3();
  13893. const b = new Vector3();
  13894. const c = new Vector3();
  13895. const centroid = new Vector3();
  13896. const uvA = new Vector2();
  13897. const uvB = new Vector2();
  13898. const uvC = new Vector2();
  13899. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  13900. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  13901. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  13902. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  13903. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  13904. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  13905. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  13906. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  13907. const azi = azimuth( centroid );
  13908. correctUV( uvA, j + 0, a, azi );
  13909. correctUV( uvB, j + 2, b, azi );
  13910. correctUV( uvC, j + 4, c, azi );
  13911. }
  13912. }
  13913. function correctUV( uv, stride, vector, azimuth ) {
  13914. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  13915. uvBuffer[ stride ] = uv.x - 1;
  13916. }
  13917. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  13918. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  13919. }
  13920. }
  13921. // Angle around the Y axis, counter-clockwise when looking from above.
  13922. function azimuth( vector ) {
  13923. return Math.atan2( vector.z, - vector.x );
  13924. }
  13925. // Angle above the XZ plane.
  13926. function inclination( vector ) {
  13927. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  13928. }
  13929. }
  13930. copy( source ) {
  13931. super.copy( source );
  13932. this.parameters = Object.assign( {}, source.parameters );
  13933. return this;
  13934. }
  13935. static fromJSON( data ) {
  13936. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  13937. }
  13938. }
  13939. class DodecahedronGeometry extends PolyhedronGeometry {
  13940. constructor( radius = 1, detail = 0 ) {
  13941. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13942. const r = 1 / t;
  13943. const vertices = [
  13944. // (±1, ±1, ±1)
  13945. -1, -1, -1, -1, -1, 1,
  13946. -1, 1, -1, -1, 1, 1,
  13947. 1, -1, -1, 1, -1, 1,
  13948. 1, 1, -1, 1, 1, 1,
  13949. // (0, ±1/φ, ±φ)
  13950. 0, - r, - t, 0, - r, t,
  13951. 0, r, - t, 0, r, t,
  13952. // (±1/φ, ±φ, 0)
  13953. - r, - t, 0, - r, t, 0,
  13954. r, - t, 0, r, t, 0,
  13955. // (±φ, 0, ±1/φ)
  13956. - t, 0, - r, t, 0, - r,
  13957. - t, 0, r, t, 0, r
  13958. ];
  13959. const indices = [
  13960. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  13961. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  13962. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  13963. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  13964. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  13965. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  13966. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  13967. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  13968. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  13969. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  13970. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  13971. 1, 12, 14, 1, 14, 5, 1, 5, 9
  13972. ];
  13973. super( vertices, indices, radius, detail );
  13974. this.type = 'DodecahedronGeometry';
  13975. this.parameters = {
  13976. radius: radius,
  13977. detail: detail
  13978. };
  13979. }
  13980. static fromJSON( data ) {
  13981. return new DodecahedronGeometry( data.radius, data.detail );
  13982. }
  13983. }
  13984. const _v0$1 = /*@__PURE__*/ new Vector3();
  13985. const _v1$1 = /*@__PURE__*/ new Vector3();
  13986. const _normal = /*@__PURE__*/ new Vector3();
  13987. const _triangle = /*@__PURE__*/ new Triangle();
  13988. class EdgesGeometry extends BufferGeometry {
  13989. constructor( geometry = null, thresholdAngle = 1 ) {
  13990. super();
  13991. this.type = 'EdgesGeometry';
  13992. this.parameters = {
  13993. geometry: geometry,
  13994. thresholdAngle: thresholdAngle
  13995. };
  13996. if ( geometry !== null ) {
  13997. const precisionPoints = 4;
  13998. const precision = Math.pow( 10, precisionPoints );
  13999. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  14000. const indexAttr = geometry.getIndex();
  14001. const positionAttr = geometry.getAttribute( 'position' );
  14002. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  14003. const indexArr = [ 0, 0, 0 ];
  14004. const vertKeys = [ 'a', 'b', 'c' ];
  14005. const hashes = new Array( 3 );
  14006. const edgeData = {};
  14007. const vertices = [];
  14008. for ( let i = 0; i < indexCount; i += 3 ) {
  14009. if ( indexAttr ) {
  14010. indexArr[ 0 ] = indexAttr.getX( i );
  14011. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  14012. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  14013. } else {
  14014. indexArr[ 0 ] = i;
  14015. indexArr[ 1 ] = i + 1;
  14016. indexArr[ 2 ] = i + 2;
  14017. }
  14018. const { a, b, c } = _triangle;
  14019. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  14020. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  14021. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  14022. _triangle.getNormal( _normal );
  14023. // create hashes for the edge from the vertices
  14024. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  14025. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  14026. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  14027. // skip degenerate triangles
  14028. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  14029. continue;
  14030. }
  14031. // iterate over every edge
  14032. for ( let j = 0; j < 3; j ++ ) {
  14033. // get the first and next vertex making up the edge
  14034. const jNext = ( j + 1 ) % 3;
  14035. const vecHash0 = hashes[ j ];
  14036. const vecHash1 = hashes[ jNext ];
  14037. const v0 = _triangle[ vertKeys[ j ] ];
  14038. const v1 = _triangle[ vertKeys[ jNext ] ];
  14039. const hash = `${ vecHash0 }_${ vecHash1 }`;
  14040. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  14041. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  14042. // if we found a sibling edge add it into the vertex array if
  14043. // it meets the angle threshold and delete the edge from the map.
  14044. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  14045. vertices.push( v0.x, v0.y, v0.z );
  14046. vertices.push( v1.x, v1.y, v1.z );
  14047. }
  14048. edgeData[ reverseHash ] = null;
  14049. } else if ( ! ( hash in edgeData ) ) {
  14050. // if we've already got an edge here then skip adding a new one
  14051. edgeData[ hash ] = {
  14052. index0: indexArr[ j ],
  14053. index1: indexArr[ jNext ],
  14054. normal: _normal.clone(),
  14055. };
  14056. }
  14057. }
  14058. }
  14059. // iterate over all remaining, unmatched edges and add them to the vertex array
  14060. for ( const key in edgeData ) {
  14061. if ( edgeData[ key ] ) {
  14062. const { index0, index1 } = edgeData[ key ];
  14063. _v0$1.fromBufferAttribute( positionAttr, index0 );
  14064. _v1$1.fromBufferAttribute( positionAttr, index1 );
  14065. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  14066. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  14067. }
  14068. }
  14069. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  14070. }
  14071. }
  14072. copy( source ) {
  14073. super.copy( source );
  14074. this.parameters = Object.assign( {}, source.parameters );
  14075. return this;
  14076. }
  14077. }
  14078. class Shape extends Path {
  14079. constructor( points ) {
  14080. super( points );
  14081. this.uuid = generateUUID();
  14082. this.type = 'Shape';
  14083. this.holes = [];
  14084. }
  14085. getPointsHoles( divisions ) {
  14086. const holesPts = [];
  14087. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  14088. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  14089. }
  14090. return holesPts;
  14091. }
  14092. // get points of shape and holes (keypoints based on segments parameter)
  14093. extractPoints( divisions ) {
  14094. return {
  14095. shape: this.getPoints( divisions ),
  14096. holes: this.getPointsHoles( divisions )
  14097. };
  14098. }
  14099. copy( source ) {
  14100. super.copy( source );
  14101. this.holes = [];
  14102. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  14103. const hole = source.holes[ i ];
  14104. this.holes.push( hole.clone() );
  14105. }
  14106. return this;
  14107. }
  14108. toJSON() {
  14109. const data = super.toJSON();
  14110. data.uuid = this.uuid;
  14111. data.holes = [];
  14112. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  14113. const hole = this.holes[ i ];
  14114. data.holes.push( hole.toJSON() );
  14115. }
  14116. return data;
  14117. }
  14118. fromJSON( json ) {
  14119. super.fromJSON( json );
  14120. this.uuid = json.uuid;
  14121. this.holes = [];
  14122. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  14123. const hole = json.holes[ i ];
  14124. this.holes.push( new Path().fromJSON( hole ) );
  14125. }
  14126. return this;
  14127. }
  14128. }
  14129. /**
  14130. * Port from https://github.com/mapbox/earcut (v2.2.4)
  14131. */
  14132. const Earcut = {
  14133. triangulate: function ( data, holeIndices, dim = 2 ) {
  14134. const hasHoles = holeIndices && holeIndices.length;
  14135. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  14136. let outerNode = linkedList( data, 0, outerLen, dim, true );
  14137. const triangles = [];
  14138. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  14139. let minX, minY, maxX, maxY, x, y, invSize;
  14140. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  14141. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  14142. if ( data.length > 80 * dim ) {
  14143. minX = maxX = data[ 0 ];
  14144. minY = maxY = data[ 1 ];
  14145. for ( let i = dim; i < outerLen; i += dim ) {
  14146. x = data[ i ];
  14147. y = data[ i + 1 ];
  14148. if ( x < minX ) minX = x;
  14149. if ( y < minY ) minY = y;
  14150. if ( x > maxX ) maxX = x;
  14151. if ( y > maxY ) maxY = y;
  14152. }
  14153. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  14154. invSize = Math.max( maxX - minX, maxY - minY );
  14155. invSize = invSize !== 0 ? 32767 / invSize : 0;
  14156. }
  14157. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  14158. return triangles;
  14159. }
  14160. };
  14161. // create a circular doubly linked list from polygon points in the specified winding order
  14162. function linkedList( data, start, end, dim, clockwise ) {
  14163. let i, last;
  14164. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  14165. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  14166. } else {
  14167. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  14168. }
  14169. if ( last && equals( last, last.next ) ) {
  14170. removeNode( last );
  14171. last = last.next;
  14172. }
  14173. return last;
  14174. }
  14175. // eliminate colinear or duplicate points
  14176. function filterPoints( start, end ) {
  14177. if ( ! start ) return start;
  14178. if ( ! end ) end = start;
  14179. let p = start,
  14180. again;
  14181. do {
  14182. again = false;
  14183. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  14184. removeNode( p );
  14185. p = end = p.prev;
  14186. if ( p === p.next ) break;
  14187. again = true;
  14188. } else {
  14189. p = p.next;
  14190. }
  14191. } while ( again || p !== end );
  14192. return end;
  14193. }
  14194. // main ear slicing loop which triangulates a polygon (given as a linked list)
  14195. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  14196. if ( ! ear ) return;
  14197. // interlink polygon nodes in z-order
  14198. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  14199. let stop = ear,
  14200. prev, next;
  14201. // iterate through ears, slicing them one by one
  14202. while ( ear.prev !== ear.next ) {
  14203. prev = ear.prev;
  14204. next = ear.next;
  14205. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  14206. // cut off the triangle
  14207. triangles.push( prev.i / dim | 0 );
  14208. triangles.push( ear.i / dim | 0 );
  14209. triangles.push( next.i / dim | 0 );
  14210. removeNode( ear );
  14211. // skipping the next vertex leads to less sliver triangles
  14212. ear = next.next;
  14213. stop = next.next;
  14214. continue;
  14215. }
  14216. ear = next;
  14217. // if we looped through the whole remaining polygon and can't find any more ears
  14218. if ( ear === stop ) {
  14219. // try filtering points and slicing again
  14220. if ( ! pass ) {
  14221. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  14222. // if this didn't work, try curing all small self-intersections locally
  14223. } else if ( pass === 1 ) {
  14224. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  14225. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  14226. // as a last resort, try splitting the remaining polygon into two
  14227. } else if ( pass === 2 ) {
  14228. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  14229. }
  14230. break;
  14231. }
  14232. }
  14233. }
  14234. // check whether a polygon node forms a valid ear with adjacent nodes
  14235. function isEar( ear ) {
  14236. const a = ear.prev,
  14237. b = ear,
  14238. c = ear.next;
  14239. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  14240. // now make sure we don't have other points inside the potential ear
  14241. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  14242. // triangle bbox; min & max are calculated like this for speed
  14243. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  14244. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  14245. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  14246. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  14247. let p = c.next;
  14248. while ( p !== a ) {
  14249. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  14250. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  14251. area( p.prev, p, p.next ) >= 0 ) return false;
  14252. p = p.next;
  14253. }
  14254. return true;
  14255. }
  14256. function isEarHashed( ear, minX, minY, invSize ) {
  14257. const a = ear.prev,
  14258. b = ear,
  14259. c = ear.next;
  14260. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  14261. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  14262. // triangle bbox; min & max are calculated like this for speed
  14263. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  14264. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  14265. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  14266. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  14267. // z-order range for the current triangle bbox;
  14268. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  14269. maxZ = zOrder( x1, y1, minX, minY, invSize );
  14270. let p = ear.prevZ,
  14271. n = ear.nextZ;
  14272. // look for points inside the triangle in both directions
  14273. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  14274. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  14275. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  14276. p = p.prevZ;
  14277. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  14278. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  14279. n = n.nextZ;
  14280. }
  14281. // look for remaining points in decreasing z-order
  14282. while ( p && p.z >= minZ ) {
  14283. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  14284. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  14285. p = p.prevZ;
  14286. }
  14287. // look for remaining points in increasing z-order
  14288. while ( n && n.z <= maxZ ) {
  14289. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  14290. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  14291. n = n.nextZ;
  14292. }
  14293. return true;
  14294. }
  14295. // go through all polygon nodes and cure small local self-intersections
  14296. function cureLocalIntersections( start, triangles, dim ) {
  14297. let p = start;
  14298. do {
  14299. const a = p.prev,
  14300. b = p.next.next;
  14301. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  14302. triangles.push( a.i / dim | 0 );
  14303. triangles.push( p.i / dim | 0 );
  14304. triangles.push( b.i / dim | 0 );
  14305. // remove two nodes involved
  14306. removeNode( p );
  14307. removeNode( p.next );
  14308. p = start = b;
  14309. }
  14310. p = p.next;
  14311. } while ( p !== start );
  14312. return filterPoints( p );
  14313. }
  14314. // try splitting polygon into two and triangulate them independently
  14315. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  14316. // look for a valid diagonal that divides the polygon into two
  14317. let a = start;
  14318. do {
  14319. let b = a.next.next;
  14320. while ( b !== a.prev ) {
  14321. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  14322. // split the polygon in two by the diagonal
  14323. let c = splitPolygon( a, b );
  14324. // filter colinear points around the cuts
  14325. a = filterPoints( a, a.next );
  14326. c = filterPoints( c, c.next );
  14327. // run earcut on each half
  14328. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  14329. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  14330. return;
  14331. }
  14332. b = b.next;
  14333. }
  14334. a = a.next;
  14335. } while ( a !== start );
  14336. }
  14337. // link every hole into the outer loop, producing a single-ring polygon without holes
  14338. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  14339. const queue = [];
  14340. let i, len, start, end, list;
  14341. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  14342. start = holeIndices[ i ] * dim;
  14343. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  14344. list = linkedList( data, start, end, dim, false );
  14345. if ( list === list.next ) list.steiner = true;
  14346. queue.push( getLeftmost( list ) );
  14347. }
  14348. queue.sort( compareX );
  14349. // process holes from left to right
  14350. for ( i = 0; i < queue.length; i ++ ) {
  14351. outerNode = eliminateHole( queue[ i ], outerNode );
  14352. }
  14353. return outerNode;
  14354. }
  14355. function compareX( a, b ) {
  14356. return a.x - b.x;
  14357. }
  14358. // find a bridge between vertices that connects hole with an outer ring and link it
  14359. function eliminateHole( hole, outerNode ) {
  14360. const bridge = findHoleBridge( hole, outerNode );
  14361. if ( ! bridge ) {
  14362. return outerNode;
  14363. }
  14364. const bridgeReverse = splitPolygon( bridge, hole );
  14365. // filter collinear points around the cuts
  14366. filterPoints( bridgeReverse, bridgeReverse.next );
  14367. return filterPoints( bridge, bridge.next );
  14368. }
  14369. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  14370. function findHoleBridge( hole, outerNode ) {
  14371. let p = outerNode,
  14372. qx = - Infinity,
  14373. m;
  14374. const hx = hole.x, hy = hole.y;
  14375. // find a segment intersected by a ray from the hole's leftmost point to the left;
  14376. // segment's endpoint with lesser x will be potential connection point
  14377. do {
  14378. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  14379. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  14380. if ( x <= hx && x > qx ) {
  14381. qx = x;
  14382. m = p.x < p.next.x ? p : p.next;
  14383. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  14384. }
  14385. }
  14386. p = p.next;
  14387. } while ( p !== outerNode );
  14388. if ( ! m ) return null;
  14389. // look for points inside the triangle of hole point, segment intersection and endpoint;
  14390. // if there are no points found, we have a valid connection;
  14391. // otherwise choose the point of the minimum angle with the ray as connection point
  14392. const stop = m,
  14393. mx = m.x,
  14394. my = m.y;
  14395. let tanMin = Infinity, tan;
  14396. p = m;
  14397. do {
  14398. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  14399. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  14400. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  14401. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  14402. m = p;
  14403. tanMin = tan;
  14404. }
  14405. }
  14406. p = p.next;
  14407. } while ( p !== stop );
  14408. return m;
  14409. }
  14410. // whether sector in vertex m contains sector in vertex p in the same coordinates
  14411. function sectorContainsSector( m, p ) {
  14412. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  14413. }
  14414. // interlink polygon nodes in z-order
  14415. function indexCurve( start, minX, minY, invSize ) {
  14416. let p = start;
  14417. do {
  14418. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  14419. p.prevZ = p.prev;
  14420. p.nextZ = p.next;
  14421. p = p.next;
  14422. } while ( p !== start );
  14423. p.prevZ.nextZ = null;
  14424. p.prevZ = null;
  14425. sortLinked( p );
  14426. }
  14427. // Simon Tatham's linked list merge sort algorithm
  14428. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  14429. function sortLinked( list ) {
  14430. let i, p, q, e, tail, numMerges, pSize, qSize,
  14431. inSize = 1;
  14432. do {
  14433. p = list;
  14434. list = null;
  14435. tail = null;
  14436. numMerges = 0;
  14437. while ( p ) {
  14438. numMerges ++;
  14439. q = p;
  14440. pSize = 0;
  14441. for ( i = 0; i < inSize; i ++ ) {
  14442. pSize ++;
  14443. q = q.nextZ;
  14444. if ( ! q ) break;
  14445. }
  14446. qSize = inSize;
  14447. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  14448. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  14449. e = p;
  14450. p = p.nextZ;
  14451. pSize --;
  14452. } else {
  14453. e = q;
  14454. q = q.nextZ;
  14455. qSize --;
  14456. }
  14457. if ( tail ) tail.nextZ = e;
  14458. else list = e;
  14459. e.prevZ = tail;
  14460. tail = e;
  14461. }
  14462. p = q;
  14463. }
  14464. tail.nextZ = null;
  14465. inSize *= 2;
  14466. } while ( numMerges > 1 );
  14467. return list;
  14468. }
  14469. // z-order of a point given coords and inverse of the longer side of data bbox
  14470. function zOrder( x, y, minX, minY, invSize ) {
  14471. // coords are transformed into non-negative 15-bit integer range
  14472. x = ( x - minX ) * invSize | 0;
  14473. y = ( y - minY ) * invSize | 0;
  14474. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  14475. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  14476. x = ( x | ( x << 2 ) ) & 0x33333333;
  14477. x = ( x | ( x << 1 ) ) & 0x55555555;
  14478. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  14479. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  14480. y = ( y | ( y << 2 ) ) & 0x33333333;
  14481. y = ( y | ( y << 1 ) ) & 0x55555555;
  14482. return x | ( y << 1 );
  14483. }
  14484. // find the leftmost node of a polygon ring
  14485. function getLeftmost( start ) {
  14486. let p = start,
  14487. leftmost = start;
  14488. do {
  14489. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  14490. p = p.next;
  14491. } while ( p !== start );
  14492. return leftmost;
  14493. }
  14494. // check if a point lies within a convex triangle
  14495. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  14496. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  14497. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  14498. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  14499. }
  14500. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  14501. function isValidDiagonal( a, b ) {
  14502. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  14503. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  14504. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  14505. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  14506. }
  14507. // signed area of a triangle
  14508. function area( p, q, r ) {
  14509. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  14510. }
  14511. // check if two points are equal
  14512. function equals( p1, p2 ) {
  14513. return p1.x === p2.x && p1.y === p2.y;
  14514. }
  14515. // check if two segments intersect
  14516. function intersects( p1, q1, p2, q2 ) {
  14517. const o1 = sign( area( p1, q1, p2 ) );
  14518. const o2 = sign( area( p1, q1, q2 ) );
  14519. const o3 = sign( area( p2, q2, p1 ) );
  14520. const o4 = sign( area( p2, q2, q1 ) );
  14521. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  14522. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  14523. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  14524. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  14525. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  14526. return false;
  14527. }
  14528. // for collinear points p, q, r, check if point q lies on segment pr
  14529. function onSegment( p, q, r ) {
  14530. 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 );
  14531. }
  14532. function sign( num ) {
  14533. return num > 0 ? 1 : num < 0 ? -1 : 0;
  14534. }
  14535. // check if a polygon diagonal intersects any polygon segments
  14536. function intersectsPolygon( a, b ) {
  14537. let p = a;
  14538. do {
  14539. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  14540. intersects( p, p.next, a, b ) ) return true;
  14541. p = p.next;
  14542. } while ( p !== a );
  14543. return false;
  14544. }
  14545. // check if a polygon diagonal is locally inside the polygon
  14546. function locallyInside( a, b ) {
  14547. return area( a.prev, a, a.next ) < 0 ?
  14548. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  14549. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  14550. }
  14551. // check if the middle point of a polygon diagonal is inside the polygon
  14552. function middleInside( a, b ) {
  14553. let p = a,
  14554. inside = false;
  14555. const px = ( a.x + b.x ) / 2,
  14556. py = ( a.y + b.y ) / 2;
  14557. do {
  14558. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  14559. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  14560. inside = ! inside;
  14561. p = p.next;
  14562. } while ( p !== a );
  14563. return inside;
  14564. }
  14565. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  14566. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  14567. function splitPolygon( a, b ) {
  14568. const a2 = new Node( a.i, a.x, a.y ),
  14569. b2 = new Node( b.i, b.x, b.y ),
  14570. an = a.next,
  14571. bp = b.prev;
  14572. a.next = b;
  14573. b.prev = a;
  14574. a2.next = an;
  14575. an.prev = a2;
  14576. b2.next = a2;
  14577. a2.prev = b2;
  14578. bp.next = b2;
  14579. b2.prev = bp;
  14580. return b2;
  14581. }
  14582. // create a node and optionally link it with previous one (in a circular doubly linked list)
  14583. function insertNode( i, x, y, last ) {
  14584. const p = new Node( i, x, y );
  14585. if ( ! last ) {
  14586. p.prev = p;
  14587. p.next = p;
  14588. } else {
  14589. p.next = last.next;
  14590. p.prev = last;
  14591. last.next.prev = p;
  14592. last.next = p;
  14593. }
  14594. return p;
  14595. }
  14596. function removeNode( p ) {
  14597. p.next.prev = p.prev;
  14598. p.prev.next = p.next;
  14599. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  14600. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  14601. }
  14602. function Node( i, x, y ) {
  14603. // vertex index in coordinates array
  14604. this.i = i;
  14605. // vertex coordinates
  14606. this.x = x;
  14607. this.y = y;
  14608. // previous and next vertex nodes in a polygon ring
  14609. this.prev = null;
  14610. this.next = null;
  14611. // z-order curve value
  14612. this.z = 0;
  14613. // previous and next nodes in z-order
  14614. this.prevZ = null;
  14615. this.nextZ = null;
  14616. // indicates whether this is a steiner point
  14617. this.steiner = false;
  14618. }
  14619. function signedArea( data, start, end, dim ) {
  14620. let sum = 0;
  14621. for ( let i = start, j = end - dim; i < end; i += dim ) {
  14622. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  14623. j = i;
  14624. }
  14625. return sum;
  14626. }
  14627. class ShapeUtils {
  14628. // calculate area of the contour polygon
  14629. static area( contour ) {
  14630. const n = contour.length;
  14631. let a = 0.0;
  14632. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  14633. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  14634. }
  14635. return a * 0.5;
  14636. }
  14637. static isClockWise( pts ) {
  14638. return ShapeUtils.area( pts ) < 0;
  14639. }
  14640. static triangulateShape( contour, holes ) {
  14641. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  14642. const holeIndices = []; // array of hole indices
  14643. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  14644. removeDupEndPts( contour );
  14645. addContour( vertices, contour );
  14646. //
  14647. let holeIndex = contour.length;
  14648. holes.forEach( removeDupEndPts );
  14649. for ( let i = 0; i < holes.length; i ++ ) {
  14650. holeIndices.push( holeIndex );
  14651. holeIndex += holes[ i ].length;
  14652. addContour( vertices, holes[ i ] );
  14653. }
  14654. //
  14655. const triangles = Earcut.triangulate( vertices, holeIndices );
  14656. //
  14657. for ( let i = 0; i < triangles.length; i += 3 ) {
  14658. faces.push( triangles.slice( i, i + 3 ) );
  14659. }
  14660. return faces;
  14661. }
  14662. }
  14663. function removeDupEndPts( points ) {
  14664. const l = points.length;
  14665. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  14666. points.pop();
  14667. }
  14668. }
  14669. function addContour( vertices, contour ) {
  14670. for ( let i = 0; i < contour.length; i ++ ) {
  14671. vertices.push( contour[ i ].x );
  14672. vertices.push( contour[ i ].y );
  14673. }
  14674. }
  14675. /**
  14676. * Creates extruded geometry from a path shape.
  14677. *
  14678. * parameters = {
  14679. *
  14680. * curveSegments: <int>, // number of points on the curves
  14681. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  14682. * depth: <float>, // Depth to extrude the shape
  14683. *
  14684. * bevelEnabled: <bool>, // turn on bevel
  14685. * bevelThickness: <float>, // how deep into the original shape bevel goes
  14686. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  14687. * bevelOffset: <float>, // how far from shape outline does bevel start
  14688. * bevelSegments: <int>, // number of bevel layers
  14689. *
  14690. * extrudePath: <THREE.Curve> // curve to extrude shape along
  14691. *
  14692. * UVGenerator: <Object> // object that provides UV generator functions
  14693. *
  14694. * }
  14695. */
  14696. class ExtrudeGeometry extends BufferGeometry {
  14697. 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 = {} ) {
  14698. super();
  14699. this.type = 'ExtrudeGeometry';
  14700. this.parameters = {
  14701. shapes: shapes,
  14702. options: options
  14703. };
  14704. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  14705. const scope = this;
  14706. const verticesArray = [];
  14707. const uvArray = [];
  14708. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  14709. const shape = shapes[ i ];
  14710. addShape( shape );
  14711. }
  14712. // build geometry
  14713. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  14714. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  14715. this.computeVertexNormals();
  14716. // functions
  14717. function addShape( shape ) {
  14718. const placeholder = [];
  14719. // options
  14720. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  14721. const steps = options.steps !== undefined ? options.steps : 1;
  14722. const depth = options.depth !== undefined ? options.depth : 1;
  14723. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  14724. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  14725. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  14726. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  14727. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  14728. const extrudePath = options.extrudePath;
  14729. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  14730. //
  14731. let extrudePts, extrudeByPath = false;
  14732. let splineTube, binormal, normal, position2;
  14733. if ( extrudePath ) {
  14734. extrudePts = extrudePath.getSpacedPoints( steps );
  14735. extrudeByPath = true;
  14736. bevelEnabled = false; // bevels not supported for path extrusion
  14737. // SETUP TNB variables
  14738. // TODO1 - have a .isClosed in spline?
  14739. splineTube = extrudePath.computeFrenetFrames( steps, false );
  14740. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  14741. binormal = new Vector3();
  14742. normal = new Vector3();
  14743. position2 = new Vector3();
  14744. }
  14745. // Safeguards if bevels are not enabled
  14746. if ( ! bevelEnabled ) {
  14747. bevelSegments = 0;
  14748. bevelThickness = 0;
  14749. bevelSize = 0;
  14750. bevelOffset = 0;
  14751. }
  14752. // Variables initialization
  14753. const shapePoints = shape.extractPoints( curveSegments );
  14754. let vertices = shapePoints.shape;
  14755. const holes = shapePoints.holes;
  14756. const reverse = ! ShapeUtils.isClockWise( vertices );
  14757. if ( reverse ) {
  14758. vertices = vertices.reverse();
  14759. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  14760. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14761. const ahole = holes[ h ];
  14762. if ( ShapeUtils.isClockWise( ahole ) ) {
  14763. holes[ h ] = ahole.reverse();
  14764. }
  14765. }
  14766. }
  14767. const faces = ShapeUtils.triangulateShape( vertices, holes );
  14768. /* Vertices */
  14769. const contour = vertices; // vertices has all points but contour has only points of circumference
  14770. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14771. const ahole = holes[ h ];
  14772. vertices = vertices.concat( ahole );
  14773. }
  14774. function scalePt2( pt, vec, size ) {
  14775. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  14776. return pt.clone().addScaledVector( vec, size );
  14777. }
  14778. const vlen = vertices.length, flen = faces.length;
  14779. // Find directions for point movement
  14780. function getBevelVec( inPt, inPrev, inNext ) {
  14781. // computes for inPt the corresponding point inPt' on a new contour
  14782. // shifted by 1 unit (length of normalized vector) to the left
  14783. // if we walk along contour clockwise, this new contour is outside the old one
  14784. //
  14785. // inPt' is the intersection of the two lines parallel to the two
  14786. // adjacent edges of inPt at a distance of 1 unit on the left side.
  14787. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  14788. // good reading for geometry algorithms (here: line-line intersection)
  14789. // http://geomalgorithms.com/a05-_intersect-1.html
  14790. const v_prev_x = inPt.x - inPrev.x,
  14791. v_prev_y = inPt.y - inPrev.y;
  14792. const v_next_x = inNext.x - inPt.x,
  14793. v_next_y = inNext.y - inPt.y;
  14794. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  14795. // check for collinear edges
  14796. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  14797. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  14798. // not collinear
  14799. // length of vectors for normalizing
  14800. const v_prev_len = Math.sqrt( v_prev_lensq );
  14801. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  14802. // shift adjacent points by unit vectors to the left
  14803. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  14804. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  14805. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  14806. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  14807. // scaling factor for v_prev to intersection point
  14808. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  14809. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  14810. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  14811. // vector from inPt to intersection point
  14812. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  14813. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  14814. // Don't normalize!, otherwise sharp corners become ugly
  14815. // but prevent crazy spikes
  14816. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  14817. if ( v_trans_lensq <= 2 ) {
  14818. return new Vector2( v_trans_x, v_trans_y );
  14819. } else {
  14820. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  14821. }
  14822. } else {
  14823. // handle special case of collinear edges
  14824. let direction_eq = false; // assumes: opposite
  14825. if ( v_prev_x > Number.EPSILON ) {
  14826. if ( v_next_x > Number.EPSILON ) {
  14827. direction_eq = true;
  14828. }
  14829. } else {
  14830. if ( v_prev_x < - Number.EPSILON ) {
  14831. if ( v_next_x < - Number.EPSILON ) {
  14832. direction_eq = true;
  14833. }
  14834. } else {
  14835. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  14836. direction_eq = true;
  14837. }
  14838. }
  14839. }
  14840. if ( direction_eq ) {
  14841. // console.log("Warning: lines are a straight sequence");
  14842. v_trans_x = - v_prev_y;
  14843. v_trans_y = v_prev_x;
  14844. shrink_by = Math.sqrt( v_prev_lensq );
  14845. } else {
  14846. // console.log("Warning: lines are a straight spike");
  14847. v_trans_x = v_prev_x;
  14848. v_trans_y = v_prev_y;
  14849. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  14850. }
  14851. }
  14852. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  14853. }
  14854. const contourMovements = [];
  14855. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14856. if ( j === il ) j = 0;
  14857. if ( k === il ) k = 0;
  14858. // (j)---(i)---(k)
  14859. // console.log('i,j,k', i, j , k)
  14860. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  14861. }
  14862. const holesMovements = [];
  14863. let oneHoleMovements, verticesMovements = contourMovements.concat();
  14864. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14865. const ahole = holes[ h ];
  14866. oneHoleMovements = [];
  14867. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14868. if ( j === il ) j = 0;
  14869. if ( k === il ) k = 0;
  14870. // (j)---(i)---(k)
  14871. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  14872. }
  14873. holesMovements.push( oneHoleMovements );
  14874. verticesMovements = verticesMovements.concat( oneHoleMovements );
  14875. }
  14876. // Loop bevelSegments, 1 for the front, 1 for the back
  14877. for ( let b = 0; b < bevelSegments; b ++ ) {
  14878. //for ( b = bevelSegments; b > 0; b -- ) {
  14879. const t = b / bevelSegments;
  14880. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  14881. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  14882. // contract shape
  14883. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  14884. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14885. v( vert.x, vert.y, - z );
  14886. }
  14887. // expand holes
  14888. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14889. const ahole = holes[ h ];
  14890. oneHoleMovements = holesMovements[ h ];
  14891. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  14892. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14893. v( vert.x, vert.y, - z );
  14894. }
  14895. }
  14896. }
  14897. const bs = bevelSize + bevelOffset;
  14898. // Back facing vertices
  14899. for ( let i = 0; i < vlen; i ++ ) {
  14900. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14901. if ( ! extrudeByPath ) {
  14902. v( vert.x, vert.y, 0 );
  14903. } else {
  14904. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  14905. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  14906. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  14907. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  14908. v( position2.x, position2.y, position2.z );
  14909. }
  14910. }
  14911. // Add stepped vertices...
  14912. // Including front facing vertices
  14913. for ( let s = 1; s <= steps; s ++ ) {
  14914. for ( let i = 0; i < vlen; i ++ ) {
  14915. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14916. if ( ! extrudeByPath ) {
  14917. v( vert.x, vert.y, depth / steps * s );
  14918. } else {
  14919. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  14920. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  14921. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  14922. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  14923. v( position2.x, position2.y, position2.z );
  14924. }
  14925. }
  14926. }
  14927. // Add bevel segments planes
  14928. //for ( b = 1; b <= bevelSegments; b ++ ) {
  14929. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  14930. const t = b / bevelSegments;
  14931. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  14932. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  14933. // contract shape
  14934. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  14935. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14936. v( vert.x, vert.y, depth + z );
  14937. }
  14938. // expand holes
  14939. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14940. const ahole = holes[ h ];
  14941. oneHoleMovements = holesMovements[ h ];
  14942. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  14943. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14944. if ( ! extrudeByPath ) {
  14945. v( vert.x, vert.y, depth + z );
  14946. } else {
  14947. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  14948. }
  14949. }
  14950. }
  14951. }
  14952. /* Faces */
  14953. // Top and bottom faces
  14954. buildLidFaces();
  14955. // Sides faces
  14956. buildSideFaces();
  14957. ///// Internal functions
  14958. function buildLidFaces() {
  14959. const start = verticesArray.length / 3;
  14960. if ( bevelEnabled ) {
  14961. let layer = 0; // steps + 1
  14962. let offset = vlen * layer;
  14963. // Bottom faces
  14964. for ( let i = 0; i < flen; i ++ ) {
  14965. const face = faces[ i ];
  14966. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  14967. }
  14968. layer = steps + bevelSegments * 2;
  14969. offset = vlen * layer;
  14970. // Top faces
  14971. for ( let i = 0; i < flen; i ++ ) {
  14972. const face = faces[ i ];
  14973. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  14974. }
  14975. } else {
  14976. // Bottom faces
  14977. for ( let i = 0; i < flen; i ++ ) {
  14978. const face = faces[ i ];
  14979. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  14980. }
  14981. // Top faces
  14982. for ( let i = 0; i < flen; i ++ ) {
  14983. const face = faces[ i ];
  14984. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  14985. }
  14986. }
  14987. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  14988. }
  14989. // Create faces for the z-sides of the shape
  14990. function buildSideFaces() {
  14991. const start = verticesArray.length / 3;
  14992. let layeroffset = 0;
  14993. sidewalls( contour, layeroffset );
  14994. layeroffset += contour.length;
  14995. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  14996. const ahole = holes[ h ];
  14997. sidewalls( ahole, layeroffset );
  14998. //, true
  14999. layeroffset += ahole.length;
  15000. }
  15001. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  15002. }
  15003. function sidewalls( contour, layeroffset ) {
  15004. let i = contour.length;
  15005. while ( -- i >= 0 ) {
  15006. const j = i;
  15007. let k = i - 1;
  15008. if ( k < 0 ) k = contour.length - 1;
  15009. //console.log('b', i,j, i-1, k,vertices.length);
  15010. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  15011. const slen1 = vlen * s;
  15012. const slen2 = vlen * ( s + 1 );
  15013. const a = layeroffset + j + slen1,
  15014. b = layeroffset + k + slen1,
  15015. c = layeroffset + k + slen2,
  15016. d = layeroffset + j + slen2;
  15017. f4( a, b, c, d );
  15018. }
  15019. }
  15020. }
  15021. function v( x, y, z ) {
  15022. placeholder.push( x );
  15023. placeholder.push( y );
  15024. placeholder.push( z );
  15025. }
  15026. function f3( a, b, c ) {
  15027. addVertex( a );
  15028. addVertex( b );
  15029. addVertex( c );
  15030. const nextIndex = verticesArray.length / 3;
  15031. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  15032. addUV( uvs[ 0 ] );
  15033. addUV( uvs[ 1 ] );
  15034. addUV( uvs[ 2 ] );
  15035. }
  15036. function f4( a, b, c, d ) {
  15037. addVertex( a );
  15038. addVertex( b );
  15039. addVertex( d );
  15040. addVertex( b );
  15041. addVertex( c );
  15042. addVertex( d );
  15043. const nextIndex = verticesArray.length / 3;
  15044. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  15045. addUV( uvs[ 0 ] );
  15046. addUV( uvs[ 1 ] );
  15047. addUV( uvs[ 3 ] );
  15048. addUV( uvs[ 1 ] );
  15049. addUV( uvs[ 2 ] );
  15050. addUV( uvs[ 3 ] );
  15051. }
  15052. function addVertex( index ) {
  15053. verticesArray.push( placeholder[ index * 3 + 0 ] );
  15054. verticesArray.push( placeholder[ index * 3 + 1 ] );
  15055. verticesArray.push( placeholder[ index * 3 + 2 ] );
  15056. }
  15057. function addUV( vector2 ) {
  15058. uvArray.push( vector2.x );
  15059. uvArray.push( vector2.y );
  15060. }
  15061. }
  15062. }
  15063. copy( source ) {
  15064. super.copy( source );
  15065. this.parameters = Object.assign( {}, source.parameters );
  15066. return this;
  15067. }
  15068. toJSON() {
  15069. const data = super.toJSON();
  15070. const shapes = this.parameters.shapes;
  15071. const options = this.parameters.options;
  15072. return toJSON$1( shapes, options, data );
  15073. }
  15074. static fromJSON( data, shapes ) {
  15075. const geometryShapes = [];
  15076. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  15077. const shape = shapes[ data.shapes[ j ] ];
  15078. geometryShapes.push( shape );
  15079. }
  15080. const extrudePath = data.options.extrudePath;
  15081. if ( extrudePath !== undefined ) {
  15082. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  15083. }
  15084. return new ExtrudeGeometry( geometryShapes, data.options );
  15085. }
  15086. }
  15087. const WorldUVGenerator = {
  15088. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  15089. const a_x = vertices[ indexA * 3 ];
  15090. const a_y = vertices[ indexA * 3 + 1 ];
  15091. const b_x = vertices[ indexB * 3 ];
  15092. const b_y = vertices[ indexB * 3 + 1 ];
  15093. const c_x = vertices[ indexC * 3 ];
  15094. const c_y = vertices[ indexC * 3 + 1 ];
  15095. return [
  15096. new Vector2( a_x, a_y ),
  15097. new Vector2( b_x, b_y ),
  15098. new Vector2( c_x, c_y )
  15099. ];
  15100. },
  15101. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  15102. const a_x = vertices[ indexA * 3 ];
  15103. const a_y = vertices[ indexA * 3 + 1 ];
  15104. const a_z = vertices[ indexA * 3 + 2 ];
  15105. const b_x = vertices[ indexB * 3 ];
  15106. const b_y = vertices[ indexB * 3 + 1 ];
  15107. const b_z = vertices[ indexB * 3 + 2 ];
  15108. const c_x = vertices[ indexC * 3 ];
  15109. const c_y = vertices[ indexC * 3 + 1 ];
  15110. const c_z = vertices[ indexC * 3 + 2 ];
  15111. const d_x = vertices[ indexD * 3 ];
  15112. const d_y = vertices[ indexD * 3 + 1 ];
  15113. const d_z = vertices[ indexD * 3 + 2 ];
  15114. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  15115. return [
  15116. new Vector2( a_x, 1 - a_z ),
  15117. new Vector2( b_x, 1 - b_z ),
  15118. new Vector2( c_x, 1 - c_z ),
  15119. new Vector2( d_x, 1 - d_z )
  15120. ];
  15121. } else {
  15122. return [
  15123. new Vector2( a_y, 1 - a_z ),
  15124. new Vector2( b_y, 1 - b_z ),
  15125. new Vector2( c_y, 1 - c_z ),
  15126. new Vector2( d_y, 1 - d_z )
  15127. ];
  15128. }
  15129. }
  15130. };
  15131. function toJSON$1( shapes, options, data ) {
  15132. data.shapes = [];
  15133. if ( Array.isArray( shapes ) ) {
  15134. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  15135. const shape = shapes[ i ];
  15136. data.shapes.push( shape.uuid );
  15137. }
  15138. } else {
  15139. data.shapes.push( shapes.uuid );
  15140. }
  15141. data.options = Object.assign( {}, options );
  15142. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  15143. return data;
  15144. }
  15145. class IcosahedronGeometry extends PolyhedronGeometry {
  15146. constructor( radius = 1, detail = 0 ) {
  15147. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15148. const vertices = [
  15149. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  15150. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  15151. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  15152. ];
  15153. const indices = [
  15154. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  15155. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  15156. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  15157. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  15158. ];
  15159. super( vertices, indices, radius, detail );
  15160. this.type = 'IcosahedronGeometry';
  15161. this.parameters = {
  15162. radius: radius,
  15163. detail: detail
  15164. };
  15165. }
  15166. static fromJSON( data ) {
  15167. return new IcosahedronGeometry( data.radius, data.detail );
  15168. }
  15169. }
  15170. class OctahedronGeometry extends PolyhedronGeometry {
  15171. constructor( radius = 1, detail = 0 ) {
  15172. const vertices = [
  15173. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  15174. 0, -1, 0, 0, 0, 1, 0, 0, -1
  15175. ];
  15176. const indices = [
  15177. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  15178. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  15179. 1, 3, 4, 1, 4, 2
  15180. ];
  15181. super( vertices, indices, radius, detail );
  15182. this.type = 'OctahedronGeometry';
  15183. this.parameters = {
  15184. radius: radius,
  15185. detail: detail
  15186. };
  15187. }
  15188. static fromJSON( data ) {
  15189. return new OctahedronGeometry( data.radius, data.detail );
  15190. }
  15191. }
  15192. class PlaneGeometry extends BufferGeometry {
  15193. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  15194. super();
  15195. this.type = 'PlaneGeometry';
  15196. this.parameters = {
  15197. width: width,
  15198. height: height,
  15199. widthSegments: widthSegments,
  15200. heightSegments: heightSegments
  15201. };
  15202. const width_half = width / 2;
  15203. const height_half = height / 2;
  15204. const gridX = Math.floor( widthSegments );
  15205. const gridY = Math.floor( heightSegments );
  15206. const gridX1 = gridX + 1;
  15207. const gridY1 = gridY + 1;
  15208. const segment_width = width / gridX;
  15209. const segment_height = height / gridY;
  15210. //
  15211. const indices = [];
  15212. const vertices = [];
  15213. const normals = [];
  15214. const uvs = [];
  15215. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15216. const y = iy * segment_height - height_half;
  15217. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15218. const x = ix * segment_width - width_half;
  15219. vertices.push( x, - y, 0 );
  15220. normals.push( 0, 0, 1 );
  15221. uvs.push( ix / gridX );
  15222. uvs.push( 1 - ( iy / gridY ) );
  15223. }
  15224. }
  15225. for ( let iy = 0; iy < gridY; iy ++ ) {
  15226. for ( let ix = 0; ix < gridX; ix ++ ) {
  15227. const a = ix + gridX1 * iy;
  15228. const b = ix + gridX1 * ( iy + 1 );
  15229. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  15230. const d = ( ix + 1 ) + gridX1 * iy;
  15231. indices.push( a, b, d );
  15232. indices.push( b, c, d );
  15233. }
  15234. }
  15235. this.setIndex( indices );
  15236. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15237. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15238. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15239. }
  15240. copy( source ) {
  15241. super.copy( source );
  15242. this.parameters = Object.assign( {}, source.parameters );
  15243. return this;
  15244. }
  15245. static fromJSON( data ) {
  15246. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  15247. }
  15248. }
  15249. class RingGeometry extends BufferGeometry {
  15250. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  15251. super();
  15252. this.type = 'RingGeometry';
  15253. this.parameters = {
  15254. innerRadius: innerRadius,
  15255. outerRadius: outerRadius,
  15256. thetaSegments: thetaSegments,
  15257. phiSegments: phiSegments,
  15258. thetaStart: thetaStart,
  15259. thetaLength: thetaLength
  15260. };
  15261. thetaSegments = Math.max( 3, thetaSegments );
  15262. phiSegments = Math.max( 1, phiSegments );
  15263. // buffers
  15264. const indices = [];
  15265. const vertices = [];
  15266. const normals = [];
  15267. const uvs = [];
  15268. // some helper variables
  15269. let radius = innerRadius;
  15270. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  15271. const vertex = new Vector3();
  15272. const uv = new Vector2();
  15273. // generate vertices, normals and uvs
  15274. for ( let j = 0; j <= phiSegments; j ++ ) {
  15275. for ( let i = 0; i <= thetaSegments; i ++ ) {
  15276. // values are generate from the inside of the ring to the outside
  15277. const segment = thetaStart + i / thetaSegments * thetaLength;
  15278. // vertex
  15279. vertex.x = radius * Math.cos( segment );
  15280. vertex.y = radius * Math.sin( segment );
  15281. vertices.push( vertex.x, vertex.y, vertex.z );
  15282. // normal
  15283. normals.push( 0, 0, 1 );
  15284. // uv
  15285. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  15286. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  15287. uvs.push( uv.x, uv.y );
  15288. }
  15289. // increase the radius for next row of vertices
  15290. radius += radiusStep;
  15291. }
  15292. // indices
  15293. for ( let j = 0; j < phiSegments; j ++ ) {
  15294. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  15295. for ( let i = 0; i < thetaSegments; i ++ ) {
  15296. const segment = i + thetaSegmentLevel;
  15297. const a = segment;
  15298. const b = segment + thetaSegments + 1;
  15299. const c = segment + thetaSegments + 2;
  15300. const d = segment + 1;
  15301. // faces
  15302. indices.push( a, b, d );
  15303. indices.push( b, c, d );
  15304. }
  15305. }
  15306. // build geometry
  15307. this.setIndex( indices );
  15308. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15309. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15310. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15311. }
  15312. copy( source ) {
  15313. super.copy( source );
  15314. this.parameters = Object.assign( {}, source.parameters );
  15315. return this;
  15316. }
  15317. static fromJSON( data ) {
  15318. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  15319. }
  15320. }
  15321. class ShapeGeometry extends BufferGeometry {
  15322. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  15323. super();
  15324. this.type = 'ShapeGeometry';
  15325. this.parameters = {
  15326. shapes: shapes,
  15327. curveSegments: curveSegments
  15328. };
  15329. // buffers
  15330. const indices = [];
  15331. const vertices = [];
  15332. const normals = [];
  15333. const uvs = [];
  15334. // helper variables
  15335. let groupStart = 0;
  15336. let groupCount = 0;
  15337. // allow single and array values for "shapes" parameter
  15338. if ( Array.isArray( shapes ) === false ) {
  15339. addShape( shapes );
  15340. } else {
  15341. for ( let i = 0; i < shapes.length; i ++ ) {
  15342. addShape( shapes[ i ] );
  15343. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  15344. groupStart += groupCount;
  15345. groupCount = 0;
  15346. }
  15347. }
  15348. // build geometry
  15349. this.setIndex( indices );
  15350. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15351. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15352. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15353. // helper functions
  15354. function addShape( shape ) {
  15355. const indexOffset = vertices.length / 3;
  15356. const points = shape.extractPoints( curveSegments );
  15357. let shapeVertices = points.shape;
  15358. const shapeHoles = points.holes;
  15359. // check direction of vertices
  15360. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  15361. shapeVertices = shapeVertices.reverse();
  15362. }
  15363. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  15364. const shapeHole = shapeHoles[ i ];
  15365. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  15366. shapeHoles[ i ] = shapeHole.reverse();
  15367. }
  15368. }
  15369. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  15370. // join vertices of inner and outer paths to a single array
  15371. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  15372. const shapeHole = shapeHoles[ i ];
  15373. shapeVertices = shapeVertices.concat( shapeHole );
  15374. }
  15375. // vertices, normals, uvs
  15376. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  15377. const vertex = shapeVertices[ i ];
  15378. vertices.push( vertex.x, vertex.y, 0 );
  15379. normals.push( 0, 0, 1 );
  15380. uvs.push( vertex.x, vertex.y ); // world uvs
  15381. }
  15382. // indices
  15383. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  15384. const face = faces[ i ];
  15385. const a = face[ 0 ] + indexOffset;
  15386. const b = face[ 1 ] + indexOffset;
  15387. const c = face[ 2 ] + indexOffset;
  15388. indices.push( a, b, c );
  15389. groupCount += 3;
  15390. }
  15391. }
  15392. }
  15393. copy( source ) {
  15394. super.copy( source );
  15395. this.parameters = Object.assign( {}, source.parameters );
  15396. return this;
  15397. }
  15398. toJSON() {
  15399. const data = super.toJSON();
  15400. const shapes = this.parameters.shapes;
  15401. return toJSON( shapes, data );
  15402. }
  15403. static fromJSON( data, shapes ) {
  15404. const geometryShapes = [];
  15405. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  15406. const shape = shapes[ data.shapes[ j ] ];
  15407. geometryShapes.push( shape );
  15408. }
  15409. return new ShapeGeometry( geometryShapes, data.curveSegments );
  15410. }
  15411. }
  15412. function toJSON( shapes, data ) {
  15413. data.shapes = [];
  15414. if ( Array.isArray( shapes ) ) {
  15415. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  15416. const shape = shapes[ i ];
  15417. data.shapes.push( shape.uuid );
  15418. }
  15419. } else {
  15420. data.shapes.push( shapes.uuid );
  15421. }
  15422. return data;
  15423. }
  15424. class SphereGeometry extends BufferGeometry {
  15425. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  15426. super();
  15427. this.type = 'SphereGeometry';
  15428. this.parameters = {
  15429. radius: radius,
  15430. widthSegments: widthSegments,
  15431. heightSegments: heightSegments,
  15432. phiStart: phiStart,
  15433. phiLength: phiLength,
  15434. thetaStart: thetaStart,
  15435. thetaLength: thetaLength
  15436. };
  15437. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  15438. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  15439. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  15440. let index = 0;
  15441. const grid = [];
  15442. const vertex = new Vector3();
  15443. const normal = new Vector3();
  15444. // buffers
  15445. const indices = [];
  15446. const vertices = [];
  15447. const normals = [];
  15448. const uvs = [];
  15449. // generate vertices, normals and uvs
  15450. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  15451. const verticesRow = [];
  15452. const v = iy / heightSegments;
  15453. // special case for the poles
  15454. let uOffset = 0;
  15455. if ( iy === 0 && thetaStart === 0 ) {
  15456. uOffset = 0.5 / widthSegments;
  15457. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  15458. uOffset = -0.5 / widthSegments;
  15459. }
  15460. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  15461. const u = ix / widthSegments;
  15462. // vertex
  15463. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15464. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  15465. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15466. vertices.push( vertex.x, vertex.y, vertex.z );
  15467. // normal
  15468. normal.copy( vertex ).normalize();
  15469. normals.push( normal.x, normal.y, normal.z );
  15470. // uv
  15471. uvs.push( u + uOffset, 1 - v );
  15472. verticesRow.push( index ++ );
  15473. }
  15474. grid.push( verticesRow );
  15475. }
  15476. // indices
  15477. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  15478. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  15479. const a = grid[ iy ][ ix + 1 ];
  15480. const b = grid[ iy ][ ix ];
  15481. const c = grid[ iy + 1 ][ ix ];
  15482. const d = grid[ iy + 1 ][ ix + 1 ];
  15483. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  15484. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  15485. }
  15486. }
  15487. // build geometry
  15488. this.setIndex( indices );
  15489. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15490. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15491. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15492. }
  15493. copy( source ) {
  15494. super.copy( source );
  15495. this.parameters = Object.assign( {}, source.parameters );
  15496. return this;
  15497. }
  15498. static fromJSON( data ) {
  15499. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  15500. }
  15501. }
  15502. class TetrahedronGeometry extends PolyhedronGeometry {
  15503. constructor( radius = 1, detail = 0 ) {
  15504. const vertices = [
  15505. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  15506. ];
  15507. const indices = [
  15508. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  15509. ];
  15510. super( vertices, indices, radius, detail );
  15511. this.type = 'TetrahedronGeometry';
  15512. this.parameters = {
  15513. radius: radius,
  15514. detail: detail
  15515. };
  15516. }
  15517. static fromJSON( data ) {
  15518. return new TetrahedronGeometry( data.radius, data.detail );
  15519. }
  15520. }
  15521. class TorusGeometry extends BufferGeometry {
  15522. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  15523. super();
  15524. this.type = 'TorusGeometry';
  15525. this.parameters = {
  15526. radius: radius,
  15527. tube: tube,
  15528. radialSegments: radialSegments,
  15529. tubularSegments: tubularSegments,
  15530. arc: arc
  15531. };
  15532. radialSegments = Math.floor( radialSegments );
  15533. tubularSegments = Math.floor( tubularSegments );
  15534. // buffers
  15535. const indices = [];
  15536. const vertices = [];
  15537. const normals = [];
  15538. const uvs = [];
  15539. // helper variables
  15540. const center = new Vector3();
  15541. const vertex = new Vector3();
  15542. const normal = new Vector3();
  15543. // generate vertices, normals and uvs
  15544. for ( let j = 0; j <= radialSegments; j ++ ) {
  15545. for ( let i = 0; i <= tubularSegments; i ++ ) {
  15546. const u = i / tubularSegments * arc;
  15547. const v = j / radialSegments * Math.PI * 2;
  15548. // vertex
  15549. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  15550. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  15551. vertex.z = tube * Math.sin( v );
  15552. vertices.push( vertex.x, vertex.y, vertex.z );
  15553. // normal
  15554. center.x = radius * Math.cos( u );
  15555. center.y = radius * Math.sin( u );
  15556. normal.subVectors( vertex, center ).normalize();
  15557. normals.push( normal.x, normal.y, normal.z );
  15558. // uv
  15559. uvs.push( i / tubularSegments );
  15560. uvs.push( j / radialSegments );
  15561. }
  15562. }
  15563. // generate indices
  15564. for ( let j = 1; j <= radialSegments; j ++ ) {
  15565. for ( let i = 1; i <= tubularSegments; i ++ ) {
  15566. // indices
  15567. const a = ( tubularSegments + 1 ) * j + i - 1;
  15568. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  15569. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  15570. const d = ( tubularSegments + 1 ) * j + i;
  15571. // faces
  15572. indices.push( a, b, d );
  15573. indices.push( b, c, d );
  15574. }
  15575. }
  15576. // build geometry
  15577. this.setIndex( indices );
  15578. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15579. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15580. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15581. }
  15582. copy( source ) {
  15583. super.copy( source );
  15584. this.parameters = Object.assign( {}, source.parameters );
  15585. return this;
  15586. }
  15587. static fromJSON( data ) {
  15588. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  15589. }
  15590. }
  15591. class TorusKnotGeometry extends BufferGeometry {
  15592. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  15593. super();
  15594. this.type = 'TorusKnotGeometry';
  15595. this.parameters = {
  15596. radius: radius,
  15597. tube: tube,
  15598. tubularSegments: tubularSegments,
  15599. radialSegments: radialSegments,
  15600. p: p,
  15601. q: q
  15602. };
  15603. tubularSegments = Math.floor( tubularSegments );
  15604. radialSegments = Math.floor( radialSegments );
  15605. // buffers
  15606. const indices = [];
  15607. const vertices = [];
  15608. const normals = [];
  15609. const uvs = [];
  15610. // helper variables
  15611. const vertex = new Vector3();
  15612. const normal = new Vector3();
  15613. const P1 = new Vector3();
  15614. const P2 = new Vector3();
  15615. const B = new Vector3();
  15616. const T = new Vector3();
  15617. const N = new Vector3();
  15618. // generate vertices, normals and uvs
  15619. for ( let i = 0; i <= tubularSegments; ++ i ) {
  15620. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  15621. const u = i / tubularSegments * p * Math.PI * 2;
  15622. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  15623. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  15624. calculatePositionOnCurve( u, p, q, radius, P1 );
  15625. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  15626. // calculate orthonormal basis
  15627. T.subVectors( P2, P1 );
  15628. N.addVectors( P2, P1 );
  15629. B.crossVectors( T, N );
  15630. N.crossVectors( B, T );
  15631. // normalize B, N. T can be ignored, we don't use it
  15632. B.normalize();
  15633. N.normalize();
  15634. for ( let j = 0; j <= radialSegments; ++ j ) {
  15635. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  15636. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  15637. const v = j / radialSegments * Math.PI * 2;
  15638. const cx = - tube * Math.cos( v );
  15639. const cy = tube * Math.sin( v );
  15640. // now calculate the final vertex position.
  15641. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  15642. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  15643. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  15644. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  15645. vertices.push( vertex.x, vertex.y, vertex.z );
  15646. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  15647. normal.subVectors( vertex, P1 ).normalize();
  15648. normals.push( normal.x, normal.y, normal.z );
  15649. // uv
  15650. uvs.push( i / tubularSegments );
  15651. uvs.push( j / radialSegments );
  15652. }
  15653. }
  15654. // generate indices
  15655. for ( let j = 1; j <= tubularSegments; j ++ ) {
  15656. for ( let i = 1; i <= radialSegments; i ++ ) {
  15657. // indices
  15658. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15659. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  15660. const c = ( radialSegments + 1 ) * j + i;
  15661. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15662. // faces
  15663. indices.push( a, b, d );
  15664. indices.push( b, c, d );
  15665. }
  15666. }
  15667. // build geometry
  15668. this.setIndex( indices );
  15669. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15670. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15671. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15672. // this function calculates the current position on the torus curve
  15673. function calculatePositionOnCurve( u, p, q, radius, position ) {
  15674. const cu = Math.cos( u );
  15675. const su = Math.sin( u );
  15676. const quOverP = q / p * u;
  15677. const cs = Math.cos( quOverP );
  15678. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  15679. position.y = radius * ( 2 + cs ) * su * 0.5;
  15680. position.z = radius * Math.sin( quOverP ) * 0.5;
  15681. }
  15682. }
  15683. copy( source ) {
  15684. super.copy( source );
  15685. this.parameters = Object.assign( {}, source.parameters );
  15686. return this;
  15687. }
  15688. static fromJSON( data ) {
  15689. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  15690. }
  15691. }
  15692. class TubeGeometry extends BufferGeometry {
  15693. 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 ) {
  15694. super();
  15695. this.type = 'TubeGeometry';
  15696. this.parameters = {
  15697. path: path,
  15698. tubularSegments: tubularSegments,
  15699. radius: radius,
  15700. radialSegments: radialSegments,
  15701. closed: closed
  15702. };
  15703. const frames = path.computeFrenetFrames( tubularSegments, closed );
  15704. // expose internals
  15705. this.tangents = frames.tangents;
  15706. this.normals = frames.normals;
  15707. this.binormals = frames.binormals;
  15708. // helper variables
  15709. const vertex = new Vector3();
  15710. const normal = new Vector3();
  15711. const uv = new Vector2();
  15712. let P = new Vector3();
  15713. // buffer
  15714. const vertices = [];
  15715. const normals = [];
  15716. const uvs = [];
  15717. const indices = [];
  15718. // create buffer data
  15719. generateBufferData();
  15720. // build geometry
  15721. this.setIndex( indices );
  15722. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15723. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15724. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15725. // functions
  15726. function generateBufferData() {
  15727. for ( let i = 0; i < tubularSegments; i ++ ) {
  15728. generateSegment( i );
  15729. }
  15730. // if the geometry is not closed, generate the last row of vertices and normals
  15731. // at the regular position on the given path
  15732. //
  15733. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  15734. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  15735. // uvs are generated in a separate function.
  15736. // this makes it easy compute correct values for closed geometries
  15737. generateUVs();
  15738. // finally create faces
  15739. generateIndices();
  15740. }
  15741. function generateSegment( i ) {
  15742. // we use getPointAt to sample evenly distributed points from the given path
  15743. P = path.getPointAt( i / tubularSegments, P );
  15744. // retrieve corresponding normal and binormal
  15745. const N = frames.normals[ i ];
  15746. const B = frames.binormals[ i ];
  15747. // generate normals and vertices for the current segment
  15748. for ( let j = 0; j <= radialSegments; j ++ ) {
  15749. const v = j / radialSegments * Math.PI * 2;
  15750. const sin = Math.sin( v );
  15751. const cos = - Math.cos( v );
  15752. // normal
  15753. normal.x = ( cos * N.x + sin * B.x );
  15754. normal.y = ( cos * N.y + sin * B.y );
  15755. normal.z = ( cos * N.z + sin * B.z );
  15756. normal.normalize();
  15757. normals.push( normal.x, normal.y, normal.z );
  15758. // vertex
  15759. vertex.x = P.x + radius * normal.x;
  15760. vertex.y = P.y + radius * normal.y;
  15761. vertex.z = P.z + radius * normal.z;
  15762. vertices.push( vertex.x, vertex.y, vertex.z );
  15763. }
  15764. }
  15765. function generateIndices() {
  15766. for ( let j = 1; j <= tubularSegments; j ++ ) {
  15767. for ( let i = 1; i <= radialSegments; i ++ ) {
  15768. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  15769. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  15770. const c = ( radialSegments + 1 ) * j + i;
  15771. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  15772. // faces
  15773. indices.push( a, b, d );
  15774. indices.push( b, c, d );
  15775. }
  15776. }
  15777. }
  15778. function generateUVs() {
  15779. for ( let i = 0; i <= tubularSegments; i ++ ) {
  15780. for ( let j = 0; j <= radialSegments; j ++ ) {
  15781. uv.x = i / tubularSegments;
  15782. uv.y = j / radialSegments;
  15783. uvs.push( uv.x, uv.y );
  15784. }
  15785. }
  15786. }
  15787. }
  15788. copy( source ) {
  15789. super.copy( source );
  15790. this.parameters = Object.assign( {}, source.parameters );
  15791. return this;
  15792. }
  15793. toJSON() {
  15794. const data = super.toJSON();
  15795. data.path = this.parameters.path.toJSON();
  15796. return data;
  15797. }
  15798. static fromJSON( data ) {
  15799. // This only works for built-in curves (e.g. CatmullRomCurve3).
  15800. // User defined curves or instances of CurvePath will not be deserialized.
  15801. return new TubeGeometry(
  15802. new Curves[ data.path.type ]().fromJSON( data.path ),
  15803. data.tubularSegments,
  15804. data.radius,
  15805. data.radialSegments,
  15806. data.closed
  15807. );
  15808. }
  15809. }
  15810. class WireframeGeometry extends BufferGeometry {
  15811. constructor( geometry = null ) {
  15812. super();
  15813. this.type = 'WireframeGeometry';
  15814. this.parameters = {
  15815. geometry: geometry
  15816. };
  15817. if ( geometry !== null ) {
  15818. // buffer
  15819. const vertices = [];
  15820. const edges = new Set();
  15821. // helper variables
  15822. const start = new Vector3();
  15823. const end = new Vector3();
  15824. if ( geometry.index !== null ) {
  15825. // indexed BufferGeometry
  15826. const position = geometry.attributes.position;
  15827. const indices = geometry.index;
  15828. let groups = geometry.groups;
  15829. if ( groups.length === 0 ) {
  15830. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  15831. }
  15832. // create a data structure that contains all edges without duplicates
  15833. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  15834. const group = groups[ o ];
  15835. const groupStart = group.start;
  15836. const groupCount = group.count;
  15837. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  15838. for ( let j = 0; j < 3; j ++ ) {
  15839. const index1 = indices.getX( i + j );
  15840. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  15841. start.fromBufferAttribute( position, index1 );
  15842. end.fromBufferAttribute( position, index2 );
  15843. if ( isUniqueEdge( start, end, edges ) === true ) {
  15844. vertices.push( start.x, start.y, start.z );
  15845. vertices.push( end.x, end.y, end.z );
  15846. }
  15847. }
  15848. }
  15849. }
  15850. } else {
  15851. // non-indexed BufferGeometry
  15852. const position = geometry.attributes.position;
  15853. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  15854. for ( let j = 0; j < 3; j ++ ) {
  15855. // three edges per triangle, an edge is represented as (index1, index2)
  15856. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  15857. const index1 = 3 * i + j;
  15858. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  15859. start.fromBufferAttribute( position, index1 );
  15860. end.fromBufferAttribute( position, index2 );
  15861. if ( isUniqueEdge( start, end, edges ) === true ) {
  15862. vertices.push( start.x, start.y, start.z );
  15863. vertices.push( end.x, end.y, end.z );
  15864. }
  15865. }
  15866. }
  15867. }
  15868. // build geometry
  15869. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15870. }
  15871. }
  15872. copy( source ) {
  15873. super.copy( source );
  15874. this.parameters = Object.assign( {}, source.parameters );
  15875. return this;
  15876. }
  15877. }
  15878. function isUniqueEdge( start, end, edges ) {
  15879. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  15880. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  15881. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  15882. return false;
  15883. } else {
  15884. edges.add( hash1 );
  15885. edges.add( hash2 );
  15886. return true;
  15887. }
  15888. }
  15889. var Geometries = /*#__PURE__*/Object.freeze({
  15890. __proto__: null,
  15891. BoxGeometry: BoxGeometry,
  15892. CapsuleGeometry: CapsuleGeometry,
  15893. CircleGeometry: CircleGeometry,
  15894. ConeGeometry: ConeGeometry,
  15895. CylinderGeometry: CylinderGeometry,
  15896. DodecahedronGeometry: DodecahedronGeometry,
  15897. EdgesGeometry: EdgesGeometry,
  15898. ExtrudeGeometry: ExtrudeGeometry,
  15899. IcosahedronGeometry: IcosahedronGeometry,
  15900. LatheGeometry: LatheGeometry,
  15901. OctahedronGeometry: OctahedronGeometry,
  15902. PlaneGeometry: PlaneGeometry,
  15903. PolyhedronGeometry: PolyhedronGeometry,
  15904. RingGeometry: RingGeometry,
  15905. ShapeGeometry: ShapeGeometry,
  15906. SphereGeometry: SphereGeometry,
  15907. TetrahedronGeometry: TetrahedronGeometry,
  15908. TorusGeometry: TorusGeometry,
  15909. TorusKnotGeometry: TorusKnotGeometry,
  15910. TubeGeometry: TubeGeometry,
  15911. WireframeGeometry: WireframeGeometry
  15912. });
  15913. class ShadowMaterial extends Material {
  15914. constructor( parameters ) {
  15915. super();
  15916. this.isShadowMaterial = true;
  15917. this.type = 'ShadowMaterial';
  15918. this.color = new Color( 0x000000 );
  15919. this.transparent = true;
  15920. this.fog = true;
  15921. this.setValues( parameters );
  15922. }
  15923. copy( source ) {
  15924. super.copy( source );
  15925. this.color.copy( source.color );
  15926. this.fog = source.fog;
  15927. return this;
  15928. }
  15929. }
  15930. class RawShaderMaterial extends ShaderMaterial {
  15931. constructor( parameters ) {
  15932. super( parameters );
  15933. this.isRawShaderMaterial = true;
  15934. this.type = 'RawShaderMaterial';
  15935. }
  15936. }
  15937. class MeshStandardMaterial extends Material {
  15938. constructor( parameters ) {
  15939. super();
  15940. this.isMeshStandardMaterial = true;
  15941. this.type = 'MeshStandardMaterial';
  15942. this.defines = { 'STANDARD': '' };
  15943. this.color = new Color( 0xffffff ); // diffuse
  15944. this.roughness = 1.0;
  15945. this.metalness = 0.0;
  15946. this.map = null;
  15947. this.lightMap = null;
  15948. this.lightMapIntensity = 1.0;
  15949. this.aoMap = null;
  15950. this.aoMapIntensity = 1.0;
  15951. this.emissive = new Color( 0x000000 );
  15952. this.emissiveIntensity = 1.0;
  15953. this.emissiveMap = null;
  15954. this.bumpMap = null;
  15955. this.bumpScale = 1;
  15956. this.normalMap = null;
  15957. this.normalMapType = TangentSpaceNormalMap;
  15958. this.normalScale = new Vector2( 1, 1 );
  15959. this.displacementMap = null;
  15960. this.displacementScale = 1;
  15961. this.displacementBias = 0;
  15962. this.roughnessMap = null;
  15963. this.metalnessMap = null;
  15964. this.alphaMap = null;
  15965. this.envMap = null;
  15966. this.envMapRotation = new Euler();
  15967. this.envMapIntensity = 1.0;
  15968. this.wireframe = false;
  15969. this.wireframeLinewidth = 1;
  15970. this.wireframeLinecap = 'round';
  15971. this.wireframeLinejoin = 'round';
  15972. this.flatShading = false;
  15973. this.fog = true;
  15974. this.setValues( parameters );
  15975. }
  15976. copy( source ) {
  15977. super.copy( source );
  15978. this.defines = { 'STANDARD': '' };
  15979. this.color.copy( source.color );
  15980. this.roughness = source.roughness;
  15981. this.metalness = source.metalness;
  15982. this.map = source.map;
  15983. this.lightMap = source.lightMap;
  15984. this.lightMapIntensity = source.lightMapIntensity;
  15985. this.aoMap = source.aoMap;
  15986. this.aoMapIntensity = source.aoMapIntensity;
  15987. this.emissive.copy( source.emissive );
  15988. this.emissiveMap = source.emissiveMap;
  15989. this.emissiveIntensity = source.emissiveIntensity;
  15990. this.bumpMap = source.bumpMap;
  15991. this.bumpScale = source.bumpScale;
  15992. this.normalMap = source.normalMap;
  15993. this.normalMapType = source.normalMapType;
  15994. this.normalScale.copy( source.normalScale );
  15995. this.displacementMap = source.displacementMap;
  15996. this.displacementScale = source.displacementScale;
  15997. this.displacementBias = source.displacementBias;
  15998. this.roughnessMap = source.roughnessMap;
  15999. this.metalnessMap = source.metalnessMap;
  16000. this.alphaMap = source.alphaMap;
  16001. this.envMap = source.envMap;
  16002. this.envMapRotation.copy( source.envMapRotation );
  16003. this.envMapIntensity = source.envMapIntensity;
  16004. this.wireframe = source.wireframe;
  16005. this.wireframeLinewidth = source.wireframeLinewidth;
  16006. this.wireframeLinecap = source.wireframeLinecap;
  16007. this.wireframeLinejoin = source.wireframeLinejoin;
  16008. this.flatShading = source.flatShading;
  16009. this.fog = source.fog;
  16010. return this;
  16011. }
  16012. }
  16013. class MeshPhysicalMaterial extends MeshStandardMaterial {
  16014. constructor( parameters ) {
  16015. super();
  16016. this.isMeshPhysicalMaterial = true;
  16017. this.defines = {
  16018. 'STANDARD': '',
  16019. 'PHYSICAL': ''
  16020. };
  16021. this.type = 'MeshPhysicalMaterial';
  16022. this.anisotropyRotation = 0;
  16023. this.anisotropyMap = null;
  16024. this.clearcoatMap = null;
  16025. this.clearcoatRoughness = 0.0;
  16026. this.clearcoatRoughnessMap = null;
  16027. this.clearcoatNormalScale = new Vector2( 1, 1 );
  16028. this.clearcoatNormalMap = null;
  16029. this.ior = 1.5;
  16030. Object.defineProperty( this, 'reflectivity', {
  16031. get: function () {
  16032. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  16033. },
  16034. set: function ( reflectivity ) {
  16035. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  16036. }
  16037. } );
  16038. this.iridescenceMap = null;
  16039. this.iridescenceIOR = 1.3;
  16040. this.iridescenceThicknessRange = [ 100, 400 ];
  16041. this.iridescenceThicknessMap = null;
  16042. this.sheenColor = new Color( 0x000000 );
  16043. this.sheenColorMap = null;
  16044. this.sheenRoughness = 1.0;
  16045. this.sheenRoughnessMap = null;
  16046. this.transmissionMap = null;
  16047. this.thickness = 0;
  16048. this.thicknessMap = null;
  16049. this.attenuationDistance = Infinity;
  16050. this.attenuationColor = new Color( 1, 1, 1 );
  16051. this.specularIntensity = 1.0;
  16052. this.specularIntensityMap = null;
  16053. this.specularColor = new Color( 1, 1, 1 );
  16054. this.specularColorMap = null;
  16055. this._anisotropy = 0;
  16056. this._clearcoat = 0;
  16057. this._dispersion = 0;
  16058. this._iridescence = 0;
  16059. this._sheen = 0.0;
  16060. this._transmission = 0;
  16061. this.setValues( parameters );
  16062. }
  16063. get anisotropy() {
  16064. return this._anisotropy;
  16065. }
  16066. set anisotropy( value ) {
  16067. if ( this._anisotropy > 0 !== value > 0 ) {
  16068. this.version ++;
  16069. }
  16070. this._anisotropy = value;
  16071. }
  16072. get clearcoat() {
  16073. return this._clearcoat;
  16074. }
  16075. set clearcoat( value ) {
  16076. if ( this._clearcoat > 0 !== value > 0 ) {
  16077. this.version ++;
  16078. }
  16079. this._clearcoat = value;
  16080. }
  16081. get iridescence() {
  16082. return this._iridescence;
  16083. }
  16084. set iridescence( value ) {
  16085. if ( this._iridescence > 0 !== value > 0 ) {
  16086. this.version ++;
  16087. }
  16088. this._iridescence = value;
  16089. }
  16090. get dispersion() {
  16091. return this._dispersion;
  16092. }
  16093. set dispersion( value ) {
  16094. if ( this._dispersion > 0 !== value > 0 ) {
  16095. this.version ++;
  16096. }
  16097. this._dispersion = value;
  16098. }
  16099. get sheen() {
  16100. return this._sheen;
  16101. }
  16102. set sheen( value ) {
  16103. if ( this._sheen > 0 !== value > 0 ) {
  16104. this.version ++;
  16105. }
  16106. this._sheen = value;
  16107. }
  16108. get transmission() {
  16109. return this._transmission;
  16110. }
  16111. set transmission( value ) {
  16112. if ( this._transmission > 0 !== value > 0 ) {
  16113. this.version ++;
  16114. }
  16115. this._transmission = value;
  16116. }
  16117. copy( source ) {
  16118. super.copy( source );
  16119. this.defines = {
  16120. 'STANDARD': '',
  16121. 'PHYSICAL': ''
  16122. };
  16123. this.anisotropy = source.anisotropy;
  16124. this.anisotropyRotation = source.anisotropyRotation;
  16125. this.anisotropyMap = source.anisotropyMap;
  16126. this.clearcoat = source.clearcoat;
  16127. this.clearcoatMap = source.clearcoatMap;
  16128. this.clearcoatRoughness = source.clearcoatRoughness;
  16129. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  16130. this.clearcoatNormalMap = source.clearcoatNormalMap;
  16131. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  16132. this.dispersion = source.dispersion;
  16133. this.ior = source.ior;
  16134. this.iridescence = source.iridescence;
  16135. this.iridescenceMap = source.iridescenceMap;
  16136. this.iridescenceIOR = source.iridescenceIOR;
  16137. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  16138. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  16139. this.sheen = source.sheen;
  16140. this.sheenColor.copy( source.sheenColor );
  16141. this.sheenColorMap = source.sheenColorMap;
  16142. this.sheenRoughness = source.sheenRoughness;
  16143. this.sheenRoughnessMap = source.sheenRoughnessMap;
  16144. this.transmission = source.transmission;
  16145. this.transmissionMap = source.transmissionMap;
  16146. this.thickness = source.thickness;
  16147. this.thicknessMap = source.thicknessMap;
  16148. this.attenuationDistance = source.attenuationDistance;
  16149. this.attenuationColor.copy( source.attenuationColor );
  16150. this.specularIntensity = source.specularIntensity;
  16151. this.specularIntensityMap = source.specularIntensityMap;
  16152. this.specularColor.copy( source.specularColor );
  16153. this.specularColorMap = source.specularColorMap;
  16154. return this;
  16155. }
  16156. }
  16157. class MeshPhongMaterial extends Material {
  16158. constructor( parameters ) {
  16159. super();
  16160. this.isMeshPhongMaterial = true;
  16161. this.type = 'MeshPhongMaterial';
  16162. this.color = new Color( 0xffffff ); // diffuse
  16163. this.specular = new Color( 0x111111 );
  16164. this.shininess = 30;
  16165. this.map = null;
  16166. this.lightMap = null;
  16167. this.lightMapIntensity = 1.0;
  16168. this.aoMap = null;
  16169. this.aoMapIntensity = 1.0;
  16170. this.emissive = new Color( 0x000000 );
  16171. this.emissiveIntensity = 1.0;
  16172. this.emissiveMap = null;
  16173. this.bumpMap = null;
  16174. this.bumpScale = 1;
  16175. this.normalMap = null;
  16176. this.normalMapType = TangentSpaceNormalMap;
  16177. this.normalScale = new Vector2( 1, 1 );
  16178. this.displacementMap = null;
  16179. this.displacementScale = 1;
  16180. this.displacementBias = 0;
  16181. this.specularMap = null;
  16182. this.alphaMap = null;
  16183. this.envMap = null;
  16184. this.envMapRotation = new Euler();
  16185. this.combine = MultiplyOperation;
  16186. this.reflectivity = 1;
  16187. this.refractionRatio = 0.98;
  16188. this.wireframe = false;
  16189. this.wireframeLinewidth = 1;
  16190. this.wireframeLinecap = 'round';
  16191. this.wireframeLinejoin = 'round';
  16192. this.flatShading = false;
  16193. this.fog = true;
  16194. this.setValues( parameters );
  16195. }
  16196. copy( source ) {
  16197. super.copy( source );
  16198. this.color.copy( source.color );
  16199. this.specular.copy( source.specular );
  16200. this.shininess = source.shininess;
  16201. this.map = source.map;
  16202. this.lightMap = source.lightMap;
  16203. this.lightMapIntensity = source.lightMapIntensity;
  16204. this.aoMap = source.aoMap;
  16205. this.aoMapIntensity = source.aoMapIntensity;
  16206. this.emissive.copy( source.emissive );
  16207. this.emissiveMap = source.emissiveMap;
  16208. this.emissiveIntensity = source.emissiveIntensity;
  16209. this.bumpMap = source.bumpMap;
  16210. this.bumpScale = source.bumpScale;
  16211. this.normalMap = source.normalMap;
  16212. this.normalMapType = source.normalMapType;
  16213. this.normalScale.copy( source.normalScale );
  16214. this.displacementMap = source.displacementMap;
  16215. this.displacementScale = source.displacementScale;
  16216. this.displacementBias = source.displacementBias;
  16217. this.specularMap = source.specularMap;
  16218. this.alphaMap = source.alphaMap;
  16219. this.envMap = source.envMap;
  16220. this.envMapRotation.copy( source.envMapRotation );
  16221. this.combine = source.combine;
  16222. this.reflectivity = source.reflectivity;
  16223. this.refractionRatio = source.refractionRatio;
  16224. this.wireframe = source.wireframe;
  16225. this.wireframeLinewidth = source.wireframeLinewidth;
  16226. this.wireframeLinecap = source.wireframeLinecap;
  16227. this.wireframeLinejoin = source.wireframeLinejoin;
  16228. this.flatShading = source.flatShading;
  16229. this.fog = source.fog;
  16230. return this;
  16231. }
  16232. }
  16233. class MeshToonMaterial extends Material {
  16234. constructor( parameters ) {
  16235. super();
  16236. this.isMeshToonMaterial = true;
  16237. this.defines = { 'TOON': '' };
  16238. this.type = 'MeshToonMaterial';
  16239. this.color = new Color( 0xffffff );
  16240. this.map = null;
  16241. this.gradientMap = null;
  16242. this.lightMap = null;
  16243. this.lightMapIntensity = 1.0;
  16244. this.aoMap = null;
  16245. this.aoMapIntensity = 1.0;
  16246. this.emissive = new Color( 0x000000 );
  16247. this.emissiveIntensity = 1.0;
  16248. this.emissiveMap = null;
  16249. this.bumpMap = null;
  16250. this.bumpScale = 1;
  16251. this.normalMap = null;
  16252. this.normalMapType = TangentSpaceNormalMap;
  16253. this.normalScale = new Vector2( 1, 1 );
  16254. this.displacementMap = null;
  16255. this.displacementScale = 1;
  16256. this.displacementBias = 0;
  16257. this.alphaMap = null;
  16258. this.wireframe = false;
  16259. this.wireframeLinewidth = 1;
  16260. this.wireframeLinecap = 'round';
  16261. this.wireframeLinejoin = 'round';
  16262. this.fog = true;
  16263. this.setValues( parameters );
  16264. }
  16265. copy( source ) {
  16266. super.copy( source );
  16267. this.color.copy( source.color );
  16268. this.map = source.map;
  16269. this.gradientMap = source.gradientMap;
  16270. this.lightMap = source.lightMap;
  16271. this.lightMapIntensity = source.lightMapIntensity;
  16272. this.aoMap = source.aoMap;
  16273. this.aoMapIntensity = source.aoMapIntensity;
  16274. this.emissive.copy( source.emissive );
  16275. this.emissiveMap = source.emissiveMap;
  16276. this.emissiveIntensity = source.emissiveIntensity;
  16277. this.bumpMap = source.bumpMap;
  16278. this.bumpScale = source.bumpScale;
  16279. this.normalMap = source.normalMap;
  16280. this.normalMapType = source.normalMapType;
  16281. this.normalScale.copy( source.normalScale );
  16282. this.displacementMap = source.displacementMap;
  16283. this.displacementScale = source.displacementScale;
  16284. this.displacementBias = source.displacementBias;
  16285. this.alphaMap = source.alphaMap;
  16286. this.wireframe = source.wireframe;
  16287. this.wireframeLinewidth = source.wireframeLinewidth;
  16288. this.wireframeLinecap = source.wireframeLinecap;
  16289. this.wireframeLinejoin = source.wireframeLinejoin;
  16290. this.fog = source.fog;
  16291. return this;
  16292. }
  16293. }
  16294. class MeshNormalMaterial extends Material {
  16295. constructor( parameters ) {
  16296. super();
  16297. this.isMeshNormalMaterial = true;
  16298. this.type = 'MeshNormalMaterial';
  16299. this.bumpMap = null;
  16300. this.bumpScale = 1;
  16301. this.normalMap = null;
  16302. this.normalMapType = TangentSpaceNormalMap;
  16303. this.normalScale = new Vector2( 1, 1 );
  16304. this.displacementMap = null;
  16305. this.displacementScale = 1;
  16306. this.displacementBias = 0;
  16307. this.wireframe = false;
  16308. this.wireframeLinewidth = 1;
  16309. this.flatShading = false;
  16310. this.setValues( parameters );
  16311. }
  16312. copy( source ) {
  16313. super.copy( source );
  16314. this.bumpMap = source.bumpMap;
  16315. this.bumpScale = source.bumpScale;
  16316. this.normalMap = source.normalMap;
  16317. this.normalMapType = source.normalMapType;
  16318. this.normalScale.copy( source.normalScale );
  16319. this.displacementMap = source.displacementMap;
  16320. this.displacementScale = source.displacementScale;
  16321. this.displacementBias = source.displacementBias;
  16322. this.wireframe = source.wireframe;
  16323. this.wireframeLinewidth = source.wireframeLinewidth;
  16324. this.flatShading = source.flatShading;
  16325. return this;
  16326. }
  16327. }
  16328. class MeshLambertMaterial extends Material {
  16329. constructor( parameters ) {
  16330. super();
  16331. this.isMeshLambertMaterial = true;
  16332. this.type = 'MeshLambertMaterial';
  16333. this.color = new Color( 0xffffff ); // diffuse
  16334. this.map = null;
  16335. this.lightMap = null;
  16336. this.lightMapIntensity = 1.0;
  16337. this.aoMap = null;
  16338. this.aoMapIntensity = 1.0;
  16339. this.emissive = new Color( 0x000000 );
  16340. this.emissiveIntensity = 1.0;
  16341. this.emissiveMap = null;
  16342. this.bumpMap = null;
  16343. this.bumpScale = 1;
  16344. this.normalMap = null;
  16345. this.normalMapType = TangentSpaceNormalMap;
  16346. this.normalScale = new Vector2( 1, 1 );
  16347. this.displacementMap = null;
  16348. this.displacementScale = 1;
  16349. this.displacementBias = 0;
  16350. this.specularMap = null;
  16351. this.alphaMap = null;
  16352. this.envMap = null;
  16353. this.envMapRotation = new Euler();
  16354. this.combine = MultiplyOperation;
  16355. this.reflectivity = 1;
  16356. this.refractionRatio = 0.98;
  16357. this.wireframe = false;
  16358. this.wireframeLinewidth = 1;
  16359. this.wireframeLinecap = 'round';
  16360. this.wireframeLinejoin = 'round';
  16361. this.flatShading = false;
  16362. this.fog = true;
  16363. this.setValues( parameters );
  16364. }
  16365. copy( source ) {
  16366. super.copy( source );
  16367. this.color.copy( source.color );
  16368. this.map = source.map;
  16369. this.lightMap = source.lightMap;
  16370. this.lightMapIntensity = source.lightMapIntensity;
  16371. this.aoMap = source.aoMap;
  16372. this.aoMapIntensity = source.aoMapIntensity;
  16373. this.emissive.copy( source.emissive );
  16374. this.emissiveMap = source.emissiveMap;
  16375. this.emissiveIntensity = source.emissiveIntensity;
  16376. this.bumpMap = source.bumpMap;
  16377. this.bumpScale = source.bumpScale;
  16378. this.normalMap = source.normalMap;
  16379. this.normalMapType = source.normalMapType;
  16380. this.normalScale.copy( source.normalScale );
  16381. this.displacementMap = source.displacementMap;
  16382. this.displacementScale = source.displacementScale;
  16383. this.displacementBias = source.displacementBias;
  16384. this.specularMap = source.specularMap;
  16385. this.alphaMap = source.alphaMap;
  16386. this.envMap = source.envMap;
  16387. this.envMapRotation.copy( source.envMapRotation );
  16388. this.combine = source.combine;
  16389. this.reflectivity = source.reflectivity;
  16390. this.refractionRatio = source.refractionRatio;
  16391. this.wireframe = source.wireframe;
  16392. this.wireframeLinewidth = source.wireframeLinewidth;
  16393. this.wireframeLinecap = source.wireframeLinecap;
  16394. this.wireframeLinejoin = source.wireframeLinejoin;
  16395. this.flatShading = source.flatShading;
  16396. this.fog = source.fog;
  16397. return this;
  16398. }
  16399. }
  16400. class MeshDepthMaterial extends Material {
  16401. constructor( parameters ) {
  16402. super();
  16403. this.isMeshDepthMaterial = true;
  16404. this.type = 'MeshDepthMaterial';
  16405. this.depthPacking = BasicDepthPacking;
  16406. this.map = null;
  16407. this.alphaMap = null;
  16408. this.displacementMap = null;
  16409. this.displacementScale = 1;
  16410. this.displacementBias = 0;
  16411. this.wireframe = false;
  16412. this.wireframeLinewidth = 1;
  16413. this.setValues( parameters );
  16414. }
  16415. copy( source ) {
  16416. super.copy( source );
  16417. this.depthPacking = source.depthPacking;
  16418. this.map = source.map;
  16419. this.alphaMap = source.alphaMap;
  16420. this.displacementMap = source.displacementMap;
  16421. this.displacementScale = source.displacementScale;
  16422. this.displacementBias = source.displacementBias;
  16423. this.wireframe = source.wireframe;
  16424. this.wireframeLinewidth = source.wireframeLinewidth;
  16425. return this;
  16426. }
  16427. }
  16428. class MeshDistanceMaterial extends Material {
  16429. constructor( parameters ) {
  16430. super();
  16431. this.isMeshDistanceMaterial = true;
  16432. this.type = 'MeshDistanceMaterial';
  16433. this.map = null;
  16434. this.alphaMap = null;
  16435. this.displacementMap = null;
  16436. this.displacementScale = 1;
  16437. this.displacementBias = 0;
  16438. this.setValues( parameters );
  16439. }
  16440. copy( source ) {
  16441. super.copy( source );
  16442. this.map = source.map;
  16443. this.alphaMap = source.alphaMap;
  16444. this.displacementMap = source.displacementMap;
  16445. this.displacementScale = source.displacementScale;
  16446. this.displacementBias = source.displacementBias;
  16447. return this;
  16448. }
  16449. }
  16450. class MeshMatcapMaterial extends Material {
  16451. constructor( parameters ) {
  16452. super();
  16453. this.isMeshMatcapMaterial = true;
  16454. this.defines = { 'MATCAP': '' };
  16455. this.type = 'MeshMatcapMaterial';
  16456. this.color = new Color( 0xffffff ); // diffuse
  16457. this.matcap = null;
  16458. this.map = null;
  16459. this.bumpMap = null;
  16460. this.bumpScale = 1;
  16461. this.normalMap = null;
  16462. this.normalMapType = TangentSpaceNormalMap;
  16463. this.normalScale = new Vector2( 1, 1 );
  16464. this.displacementMap = null;
  16465. this.displacementScale = 1;
  16466. this.displacementBias = 0;
  16467. this.alphaMap = null;
  16468. this.flatShading = false;
  16469. this.fog = true;
  16470. this.setValues( parameters );
  16471. }
  16472. copy( source ) {
  16473. super.copy( source );
  16474. this.defines = { 'MATCAP': '' };
  16475. this.color.copy( source.color );
  16476. this.matcap = source.matcap;
  16477. this.map = source.map;
  16478. this.bumpMap = source.bumpMap;
  16479. this.bumpScale = source.bumpScale;
  16480. this.normalMap = source.normalMap;
  16481. this.normalMapType = source.normalMapType;
  16482. this.normalScale.copy( source.normalScale );
  16483. this.displacementMap = source.displacementMap;
  16484. this.displacementScale = source.displacementScale;
  16485. this.displacementBias = source.displacementBias;
  16486. this.alphaMap = source.alphaMap;
  16487. this.flatShading = source.flatShading;
  16488. this.fog = source.fog;
  16489. return this;
  16490. }
  16491. }
  16492. class LineDashedMaterial extends LineBasicMaterial {
  16493. constructor( parameters ) {
  16494. super();
  16495. this.isLineDashedMaterial = true;
  16496. this.type = 'LineDashedMaterial';
  16497. this.scale = 1;
  16498. this.dashSize = 3;
  16499. this.gapSize = 1;
  16500. this.setValues( parameters );
  16501. }
  16502. copy( source ) {
  16503. super.copy( source );
  16504. this.scale = source.scale;
  16505. this.dashSize = source.dashSize;
  16506. this.gapSize = source.gapSize;
  16507. return this;
  16508. }
  16509. }
  16510. // converts an array to a specific type
  16511. function convertArray( array, type, forceClone ) {
  16512. if ( ! array || // let 'undefined' and 'null' pass
  16513. ! forceClone && array.constructor === type ) return array;
  16514. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  16515. return new type( array ); // create typed array
  16516. }
  16517. return Array.prototype.slice.call( array ); // create Array
  16518. }
  16519. function isTypedArray( object ) {
  16520. return ArrayBuffer.isView( object ) &&
  16521. ! ( object instanceof DataView );
  16522. }
  16523. // returns an array by which times and values can be sorted
  16524. function getKeyframeOrder( times ) {
  16525. function compareTime( i, j ) {
  16526. return times[ i ] - times[ j ];
  16527. }
  16528. const n = times.length;
  16529. const result = new Array( n );
  16530. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  16531. result.sort( compareTime );
  16532. return result;
  16533. }
  16534. // uses the array previously returned by 'getKeyframeOrder' to sort data
  16535. function sortedArray( values, stride, order ) {
  16536. const nValues = values.length;
  16537. const result = new values.constructor( nValues );
  16538. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  16539. const srcOffset = order[ i ] * stride;
  16540. for ( let j = 0; j !== stride; ++ j ) {
  16541. result[ dstOffset ++ ] = values[ srcOffset + j ];
  16542. }
  16543. }
  16544. return result;
  16545. }
  16546. // function for parsing AOS keyframe formats
  16547. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  16548. let i = 1, key = jsonKeys[ 0 ];
  16549. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  16550. key = jsonKeys[ i ++ ];
  16551. }
  16552. if ( key === undefined ) return; // no data
  16553. let value = key[ valuePropertyName ];
  16554. if ( value === undefined ) return; // no data
  16555. if ( Array.isArray( value ) ) {
  16556. do {
  16557. value = key[ valuePropertyName ];
  16558. if ( value !== undefined ) {
  16559. times.push( key.time );
  16560. values.push( ...value ); // push all elements
  16561. }
  16562. key = jsonKeys[ i ++ ];
  16563. } while ( key !== undefined );
  16564. } else if ( value.toArray !== undefined ) {
  16565. // ...assume THREE.Math-ish
  16566. do {
  16567. value = key[ valuePropertyName ];
  16568. if ( value !== undefined ) {
  16569. times.push( key.time );
  16570. value.toArray( values, values.length );
  16571. }
  16572. key = jsonKeys[ i ++ ];
  16573. } while ( key !== undefined );
  16574. } else {
  16575. // otherwise push as-is
  16576. do {
  16577. value = key[ valuePropertyName ];
  16578. if ( value !== undefined ) {
  16579. times.push( key.time );
  16580. values.push( value );
  16581. }
  16582. key = jsonKeys[ i ++ ];
  16583. } while ( key !== undefined );
  16584. }
  16585. }
  16586. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  16587. const clip = sourceClip.clone();
  16588. clip.name = name;
  16589. const tracks = [];
  16590. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  16591. const track = clip.tracks[ i ];
  16592. const valueSize = track.getValueSize();
  16593. const times = [];
  16594. const values = [];
  16595. for ( let j = 0; j < track.times.length; ++ j ) {
  16596. const frame = track.times[ j ] * fps;
  16597. if ( frame < startFrame || frame >= endFrame ) continue;
  16598. times.push( track.times[ j ] );
  16599. for ( let k = 0; k < valueSize; ++ k ) {
  16600. values.push( track.values[ j * valueSize + k ] );
  16601. }
  16602. }
  16603. if ( times.length === 0 ) continue;
  16604. track.times = convertArray( times, track.times.constructor );
  16605. track.values = convertArray( values, track.values.constructor );
  16606. tracks.push( track );
  16607. }
  16608. clip.tracks = tracks;
  16609. // find minimum .times value across all tracks in the trimmed clip
  16610. let minStartTime = Infinity;
  16611. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  16612. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  16613. minStartTime = clip.tracks[ i ].times[ 0 ];
  16614. }
  16615. }
  16616. // shift all tracks such that clip begins at t=0
  16617. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  16618. clip.tracks[ i ].shift( -1 * minStartTime );
  16619. }
  16620. clip.resetDuration();
  16621. return clip;
  16622. }
  16623. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  16624. if ( fps <= 0 ) fps = 30;
  16625. const numTracks = referenceClip.tracks.length;
  16626. const referenceTime = referenceFrame / fps;
  16627. // Make each track's values relative to the values at the reference frame
  16628. for ( let i = 0; i < numTracks; ++ i ) {
  16629. const referenceTrack = referenceClip.tracks[ i ];
  16630. const referenceTrackType = referenceTrack.ValueTypeName;
  16631. // Skip this track if it's non-numeric
  16632. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  16633. // Find the track in the target clip whose name and type matches the reference track
  16634. const targetTrack = targetClip.tracks.find( function ( track ) {
  16635. return track.name === referenceTrack.name
  16636. && track.ValueTypeName === referenceTrackType;
  16637. } );
  16638. if ( targetTrack === undefined ) continue;
  16639. let referenceOffset = 0;
  16640. const referenceValueSize = referenceTrack.getValueSize();
  16641. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  16642. referenceOffset = referenceValueSize / 3;
  16643. }
  16644. let targetOffset = 0;
  16645. const targetValueSize = targetTrack.getValueSize();
  16646. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  16647. targetOffset = targetValueSize / 3;
  16648. }
  16649. const lastIndex = referenceTrack.times.length - 1;
  16650. let referenceValue;
  16651. // Find the value to subtract out of the track
  16652. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  16653. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  16654. const startIndex = referenceOffset;
  16655. const endIndex = referenceValueSize - referenceOffset;
  16656. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  16657. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  16658. // Reference frame is after the last keyframe, so just use the last keyframe
  16659. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  16660. const endIndex = startIndex + referenceValueSize - referenceOffset;
  16661. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  16662. } else {
  16663. // Interpolate to the reference value
  16664. const interpolant = referenceTrack.createInterpolant();
  16665. const startIndex = referenceOffset;
  16666. const endIndex = referenceValueSize - referenceOffset;
  16667. interpolant.evaluate( referenceTime );
  16668. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  16669. }
  16670. // Conjugate the quaternion
  16671. if ( referenceTrackType === 'quaternion' ) {
  16672. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  16673. referenceQuat.toArray( referenceValue );
  16674. }
  16675. // Subtract the reference value from all of the track values
  16676. const numTimes = targetTrack.times.length;
  16677. for ( let j = 0; j < numTimes; ++ j ) {
  16678. const valueStart = j * targetValueSize + targetOffset;
  16679. if ( referenceTrackType === 'quaternion' ) {
  16680. // Multiply the conjugate for quaternion track types
  16681. Quaternion.multiplyQuaternionsFlat(
  16682. targetTrack.values,
  16683. valueStart,
  16684. referenceValue,
  16685. 0,
  16686. targetTrack.values,
  16687. valueStart
  16688. );
  16689. } else {
  16690. const valueEnd = targetValueSize - targetOffset * 2;
  16691. // Subtract each value for all other numeric track types
  16692. for ( let k = 0; k < valueEnd; ++ k ) {
  16693. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  16694. }
  16695. }
  16696. }
  16697. }
  16698. targetClip.blendMode = AdditiveAnimationBlendMode;
  16699. return targetClip;
  16700. }
  16701. const AnimationUtils = {
  16702. convertArray: convertArray,
  16703. isTypedArray: isTypedArray,
  16704. getKeyframeOrder: getKeyframeOrder,
  16705. sortedArray: sortedArray,
  16706. flattenJSON: flattenJSON,
  16707. subclip: subclip,
  16708. makeClipAdditive: makeClipAdditive
  16709. };
  16710. /**
  16711. * Abstract base class of interpolants over parametric samples.
  16712. *
  16713. * The parameter domain is one dimensional, typically the time or a path
  16714. * along a curve defined by the data.
  16715. *
  16716. * The sample values can have any dimensionality and derived classes may
  16717. * apply special interpretations to the data.
  16718. *
  16719. * This class provides the interval seek in a Template Method, deferring
  16720. * the actual interpolation to derived classes.
  16721. *
  16722. * Time complexity is O(1) for linear access crossing at most two points
  16723. * and O(log N) for random access, where N is the number of positions.
  16724. *
  16725. * References:
  16726. *
  16727. * http://www.oodesign.com/template-method-pattern.html
  16728. *
  16729. */
  16730. class Interpolant {
  16731. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  16732. this.parameterPositions = parameterPositions;
  16733. this._cachedIndex = 0;
  16734. this.resultBuffer = resultBuffer !== undefined ?
  16735. resultBuffer : new sampleValues.constructor( sampleSize );
  16736. this.sampleValues = sampleValues;
  16737. this.valueSize = sampleSize;
  16738. this.settings = null;
  16739. this.DefaultSettings_ = {};
  16740. }
  16741. evaluate( t ) {
  16742. const pp = this.parameterPositions;
  16743. let i1 = this._cachedIndex,
  16744. t1 = pp[ i1 ],
  16745. t0 = pp[ i1 - 1 ];
  16746. validate_interval: {
  16747. seek: {
  16748. let right;
  16749. linear_scan: {
  16750. //- See http://jsperf.com/comparison-to-undefined/3
  16751. //- slower code:
  16752. //-
  16753. //- if ( t >= t1 || t1 === undefined ) {
  16754. forward_scan: if ( ! ( t < t1 ) ) {
  16755. for ( let giveUpAt = i1 + 2; ; ) {
  16756. if ( t1 === undefined ) {
  16757. if ( t < t0 ) break forward_scan;
  16758. // after end
  16759. i1 = pp.length;
  16760. this._cachedIndex = i1;
  16761. return this.copySampleValue_( i1 - 1 );
  16762. }
  16763. if ( i1 === giveUpAt ) break; // this loop
  16764. t0 = t1;
  16765. t1 = pp[ ++ i1 ];
  16766. if ( t < t1 ) {
  16767. // we have arrived at the sought interval
  16768. break seek;
  16769. }
  16770. }
  16771. // prepare binary search on the right side of the index
  16772. right = pp.length;
  16773. break linear_scan;
  16774. }
  16775. //- slower code:
  16776. //- if ( t < t0 || t0 === undefined ) {
  16777. if ( ! ( t >= t0 ) ) {
  16778. // looping?
  16779. const t1global = pp[ 1 ];
  16780. if ( t < t1global ) {
  16781. i1 = 2; // + 1, using the scan for the details
  16782. t0 = t1global;
  16783. }
  16784. // linear reverse scan
  16785. for ( let giveUpAt = i1 - 2; ; ) {
  16786. if ( t0 === undefined ) {
  16787. // before start
  16788. this._cachedIndex = 0;
  16789. return this.copySampleValue_( 0 );
  16790. }
  16791. if ( i1 === giveUpAt ) break; // this loop
  16792. t1 = t0;
  16793. t0 = pp[ -- i1 - 1 ];
  16794. if ( t >= t0 ) {
  16795. // we have arrived at the sought interval
  16796. break seek;
  16797. }
  16798. }
  16799. // prepare binary search on the left side of the index
  16800. right = i1;
  16801. i1 = 0;
  16802. break linear_scan;
  16803. }
  16804. // the interval is valid
  16805. break validate_interval;
  16806. } // linear scan
  16807. // binary search
  16808. while ( i1 < right ) {
  16809. const mid = ( i1 + right ) >>> 1;
  16810. if ( t < pp[ mid ] ) {
  16811. right = mid;
  16812. } else {
  16813. i1 = mid + 1;
  16814. }
  16815. }
  16816. t1 = pp[ i1 ];
  16817. t0 = pp[ i1 - 1 ];
  16818. // check boundary cases, again
  16819. if ( t0 === undefined ) {
  16820. this._cachedIndex = 0;
  16821. return this.copySampleValue_( 0 );
  16822. }
  16823. if ( t1 === undefined ) {
  16824. i1 = pp.length;
  16825. this._cachedIndex = i1;
  16826. return this.copySampleValue_( i1 - 1 );
  16827. }
  16828. } // seek
  16829. this._cachedIndex = i1;
  16830. this.intervalChanged_( i1, t0, t1 );
  16831. } // validate_interval
  16832. return this.interpolate_( i1, t0, t, t1 );
  16833. }
  16834. getSettings_() {
  16835. return this.settings || this.DefaultSettings_;
  16836. }
  16837. copySampleValue_( index ) {
  16838. // copies a sample value to the result buffer
  16839. const result = this.resultBuffer,
  16840. values = this.sampleValues,
  16841. stride = this.valueSize,
  16842. offset = index * stride;
  16843. for ( let i = 0; i !== stride; ++ i ) {
  16844. result[ i ] = values[ offset + i ];
  16845. }
  16846. return result;
  16847. }
  16848. // Template methods for derived classes:
  16849. interpolate_( /* i1, t0, t, t1 */ ) {
  16850. throw new Error( 'call to abstract method' );
  16851. // implementations shall return this.resultBuffer
  16852. }
  16853. intervalChanged_( /* i1, t0, t1 */ ) {
  16854. // empty
  16855. }
  16856. }
  16857. /**
  16858. * Fast and simple cubic spline interpolant.
  16859. *
  16860. * It was derived from a Hermitian construction setting the first derivative
  16861. * at each sample position to the linear slope between neighboring positions
  16862. * over their parameter interval.
  16863. */
  16864. class CubicInterpolant extends Interpolant {
  16865. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  16866. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  16867. this._weightPrev = -0;
  16868. this._offsetPrev = -0;
  16869. this._weightNext = -0;
  16870. this._offsetNext = -0;
  16871. this.DefaultSettings_ = {
  16872. endingStart: ZeroCurvatureEnding,
  16873. endingEnd: ZeroCurvatureEnding
  16874. };
  16875. }
  16876. intervalChanged_( i1, t0, t1 ) {
  16877. const pp = this.parameterPositions;
  16878. let iPrev = i1 - 2,
  16879. iNext = i1 + 1,
  16880. tPrev = pp[ iPrev ],
  16881. tNext = pp[ iNext ];
  16882. if ( tPrev === undefined ) {
  16883. switch ( this.getSettings_().endingStart ) {
  16884. case ZeroSlopeEnding:
  16885. // f'(t0) = 0
  16886. iPrev = i1;
  16887. tPrev = 2 * t0 - t1;
  16888. break;
  16889. case WrapAroundEnding:
  16890. // use the other end of the curve
  16891. iPrev = pp.length - 2;
  16892. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  16893. break;
  16894. default: // ZeroCurvatureEnding
  16895. // f''(t0) = 0 a.k.a. Natural Spline
  16896. iPrev = i1;
  16897. tPrev = t1;
  16898. }
  16899. }
  16900. if ( tNext === undefined ) {
  16901. switch ( this.getSettings_().endingEnd ) {
  16902. case ZeroSlopeEnding:
  16903. // f'(tN) = 0
  16904. iNext = i1;
  16905. tNext = 2 * t1 - t0;
  16906. break;
  16907. case WrapAroundEnding:
  16908. // use the other end of the curve
  16909. iNext = 1;
  16910. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  16911. break;
  16912. default: // ZeroCurvatureEnding
  16913. // f''(tN) = 0, a.k.a. Natural Spline
  16914. iNext = i1 - 1;
  16915. tNext = t0;
  16916. }
  16917. }
  16918. const halfDt = ( t1 - t0 ) * 0.5,
  16919. stride = this.valueSize;
  16920. this._weightPrev = halfDt / ( t0 - tPrev );
  16921. this._weightNext = halfDt / ( tNext - t1 );
  16922. this._offsetPrev = iPrev * stride;
  16923. this._offsetNext = iNext * stride;
  16924. }
  16925. interpolate_( i1, t0, t, t1 ) {
  16926. const result = this.resultBuffer,
  16927. values = this.sampleValues,
  16928. stride = this.valueSize,
  16929. o1 = i1 * stride, o0 = o1 - stride,
  16930. oP = this._offsetPrev, oN = this._offsetNext,
  16931. wP = this._weightPrev, wN = this._weightNext,
  16932. p = ( t - t0 ) / ( t1 - t0 ),
  16933. pp = p * p,
  16934. ppp = pp * p;
  16935. // evaluate polynomials
  16936. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  16937. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  16938. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  16939. const sN = wN * ppp - wN * pp;
  16940. // combine data linearly
  16941. for ( let i = 0; i !== stride; ++ i ) {
  16942. result[ i ] =
  16943. sP * values[ oP + i ] +
  16944. s0 * values[ o0 + i ] +
  16945. s1 * values[ o1 + i ] +
  16946. sN * values[ oN + i ];
  16947. }
  16948. return result;
  16949. }
  16950. }
  16951. class LinearInterpolant extends Interpolant {
  16952. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  16953. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  16954. }
  16955. interpolate_( i1, t0, t, t1 ) {
  16956. const result = this.resultBuffer,
  16957. values = this.sampleValues,
  16958. stride = this.valueSize,
  16959. offset1 = i1 * stride,
  16960. offset0 = offset1 - stride,
  16961. weight1 = ( t - t0 ) / ( t1 - t0 ),
  16962. weight0 = 1 - weight1;
  16963. for ( let i = 0; i !== stride; ++ i ) {
  16964. result[ i ] =
  16965. values[ offset0 + i ] * weight0 +
  16966. values[ offset1 + i ] * weight1;
  16967. }
  16968. return result;
  16969. }
  16970. }
  16971. /**
  16972. *
  16973. * Interpolant that evaluates to the sample value at the position preceding
  16974. * the parameter.
  16975. */
  16976. class DiscreteInterpolant extends Interpolant {
  16977. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  16978. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  16979. }
  16980. interpolate_( i1 /*, t0, t, t1 */ ) {
  16981. return this.copySampleValue_( i1 - 1 );
  16982. }
  16983. }
  16984. class KeyframeTrack {
  16985. constructor( name, times, values, interpolation ) {
  16986. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  16987. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  16988. this.name = name;
  16989. this.times = convertArray( times, this.TimeBufferType );
  16990. this.values = convertArray( values, this.ValueBufferType );
  16991. this.setInterpolation( interpolation || this.DefaultInterpolation );
  16992. }
  16993. // Serialization (in static context, because of constructor invocation
  16994. // and automatic invocation of .toJSON):
  16995. static toJSON( track ) {
  16996. const trackType = track.constructor;
  16997. let json;
  16998. // derived classes can define a static toJSON method
  16999. if ( trackType.toJSON !== this.toJSON ) {
  17000. json = trackType.toJSON( track );
  17001. } else {
  17002. // by default, we assume the data can be serialized as-is
  17003. json = {
  17004. 'name': track.name,
  17005. 'times': convertArray( track.times, Array ),
  17006. 'values': convertArray( track.values, Array )
  17007. };
  17008. const interpolation = track.getInterpolation();
  17009. if ( interpolation !== track.DefaultInterpolation ) {
  17010. json.interpolation = interpolation;
  17011. }
  17012. }
  17013. json.type = track.ValueTypeName; // mandatory
  17014. return json;
  17015. }
  17016. InterpolantFactoryMethodDiscrete( result ) {
  17017. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  17018. }
  17019. InterpolantFactoryMethodLinear( result ) {
  17020. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  17021. }
  17022. InterpolantFactoryMethodSmooth( result ) {
  17023. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  17024. }
  17025. setInterpolation( interpolation ) {
  17026. let factoryMethod;
  17027. switch ( interpolation ) {
  17028. case InterpolateDiscrete:
  17029. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  17030. break;
  17031. case InterpolateLinear:
  17032. factoryMethod = this.InterpolantFactoryMethodLinear;
  17033. break;
  17034. case InterpolateSmooth:
  17035. factoryMethod = this.InterpolantFactoryMethodSmooth;
  17036. break;
  17037. }
  17038. if ( factoryMethod === undefined ) {
  17039. const message = 'unsupported interpolation for ' +
  17040. this.ValueTypeName + ' keyframe track named ' + this.name;
  17041. if ( this.createInterpolant === undefined ) {
  17042. // fall back to default, unless the default itself is messed up
  17043. if ( interpolation !== this.DefaultInterpolation ) {
  17044. this.setInterpolation( this.DefaultInterpolation );
  17045. } else {
  17046. throw new Error( message ); // fatal, in this case
  17047. }
  17048. }
  17049. console.warn( 'THREE.KeyframeTrack:', message );
  17050. return this;
  17051. }
  17052. this.createInterpolant = factoryMethod;
  17053. return this;
  17054. }
  17055. getInterpolation() {
  17056. switch ( this.createInterpolant ) {
  17057. case this.InterpolantFactoryMethodDiscrete:
  17058. return InterpolateDiscrete;
  17059. case this.InterpolantFactoryMethodLinear:
  17060. return InterpolateLinear;
  17061. case this.InterpolantFactoryMethodSmooth:
  17062. return InterpolateSmooth;
  17063. }
  17064. }
  17065. getValueSize() {
  17066. return this.values.length / this.times.length;
  17067. }
  17068. // move all keyframes either forwards or backwards in time
  17069. shift( timeOffset ) {
  17070. if ( timeOffset !== 0.0 ) {
  17071. const times = this.times;
  17072. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  17073. times[ i ] += timeOffset;
  17074. }
  17075. }
  17076. return this;
  17077. }
  17078. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  17079. scale( timeScale ) {
  17080. if ( timeScale !== 1.0 ) {
  17081. const times = this.times;
  17082. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  17083. times[ i ] *= timeScale;
  17084. }
  17085. }
  17086. return this;
  17087. }
  17088. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  17089. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  17090. trim( startTime, endTime ) {
  17091. const times = this.times,
  17092. nKeys = times.length;
  17093. let from = 0,
  17094. to = nKeys - 1;
  17095. while ( from !== nKeys && times[ from ] < startTime ) {
  17096. ++ from;
  17097. }
  17098. while ( to !== -1 && times[ to ] > endTime ) {
  17099. -- to;
  17100. }
  17101. ++ to; // inclusive -> exclusive bound
  17102. if ( from !== 0 || to !== nKeys ) {
  17103. // empty tracks are forbidden, so keep at least one keyframe
  17104. if ( from >= to ) {
  17105. to = Math.max( to, 1 );
  17106. from = to - 1;
  17107. }
  17108. const stride = this.getValueSize();
  17109. this.times = times.slice( from, to );
  17110. this.values = this.values.slice( from * stride, to * stride );
  17111. }
  17112. return this;
  17113. }
  17114. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  17115. validate() {
  17116. let valid = true;
  17117. const valueSize = this.getValueSize();
  17118. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  17119. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  17120. valid = false;
  17121. }
  17122. const times = this.times,
  17123. values = this.values,
  17124. nKeys = times.length;
  17125. if ( nKeys === 0 ) {
  17126. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  17127. valid = false;
  17128. }
  17129. let prevTime = null;
  17130. for ( let i = 0; i !== nKeys; i ++ ) {
  17131. const currTime = times[ i ];
  17132. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  17133. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  17134. valid = false;
  17135. break;
  17136. }
  17137. if ( prevTime !== null && prevTime > currTime ) {
  17138. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  17139. valid = false;
  17140. break;
  17141. }
  17142. prevTime = currTime;
  17143. }
  17144. if ( values !== undefined ) {
  17145. if ( isTypedArray( values ) ) {
  17146. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  17147. const value = values[ i ];
  17148. if ( isNaN( value ) ) {
  17149. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  17150. valid = false;
  17151. break;
  17152. }
  17153. }
  17154. }
  17155. }
  17156. return valid;
  17157. }
  17158. // removes equivalent sequential keys as common in morph target sequences
  17159. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  17160. optimize() {
  17161. // times or values may be shared with other tracks, so overwriting is unsafe
  17162. const times = this.times.slice(),
  17163. values = this.values.slice(),
  17164. stride = this.getValueSize(),
  17165. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  17166. lastIndex = times.length - 1;
  17167. let writeIndex = 1;
  17168. for ( let i = 1; i < lastIndex; ++ i ) {
  17169. let keep = false;
  17170. const time = times[ i ];
  17171. const timeNext = times[ i + 1 ];
  17172. // remove adjacent keyframes scheduled at the same time
  17173. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  17174. if ( ! smoothInterpolation ) {
  17175. // remove unnecessary keyframes same as their neighbors
  17176. const offset = i * stride,
  17177. offsetP = offset - stride,
  17178. offsetN = offset + stride;
  17179. for ( let j = 0; j !== stride; ++ j ) {
  17180. const value = values[ offset + j ];
  17181. if ( value !== values[ offsetP + j ] ||
  17182. value !== values[ offsetN + j ] ) {
  17183. keep = true;
  17184. break;
  17185. }
  17186. }
  17187. } else {
  17188. keep = true;
  17189. }
  17190. }
  17191. // in-place compaction
  17192. if ( keep ) {
  17193. if ( i !== writeIndex ) {
  17194. times[ writeIndex ] = times[ i ];
  17195. const readOffset = i * stride,
  17196. writeOffset = writeIndex * stride;
  17197. for ( let j = 0; j !== stride; ++ j ) {
  17198. values[ writeOffset + j ] = values[ readOffset + j ];
  17199. }
  17200. }
  17201. ++ writeIndex;
  17202. }
  17203. }
  17204. // flush last keyframe (compaction looks ahead)
  17205. if ( lastIndex > 0 ) {
  17206. times[ writeIndex ] = times[ lastIndex ];
  17207. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  17208. values[ writeOffset + j ] = values[ readOffset + j ];
  17209. }
  17210. ++ writeIndex;
  17211. }
  17212. if ( writeIndex !== times.length ) {
  17213. this.times = times.slice( 0, writeIndex );
  17214. this.values = values.slice( 0, writeIndex * stride );
  17215. } else {
  17216. this.times = times;
  17217. this.values = values;
  17218. }
  17219. return this;
  17220. }
  17221. clone() {
  17222. const times = this.times.slice();
  17223. const values = this.values.slice();
  17224. const TypedKeyframeTrack = this.constructor;
  17225. const track = new TypedKeyframeTrack( this.name, times, values );
  17226. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  17227. track.createInterpolant = this.createInterpolant;
  17228. return track;
  17229. }
  17230. }
  17231. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  17232. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  17233. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  17234. /**
  17235. * A Track of Boolean keyframe values.
  17236. */
  17237. class BooleanKeyframeTrack extends KeyframeTrack {
  17238. // No interpolation parameter because only InterpolateDiscrete is valid.
  17239. constructor( name, times, values ) {
  17240. super( name, times, values );
  17241. }
  17242. }
  17243. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  17244. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  17245. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  17246. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  17247. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  17248. /**
  17249. * A Track of keyframe values that represent color.
  17250. */
  17251. class ColorKeyframeTrack extends KeyframeTrack {}
  17252. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  17253. /**
  17254. * A Track of numeric keyframe values.
  17255. */
  17256. class NumberKeyframeTrack extends KeyframeTrack {}
  17257. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  17258. /**
  17259. * Spherical linear unit quaternion interpolant.
  17260. */
  17261. class QuaternionLinearInterpolant extends Interpolant {
  17262. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  17263. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  17264. }
  17265. interpolate_( i1, t0, t, t1 ) {
  17266. const result = this.resultBuffer,
  17267. values = this.sampleValues,
  17268. stride = this.valueSize,
  17269. alpha = ( t - t0 ) / ( t1 - t0 );
  17270. let offset = i1 * stride;
  17271. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  17272. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  17273. }
  17274. return result;
  17275. }
  17276. }
  17277. /**
  17278. * A Track of quaternion keyframe values.
  17279. */
  17280. class QuaternionKeyframeTrack extends KeyframeTrack {
  17281. InterpolantFactoryMethodLinear( result ) {
  17282. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  17283. }
  17284. }
  17285. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  17286. // ValueBufferType is inherited
  17287. // DefaultInterpolation is inherited;
  17288. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  17289. /**
  17290. * A Track that interpolates Strings
  17291. */
  17292. class StringKeyframeTrack extends KeyframeTrack {
  17293. // No interpolation parameter because only InterpolateDiscrete is valid.
  17294. constructor( name, times, values ) {
  17295. super( name, times, values );
  17296. }
  17297. }
  17298. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  17299. StringKeyframeTrack.prototype.ValueBufferType = Array;
  17300. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  17301. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  17302. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  17303. /**
  17304. * A Track of vectored keyframe values.
  17305. */
  17306. class VectorKeyframeTrack extends KeyframeTrack {}
  17307. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  17308. class AnimationClip {
  17309. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  17310. this.name = name;
  17311. this.tracks = tracks;
  17312. this.duration = duration;
  17313. this.blendMode = blendMode;
  17314. this.uuid = generateUUID();
  17315. // this means it should figure out its duration by scanning the tracks
  17316. if ( this.duration < 0 ) {
  17317. this.resetDuration();
  17318. }
  17319. }
  17320. static parse( json ) {
  17321. const tracks = [],
  17322. jsonTracks = json.tracks,
  17323. frameTime = 1.0 / ( json.fps || 1.0 );
  17324. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  17325. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  17326. }
  17327. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  17328. clip.uuid = json.uuid;
  17329. return clip;
  17330. }
  17331. static toJSON( clip ) {
  17332. const tracks = [],
  17333. clipTracks = clip.tracks;
  17334. const json = {
  17335. 'name': clip.name,
  17336. 'duration': clip.duration,
  17337. 'tracks': tracks,
  17338. 'uuid': clip.uuid,
  17339. 'blendMode': clip.blendMode
  17340. };
  17341. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  17342. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  17343. }
  17344. return json;
  17345. }
  17346. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  17347. const numMorphTargets = morphTargetSequence.length;
  17348. const tracks = [];
  17349. for ( let i = 0; i < numMorphTargets; i ++ ) {
  17350. let times = [];
  17351. let values = [];
  17352. times.push(
  17353. ( i + numMorphTargets - 1 ) % numMorphTargets,
  17354. i,
  17355. ( i + 1 ) % numMorphTargets );
  17356. values.push( 0, 1, 0 );
  17357. const order = getKeyframeOrder( times );
  17358. times = sortedArray( times, 1, order );
  17359. values = sortedArray( values, 1, order );
  17360. // if there is a key at the first frame, duplicate it as the
  17361. // last frame as well for perfect loop.
  17362. if ( ! noLoop && times[ 0 ] === 0 ) {
  17363. times.push( numMorphTargets );
  17364. values.push( values[ 0 ] );
  17365. }
  17366. tracks.push(
  17367. new NumberKeyframeTrack(
  17368. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  17369. times, values
  17370. ).scale( 1.0 / fps ) );
  17371. }
  17372. return new this( name, -1, tracks );
  17373. }
  17374. static findByName( objectOrClipArray, name ) {
  17375. let clipArray = objectOrClipArray;
  17376. if ( ! Array.isArray( objectOrClipArray ) ) {
  17377. const o = objectOrClipArray;
  17378. clipArray = o.geometry && o.geometry.animations || o.animations;
  17379. }
  17380. for ( let i = 0; i < clipArray.length; i ++ ) {
  17381. if ( clipArray[ i ].name === name ) {
  17382. return clipArray[ i ];
  17383. }
  17384. }
  17385. return null;
  17386. }
  17387. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  17388. const animationToMorphTargets = {};
  17389. // tested with https://regex101.com/ on trick sequences
  17390. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  17391. const pattern = /^([\w-]*?)([\d]+)$/;
  17392. // sort morph target names into animation groups based
  17393. // patterns like Walk_001, Walk_002, Run_001, Run_002
  17394. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  17395. const morphTarget = morphTargets[ i ];
  17396. const parts = morphTarget.name.match( pattern );
  17397. if ( parts && parts.length > 1 ) {
  17398. const name = parts[ 1 ];
  17399. let animationMorphTargets = animationToMorphTargets[ name ];
  17400. if ( ! animationMorphTargets ) {
  17401. animationToMorphTargets[ name ] = animationMorphTargets = [];
  17402. }
  17403. animationMorphTargets.push( morphTarget );
  17404. }
  17405. }
  17406. const clips = [];
  17407. for ( const name in animationToMorphTargets ) {
  17408. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  17409. }
  17410. return clips;
  17411. }
  17412. // parse the animation.hierarchy format
  17413. static parseAnimation( animation, bones ) {
  17414. if ( ! animation ) {
  17415. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  17416. return null;
  17417. }
  17418. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  17419. // only return track if there are actually keys.
  17420. if ( animationKeys.length !== 0 ) {
  17421. const times = [];
  17422. const values = [];
  17423. flattenJSON( animationKeys, times, values, propertyName );
  17424. // empty keys are filtered out, so check again
  17425. if ( times.length !== 0 ) {
  17426. destTracks.push( new trackType( trackName, times, values ) );
  17427. }
  17428. }
  17429. };
  17430. const tracks = [];
  17431. const clipName = animation.name || 'default';
  17432. const fps = animation.fps || 30;
  17433. const blendMode = animation.blendMode;
  17434. // automatic length determination in AnimationClip.
  17435. let duration = animation.length || -1;
  17436. const hierarchyTracks = animation.hierarchy || [];
  17437. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  17438. const animationKeys = hierarchyTracks[ h ].keys;
  17439. // skip empty tracks
  17440. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  17441. // process morph targets
  17442. if ( animationKeys[ 0 ].morphTargets ) {
  17443. // figure out all morph targets used in this track
  17444. const morphTargetNames = {};
  17445. let k;
  17446. for ( k = 0; k < animationKeys.length; k ++ ) {
  17447. if ( animationKeys[ k ].morphTargets ) {
  17448. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  17449. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  17450. }
  17451. }
  17452. }
  17453. // create a track for each morph target with all zero
  17454. // morphTargetInfluences except for the keys in which
  17455. // the morphTarget is named.
  17456. for ( const morphTargetName in morphTargetNames ) {
  17457. const times = [];
  17458. const values = [];
  17459. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  17460. const animationKey = animationKeys[ k ];
  17461. times.push( animationKey.time );
  17462. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  17463. }
  17464. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  17465. }
  17466. duration = morphTargetNames.length * fps;
  17467. } else {
  17468. // ...assume skeletal animation
  17469. const boneName = '.bones[' + bones[ h ].name + ']';
  17470. addNonemptyTrack(
  17471. VectorKeyframeTrack, boneName + '.position',
  17472. animationKeys, 'pos', tracks );
  17473. addNonemptyTrack(
  17474. QuaternionKeyframeTrack, boneName + '.quaternion',
  17475. animationKeys, 'rot', tracks );
  17476. addNonemptyTrack(
  17477. VectorKeyframeTrack, boneName + '.scale',
  17478. animationKeys, 'scl', tracks );
  17479. }
  17480. }
  17481. if ( tracks.length === 0 ) {
  17482. return null;
  17483. }
  17484. const clip = new this( clipName, duration, tracks, blendMode );
  17485. return clip;
  17486. }
  17487. resetDuration() {
  17488. const tracks = this.tracks;
  17489. let duration = 0;
  17490. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  17491. const track = this.tracks[ i ];
  17492. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  17493. }
  17494. this.duration = duration;
  17495. return this;
  17496. }
  17497. trim() {
  17498. for ( let i = 0; i < this.tracks.length; i ++ ) {
  17499. this.tracks[ i ].trim( 0, this.duration );
  17500. }
  17501. return this;
  17502. }
  17503. validate() {
  17504. let valid = true;
  17505. for ( let i = 0; i < this.tracks.length; i ++ ) {
  17506. valid = valid && this.tracks[ i ].validate();
  17507. }
  17508. return valid;
  17509. }
  17510. optimize() {
  17511. for ( let i = 0; i < this.tracks.length; i ++ ) {
  17512. this.tracks[ i ].optimize();
  17513. }
  17514. return this;
  17515. }
  17516. clone() {
  17517. const tracks = [];
  17518. for ( let i = 0; i < this.tracks.length; i ++ ) {
  17519. tracks.push( this.tracks[ i ].clone() );
  17520. }
  17521. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  17522. }
  17523. toJSON() {
  17524. return this.constructor.toJSON( this );
  17525. }
  17526. }
  17527. function getTrackTypeForValueTypeName( typeName ) {
  17528. switch ( typeName.toLowerCase() ) {
  17529. case 'scalar':
  17530. case 'double':
  17531. case 'float':
  17532. case 'number':
  17533. case 'integer':
  17534. return NumberKeyframeTrack;
  17535. case 'vector':
  17536. case 'vector2':
  17537. case 'vector3':
  17538. case 'vector4':
  17539. return VectorKeyframeTrack;
  17540. case 'color':
  17541. return ColorKeyframeTrack;
  17542. case 'quaternion':
  17543. return QuaternionKeyframeTrack;
  17544. case 'bool':
  17545. case 'boolean':
  17546. return BooleanKeyframeTrack;
  17547. case 'string':
  17548. return StringKeyframeTrack;
  17549. }
  17550. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  17551. }
  17552. function parseKeyframeTrack( json ) {
  17553. if ( json.type === undefined ) {
  17554. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  17555. }
  17556. const trackType = getTrackTypeForValueTypeName( json.type );
  17557. if ( json.times === undefined ) {
  17558. const times = [], values = [];
  17559. flattenJSON( json.keys, times, values, 'value' );
  17560. json.times = times;
  17561. json.values = values;
  17562. }
  17563. // derived classes can define a static parse method
  17564. if ( trackType.parse !== undefined ) {
  17565. return trackType.parse( json );
  17566. } else {
  17567. // by default, we assume a constructor compatible with the base
  17568. return new trackType( json.name, json.times, json.values, json.interpolation );
  17569. }
  17570. }
  17571. const Cache = {
  17572. enabled: false,
  17573. files: {},
  17574. add: function ( key, file ) {
  17575. if ( this.enabled === false ) return;
  17576. // console.log( 'THREE.Cache', 'Adding key:', key );
  17577. this.files[ key ] = file;
  17578. },
  17579. get: function ( key ) {
  17580. if ( this.enabled === false ) return;
  17581. // console.log( 'THREE.Cache', 'Checking key:', key );
  17582. return this.files[ key ];
  17583. },
  17584. remove: function ( key ) {
  17585. delete this.files[ key ];
  17586. },
  17587. clear: function () {
  17588. this.files = {};
  17589. }
  17590. };
  17591. class LoadingManager {
  17592. constructor( onLoad, onProgress, onError ) {
  17593. const scope = this;
  17594. let isLoading = false;
  17595. let itemsLoaded = 0;
  17596. let itemsTotal = 0;
  17597. let urlModifier = undefined;
  17598. const handlers = [];
  17599. // Refer to #5689 for the reason why we don't set .onStart
  17600. // in the constructor
  17601. this.onStart = undefined;
  17602. this.onLoad = onLoad;
  17603. this.onProgress = onProgress;
  17604. this.onError = onError;
  17605. this.itemStart = function ( url ) {
  17606. itemsTotal ++;
  17607. if ( isLoading === false ) {
  17608. if ( scope.onStart !== undefined ) {
  17609. scope.onStart( url, itemsLoaded, itemsTotal );
  17610. }
  17611. }
  17612. isLoading = true;
  17613. };
  17614. this.itemEnd = function ( url ) {
  17615. itemsLoaded ++;
  17616. if ( scope.onProgress !== undefined ) {
  17617. scope.onProgress( url, itemsLoaded, itemsTotal );
  17618. }
  17619. if ( itemsLoaded === itemsTotal ) {
  17620. isLoading = false;
  17621. if ( scope.onLoad !== undefined ) {
  17622. scope.onLoad();
  17623. }
  17624. }
  17625. };
  17626. this.itemError = function ( url ) {
  17627. if ( scope.onError !== undefined ) {
  17628. scope.onError( url );
  17629. }
  17630. };
  17631. this.resolveURL = function ( url ) {
  17632. if ( urlModifier ) {
  17633. return urlModifier( url );
  17634. }
  17635. return url;
  17636. };
  17637. this.setURLModifier = function ( transform ) {
  17638. urlModifier = transform;
  17639. return this;
  17640. };
  17641. this.addHandler = function ( regex, loader ) {
  17642. handlers.push( regex, loader );
  17643. return this;
  17644. };
  17645. this.removeHandler = function ( regex ) {
  17646. const index = handlers.indexOf( regex );
  17647. if ( index !== -1 ) {
  17648. handlers.splice( index, 2 );
  17649. }
  17650. return this;
  17651. };
  17652. this.getHandler = function ( file ) {
  17653. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  17654. const regex = handlers[ i ];
  17655. const loader = handlers[ i + 1 ];
  17656. if ( regex.global ) regex.lastIndex = 0; // see #17920
  17657. if ( regex.test( file ) ) {
  17658. return loader;
  17659. }
  17660. }
  17661. return null;
  17662. };
  17663. }
  17664. }
  17665. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  17666. class Loader {
  17667. constructor( manager ) {
  17668. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  17669. this.crossOrigin = 'anonymous';
  17670. this.withCredentials = false;
  17671. this.path = '';
  17672. this.resourcePath = '';
  17673. this.requestHeader = {};
  17674. }
  17675. load( /* url, onLoad, onProgress, onError */ ) {}
  17676. loadAsync( url, onProgress ) {
  17677. const scope = this;
  17678. return new Promise( function ( resolve, reject ) {
  17679. scope.load( url, resolve, onProgress, reject );
  17680. } );
  17681. }
  17682. parse( /* data */ ) {}
  17683. setCrossOrigin( crossOrigin ) {
  17684. this.crossOrigin = crossOrigin;
  17685. return this;
  17686. }
  17687. setWithCredentials( value ) {
  17688. this.withCredentials = value;
  17689. return this;
  17690. }
  17691. setPath( path ) {
  17692. this.path = path;
  17693. return this;
  17694. }
  17695. setResourcePath( resourcePath ) {
  17696. this.resourcePath = resourcePath;
  17697. return this;
  17698. }
  17699. setRequestHeader( requestHeader ) {
  17700. this.requestHeader = requestHeader;
  17701. return this;
  17702. }
  17703. }
  17704. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  17705. const loading = {};
  17706. class HttpError extends Error {
  17707. constructor( message, response ) {
  17708. super( message );
  17709. this.response = response;
  17710. }
  17711. }
  17712. class FileLoader extends Loader {
  17713. constructor( manager ) {
  17714. super( manager );
  17715. }
  17716. load( url, onLoad, onProgress, onError ) {
  17717. if ( url === undefined ) url = '';
  17718. if ( this.path !== undefined ) url = this.path + url;
  17719. url = this.manager.resolveURL( url );
  17720. const cached = Cache.get( url );
  17721. if ( cached !== undefined ) {
  17722. this.manager.itemStart( url );
  17723. setTimeout( () => {
  17724. if ( onLoad ) onLoad( cached );
  17725. this.manager.itemEnd( url );
  17726. }, 0 );
  17727. return cached;
  17728. }
  17729. // Check if request is duplicate
  17730. if ( loading[ url ] !== undefined ) {
  17731. loading[ url ].push( {
  17732. onLoad: onLoad,
  17733. onProgress: onProgress,
  17734. onError: onError
  17735. } );
  17736. return;
  17737. }
  17738. // Initialise array for duplicate requests
  17739. loading[ url ] = [];
  17740. loading[ url ].push( {
  17741. onLoad: onLoad,
  17742. onProgress: onProgress,
  17743. onError: onError,
  17744. } );
  17745. // create request
  17746. const req = new Request( url, {
  17747. headers: new Headers( this.requestHeader ),
  17748. credentials: this.withCredentials ? 'include' : 'same-origin',
  17749. // An abort controller could be added within a future PR
  17750. } );
  17751. // record states ( avoid data race )
  17752. const mimeType = this.mimeType;
  17753. const responseType = this.responseType;
  17754. // start the fetch
  17755. fetch( req )
  17756. .then( response => {
  17757. if ( response.status === 200 || response.status === 0 ) {
  17758. // Some browsers return HTTP Status 0 when using non-http protocol
  17759. // e.g. 'file://' or 'data://'. Handle as success.
  17760. if ( response.status === 0 ) {
  17761. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  17762. }
  17763. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  17764. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  17765. return response;
  17766. }
  17767. const callbacks = loading[ url ];
  17768. const reader = response.body.getReader();
  17769. // Nginx needs X-File-Size check
  17770. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  17771. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  17772. const total = contentLength ? parseInt( contentLength ) : 0;
  17773. const lengthComputable = total !== 0;
  17774. let loaded = 0;
  17775. // periodically read data into the new stream tracking while download progress
  17776. const stream = new ReadableStream( {
  17777. start( controller ) {
  17778. readData();
  17779. function readData() {
  17780. reader.read().then( ( { done, value } ) => {
  17781. if ( done ) {
  17782. controller.close();
  17783. } else {
  17784. loaded += value.byteLength;
  17785. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  17786. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  17787. const callback = callbacks[ i ];
  17788. if ( callback.onProgress ) callback.onProgress( event );
  17789. }
  17790. controller.enqueue( value );
  17791. readData();
  17792. }
  17793. }, ( e ) => {
  17794. controller.error( e );
  17795. } );
  17796. }
  17797. }
  17798. } );
  17799. return new Response( stream );
  17800. } else {
  17801. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  17802. }
  17803. } )
  17804. .then( response => {
  17805. switch ( responseType ) {
  17806. case 'arraybuffer':
  17807. return response.arrayBuffer();
  17808. case 'blob':
  17809. return response.blob();
  17810. case 'document':
  17811. return response.text()
  17812. .then( text => {
  17813. const parser = new DOMParser();
  17814. return parser.parseFromString( text, mimeType );
  17815. } );
  17816. case 'json':
  17817. return response.json();
  17818. default:
  17819. if ( mimeType === undefined ) {
  17820. return response.text();
  17821. } else {
  17822. // sniff encoding
  17823. const re = /charset="?([^;"\s]*)"?/i;
  17824. const exec = re.exec( mimeType );
  17825. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  17826. const decoder = new TextDecoder( label );
  17827. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  17828. }
  17829. }
  17830. } )
  17831. .then( data => {
  17832. // Add to cache only on HTTP success, so that we do not cache
  17833. // error response bodies as proper responses to requests.
  17834. Cache.add( url, data );
  17835. const callbacks = loading[ url ];
  17836. delete loading[ url ];
  17837. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  17838. const callback = callbacks[ i ];
  17839. if ( callback.onLoad ) callback.onLoad( data );
  17840. }
  17841. } )
  17842. .catch( err => {
  17843. // Abort errors and other errors are handled the same
  17844. const callbacks = loading[ url ];
  17845. if ( callbacks === undefined ) {
  17846. // When onLoad was called and url was deleted in `loading`
  17847. this.manager.itemError( url );
  17848. throw err;
  17849. }
  17850. delete loading[ url ];
  17851. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  17852. const callback = callbacks[ i ];
  17853. if ( callback.onError ) callback.onError( err );
  17854. }
  17855. this.manager.itemError( url );
  17856. } )
  17857. .finally( () => {
  17858. this.manager.itemEnd( url );
  17859. } );
  17860. this.manager.itemStart( url );
  17861. }
  17862. setResponseType( value ) {
  17863. this.responseType = value;
  17864. return this;
  17865. }
  17866. setMimeType( value ) {
  17867. this.mimeType = value;
  17868. return this;
  17869. }
  17870. }
  17871. class AnimationLoader extends Loader {
  17872. constructor( manager ) {
  17873. super( manager );
  17874. }
  17875. load( url, onLoad, onProgress, onError ) {
  17876. const scope = this;
  17877. const loader = new FileLoader( this.manager );
  17878. loader.setPath( this.path );
  17879. loader.setRequestHeader( this.requestHeader );
  17880. loader.setWithCredentials( this.withCredentials );
  17881. loader.load( url, function ( text ) {
  17882. try {
  17883. onLoad( scope.parse( JSON.parse( text ) ) );
  17884. } catch ( e ) {
  17885. if ( onError ) {
  17886. onError( e );
  17887. } else {
  17888. console.error( e );
  17889. }
  17890. scope.manager.itemError( url );
  17891. }
  17892. }, onProgress, onError );
  17893. }
  17894. parse( json ) {
  17895. const animations = [];
  17896. for ( let i = 0; i < json.length; i ++ ) {
  17897. const clip = AnimationClip.parse( json[ i ] );
  17898. animations.push( clip );
  17899. }
  17900. return animations;
  17901. }
  17902. }
  17903. /**
  17904. * Abstract Base class to block based textures loader (dds, pvr, ...)
  17905. *
  17906. * Sub classes have to implement the parse() method which will be used in load().
  17907. */
  17908. class CompressedTextureLoader extends Loader {
  17909. constructor( manager ) {
  17910. super( manager );
  17911. }
  17912. load( url, onLoad, onProgress, onError ) {
  17913. const scope = this;
  17914. const images = [];
  17915. const texture = new CompressedTexture();
  17916. const loader = new FileLoader( this.manager );
  17917. loader.setPath( this.path );
  17918. loader.setResponseType( 'arraybuffer' );
  17919. loader.setRequestHeader( this.requestHeader );
  17920. loader.setWithCredentials( scope.withCredentials );
  17921. let loaded = 0;
  17922. function loadTexture( i ) {
  17923. loader.load( url[ i ], function ( buffer ) {
  17924. const texDatas = scope.parse( buffer, true );
  17925. images[ i ] = {
  17926. width: texDatas.width,
  17927. height: texDatas.height,
  17928. format: texDatas.format,
  17929. mipmaps: texDatas.mipmaps
  17930. };
  17931. loaded += 1;
  17932. if ( loaded === 6 ) {
  17933. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  17934. texture.image = images;
  17935. texture.format = texDatas.format;
  17936. texture.needsUpdate = true;
  17937. if ( onLoad ) onLoad( texture );
  17938. }
  17939. }, onProgress, onError );
  17940. }
  17941. if ( Array.isArray( url ) ) {
  17942. for ( let i = 0, il = url.length; i < il; ++ i ) {
  17943. loadTexture( i );
  17944. }
  17945. } else {
  17946. // compressed cubemap texture stored in a single DDS file
  17947. loader.load( url, function ( buffer ) {
  17948. const texDatas = scope.parse( buffer, true );
  17949. if ( texDatas.isCubemap ) {
  17950. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  17951. for ( let f = 0; f < faces; f ++ ) {
  17952. images[ f ] = { mipmaps: [] };
  17953. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  17954. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  17955. images[ f ].format = texDatas.format;
  17956. images[ f ].width = texDatas.width;
  17957. images[ f ].height = texDatas.height;
  17958. }
  17959. }
  17960. texture.image = images;
  17961. } else {
  17962. texture.image.width = texDatas.width;
  17963. texture.image.height = texDatas.height;
  17964. texture.mipmaps = texDatas.mipmaps;
  17965. }
  17966. if ( texDatas.mipmapCount === 1 ) {
  17967. texture.minFilter = LinearFilter;
  17968. }
  17969. texture.format = texDatas.format;
  17970. texture.needsUpdate = true;
  17971. if ( onLoad ) onLoad( texture );
  17972. }, onProgress, onError );
  17973. }
  17974. return texture;
  17975. }
  17976. }
  17977. class ImageLoader extends Loader {
  17978. constructor( manager ) {
  17979. super( manager );
  17980. }
  17981. load( url, onLoad, onProgress, onError ) {
  17982. if ( this.path !== undefined ) url = this.path + url;
  17983. url = this.manager.resolveURL( url );
  17984. const scope = this;
  17985. const cached = Cache.get( url );
  17986. if ( cached !== undefined ) {
  17987. scope.manager.itemStart( url );
  17988. setTimeout( function () {
  17989. if ( onLoad ) onLoad( cached );
  17990. scope.manager.itemEnd( url );
  17991. }, 0 );
  17992. return cached;
  17993. }
  17994. const image = createElementNS( 'img' );
  17995. function onImageLoad() {
  17996. removeEventListeners();
  17997. Cache.add( url, this );
  17998. if ( onLoad ) onLoad( this );
  17999. scope.manager.itemEnd( url );
  18000. }
  18001. function onImageError( event ) {
  18002. removeEventListeners();
  18003. if ( onError ) onError( event );
  18004. scope.manager.itemError( url );
  18005. scope.manager.itemEnd( url );
  18006. }
  18007. function removeEventListeners() {
  18008. image.removeEventListener( 'load', onImageLoad, false );
  18009. image.removeEventListener( 'error', onImageError, false );
  18010. }
  18011. image.addEventListener( 'load', onImageLoad, false );
  18012. image.addEventListener( 'error', onImageError, false );
  18013. if ( url.slice( 0, 5 ) !== 'data:' ) {
  18014. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  18015. }
  18016. scope.manager.itemStart( url );
  18017. image.src = url;
  18018. return image;
  18019. }
  18020. }
  18021. class CubeTextureLoader extends Loader {
  18022. constructor( manager ) {
  18023. super( manager );
  18024. }
  18025. load( urls, onLoad, onProgress, onError ) {
  18026. const texture = new CubeTexture();
  18027. texture.colorSpace = SRGBColorSpace;
  18028. const loader = new ImageLoader( this.manager );
  18029. loader.setCrossOrigin( this.crossOrigin );
  18030. loader.setPath( this.path );
  18031. let loaded = 0;
  18032. function loadTexture( i ) {
  18033. loader.load( urls[ i ], function ( image ) {
  18034. texture.images[ i ] = image;
  18035. loaded ++;
  18036. if ( loaded === 6 ) {
  18037. texture.needsUpdate = true;
  18038. if ( onLoad ) onLoad( texture );
  18039. }
  18040. }, undefined, onError );
  18041. }
  18042. for ( let i = 0; i < urls.length; ++ i ) {
  18043. loadTexture( i );
  18044. }
  18045. return texture;
  18046. }
  18047. }
  18048. /**
  18049. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  18050. *
  18051. * Sub classes have to implement the parse() method which will be used in load().
  18052. */
  18053. class DataTextureLoader extends Loader {
  18054. constructor( manager ) {
  18055. super( manager );
  18056. }
  18057. load( url, onLoad, onProgress, onError ) {
  18058. const scope = this;
  18059. const texture = new DataTexture();
  18060. const loader = new FileLoader( this.manager );
  18061. loader.setResponseType( 'arraybuffer' );
  18062. loader.setRequestHeader( this.requestHeader );
  18063. loader.setPath( this.path );
  18064. loader.setWithCredentials( scope.withCredentials );
  18065. loader.load( url, function ( buffer ) {
  18066. let texData;
  18067. try {
  18068. texData = scope.parse( buffer );
  18069. } catch ( error ) {
  18070. if ( onError !== undefined ) {
  18071. onError( error );
  18072. } else {
  18073. console.error( error );
  18074. return;
  18075. }
  18076. }
  18077. if ( texData.image !== undefined ) {
  18078. texture.image = texData.image;
  18079. } else if ( texData.data !== undefined ) {
  18080. texture.image.width = texData.width;
  18081. texture.image.height = texData.height;
  18082. texture.image.data = texData.data;
  18083. }
  18084. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  18085. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  18086. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  18087. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  18088. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  18089. if ( texData.colorSpace !== undefined ) {
  18090. texture.colorSpace = texData.colorSpace;
  18091. }
  18092. if ( texData.flipY !== undefined ) {
  18093. texture.flipY = texData.flipY;
  18094. }
  18095. if ( texData.format !== undefined ) {
  18096. texture.format = texData.format;
  18097. }
  18098. if ( texData.type !== undefined ) {
  18099. texture.type = texData.type;
  18100. }
  18101. if ( texData.mipmaps !== undefined ) {
  18102. texture.mipmaps = texData.mipmaps;
  18103. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  18104. }
  18105. if ( texData.mipmapCount === 1 ) {
  18106. texture.minFilter = LinearFilter;
  18107. }
  18108. if ( texData.generateMipmaps !== undefined ) {
  18109. texture.generateMipmaps = texData.generateMipmaps;
  18110. }
  18111. texture.needsUpdate = true;
  18112. if ( onLoad ) onLoad( texture, texData );
  18113. }, onProgress, onError );
  18114. return texture;
  18115. }
  18116. }
  18117. class TextureLoader extends Loader {
  18118. constructor( manager ) {
  18119. super( manager );
  18120. }
  18121. load( url, onLoad, onProgress, onError ) {
  18122. const texture = new Texture();
  18123. const loader = new ImageLoader( this.manager );
  18124. loader.setCrossOrigin( this.crossOrigin );
  18125. loader.setPath( this.path );
  18126. loader.load( url, function ( image ) {
  18127. texture.image = image;
  18128. texture.needsUpdate = true;
  18129. if ( onLoad !== undefined ) {
  18130. onLoad( texture );
  18131. }
  18132. }, onProgress, onError );
  18133. return texture;
  18134. }
  18135. }
  18136. class Light extends Object3D {
  18137. constructor( color, intensity = 1 ) {
  18138. super();
  18139. this.isLight = true;
  18140. this.type = 'Light';
  18141. this.color = new Color( color );
  18142. this.intensity = intensity;
  18143. }
  18144. dispose() {
  18145. // Empty here in base class; some subclasses override.
  18146. }
  18147. copy( source, recursive ) {
  18148. super.copy( source, recursive );
  18149. this.color.copy( source.color );
  18150. this.intensity = source.intensity;
  18151. return this;
  18152. }
  18153. toJSON( meta ) {
  18154. const data = super.toJSON( meta );
  18155. data.object.color = this.color.getHex();
  18156. data.object.intensity = this.intensity;
  18157. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  18158. if ( this.distance !== undefined ) data.object.distance = this.distance;
  18159. if ( this.angle !== undefined ) data.object.angle = this.angle;
  18160. if ( this.decay !== undefined ) data.object.decay = this.decay;
  18161. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  18162. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  18163. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  18164. return data;
  18165. }
  18166. }
  18167. class HemisphereLight extends Light {
  18168. constructor( skyColor, groundColor, intensity ) {
  18169. super( skyColor, intensity );
  18170. this.isHemisphereLight = true;
  18171. this.type = 'HemisphereLight';
  18172. this.position.copy( Object3D.DEFAULT_UP );
  18173. this.updateMatrix();
  18174. this.groundColor = new Color( groundColor );
  18175. }
  18176. copy( source, recursive ) {
  18177. super.copy( source, recursive );
  18178. this.groundColor.copy( source.groundColor );
  18179. return this;
  18180. }
  18181. }
  18182. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  18183. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  18184. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  18185. class LightShadow {
  18186. constructor( camera ) {
  18187. this.camera = camera;
  18188. this.intensity = 1;
  18189. this.bias = 0;
  18190. this.normalBias = 0;
  18191. this.radius = 1;
  18192. this.blurSamples = 8;
  18193. this.mapSize = new Vector2( 512, 512 );
  18194. this.map = null;
  18195. this.mapPass = null;
  18196. this.matrix = new Matrix4();
  18197. this.autoUpdate = true;
  18198. this.needsUpdate = false;
  18199. this._frustum = new Frustum();
  18200. this._frameExtents = new Vector2( 1, 1 );
  18201. this._viewportCount = 1;
  18202. this._viewports = [
  18203. new Vector4( 0, 0, 1, 1 )
  18204. ];
  18205. }
  18206. getViewportCount() {
  18207. return this._viewportCount;
  18208. }
  18209. getFrustum() {
  18210. return this._frustum;
  18211. }
  18212. updateMatrices( light ) {
  18213. const shadowCamera = this.camera;
  18214. const shadowMatrix = this.matrix;
  18215. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  18216. shadowCamera.position.copy( _lightPositionWorld$1 );
  18217. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  18218. shadowCamera.lookAt( _lookTarget$1 );
  18219. shadowCamera.updateMatrixWorld();
  18220. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  18221. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  18222. shadowMatrix.set(
  18223. 0.5, 0.0, 0.0, 0.5,
  18224. 0.0, 0.5, 0.0, 0.5,
  18225. 0.0, 0.0, 0.5, 0.5,
  18226. 0.0, 0.0, 0.0, 1.0
  18227. );
  18228. shadowMatrix.multiply( _projScreenMatrix$1 );
  18229. }
  18230. getViewport( viewportIndex ) {
  18231. return this._viewports[ viewportIndex ];
  18232. }
  18233. getFrameExtents() {
  18234. return this._frameExtents;
  18235. }
  18236. dispose() {
  18237. if ( this.map ) {
  18238. this.map.dispose();
  18239. }
  18240. if ( this.mapPass ) {
  18241. this.mapPass.dispose();
  18242. }
  18243. }
  18244. copy( source ) {
  18245. this.camera = source.camera.clone();
  18246. this.intensity = source.intensity;
  18247. this.bias = source.bias;
  18248. this.radius = source.radius;
  18249. this.mapSize.copy( source.mapSize );
  18250. return this;
  18251. }
  18252. clone() {
  18253. return new this.constructor().copy( this );
  18254. }
  18255. toJSON() {
  18256. const object = {};
  18257. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  18258. if ( this.bias !== 0 ) object.bias = this.bias;
  18259. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  18260. if ( this.radius !== 1 ) object.radius = this.radius;
  18261. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  18262. object.camera = this.camera.toJSON( false ).object;
  18263. delete object.camera.matrix;
  18264. return object;
  18265. }
  18266. }
  18267. class SpotLightShadow extends LightShadow {
  18268. constructor() {
  18269. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  18270. this.isSpotLightShadow = true;
  18271. this.focus = 1;
  18272. }
  18273. updateMatrices( light ) {
  18274. const camera = this.camera;
  18275. const fov = RAD2DEG * 2 * light.angle * this.focus;
  18276. const aspect = this.mapSize.width / this.mapSize.height;
  18277. const far = light.distance || camera.far;
  18278. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  18279. camera.fov = fov;
  18280. camera.aspect = aspect;
  18281. camera.far = far;
  18282. camera.updateProjectionMatrix();
  18283. }
  18284. super.updateMatrices( light );
  18285. }
  18286. copy( source ) {
  18287. super.copy( source );
  18288. this.focus = source.focus;
  18289. return this;
  18290. }
  18291. }
  18292. class SpotLight extends Light {
  18293. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  18294. super( color, intensity );
  18295. this.isSpotLight = true;
  18296. this.type = 'SpotLight';
  18297. this.position.copy( Object3D.DEFAULT_UP );
  18298. this.updateMatrix();
  18299. this.target = new Object3D();
  18300. this.distance = distance;
  18301. this.angle = angle;
  18302. this.penumbra = penumbra;
  18303. this.decay = decay;
  18304. this.map = null;
  18305. this.shadow = new SpotLightShadow();
  18306. }
  18307. get power() {
  18308. // compute the light's luminous power (in lumens) from its intensity (in candela)
  18309. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  18310. return this.intensity * Math.PI;
  18311. }
  18312. set power( power ) {
  18313. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  18314. this.intensity = power / Math.PI;
  18315. }
  18316. dispose() {
  18317. this.shadow.dispose();
  18318. }
  18319. copy( source, recursive ) {
  18320. super.copy( source, recursive );
  18321. this.distance = source.distance;
  18322. this.angle = source.angle;
  18323. this.penumbra = source.penumbra;
  18324. this.decay = source.decay;
  18325. this.target = source.target.clone();
  18326. this.shadow = source.shadow.clone();
  18327. return this;
  18328. }
  18329. }
  18330. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  18331. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  18332. const _lookTarget = /*@__PURE__*/ new Vector3();
  18333. class PointLightShadow extends LightShadow {
  18334. constructor() {
  18335. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  18336. this.isPointLightShadow = true;
  18337. this._frameExtents = new Vector2( 4, 2 );
  18338. this._viewportCount = 6;
  18339. this._viewports = [
  18340. // These viewports map a cube-map onto a 2D texture with the
  18341. // following orientation:
  18342. //
  18343. // xzXZ
  18344. // y Y
  18345. //
  18346. // X - Positive x direction
  18347. // x - Negative x direction
  18348. // Y - Positive y direction
  18349. // y - Negative y direction
  18350. // Z - Positive z direction
  18351. // z - Negative z direction
  18352. // positive X
  18353. new Vector4( 2, 1, 1, 1 ),
  18354. // negative X
  18355. new Vector4( 0, 1, 1, 1 ),
  18356. // positive Z
  18357. new Vector4( 3, 1, 1, 1 ),
  18358. // negative Z
  18359. new Vector4( 1, 1, 1, 1 ),
  18360. // positive Y
  18361. new Vector4( 3, 0, 1, 1 ),
  18362. // negative Y
  18363. new Vector4( 1, 0, 1, 1 )
  18364. ];
  18365. this._cubeDirections = [
  18366. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  18367. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  18368. ];
  18369. this._cubeUps = [
  18370. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  18371. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  18372. ];
  18373. }
  18374. updateMatrices( light, viewportIndex = 0 ) {
  18375. const camera = this.camera;
  18376. const shadowMatrix = this.matrix;
  18377. const far = light.distance || camera.far;
  18378. if ( far !== camera.far ) {
  18379. camera.far = far;
  18380. camera.updateProjectionMatrix();
  18381. }
  18382. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  18383. camera.position.copy( _lightPositionWorld );
  18384. _lookTarget.copy( camera.position );
  18385. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  18386. camera.up.copy( this._cubeUps[ viewportIndex ] );
  18387. camera.lookAt( _lookTarget );
  18388. camera.updateMatrixWorld();
  18389. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  18390. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  18391. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  18392. }
  18393. }
  18394. class PointLight extends Light {
  18395. constructor( color, intensity, distance = 0, decay = 2 ) {
  18396. super( color, intensity );
  18397. this.isPointLight = true;
  18398. this.type = 'PointLight';
  18399. this.distance = distance;
  18400. this.decay = decay;
  18401. this.shadow = new PointLightShadow();
  18402. }
  18403. get power() {
  18404. // compute the light's luminous power (in lumens) from its intensity (in candela)
  18405. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  18406. return this.intensity * 4 * Math.PI;
  18407. }
  18408. set power( power ) {
  18409. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  18410. this.intensity = power / ( 4 * Math.PI );
  18411. }
  18412. dispose() {
  18413. this.shadow.dispose();
  18414. }
  18415. copy( source, recursive ) {
  18416. super.copy( source, recursive );
  18417. this.distance = source.distance;
  18418. this.decay = source.decay;
  18419. this.shadow = source.shadow.clone();
  18420. return this;
  18421. }
  18422. }
  18423. class OrthographicCamera extends Camera {
  18424. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  18425. super();
  18426. this.isOrthographicCamera = true;
  18427. this.type = 'OrthographicCamera';
  18428. this.zoom = 1;
  18429. this.view = null;
  18430. this.left = left;
  18431. this.right = right;
  18432. this.top = top;
  18433. this.bottom = bottom;
  18434. this.near = near;
  18435. this.far = far;
  18436. this.updateProjectionMatrix();
  18437. }
  18438. copy( source, recursive ) {
  18439. super.copy( source, recursive );
  18440. this.left = source.left;
  18441. this.right = source.right;
  18442. this.top = source.top;
  18443. this.bottom = source.bottom;
  18444. this.near = source.near;
  18445. this.far = source.far;
  18446. this.zoom = source.zoom;
  18447. this.view = source.view === null ? null : Object.assign( {}, source.view );
  18448. return this;
  18449. }
  18450. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  18451. if ( this.view === null ) {
  18452. this.view = {
  18453. enabled: true,
  18454. fullWidth: 1,
  18455. fullHeight: 1,
  18456. offsetX: 0,
  18457. offsetY: 0,
  18458. width: 1,
  18459. height: 1
  18460. };
  18461. }
  18462. this.view.enabled = true;
  18463. this.view.fullWidth = fullWidth;
  18464. this.view.fullHeight = fullHeight;
  18465. this.view.offsetX = x;
  18466. this.view.offsetY = y;
  18467. this.view.width = width;
  18468. this.view.height = height;
  18469. this.updateProjectionMatrix();
  18470. }
  18471. clearViewOffset() {
  18472. if ( this.view !== null ) {
  18473. this.view.enabled = false;
  18474. }
  18475. this.updateProjectionMatrix();
  18476. }
  18477. updateProjectionMatrix() {
  18478. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  18479. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  18480. const cx = ( this.right + this.left ) / 2;
  18481. const cy = ( this.top + this.bottom ) / 2;
  18482. let left = cx - dx;
  18483. let right = cx + dx;
  18484. let top = cy + dy;
  18485. let bottom = cy - dy;
  18486. if ( this.view !== null && this.view.enabled ) {
  18487. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  18488. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  18489. left += scaleW * this.view.offsetX;
  18490. right = left + scaleW * this.view.width;
  18491. top -= scaleH * this.view.offsetY;
  18492. bottom = top - scaleH * this.view.height;
  18493. }
  18494. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  18495. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  18496. }
  18497. toJSON( meta ) {
  18498. const data = super.toJSON( meta );
  18499. data.object.zoom = this.zoom;
  18500. data.object.left = this.left;
  18501. data.object.right = this.right;
  18502. data.object.top = this.top;
  18503. data.object.bottom = this.bottom;
  18504. data.object.near = this.near;
  18505. data.object.far = this.far;
  18506. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  18507. return data;
  18508. }
  18509. }
  18510. class DirectionalLightShadow extends LightShadow {
  18511. constructor() {
  18512. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  18513. this.isDirectionalLightShadow = true;
  18514. }
  18515. }
  18516. class DirectionalLight extends Light {
  18517. constructor( color, intensity ) {
  18518. super( color, intensity );
  18519. this.isDirectionalLight = true;
  18520. this.type = 'DirectionalLight';
  18521. this.position.copy( Object3D.DEFAULT_UP );
  18522. this.updateMatrix();
  18523. this.target = new Object3D();
  18524. this.shadow = new DirectionalLightShadow();
  18525. }
  18526. dispose() {
  18527. this.shadow.dispose();
  18528. }
  18529. copy( source ) {
  18530. super.copy( source );
  18531. this.target = source.target.clone();
  18532. this.shadow = source.shadow.clone();
  18533. return this;
  18534. }
  18535. }
  18536. class AmbientLight extends Light {
  18537. constructor( color, intensity ) {
  18538. super( color, intensity );
  18539. this.isAmbientLight = true;
  18540. this.type = 'AmbientLight';
  18541. }
  18542. }
  18543. class RectAreaLight extends Light {
  18544. constructor( color, intensity, width = 10, height = 10 ) {
  18545. super( color, intensity );
  18546. this.isRectAreaLight = true;
  18547. this.type = 'RectAreaLight';
  18548. this.width = width;
  18549. this.height = height;
  18550. }
  18551. get power() {
  18552. // compute the light's luminous power (in lumens) from its intensity (in nits)
  18553. return this.intensity * this.width * this.height * Math.PI;
  18554. }
  18555. set power( power ) {
  18556. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  18557. this.intensity = power / ( this.width * this.height * Math.PI );
  18558. }
  18559. copy( source ) {
  18560. super.copy( source );
  18561. this.width = source.width;
  18562. this.height = source.height;
  18563. return this;
  18564. }
  18565. toJSON( meta ) {
  18566. const data = super.toJSON( meta );
  18567. data.object.width = this.width;
  18568. data.object.height = this.height;
  18569. return data;
  18570. }
  18571. }
  18572. /**
  18573. * Primary reference:
  18574. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  18575. *
  18576. * Secondary reference:
  18577. * https://www.ppsloan.org/publications/StupidSH36.pdf
  18578. */
  18579. // 3-band SH defined by 9 coefficients
  18580. class SphericalHarmonics3 {
  18581. constructor() {
  18582. this.isSphericalHarmonics3 = true;
  18583. this.coefficients = [];
  18584. for ( let i = 0; i < 9; i ++ ) {
  18585. this.coefficients.push( new Vector3() );
  18586. }
  18587. }
  18588. set( coefficients ) {
  18589. for ( let i = 0; i < 9; i ++ ) {
  18590. this.coefficients[ i ].copy( coefficients[ i ] );
  18591. }
  18592. return this;
  18593. }
  18594. zero() {
  18595. for ( let i = 0; i < 9; i ++ ) {
  18596. this.coefficients[ i ].set( 0, 0, 0 );
  18597. }
  18598. return this;
  18599. }
  18600. // get the radiance in the direction of the normal
  18601. // target is a Vector3
  18602. getAt( normal, target ) {
  18603. // normal is assumed to be unit length
  18604. const x = normal.x, y = normal.y, z = normal.z;
  18605. const coeff = this.coefficients;
  18606. // band 0
  18607. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  18608. // band 1
  18609. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  18610. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  18611. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  18612. // band 2
  18613. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  18614. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  18615. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  18616. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  18617. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  18618. return target;
  18619. }
  18620. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  18621. // target is a Vector3
  18622. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  18623. getIrradianceAt( normal, target ) {
  18624. // normal is assumed to be unit length
  18625. const x = normal.x, y = normal.y, z = normal.z;
  18626. const coeff = this.coefficients;
  18627. // band 0
  18628. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  18629. // band 1
  18630. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  18631. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  18632. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  18633. // band 2
  18634. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  18635. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  18636. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  18637. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  18638. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  18639. return target;
  18640. }
  18641. add( sh ) {
  18642. for ( let i = 0; i < 9; i ++ ) {
  18643. this.coefficients[ i ].add( sh.coefficients[ i ] );
  18644. }
  18645. return this;
  18646. }
  18647. addScaledSH( sh, s ) {
  18648. for ( let i = 0; i < 9; i ++ ) {
  18649. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  18650. }
  18651. return this;
  18652. }
  18653. scale( s ) {
  18654. for ( let i = 0; i < 9; i ++ ) {
  18655. this.coefficients[ i ].multiplyScalar( s );
  18656. }
  18657. return this;
  18658. }
  18659. lerp( sh, alpha ) {
  18660. for ( let i = 0; i < 9; i ++ ) {
  18661. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  18662. }
  18663. return this;
  18664. }
  18665. equals( sh ) {
  18666. for ( let i = 0; i < 9; i ++ ) {
  18667. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  18668. return false;
  18669. }
  18670. }
  18671. return true;
  18672. }
  18673. copy( sh ) {
  18674. return this.set( sh.coefficients );
  18675. }
  18676. clone() {
  18677. return new this.constructor().copy( this );
  18678. }
  18679. fromArray( array, offset = 0 ) {
  18680. const coefficients = this.coefficients;
  18681. for ( let i = 0; i < 9; i ++ ) {
  18682. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  18683. }
  18684. return this;
  18685. }
  18686. toArray( array = [], offset = 0 ) {
  18687. const coefficients = this.coefficients;
  18688. for ( let i = 0; i < 9; i ++ ) {
  18689. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  18690. }
  18691. return array;
  18692. }
  18693. // evaluate the basis functions
  18694. // shBasis is an Array[ 9 ]
  18695. static getBasisAt( normal, shBasis ) {
  18696. // normal is assumed to be unit length
  18697. const x = normal.x, y = normal.y, z = normal.z;
  18698. // band 0
  18699. shBasis[ 0 ] = 0.282095;
  18700. // band 1
  18701. shBasis[ 1 ] = 0.488603 * y;
  18702. shBasis[ 2 ] = 0.488603 * z;
  18703. shBasis[ 3 ] = 0.488603 * x;
  18704. // band 2
  18705. shBasis[ 4 ] = 1.092548 * x * y;
  18706. shBasis[ 5 ] = 1.092548 * y * z;
  18707. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  18708. shBasis[ 7 ] = 1.092548 * x * z;
  18709. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  18710. }
  18711. }
  18712. class LightProbe extends Light {
  18713. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  18714. super( undefined, intensity );
  18715. this.isLightProbe = true;
  18716. this.sh = sh;
  18717. }
  18718. copy( source ) {
  18719. super.copy( source );
  18720. this.sh.copy( source.sh );
  18721. return this;
  18722. }
  18723. fromJSON( json ) {
  18724. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  18725. this.sh.fromArray( json.sh );
  18726. return this;
  18727. }
  18728. toJSON( meta ) {
  18729. const data = super.toJSON( meta );
  18730. data.object.sh = this.sh.toArray();
  18731. return data;
  18732. }
  18733. }
  18734. class MaterialLoader extends Loader {
  18735. constructor( manager ) {
  18736. super( manager );
  18737. this.textures = {};
  18738. }
  18739. load( url, onLoad, onProgress, onError ) {
  18740. const scope = this;
  18741. const loader = new FileLoader( scope.manager );
  18742. loader.setPath( scope.path );
  18743. loader.setRequestHeader( scope.requestHeader );
  18744. loader.setWithCredentials( scope.withCredentials );
  18745. loader.load( url, function ( text ) {
  18746. try {
  18747. onLoad( scope.parse( JSON.parse( text ) ) );
  18748. } catch ( e ) {
  18749. if ( onError ) {
  18750. onError( e );
  18751. } else {
  18752. console.error( e );
  18753. }
  18754. scope.manager.itemError( url );
  18755. }
  18756. }, onProgress, onError );
  18757. }
  18758. parse( json ) {
  18759. const textures = this.textures;
  18760. function getTexture( name ) {
  18761. if ( textures[ name ] === undefined ) {
  18762. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  18763. }
  18764. return textures[ name ];
  18765. }
  18766. const material = this.createMaterialFromType( json.type );
  18767. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  18768. if ( json.name !== undefined ) material.name = json.name;
  18769. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  18770. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  18771. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  18772. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  18773. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  18774. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  18775. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  18776. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  18777. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  18778. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  18779. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  18780. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  18781. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  18782. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  18783. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  18784. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  18785. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  18786. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  18787. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  18788. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  18789. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  18790. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  18791. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  18792. if ( json.fog !== undefined ) material.fog = json.fog;
  18793. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  18794. if ( json.blending !== undefined ) material.blending = json.blending;
  18795. if ( json.combine !== undefined ) material.combine = json.combine;
  18796. if ( json.side !== undefined ) material.side = json.side;
  18797. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  18798. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  18799. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  18800. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  18801. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  18802. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  18803. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  18804. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  18805. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  18806. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  18807. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  18808. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  18809. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  18810. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  18811. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  18812. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  18813. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  18814. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  18815. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  18816. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  18817. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  18818. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  18819. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  18820. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  18821. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  18822. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  18823. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  18824. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  18825. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  18826. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  18827. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  18828. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  18829. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  18830. if ( json.scale !== undefined ) material.scale = json.scale;
  18831. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  18832. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  18833. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  18834. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  18835. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  18836. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  18837. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  18838. if ( json.visible !== undefined ) material.visible = json.visible;
  18839. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  18840. if ( json.userData !== undefined ) material.userData = json.userData;
  18841. if ( json.vertexColors !== undefined ) {
  18842. if ( typeof json.vertexColors === 'number' ) {
  18843. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  18844. } else {
  18845. material.vertexColors = json.vertexColors;
  18846. }
  18847. }
  18848. // Shader Material
  18849. if ( json.uniforms !== undefined ) {
  18850. for ( const name in json.uniforms ) {
  18851. const uniform = json.uniforms[ name ];
  18852. material.uniforms[ name ] = {};
  18853. switch ( uniform.type ) {
  18854. case 't':
  18855. material.uniforms[ name ].value = getTexture( uniform.value );
  18856. break;
  18857. case 'c':
  18858. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  18859. break;
  18860. case 'v2':
  18861. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  18862. break;
  18863. case 'v3':
  18864. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  18865. break;
  18866. case 'v4':
  18867. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  18868. break;
  18869. case 'm3':
  18870. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  18871. break;
  18872. case 'm4':
  18873. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  18874. break;
  18875. default:
  18876. material.uniforms[ name ].value = uniform.value;
  18877. }
  18878. }
  18879. }
  18880. if ( json.defines !== undefined ) material.defines = json.defines;
  18881. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  18882. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  18883. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  18884. if ( json.extensions !== undefined ) {
  18885. for ( const key in json.extensions ) {
  18886. material.extensions[ key ] = json.extensions[ key ];
  18887. }
  18888. }
  18889. if ( json.lights !== undefined ) material.lights = json.lights;
  18890. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  18891. // for PointsMaterial
  18892. if ( json.size !== undefined ) material.size = json.size;
  18893. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  18894. // maps
  18895. if ( json.map !== undefined ) material.map = getTexture( json.map );
  18896. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  18897. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  18898. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  18899. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  18900. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  18901. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  18902. if ( json.normalScale !== undefined ) {
  18903. let normalScale = json.normalScale;
  18904. if ( Array.isArray( normalScale ) === false ) {
  18905. // Blender exporter used to export a scalar. See #7459
  18906. normalScale = [ normalScale, normalScale ];
  18907. }
  18908. material.normalScale = new Vector2().fromArray( normalScale );
  18909. }
  18910. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  18911. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  18912. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  18913. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  18914. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  18915. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  18916. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  18917. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  18918. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  18919. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  18920. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  18921. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  18922. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  18923. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  18924. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  18925. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  18926. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  18927. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  18928. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  18929. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  18930. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  18931. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  18932. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  18933. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  18934. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  18935. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  18936. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  18937. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  18938. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  18939. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  18940. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  18941. return material;
  18942. }
  18943. setTextures( value ) {
  18944. this.textures = value;
  18945. return this;
  18946. }
  18947. createMaterialFromType( type ) {
  18948. return MaterialLoader.createMaterialFromType( type );
  18949. }
  18950. static createMaterialFromType( type ) {
  18951. const materialLib = {
  18952. ShadowMaterial,
  18953. SpriteMaterial,
  18954. RawShaderMaterial,
  18955. ShaderMaterial,
  18956. PointsMaterial,
  18957. MeshPhysicalMaterial,
  18958. MeshStandardMaterial,
  18959. MeshPhongMaterial,
  18960. MeshToonMaterial,
  18961. MeshNormalMaterial,
  18962. MeshLambertMaterial,
  18963. MeshDepthMaterial,
  18964. MeshDistanceMaterial,
  18965. MeshBasicMaterial,
  18966. MeshMatcapMaterial,
  18967. LineDashedMaterial,
  18968. LineBasicMaterial,
  18969. Material
  18970. };
  18971. return new materialLib[ type ]();
  18972. }
  18973. }
  18974. class LoaderUtils {
  18975. static decodeText( array ) { // @deprecated, r165
  18976. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  18977. if ( typeof TextDecoder !== 'undefined' ) {
  18978. return new TextDecoder().decode( array );
  18979. }
  18980. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  18981. // throws a "maximum call stack size exceeded" error for large arrays.
  18982. let s = '';
  18983. for ( let i = 0, il = array.length; i < il; i ++ ) {
  18984. // Implicitly assumes little-endian.
  18985. s += String.fromCharCode( array[ i ] );
  18986. }
  18987. try {
  18988. // merges multi-byte utf-8 characters.
  18989. return decodeURIComponent( escape( s ) );
  18990. } catch ( e ) { // see #16358
  18991. return s;
  18992. }
  18993. }
  18994. static extractUrlBase( url ) {
  18995. const index = url.lastIndexOf( '/' );
  18996. if ( index === -1 ) return './';
  18997. return url.slice( 0, index + 1 );
  18998. }
  18999. static resolveURL( url, path ) {
  19000. // Invalid URL
  19001. if ( typeof url !== 'string' || url === '' ) return '';
  19002. // Host Relative URL
  19003. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  19004. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  19005. }
  19006. // Absolute URL http://,https://,//
  19007. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  19008. // Data URI
  19009. if ( /^data:.*,.*$/i.test( url ) ) return url;
  19010. // Blob URL
  19011. if ( /^blob:.*$/i.test( url ) ) return url;
  19012. // Relative URL
  19013. return path + url;
  19014. }
  19015. }
  19016. class InstancedBufferGeometry extends BufferGeometry {
  19017. constructor() {
  19018. super();
  19019. this.isInstancedBufferGeometry = true;
  19020. this.type = 'InstancedBufferGeometry';
  19021. this.instanceCount = Infinity;
  19022. }
  19023. copy( source ) {
  19024. super.copy( source );
  19025. this.instanceCount = source.instanceCount;
  19026. return this;
  19027. }
  19028. toJSON() {
  19029. const data = super.toJSON();
  19030. data.instanceCount = this.instanceCount;
  19031. data.isInstancedBufferGeometry = true;
  19032. return data;
  19033. }
  19034. }
  19035. class BufferGeometryLoader extends Loader {
  19036. constructor( manager ) {
  19037. super( manager );
  19038. }
  19039. load( url, onLoad, onProgress, onError ) {
  19040. const scope = this;
  19041. const loader = new FileLoader( scope.manager );
  19042. loader.setPath( scope.path );
  19043. loader.setRequestHeader( scope.requestHeader );
  19044. loader.setWithCredentials( scope.withCredentials );
  19045. loader.load( url, function ( text ) {
  19046. try {
  19047. onLoad( scope.parse( JSON.parse( text ) ) );
  19048. } catch ( e ) {
  19049. if ( onError ) {
  19050. onError( e );
  19051. } else {
  19052. console.error( e );
  19053. }
  19054. scope.manager.itemError( url );
  19055. }
  19056. }, onProgress, onError );
  19057. }
  19058. parse( json ) {
  19059. const interleavedBufferMap = {};
  19060. const arrayBufferMap = {};
  19061. function getInterleavedBuffer( json, uuid ) {
  19062. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  19063. const interleavedBuffers = json.interleavedBuffers;
  19064. const interleavedBuffer = interleavedBuffers[ uuid ];
  19065. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  19066. const array = getTypedArray( interleavedBuffer.type, buffer );
  19067. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  19068. ib.uuid = interleavedBuffer.uuid;
  19069. interleavedBufferMap[ uuid ] = ib;
  19070. return ib;
  19071. }
  19072. function getArrayBuffer( json, uuid ) {
  19073. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  19074. const arrayBuffers = json.arrayBuffers;
  19075. const arrayBuffer = arrayBuffers[ uuid ];
  19076. const ab = new Uint32Array( arrayBuffer ).buffer;
  19077. arrayBufferMap[ uuid ] = ab;
  19078. return ab;
  19079. }
  19080. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  19081. const index = json.data.index;
  19082. if ( index !== undefined ) {
  19083. const typedArray = getTypedArray( index.type, index.array );
  19084. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  19085. }
  19086. const attributes = json.data.attributes;
  19087. for ( const key in attributes ) {
  19088. const attribute = attributes[ key ];
  19089. let bufferAttribute;
  19090. if ( attribute.isInterleavedBufferAttribute ) {
  19091. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  19092. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  19093. } else {
  19094. const typedArray = getTypedArray( attribute.type, attribute.array );
  19095. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  19096. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  19097. }
  19098. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  19099. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  19100. geometry.setAttribute( key, bufferAttribute );
  19101. }
  19102. const morphAttributes = json.data.morphAttributes;
  19103. if ( morphAttributes ) {
  19104. for ( const key in morphAttributes ) {
  19105. const attributeArray = morphAttributes[ key ];
  19106. const array = [];
  19107. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  19108. const attribute = attributeArray[ i ];
  19109. let bufferAttribute;
  19110. if ( attribute.isInterleavedBufferAttribute ) {
  19111. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  19112. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  19113. } else {
  19114. const typedArray = getTypedArray( attribute.type, attribute.array );
  19115. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  19116. }
  19117. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  19118. array.push( bufferAttribute );
  19119. }
  19120. geometry.morphAttributes[ key ] = array;
  19121. }
  19122. }
  19123. const morphTargetsRelative = json.data.morphTargetsRelative;
  19124. if ( morphTargetsRelative ) {
  19125. geometry.morphTargetsRelative = true;
  19126. }
  19127. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  19128. if ( groups !== undefined ) {
  19129. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  19130. const group = groups[ i ];
  19131. geometry.addGroup( group.start, group.count, group.materialIndex );
  19132. }
  19133. }
  19134. const boundingSphere = json.data.boundingSphere;
  19135. if ( boundingSphere !== undefined ) {
  19136. const center = new Vector3();
  19137. if ( boundingSphere.center !== undefined ) {
  19138. center.fromArray( boundingSphere.center );
  19139. }
  19140. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  19141. }
  19142. if ( json.name ) geometry.name = json.name;
  19143. if ( json.userData ) geometry.userData = json.userData;
  19144. return geometry;
  19145. }
  19146. }
  19147. class ObjectLoader extends Loader {
  19148. constructor( manager ) {
  19149. super( manager );
  19150. }
  19151. load( url, onLoad, onProgress, onError ) {
  19152. const scope = this;
  19153. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  19154. this.resourcePath = this.resourcePath || path;
  19155. const loader = new FileLoader( this.manager );
  19156. loader.setPath( this.path );
  19157. loader.setRequestHeader( this.requestHeader );
  19158. loader.setWithCredentials( this.withCredentials );
  19159. loader.load( url, function ( text ) {
  19160. let json = null;
  19161. try {
  19162. json = JSON.parse( text );
  19163. } catch ( error ) {
  19164. if ( onError !== undefined ) onError( error );
  19165. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  19166. return;
  19167. }
  19168. const metadata = json.metadata;
  19169. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  19170. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  19171. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  19172. return;
  19173. }
  19174. scope.parse( json, onLoad );
  19175. }, onProgress, onError );
  19176. }
  19177. async loadAsync( url, onProgress ) {
  19178. const scope = this;
  19179. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  19180. this.resourcePath = this.resourcePath || path;
  19181. const loader = new FileLoader( this.manager );
  19182. loader.setPath( this.path );
  19183. loader.setRequestHeader( this.requestHeader );
  19184. loader.setWithCredentials( this.withCredentials );
  19185. const text = await loader.loadAsync( url, onProgress );
  19186. const json = JSON.parse( text );
  19187. const metadata = json.metadata;
  19188. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  19189. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  19190. }
  19191. return await scope.parseAsync( json );
  19192. }
  19193. parse( json, onLoad ) {
  19194. const animations = this.parseAnimations( json.animations );
  19195. const shapes = this.parseShapes( json.shapes );
  19196. const geometries = this.parseGeometries( json.geometries, shapes );
  19197. const images = this.parseImages( json.images, function () {
  19198. if ( onLoad !== undefined ) onLoad( object );
  19199. } );
  19200. const textures = this.parseTextures( json.textures, images );
  19201. const materials = this.parseMaterials( json.materials, textures );
  19202. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  19203. const skeletons = this.parseSkeletons( json.skeletons, object );
  19204. this.bindSkeletons( object, skeletons );
  19205. this.bindLightTargets( object );
  19206. //
  19207. if ( onLoad !== undefined ) {
  19208. let hasImages = false;
  19209. for ( const uuid in images ) {
  19210. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  19211. hasImages = true;
  19212. break;
  19213. }
  19214. }
  19215. if ( hasImages === false ) onLoad( object );
  19216. }
  19217. return object;
  19218. }
  19219. async parseAsync( json ) {
  19220. const animations = this.parseAnimations( json.animations );
  19221. const shapes = this.parseShapes( json.shapes );
  19222. const geometries = this.parseGeometries( json.geometries, shapes );
  19223. const images = await this.parseImagesAsync( json.images );
  19224. const textures = this.parseTextures( json.textures, images );
  19225. const materials = this.parseMaterials( json.materials, textures );
  19226. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  19227. const skeletons = this.parseSkeletons( json.skeletons, object );
  19228. this.bindSkeletons( object, skeletons );
  19229. this.bindLightTargets( object );
  19230. return object;
  19231. }
  19232. parseShapes( json ) {
  19233. const shapes = {};
  19234. if ( json !== undefined ) {
  19235. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19236. const shape = new Shape().fromJSON( json[ i ] );
  19237. shapes[ shape.uuid ] = shape;
  19238. }
  19239. }
  19240. return shapes;
  19241. }
  19242. parseSkeletons( json, object ) {
  19243. const skeletons = {};
  19244. const bones = {};
  19245. // generate bone lookup table
  19246. object.traverse( function ( child ) {
  19247. if ( child.isBone ) bones[ child.uuid ] = child;
  19248. } );
  19249. // create skeletons
  19250. if ( json !== undefined ) {
  19251. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19252. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  19253. skeletons[ skeleton.uuid ] = skeleton;
  19254. }
  19255. }
  19256. return skeletons;
  19257. }
  19258. parseGeometries( json, shapes ) {
  19259. const geometries = {};
  19260. if ( json !== undefined ) {
  19261. const bufferGeometryLoader = new BufferGeometryLoader();
  19262. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19263. let geometry;
  19264. const data = json[ i ];
  19265. switch ( data.type ) {
  19266. case 'BufferGeometry':
  19267. case 'InstancedBufferGeometry':
  19268. geometry = bufferGeometryLoader.parse( data );
  19269. break;
  19270. default:
  19271. if ( data.type in Geometries ) {
  19272. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  19273. } else {
  19274. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  19275. }
  19276. }
  19277. geometry.uuid = data.uuid;
  19278. if ( data.name !== undefined ) geometry.name = data.name;
  19279. if ( data.userData !== undefined ) geometry.userData = data.userData;
  19280. geometries[ data.uuid ] = geometry;
  19281. }
  19282. }
  19283. return geometries;
  19284. }
  19285. parseMaterials( json, textures ) {
  19286. const cache = {}; // MultiMaterial
  19287. const materials = {};
  19288. if ( json !== undefined ) {
  19289. const loader = new MaterialLoader();
  19290. loader.setTextures( textures );
  19291. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19292. const data = json[ i ];
  19293. if ( cache[ data.uuid ] === undefined ) {
  19294. cache[ data.uuid ] = loader.parse( data );
  19295. }
  19296. materials[ data.uuid ] = cache[ data.uuid ];
  19297. }
  19298. }
  19299. return materials;
  19300. }
  19301. parseAnimations( json ) {
  19302. const animations = {};
  19303. if ( json !== undefined ) {
  19304. for ( let i = 0; i < json.length; i ++ ) {
  19305. const data = json[ i ];
  19306. const clip = AnimationClip.parse( data );
  19307. animations[ clip.uuid ] = clip;
  19308. }
  19309. }
  19310. return animations;
  19311. }
  19312. parseImages( json, onLoad ) {
  19313. const scope = this;
  19314. const images = {};
  19315. let loader;
  19316. function loadImage( url ) {
  19317. scope.manager.itemStart( url );
  19318. return loader.load( url, function () {
  19319. scope.manager.itemEnd( url );
  19320. }, undefined, function () {
  19321. scope.manager.itemError( url );
  19322. scope.manager.itemEnd( url );
  19323. } );
  19324. }
  19325. function deserializeImage( image ) {
  19326. if ( typeof image === 'string' ) {
  19327. const url = image;
  19328. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  19329. return loadImage( path );
  19330. } else {
  19331. if ( image.data ) {
  19332. return {
  19333. data: getTypedArray( image.type, image.data ),
  19334. width: image.width,
  19335. height: image.height
  19336. };
  19337. } else {
  19338. return null;
  19339. }
  19340. }
  19341. }
  19342. if ( json !== undefined && json.length > 0 ) {
  19343. const manager = new LoadingManager( onLoad );
  19344. loader = new ImageLoader( manager );
  19345. loader.setCrossOrigin( this.crossOrigin );
  19346. for ( let i = 0, il = json.length; i < il; i ++ ) {
  19347. const image = json[ i ];
  19348. const url = image.url;
  19349. if ( Array.isArray( url ) ) {
  19350. // load array of images e.g CubeTexture
  19351. const imageArray = [];
  19352. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  19353. const currentUrl = url[ j ];
  19354. const deserializedImage = deserializeImage( currentUrl );
  19355. if ( deserializedImage !== null ) {
  19356. if ( deserializedImage instanceof HTMLImageElement ) {
  19357. imageArray.push( deserializedImage );
  19358. } else {
  19359. // special case: handle array of data textures for cube textures
  19360. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  19361. }
  19362. }
  19363. }
  19364. images[ image.uuid ] = new Source( imageArray );
  19365. } else {
  19366. // load single image
  19367. const deserializedImage = deserializeImage( image.url );
  19368. images[ image.uuid ] = new Source( deserializedImage );
  19369. }
  19370. }
  19371. }
  19372. return images;
  19373. }
  19374. async parseImagesAsync( json ) {
  19375. const scope = this;
  19376. const images = {};
  19377. let loader;
  19378. async function deserializeImage( image ) {
  19379. if ( typeof image === 'string' ) {
  19380. const url = image;
  19381. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  19382. return await loader.loadAsync( path );
  19383. } else {
  19384. if ( image.data ) {
  19385. return {
  19386. data: getTypedArray( image.type, image.data ),
  19387. width: image.width,
  19388. height: image.height
  19389. };
  19390. } else {
  19391. return null;
  19392. }
  19393. }
  19394. }
  19395. if ( json !== undefined && json.length > 0 ) {
  19396. loader = new ImageLoader( this.manager );
  19397. loader.setCrossOrigin( this.crossOrigin );
  19398. for ( let i = 0, il = json.length; i < il; i ++ ) {
  19399. const image = json[ i ];
  19400. const url = image.url;
  19401. if ( Array.isArray( url ) ) {
  19402. // load array of images e.g CubeTexture
  19403. const imageArray = [];
  19404. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  19405. const currentUrl = url[ j ];
  19406. const deserializedImage = await deserializeImage( currentUrl );
  19407. if ( deserializedImage !== null ) {
  19408. if ( deserializedImage instanceof HTMLImageElement ) {
  19409. imageArray.push( deserializedImage );
  19410. } else {
  19411. // special case: handle array of data textures for cube textures
  19412. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  19413. }
  19414. }
  19415. }
  19416. images[ image.uuid ] = new Source( imageArray );
  19417. } else {
  19418. // load single image
  19419. const deserializedImage = await deserializeImage( image.url );
  19420. images[ image.uuid ] = new Source( deserializedImage );
  19421. }
  19422. }
  19423. }
  19424. return images;
  19425. }
  19426. parseTextures( json, images ) {
  19427. function parseConstant( value, type ) {
  19428. if ( typeof value === 'number' ) return value;
  19429. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  19430. return type[ value ];
  19431. }
  19432. const textures = {};
  19433. if ( json !== undefined ) {
  19434. for ( let i = 0, l = json.length; i < l; i ++ ) {
  19435. const data = json[ i ];
  19436. if ( data.image === undefined ) {
  19437. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  19438. }
  19439. if ( images[ data.image ] === undefined ) {
  19440. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  19441. }
  19442. const source = images[ data.image ];
  19443. const image = source.data;
  19444. let texture;
  19445. if ( Array.isArray( image ) ) {
  19446. texture = new CubeTexture();
  19447. if ( image.length === 6 ) texture.needsUpdate = true;
  19448. } else {
  19449. if ( image && image.data ) {
  19450. texture = new DataTexture();
  19451. } else {
  19452. texture = new Texture();
  19453. }
  19454. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  19455. }
  19456. texture.source = source;
  19457. texture.uuid = data.uuid;
  19458. if ( data.name !== undefined ) texture.name = data.name;
  19459. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  19460. if ( data.channel !== undefined ) texture.channel = data.channel;
  19461. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  19462. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  19463. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  19464. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  19465. if ( data.wrap !== undefined ) {
  19466. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  19467. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  19468. }
  19469. if ( data.format !== undefined ) texture.format = data.format;
  19470. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  19471. if ( data.type !== undefined ) texture.type = data.type;
  19472. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  19473. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  19474. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  19475. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  19476. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  19477. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  19478. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  19479. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  19480. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  19481. if ( data.userData !== undefined ) texture.userData = data.userData;
  19482. textures[ data.uuid ] = texture;
  19483. }
  19484. }
  19485. return textures;
  19486. }
  19487. parseObject( data, geometries, materials, textures, animations ) {
  19488. let object;
  19489. function getGeometry( name ) {
  19490. if ( geometries[ name ] === undefined ) {
  19491. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  19492. }
  19493. return geometries[ name ];
  19494. }
  19495. function getMaterial( name ) {
  19496. if ( name === undefined ) return undefined;
  19497. if ( Array.isArray( name ) ) {
  19498. const array = [];
  19499. for ( let i = 0, l = name.length; i < l; i ++ ) {
  19500. const uuid = name[ i ];
  19501. if ( materials[ uuid ] === undefined ) {
  19502. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  19503. }
  19504. array.push( materials[ uuid ] );
  19505. }
  19506. return array;
  19507. }
  19508. if ( materials[ name ] === undefined ) {
  19509. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  19510. }
  19511. return materials[ name ];
  19512. }
  19513. function getTexture( uuid ) {
  19514. if ( textures[ uuid ] === undefined ) {
  19515. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  19516. }
  19517. return textures[ uuid ];
  19518. }
  19519. let geometry, material;
  19520. switch ( data.type ) {
  19521. case 'Scene':
  19522. object = new Scene();
  19523. if ( data.background !== undefined ) {
  19524. if ( Number.isInteger( data.background ) ) {
  19525. object.background = new Color( data.background );
  19526. } else {
  19527. object.background = getTexture( data.background );
  19528. }
  19529. }
  19530. if ( data.environment !== undefined ) {
  19531. object.environment = getTexture( data.environment );
  19532. }
  19533. if ( data.fog !== undefined ) {
  19534. if ( data.fog.type === 'Fog' ) {
  19535. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  19536. } else if ( data.fog.type === 'FogExp2' ) {
  19537. object.fog = new FogExp2( data.fog.color, data.fog.density );
  19538. }
  19539. if ( data.fog.name !== '' ) {
  19540. object.fog.name = data.fog.name;
  19541. }
  19542. }
  19543. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  19544. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  19545. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  19546. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  19547. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  19548. break;
  19549. case 'PerspectiveCamera':
  19550. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  19551. if ( data.focus !== undefined ) object.focus = data.focus;
  19552. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  19553. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  19554. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  19555. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  19556. break;
  19557. case 'OrthographicCamera':
  19558. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  19559. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  19560. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  19561. break;
  19562. case 'AmbientLight':
  19563. object = new AmbientLight( data.color, data.intensity );
  19564. break;
  19565. case 'DirectionalLight':
  19566. object = new DirectionalLight( data.color, data.intensity );
  19567. object.target = data.target || '';
  19568. break;
  19569. case 'PointLight':
  19570. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  19571. break;
  19572. case 'RectAreaLight':
  19573. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  19574. break;
  19575. case 'SpotLight':
  19576. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  19577. object.target = data.target || '';
  19578. break;
  19579. case 'HemisphereLight':
  19580. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  19581. break;
  19582. case 'LightProbe':
  19583. object = new LightProbe().fromJSON( data );
  19584. break;
  19585. case 'SkinnedMesh':
  19586. geometry = getGeometry( data.geometry );
  19587. material = getMaterial( data.material );
  19588. object = new SkinnedMesh( geometry, material );
  19589. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  19590. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  19591. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  19592. break;
  19593. case 'Mesh':
  19594. geometry = getGeometry( data.geometry );
  19595. material = getMaterial( data.material );
  19596. object = new Mesh( geometry, material );
  19597. break;
  19598. case 'InstancedMesh':
  19599. geometry = getGeometry( data.geometry );
  19600. material = getMaterial( data.material );
  19601. const count = data.count;
  19602. const instanceMatrix = data.instanceMatrix;
  19603. const instanceColor = data.instanceColor;
  19604. object = new InstancedMesh( geometry, material, count );
  19605. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  19606. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  19607. break;
  19608. case 'BatchedMesh':
  19609. geometry = getGeometry( data.geometry );
  19610. material = getMaterial( data.material );
  19611. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  19612. object.geometry = geometry;
  19613. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  19614. object.sortObjects = data.sortObjects;
  19615. object._drawRanges = data.drawRanges;
  19616. object._reservedRanges = data.reservedRanges;
  19617. object._visibility = data.visibility;
  19618. object._active = data.active;
  19619. object._bounds = data.bounds.map( bound => {
  19620. const box = new Box3();
  19621. box.min.fromArray( bound.boxMin );
  19622. box.max.fromArray( bound.boxMax );
  19623. const sphere = new Sphere();
  19624. sphere.radius = bound.sphereRadius;
  19625. sphere.center.fromArray( bound.sphereCenter );
  19626. return {
  19627. boxInitialized: bound.boxInitialized,
  19628. box: box,
  19629. sphereInitialized: bound.sphereInitialized,
  19630. sphere: sphere
  19631. };
  19632. } );
  19633. object._maxInstanceCount = data.maxInstanceCount;
  19634. object._maxVertexCount = data.maxVertexCount;
  19635. object._maxIndexCount = data.maxIndexCount;
  19636. object._geometryInitialized = data.geometryInitialized;
  19637. object._geometryCount = data.geometryCount;
  19638. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  19639. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  19640. break;
  19641. case 'LOD':
  19642. object = new LOD();
  19643. break;
  19644. case 'Line':
  19645. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  19646. break;
  19647. case 'LineLoop':
  19648. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  19649. break;
  19650. case 'LineSegments':
  19651. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  19652. break;
  19653. case 'PointCloud':
  19654. case 'Points':
  19655. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  19656. break;
  19657. case 'Sprite':
  19658. object = new Sprite( getMaterial( data.material ) );
  19659. break;
  19660. case 'Group':
  19661. object = new Group();
  19662. break;
  19663. case 'Bone':
  19664. object = new Bone();
  19665. break;
  19666. default:
  19667. object = new Object3D();
  19668. }
  19669. object.uuid = data.uuid;
  19670. if ( data.name !== undefined ) object.name = data.name;
  19671. if ( data.matrix !== undefined ) {
  19672. object.matrix.fromArray( data.matrix );
  19673. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  19674. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  19675. } else {
  19676. if ( data.position !== undefined ) object.position.fromArray( data.position );
  19677. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  19678. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  19679. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  19680. }
  19681. if ( data.up !== undefined ) object.up.fromArray( data.up );
  19682. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  19683. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  19684. if ( data.shadow ) {
  19685. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  19686. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  19687. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  19688. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  19689. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  19690. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  19691. }
  19692. if ( data.visible !== undefined ) object.visible = data.visible;
  19693. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  19694. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  19695. if ( data.userData !== undefined ) object.userData = data.userData;
  19696. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  19697. if ( data.children !== undefined ) {
  19698. const children = data.children;
  19699. for ( let i = 0; i < children.length; i ++ ) {
  19700. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  19701. }
  19702. }
  19703. if ( data.animations !== undefined ) {
  19704. const objectAnimations = data.animations;
  19705. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  19706. const uuid = objectAnimations[ i ];
  19707. object.animations.push( animations[ uuid ] );
  19708. }
  19709. }
  19710. if ( data.type === 'LOD' ) {
  19711. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  19712. const levels = data.levels;
  19713. for ( let l = 0; l < levels.length; l ++ ) {
  19714. const level = levels[ l ];
  19715. const child = object.getObjectByProperty( 'uuid', level.object );
  19716. if ( child !== undefined ) {
  19717. object.addLevel( child, level.distance, level.hysteresis );
  19718. }
  19719. }
  19720. }
  19721. return object;
  19722. }
  19723. bindSkeletons( object, skeletons ) {
  19724. if ( Object.keys( skeletons ).length === 0 ) return;
  19725. object.traverse( function ( child ) {
  19726. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  19727. const skeleton = skeletons[ child.skeleton ];
  19728. if ( skeleton === undefined ) {
  19729. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  19730. } else {
  19731. child.bind( skeleton, child.bindMatrix );
  19732. }
  19733. }
  19734. } );
  19735. }
  19736. bindLightTargets( object ) {
  19737. object.traverse( function ( child ) {
  19738. if ( child.isDirectionalLight || child.isSpotLight ) {
  19739. const uuid = child.target;
  19740. const target = object.getObjectByProperty( 'uuid', uuid );
  19741. if ( target !== undefined ) {
  19742. child.target = target;
  19743. } else {
  19744. child.target = new Object3D();
  19745. }
  19746. }
  19747. } );
  19748. }
  19749. }
  19750. const TEXTURE_MAPPING = {
  19751. UVMapping: UVMapping,
  19752. CubeReflectionMapping: CubeReflectionMapping,
  19753. CubeRefractionMapping: CubeRefractionMapping,
  19754. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  19755. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  19756. CubeUVReflectionMapping: CubeUVReflectionMapping
  19757. };
  19758. const TEXTURE_WRAPPING = {
  19759. RepeatWrapping: RepeatWrapping,
  19760. ClampToEdgeWrapping: ClampToEdgeWrapping,
  19761. MirroredRepeatWrapping: MirroredRepeatWrapping
  19762. };
  19763. const TEXTURE_FILTER = {
  19764. NearestFilter: NearestFilter,
  19765. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  19766. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  19767. LinearFilter: LinearFilter,
  19768. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  19769. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  19770. };
  19771. class ImageBitmapLoader extends Loader {
  19772. constructor( manager ) {
  19773. super( manager );
  19774. this.isImageBitmapLoader = true;
  19775. if ( typeof createImageBitmap === 'undefined' ) {
  19776. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  19777. }
  19778. if ( typeof fetch === 'undefined' ) {
  19779. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  19780. }
  19781. this.options = { premultiplyAlpha: 'none' };
  19782. }
  19783. setOptions( options ) {
  19784. this.options = options;
  19785. return this;
  19786. }
  19787. load( url, onLoad, onProgress, onError ) {
  19788. if ( url === undefined ) url = '';
  19789. if ( this.path !== undefined ) url = this.path + url;
  19790. url = this.manager.resolveURL( url );
  19791. const scope = this;
  19792. const cached = Cache.get( url );
  19793. if ( cached !== undefined ) {
  19794. scope.manager.itemStart( url );
  19795. // If cached is a promise, wait for it to resolve
  19796. if ( cached.then ) {
  19797. cached.then( imageBitmap => {
  19798. if ( onLoad ) onLoad( imageBitmap );
  19799. scope.manager.itemEnd( url );
  19800. } ).catch( e => {
  19801. if ( onError ) onError( e );
  19802. } );
  19803. return;
  19804. }
  19805. // If cached is not a promise (i.e., it's already an imageBitmap)
  19806. setTimeout( function () {
  19807. if ( onLoad ) onLoad( cached );
  19808. scope.manager.itemEnd( url );
  19809. }, 0 );
  19810. return cached;
  19811. }
  19812. const fetchOptions = {};
  19813. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  19814. fetchOptions.headers = this.requestHeader;
  19815. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  19816. return res.blob();
  19817. } ).then( function ( blob ) {
  19818. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  19819. } ).then( function ( imageBitmap ) {
  19820. Cache.add( url, imageBitmap );
  19821. if ( onLoad ) onLoad( imageBitmap );
  19822. scope.manager.itemEnd( url );
  19823. return imageBitmap;
  19824. } ).catch( function ( e ) {
  19825. if ( onError ) onError( e );
  19826. Cache.remove( url );
  19827. scope.manager.itemError( url );
  19828. scope.manager.itemEnd( url );
  19829. } );
  19830. Cache.add( url, promise );
  19831. scope.manager.itemStart( url );
  19832. }
  19833. }
  19834. let _context;
  19835. class AudioContext {
  19836. static getContext() {
  19837. if ( _context === undefined ) {
  19838. _context = new ( window.AudioContext || window.webkitAudioContext )();
  19839. }
  19840. return _context;
  19841. }
  19842. static setContext( value ) {
  19843. _context = value;
  19844. }
  19845. }
  19846. class AudioLoader extends Loader {
  19847. constructor( manager ) {
  19848. super( manager );
  19849. }
  19850. load( url, onLoad, onProgress, onError ) {
  19851. const scope = this;
  19852. const loader = new FileLoader( this.manager );
  19853. loader.setResponseType( 'arraybuffer' );
  19854. loader.setPath( this.path );
  19855. loader.setRequestHeader( this.requestHeader );
  19856. loader.setWithCredentials( this.withCredentials );
  19857. loader.load( url, function ( buffer ) {
  19858. try {
  19859. // Create a copy of the buffer. The `decodeAudioData` method
  19860. // detaches the buffer when complete, preventing reuse.
  19861. const bufferCopy = buffer.slice( 0 );
  19862. const context = AudioContext.getContext();
  19863. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  19864. onLoad( audioBuffer );
  19865. } ).catch( handleError );
  19866. } catch ( e ) {
  19867. handleError( e );
  19868. }
  19869. }, onProgress, onError );
  19870. function handleError( e ) {
  19871. if ( onError ) {
  19872. onError( e );
  19873. } else {
  19874. console.error( e );
  19875. }
  19876. scope.manager.itemError( url );
  19877. }
  19878. }
  19879. }
  19880. const _eyeRight = /*@__PURE__*/ new Matrix4();
  19881. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  19882. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  19883. class StereoCamera {
  19884. constructor() {
  19885. this.type = 'StereoCamera';
  19886. this.aspect = 1;
  19887. this.eyeSep = 0.064;
  19888. this.cameraL = new PerspectiveCamera();
  19889. this.cameraL.layers.enable( 1 );
  19890. this.cameraL.matrixAutoUpdate = false;
  19891. this.cameraR = new PerspectiveCamera();
  19892. this.cameraR.layers.enable( 2 );
  19893. this.cameraR.matrixAutoUpdate = false;
  19894. this._cache = {
  19895. focus: null,
  19896. fov: null,
  19897. aspect: null,
  19898. near: null,
  19899. far: null,
  19900. zoom: null,
  19901. eyeSep: null
  19902. };
  19903. }
  19904. update( camera ) {
  19905. const cache = this._cache;
  19906. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  19907. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  19908. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  19909. if ( needsUpdate ) {
  19910. cache.focus = camera.focus;
  19911. cache.fov = camera.fov;
  19912. cache.aspect = camera.aspect * this.aspect;
  19913. cache.near = camera.near;
  19914. cache.far = camera.far;
  19915. cache.zoom = camera.zoom;
  19916. cache.eyeSep = this.eyeSep;
  19917. // Off-axis stereoscopic effect based on
  19918. // http://paulbourke.net/stereographics/stereorender/
  19919. _projectionMatrix.copy( camera.projectionMatrix );
  19920. const eyeSepHalf = cache.eyeSep / 2;
  19921. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  19922. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  19923. let xmin, xmax;
  19924. // translate xOffset
  19925. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  19926. _eyeRight.elements[ 12 ] = eyeSepHalf;
  19927. // for left eye
  19928. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  19929. xmax = ymax * cache.aspect + eyeSepOnProjection;
  19930. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  19931. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19932. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  19933. // for right eye
  19934. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  19935. xmax = ymax * cache.aspect - eyeSepOnProjection;
  19936. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  19937. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19938. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  19939. }
  19940. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  19941. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  19942. }
  19943. }
  19944. class ArrayCamera extends PerspectiveCamera {
  19945. constructor( array = [] ) {
  19946. super();
  19947. this.isArrayCamera = true;
  19948. this.cameras = array;
  19949. this.index = 0;
  19950. }
  19951. }
  19952. class Clock {
  19953. constructor( autoStart = true ) {
  19954. this.autoStart = autoStart;
  19955. this.startTime = 0;
  19956. this.oldTime = 0;
  19957. this.elapsedTime = 0;
  19958. this.running = false;
  19959. }
  19960. start() {
  19961. this.startTime = now();
  19962. this.oldTime = this.startTime;
  19963. this.elapsedTime = 0;
  19964. this.running = true;
  19965. }
  19966. stop() {
  19967. this.getElapsedTime();
  19968. this.running = false;
  19969. this.autoStart = false;
  19970. }
  19971. getElapsedTime() {
  19972. this.getDelta();
  19973. return this.elapsedTime;
  19974. }
  19975. getDelta() {
  19976. let diff = 0;
  19977. if ( this.autoStart && ! this.running ) {
  19978. this.start();
  19979. return 0;
  19980. }
  19981. if ( this.running ) {
  19982. const newTime = now();
  19983. diff = ( newTime - this.oldTime ) / 1000;
  19984. this.oldTime = newTime;
  19985. this.elapsedTime += diff;
  19986. }
  19987. return diff;
  19988. }
  19989. }
  19990. function now() {
  19991. return performance.now();
  19992. }
  19993. const _position$1 = /*@__PURE__*/ new Vector3();
  19994. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  19995. const _scale$1 = /*@__PURE__*/ new Vector3();
  19996. const _orientation$1 = /*@__PURE__*/ new Vector3();
  19997. class AudioListener extends Object3D {
  19998. constructor() {
  19999. super();
  20000. this.type = 'AudioListener';
  20001. this.context = AudioContext.getContext();
  20002. this.gain = this.context.createGain();
  20003. this.gain.connect( this.context.destination );
  20004. this.filter = null;
  20005. this.timeDelta = 0;
  20006. // private
  20007. this._clock = new Clock();
  20008. }
  20009. getInput() {
  20010. return this.gain;
  20011. }
  20012. removeFilter() {
  20013. if ( this.filter !== null ) {
  20014. this.gain.disconnect( this.filter );
  20015. this.filter.disconnect( this.context.destination );
  20016. this.gain.connect( this.context.destination );
  20017. this.filter = null;
  20018. }
  20019. return this;
  20020. }
  20021. getFilter() {
  20022. return this.filter;
  20023. }
  20024. setFilter( value ) {
  20025. if ( this.filter !== null ) {
  20026. this.gain.disconnect( this.filter );
  20027. this.filter.disconnect( this.context.destination );
  20028. } else {
  20029. this.gain.disconnect( this.context.destination );
  20030. }
  20031. this.filter = value;
  20032. this.gain.connect( this.filter );
  20033. this.filter.connect( this.context.destination );
  20034. return this;
  20035. }
  20036. getMasterVolume() {
  20037. return this.gain.gain.value;
  20038. }
  20039. setMasterVolume( value ) {
  20040. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  20041. return this;
  20042. }
  20043. updateMatrixWorld( force ) {
  20044. super.updateMatrixWorld( force );
  20045. const listener = this.context.listener;
  20046. const up = this.up;
  20047. this.timeDelta = this._clock.getDelta();
  20048. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  20049. _orientation$1.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  20050. if ( listener.positionX ) {
  20051. // code path for Chrome (see #14393)
  20052. const endTime = this.context.currentTime + this.timeDelta;
  20053. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  20054. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  20055. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  20056. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  20057. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  20058. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  20059. listener.upX.linearRampToValueAtTime( up.x, endTime );
  20060. listener.upY.linearRampToValueAtTime( up.y, endTime );
  20061. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  20062. } else {
  20063. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  20064. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  20065. }
  20066. }
  20067. }
  20068. class Audio extends Object3D {
  20069. constructor( listener ) {
  20070. super();
  20071. this.type = 'Audio';
  20072. this.listener = listener;
  20073. this.context = listener.context;
  20074. this.gain = this.context.createGain();
  20075. this.gain.connect( listener.getInput() );
  20076. this.autoplay = false;
  20077. this.buffer = null;
  20078. this.detune = 0;
  20079. this.loop = false;
  20080. this.loopStart = 0;
  20081. this.loopEnd = 0;
  20082. this.offset = 0;
  20083. this.duration = undefined;
  20084. this.playbackRate = 1;
  20085. this.isPlaying = false;
  20086. this.hasPlaybackControl = true;
  20087. this.source = null;
  20088. this.sourceType = 'empty';
  20089. this._startedAt = 0;
  20090. this._progress = 0;
  20091. this._connected = false;
  20092. this.filters = [];
  20093. }
  20094. getOutput() {
  20095. return this.gain;
  20096. }
  20097. setNodeSource( audioNode ) {
  20098. this.hasPlaybackControl = false;
  20099. this.sourceType = 'audioNode';
  20100. this.source = audioNode;
  20101. this.connect();
  20102. return this;
  20103. }
  20104. setMediaElementSource( mediaElement ) {
  20105. this.hasPlaybackControl = false;
  20106. this.sourceType = 'mediaNode';
  20107. this.source = this.context.createMediaElementSource( mediaElement );
  20108. this.connect();
  20109. return this;
  20110. }
  20111. setMediaStreamSource( mediaStream ) {
  20112. this.hasPlaybackControl = false;
  20113. this.sourceType = 'mediaStreamNode';
  20114. this.source = this.context.createMediaStreamSource( mediaStream );
  20115. this.connect();
  20116. return this;
  20117. }
  20118. setBuffer( audioBuffer ) {
  20119. this.buffer = audioBuffer;
  20120. this.sourceType = 'buffer';
  20121. if ( this.autoplay ) this.play();
  20122. return this;
  20123. }
  20124. play( delay = 0 ) {
  20125. if ( this.isPlaying === true ) {
  20126. console.warn( 'THREE.Audio: Audio is already playing.' );
  20127. return;
  20128. }
  20129. if ( this.hasPlaybackControl === false ) {
  20130. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20131. return;
  20132. }
  20133. this._startedAt = this.context.currentTime + delay;
  20134. const source = this.context.createBufferSource();
  20135. source.buffer = this.buffer;
  20136. source.loop = this.loop;
  20137. source.loopStart = this.loopStart;
  20138. source.loopEnd = this.loopEnd;
  20139. source.onended = this.onEnded.bind( this );
  20140. source.start( this._startedAt, this._progress + this.offset, this.duration );
  20141. this.isPlaying = true;
  20142. this.source = source;
  20143. this.setDetune( this.detune );
  20144. this.setPlaybackRate( this.playbackRate );
  20145. return this.connect();
  20146. }
  20147. pause() {
  20148. if ( this.hasPlaybackControl === false ) {
  20149. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20150. return;
  20151. }
  20152. if ( this.isPlaying === true ) {
  20153. // update current progress
  20154. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  20155. if ( this.loop === true ) {
  20156. // ensure _progress does not exceed duration with looped audios
  20157. this._progress = this._progress % ( this.duration || this.buffer.duration );
  20158. }
  20159. this.source.stop();
  20160. this.source.onended = null;
  20161. this.isPlaying = false;
  20162. }
  20163. return this;
  20164. }
  20165. stop( delay = 0 ) {
  20166. if ( this.hasPlaybackControl === false ) {
  20167. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20168. return;
  20169. }
  20170. this._progress = 0;
  20171. if ( this.source !== null ) {
  20172. this.source.stop( this.context.currentTime + delay );
  20173. this.source.onended = null;
  20174. }
  20175. this.isPlaying = false;
  20176. return this;
  20177. }
  20178. connect() {
  20179. if ( this.filters.length > 0 ) {
  20180. this.source.connect( this.filters[ 0 ] );
  20181. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  20182. this.filters[ i - 1 ].connect( this.filters[ i ] );
  20183. }
  20184. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  20185. } else {
  20186. this.source.connect( this.getOutput() );
  20187. }
  20188. this._connected = true;
  20189. return this;
  20190. }
  20191. disconnect() {
  20192. if ( this._connected === false ) {
  20193. return;
  20194. }
  20195. if ( this.filters.length > 0 ) {
  20196. this.source.disconnect( this.filters[ 0 ] );
  20197. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  20198. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  20199. }
  20200. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  20201. } else {
  20202. this.source.disconnect( this.getOutput() );
  20203. }
  20204. this._connected = false;
  20205. return this;
  20206. }
  20207. getFilters() {
  20208. return this.filters;
  20209. }
  20210. setFilters( value ) {
  20211. if ( ! value ) value = [];
  20212. if ( this._connected === true ) {
  20213. this.disconnect();
  20214. this.filters = value.slice();
  20215. this.connect();
  20216. } else {
  20217. this.filters = value.slice();
  20218. }
  20219. return this;
  20220. }
  20221. setDetune( value ) {
  20222. this.detune = value;
  20223. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  20224. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  20225. }
  20226. return this;
  20227. }
  20228. getDetune() {
  20229. return this.detune;
  20230. }
  20231. getFilter() {
  20232. return this.getFilters()[ 0 ];
  20233. }
  20234. setFilter( filter ) {
  20235. return this.setFilters( filter ? [ filter ] : [] );
  20236. }
  20237. setPlaybackRate( value ) {
  20238. if ( this.hasPlaybackControl === false ) {
  20239. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20240. return;
  20241. }
  20242. this.playbackRate = value;
  20243. if ( this.isPlaying === true ) {
  20244. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  20245. }
  20246. return this;
  20247. }
  20248. getPlaybackRate() {
  20249. return this.playbackRate;
  20250. }
  20251. onEnded() {
  20252. this.isPlaying = false;
  20253. this._progress = 0;
  20254. }
  20255. getLoop() {
  20256. if ( this.hasPlaybackControl === false ) {
  20257. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20258. return false;
  20259. }
  20260. return this.loop;
  20261. }
  20262. setLoop( value ) {
  20263. if ( this.hasPlaybackControl === false ) {
  20264. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  20265. return;
  20266. }
  20267. this.loop = value;
  20268. if ( this.isPlaying === true ) {
  20269. this.source.loop = this.loop;
  20270. }
  20271. return this;
  20272. }
  20273. setLoopStart( value ) {
  20274. this.loopStart = value;
  20275. return this;
  20276. }
  20277. setLoopEnd( value ) {
  20278. this.loopEnd = value;
  20279. return this;
  20280. }
  20281. getVolume() {
  20282. return this.gain.gain.value;
  20283. }
  20284. setVolume( value ) {
  20285. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  20286. return this;
  20287. }
  20288. copy( source, recursive ) {
  20289. super.copy( source, recursive );
  20290. if ( source.sourceType !== 'buffer' ) {
  20291. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  20292. return this;
  20293. }
  20294. this.autoplay = source.autoplay;
  20295. this.buffer = source.buffer;
  20296. this.detune = source.detune;
  20297. this.loop = source.loop;
  20298. this.loopStart = source.loopStart;
  20299. this.loopEnd = source.loopEnd;
  20300. this.offset = source.offset;
  20301. this.duration = source.duration;
  20302. this.playbackRate = source.playbackRate;
  20303. this.hasPlaybackControl = source.hasPlaybackControl;
  20304. this.sourceType = source.sourceType;
  20305. this.filters = source.filters.slice();
  20306. return this;
  20307. }
  20308. clone( recursive ) {
  20309. return new this.constructor( this.listener ).copy( this, recursive );
  20310. }
  20311. }
  20312. const _position = /*@__PURE__*/ new Vector3();
  20313. const _quaternion = /*@__PURE__*/ new Quaternion();
  20314. const _scale = /*@__PURE__*/ new Vector3();
  20315. const _orientation = /*@__PURE__*/ new Vector3();
  20316. class PositionalAudio extends Audio {
  20317. constructor( listener ) {
  20318. super( listener );
  20319. this.panner = this.context.createPanner();
  20320. this.panner.panningModel = 'HRTF';
  20321. this.panner.connect( this.gain );
  20322. }
  20323. connect() {
  20324. super.connect();
  20325. this.panner.connect( this.gain );
  20326. }
  20327. disconnect() {
  20328. super.disconnect();
  20329. this.panner.disconnect( this.gain );
  20330. }
  20331. getOutput() {
  20332. return this.panner;
  20333. }
  20334. getRefDistance() {
  20335. return this.panner.refDistance;
  20336. }
  20337. setRefDistance( value ) {
  20338. this.panner.refDistance = value;
  20339. return this;
  20340. }
  20341. getRolloffFactor() {
  20342. return this.panner.rolloffFactor;
  20343. }
  20344. setRolloffFactor( value ) {
  20345. this.panner.rolloffFactor = value;
  20346. return this;
  20347. }
  20348. getDistanceModel() {
  20349. return this.panner.distanceModel;
  20350. }
  20351. setDistanceModel( value ) {
  20352. this.panner.distanceModel = value;
  20353. return this;
  20354. }
  20355. getMaxDistance() {
  20356. return this.panner.maxDistance;
  20357. }
  20358. setMaxDistance( value ) {
  20359. this.panner.maxDistance = value;
  20360. return this;
  20361. }
  20362. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  20363. this.panner.coneInnerAngle = coneInnerAngle;
  20364. this.panner.coneOuterAngle = coneOuterAngle;
  20365. this.panner.coneOuterGain = coneOuterGain;
  20366. return this;
  20367. }
  20368. updateMatrixWorld( force ) {
  20369. super.updateMatrixWorld( force );
  20370. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  20371. this.matrixWorld.decompose( _position, _quaternion, _scale );
  20372. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  20373. const panner = this.panner;
  20374. if ( panner.positionX ) {
  20375. // code path for Chrome and Firefox (see #14393)
  20376. const endTime = this.context.currentTime + this.listener.timeDelta;
  20377. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  20378. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  20379. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  20380. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  20381. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  20382. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  20383. } else {
  20384. panner.setPosition( _position.x, _position.y, _position.z );
  20385. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  20386. }
  20387. }
  20388. }
  20389. class AudioAnalyser {
  20390. constructor( audio, fftSize = 2048 ) {
  20391. this.analyser = audio.context.createAnalyser();
  20392. this.analyser.fftSize = fftSize;
  20393. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  20394. audio.getOutput().connect( this.analyser );
  20395. }
  20396. getFrequencyData() {
  20397. this.analyser.getByteFrequencyData( this.data );
  20398. return this.data;
  20399. }
  20400. getAverageFrequency() {
  20401. let value = 0;
  20402. const data = this.getFrequencyData();
  20403. for ( let i = 0; i < data.length; i ++ ) {
  20404. value += data[ i ];
  20405. }
  20406. return value / data.length;
  20407. }
  20408. }
  20409. class PropertyMixer {
  20410. constructor( binding, typeName, valueSize ) {
  20411. this.binding = binding;
  20412. this.valueSize = valueSize;
  20413. let mixFunction,
  20414. mixFunctionAdditive,
  20415. setIdentity;
  20416. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  20417. //
  20418. // interpolators can use .buffer as their .result
  20419. // the data then goes to 'incoming'
  20420. //
  20421. // 'accu0' and 'accu1' are used frame-interleaved for
  20422. // the cumulative result and are compared to detect
  20423. // changes
  20424. //
  20425. // 'orig' stores the original state of the property
  20426. //
  20427. // 'add' is used for additive cumulative results
  20428. //
  20429. // 'work' is optional and is only present for quaternion types. It is used
  20430. // to store intermediate quaternion multiplication results
  20431. switch ( typeName ) {
  20432. case 'quaternion':
  20433. mixFunction = this._slerp;
  20434. mixFunctionAdditive = this._slerpAdditive;
  20435. setIdentity = this._setAdditiveIdentityQuaternion;
  20436. this.buffer = new Float64Array( valueSize * 6 );
  20437. this._workIndex = 5;
  20438. break;
  20439. case 'string':
  20440. case 'bool':
  20441. mixFunction = this._select;
  20442. // Use the regular mix function and for additive on these types,
  20443. // additive is not relevant for non-numeric types
  20444. mixFunctionAdditive = this._select;
  20445. setIdentity = this._setAdditiveIdentityOther;
  20446. this.buffer = new Array( valueSize * 5 );
  20447. break;
  20448. default:
  20449. mixFunction = this._lerp;
  20450. mixFunctionAdditive = this._lerpAdditive;
  20451. setIdentity = this._setAdditiveIdentityNumeric;
  20452. this.buffer = new Float64Array( valueSize * 5 );
  20453. }
  20454. this._mixBufferRegion = mixFunction;
  20455. this._mixBufferRegionAdditive = mixFunctionAdditive;
  20456. this._setIdentity = setIdentity;
  20457. this._origIndex = 3;
  20458. this._addIndex = 4;
  20459. this.cumulativeWeight = 0;
  20460. this.cumulativeWeightAdditive = 0;
  20461. this.useCount = 0;
  20462. this.referenceCount = 0;
  20463. }
  20464. // accumulate data in the 'incoming' region into 'accu<i>'
  20465. accumulate( accuIndex, weight ) {
  20466. // note: happily accumulating nothing when weight = 0, the caller knows
  20467. // the weight and shouldn't have made the call in the first place
  20468. const buffer = this.buffer,
  20469. stride = this.valueSize,
  20470. offset = accuIndex * stride + stride;
  20471. let currentWeight = this.cumulativeWeight;
  20472. if ( currentWeight === 0 ) {
  20473. // accuN := incoming * weight
  20474. for ( let i = 0; i !== stride; ++ i ) {
  20475. buffer[ offset + i ] = buffer[ i ];
  20476. }
  20477. currentWeight = weight;
  20478. } else {
  20479. // accuN := accuN + incoming * weight
  20480. currentWeight += weight;
  20481. const mix = weight / currentWeight;
  20482. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  20483. }
  20484. this.cumulativeWeight = currentWeight;
  20485. }
  20486. // accumulate data in the 'incoming' region into 'add'
  20487. accumulateAdditive( weight ) {
  20488. const buffer = this.buffer,
  20489. stride = this.valueSize,
  20490. offset = stride * this._addIndex;
  20491. if ( this.cumulativeWeightAdditive === 0 ) {
  20492. // add = identity
  20493. this._setIdentity();
  20494. }
  20495. // add := add + incoming * weight
  20496. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  20497. this.cumulativeWeightAdditive += weight;
  20498. }
  20499. // apply the state of 'accu<i>' to the binding when accus differ
  20500. apply( accuIndex ) {
  20501. const stride = this.valueSize,
  20502. buffer = this.buffer,
  20503. offset = accuIndex * stride + stride,
  20504. weight = this.cumulativeWeight,
  20505. weightAdditive = this.cumulativeWeightAdditive,
  20506. binding = this.binding;
  20507. this.cumulativeWeight = 0;
  20508. this.cumulativeWeightAdditive = 0;
  20509. if ( weight < 1 ) {
  20510. // accuN := accuN + original * ( 1 - cumulativeWeight )
  20511. const originalValueOffset = stride * this._origIndex;
  20512. this._mixBufferRegion(
  20513. buffer, offset, originalValueOffset, 1 - weight, stride );
  20514. }
  20515. if ( weightAdditive > 0 ) {
  20516. // accuN := accuN + additive accuN
  20517. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  20518. }
  20519. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  20520. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  20521. // value has changed -> update scene graph
  20522. binding.setValue( buffer, offset );
  20523. break;
  20524. }
  20525. }
  20526. }
  20527. // remember the state of the bound property and copy it to both accus
  20528. saveOriginalState() {
  20529. const binding = this.binding;
  20530. const buffer = this.buffer,
  20531. stride = this.valueSize,
  20532. originalValueOffset = stride * this._origIndex;
  20533. binding.getValue( buffer, originalValueOffset );
  20534. // accu[0..1] := orig -- initially detect changes against the original
  20535. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  20536. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  20537. }
  20538. // Add to identity for additive
  20539. this._setIdentity();
  20540. this.cumulativeWeight = 0;
  20541. this.cumulativeWeightAdditive = 0;
  20542. }
  20543. // apply the state previously taken via 'saveOriginalState' to the binding
  20544. restoreOriginalState() {
  20545. const originalValueOffset = this.valueSize * 3;
  20546. this.binding.setValue( this.buffer, originalValueOffset );
  20547. }
  20548. _setAdditiveIdentityNumeric() {
  20549. const startIndex = this._addIndex * this.valueSize;
  20550. const endIndex = startIndex + this.valueSize;
  20551. for ( let i = startIndex; i < endIndex; i ++ ) {
  20552. this.buffer[ i ] = 0;
  20553. }
  20554. }
  20555. _setAdditiveIdentityQuaternion() {
  20556. this._setAdditiveIdentityNumeric();
  20557. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  20558. }
  20559. _setAdditiveIdentityOther() {
  20560. const startIndex = this._origIndex * this.valueSize;
  20561. const targetIndex = this._addIndex * this.valueSize;
  20562. for ( let i = 0; i < this.valueSize; i ++ ) {
  20563. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  20564. }
  20565. }
  20566. // mix functions
  20567. _select( buffer, dstOffset, srcOffset, t, stride ) {
  20568. if ( t >= 0.5 ) {
  20569. for ( let i = 0; i !== stride; ++ i ) {
  20570. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  20571. }
  20572. }
  20573. }
  20574. _slerp( buffer, dstOffset, srcOffset, t ) {
  20575. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  20576. }
  20577. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  20578. const workOffset = this._workIndex * stride;
  20579. // Store result in intermediate buffer offset
  20580. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  20581. // Slerp to the intermediate result
  20582. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  20583. }
  20584. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  20585. const s = 1 - t;
  20586. for ( let i = 0; i !== stride; ++ i ) {
  20587. const j = dstOffset + i;
  20588. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  20589. }
  20590. }
  20591. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  20592. for ( let i = 0; i !== stride; ++ i ) {
  20593. const j = dstOffset + i;
  20594. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  20595. }
  20596. }
  20597. }
  20598. // Characters [].:/ are reserved for track binding syntax.
  20599. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  20600. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  20601. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  20602. // only latin characters, and the unicode \p{L} is not yet supported. So
  20603. // instead, we exclude reserved characters and match everything else.
  20604. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  20605. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  20606. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  20607. // be matched to parse the rest of the track name.
  20608. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  20609. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  20610. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  20611. // Object on target node, and accessor. May not contain reserved
  20612. // characters. Accessor may contain any character except closing bracket.
  20613. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  20614. // Property and accessor. May not contain reserved characters. Accessor may
  20615. // contain any non-bracket characters.
  20616. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  20617. const _trackRe = new RegExp( ''
  20618. + '^'
  20619. + _directoryRe
  20620. + _nodeRe
  20621. + _objectRe
  20622. + _propertyRe
  20623. + '$'
  20624. );
  20625. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  20626. class Composite {
  20627. constructor( targetGroup, path, optionalParsedPath ) {
  20628. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  20629. this._targetGroup = targetGroup;
  20630. this._bindings = targetGroup.subscribe_( path, parsedPath );
  20631. }
  20632. getValue( array, offset ) {
  20633. this.bind(); // bind all binding
  20634. const firstValidIndex = this._targetGroup.nCachedObjects_,
  20635. binding = this._bindings[ firstValidIndex ];
  20636. // and only call .getValue on the first
  20637. if ( binding !== undefined ) binding.getValue( array, offset );
  20638. }
  20639. setValue( array, offset ) {
  20640. const bindings = this._bindings;
  20641. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  20642. bindings[ i ].setValue( array, offset );
  20643. }
  20644. }
  20645. bind() {
  20646. const bindings = this._bindings;
  20647. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  20648. bindings[ i ].bind();
  20649. }
  20650. }
  20651. unbind() {
  20652. const bindings = this._bindings;
  20653. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  20654. bindings[ i ].unbind();
  20655. }
  20656. }
  20657. }
  20658. // Note: This class uses a State pattern on a per-method basis:
  20659. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  20660. // prototype version of these methods with one that represents
  20661. // the bound state. When the property is not found, the methods
  20662. // become no-ops.
  20663. class PropertyBinding {
  20664. constructor( rootNode, path, parsedPath ) {
  20665. this.path = path;
  20666. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  20667. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  20668. this.rootNode = rootNode;
  20669. // initial state of these methods that calls 'bind'
  20670. this.getValue = this._getValue_unbound;
  20671. this.setValue = this._setValue_unbound;
  20672. }
  20673. static create( root, path, parsedPath ) {
  20674. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  20675. return new PropertyBinding( root, path, parsedPath );
  20676. } else {
  20677. return new PropertyBinding.Composite( root, path, parsedPath );
  20678. }
  20679. }
  20680. /**
  20681. * Replaces spaces with underscores and removes unsupported characters from
  20682. * node names, to ensure compatibility with parseTrackName().
  20683. *
  20684. * @param {string} name Node name to be sanitized.
  20685. * @return {string}
  20686. */
  20687. static sanitizeNodeName( name ) {
  20688. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  20689. }
  20690. static parseTrackName( trackName ) {
  20691. const matches = _trackRe.exec( trackName );
  20692. if ( matches === null ) {
  20693. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  20694. }
  20695. const results = {
  20696. // directoryName: matches[ 1 ], // (tschw) currently unused
  20697. nodeName: matches[ 2 ],
  20698. objectName: matches[ 3 ],
  20699. objectIndex: matches[ 4 ],
  20700. propertyName: matches[ 5 ], // required
  20701. propertyIndex: matches[ 6 ]
  20702. };
  20703. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  20704. if ( lastDot !== undefined && lastDot !== -1 ) {
  20705. const objectName = results.nodeName.substring( lastDot + 1 );
  20706. // Object names must be checked against an allowlist. Otherwise, there
  20707. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  20708. // 'bar' could be the objectName, or part of a nodeName (which can
  20709. // include '.' characters).
  20710. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  20711. results.nodeName = results.nodeName.substring( 0, lastDot );
  20712. results.objectName = objectName;
  20713. }
  20714. }
  20715. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  20716. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  20717. }
  20718. return results;
  20719. }
  20720. static findNode( root, nodeName ) {
  20721. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  20722. return root;
  20723. }
  20724. // search into skeleton bones.
  20725. if ( root.skeleton ) {
  20726. const bone = root.skeleton.getBoneByName( nodeName );
  20727. if ( bone !== undefined ) {
  20728. return bone;
  20729. }
  20730. }
  20731. // search into node subtree.
  20732. if ( root.children ) {
  20733. const searchNodeSubtree = function ( children ) {
  20734. for ( let i = 0; i < children.length; i ++ ) {
  20735. const childNode = children[ i ];
  20736. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  20737. return childNode;
  20738. }
  20739. const result = searchNodeSubtree( childNode.children );
  20740. if ( result ) return result;
  20741. }
  20742. return null;
  20743. };
  20744. const subTreeNode = searchNodeSubtree( root.children );
  20745. if ( subTreeNode ) {
  20746. return subTreeNode;
  20747. }
  20748. }
  20749. return null;
  20750. }
  20751. // these are used to "bind" a nonexistent property
  20752. _getValue_unavailable() {}
  20753. _setValue_unavailable() {}
  20754. // Getters
  20755. _getValue_direct( buffer, offset ) {
  20756. buffer[ offset ] = this.targetObject[ this.propertyName ];
  20757. }
  20758. _getValue_array( buffer, offset ) {
  20759. const source = this.resolvedProperty;
  20760. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  20761. buffer[ offset ++ ] = source[ i ];
  20762. }
  20763. }
  20764. _getValue_arrayElement( buffer, offset ) {
  20765. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  20766. }
  20767. _getValue_toArray( buffer, offset ) {
  20768. this.resolvedProperty.toArray( buffer, offset );
  20769. }
  20770. // Direct
  20771. _setValue_direct( buffer, offset ) {
  20772. this.targetObject[ this.propertyName ] = buffer[ offset ];
  20773. }
  20774. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  20775. this.targetObject[ this.propertyName ] = buffer[ offset ];
  20776. this.targetObject.needsUpdate = true;
  20777. }
  20778. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20779. this.targetObject[ this.propertyName ] = buffer[ offset ];
  20780. this.targetObject.matrixWorldNeedsUpdate = true;
  20781. }
  20782. // EntireArray
  20783. _setValue_array( buffer, offset ) {
  20784. const dest = this.resolvedProperty;
  20785. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  20786. dest[ i ] = buffer[ offset ++ ];
  20787. }
  20788. }
  20789. _setValue_array_setNeedsUpdate( buffer, offset ) {
  20790. const dest = this.resolvedProperty;
  20791. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  20792. dest[ i ] = buffer[ offset ++ ];
  20793. }
  20794. this.targetObject.needsUpdate = true;
  20795. }
  20796. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20797. const dest = this.resolvedProperty;
  20798. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  20799. dest[ i ] = buffer[ offset ++ ];
  20800. }
  20801. this.targetObject.matrixWorldNeedsUpdate = true;
  20802. }
  20803. // ArrayElement
  20804. _setValue_arrayElement( buffer, offset ) {
  20805. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20806. }
  20807. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  20808. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20809. this.targetObject.needsUpdate = true;
  20810. }
  20811. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20812. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  20813. this.targetObject.matrixWorldNeedsUpdate = true;
  20814. }
  20815. // HasToFromArray
  20816. _setValue_fromArray( buffer, offset ) {
  20817. this.resolvedProperty.fromArray( buffer, offset );
  20818. }
  20819. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  20820. this.resolvedProperty.fromArray( buffer, offset );
  20821. this.targetObject.needsUpdate = true;
  20822. }
  20823. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  20824. this.resolvedProperty.fromArray( buffer, offset );
  20825. this.targetObject.matrixWorldNeedsUpdate = true;
  20826. }
  20827. _getValue_unbound( targetArray, offset ) {
  20828. this.bind();
  20829. this.getValue( targetArray, offset );
  20830. }
  20831. _setValue_unbound( sourceArray, offset ) {
  20832. this.bind();
  20833. this.setValue( sourceArray, offset );
  20834. }
  20835. // create getter / setter pair for a property in the scene graph
  20836. bind() {
  20837. let targetObject = this.node;
  20838. const parsedPath = this.parsedPath;
  20839. const objectName = parsedPath.objectName;
  20840. const propertyName = parsedPath.propertyName;
  20841. let propertyIndex = parsedPath.propertyIndex;
  20842. if ( ! targetObject ) {
  20843. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  20844. this.node = targetObject;
  20845. }
  20846. // set fail state so we can just 'return' on error
  20847. this.getValue = this._getValue_unavailable;
  20848. this.setValue = this._setValue_unavailable;
  20849. // ensure there is a value node
  20850. if ( ! targetObject ) {
  20851. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  20852. return;
  20853. }
  20854. if ( objectName ) {
  20855. let objectIndex = parsedPath.objectIndex;
  20856. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  20857. switch ( objectName ) {
  20858. case 'materials':
  20859. if ( ! targetObject.material ) {
  20860. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  20861. return;
  20862. }
  20863. if ( ! targetObject.material.materials ) {
  20864. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  20865. return;
  20866. }
  20867. targetObject = targetObject.material.materials;
  20868. break;
  20869. case 'bones':
  20870. if ( ! targetObject.skeleton ) {
  20871. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  20872. return;
  20873. }
  20874. // potential future optimization: skip this if propertyIndex is already an integer
  20875. // and convert the integer string to a true integer.
  20876. targetObject = targetObject.skeleton.bones;
  20877. // support resolving morphTarget names into indices.
  20878. for ( let i = 0; i < targetObject.length; i ++ ) {
  20879. if ( targetObject[ i ].name === objectIndex ) {
  20880. objectIndex = i;
  20881. break;
  20882. }
  20883. }
  20884. break;
  20885. case 'map':
  20886. if ( 'map' in targetObject ) {
  20887. targetObject = targetObject.map;
  20888. break;
  20889. }
  20890. if ( ! targetObject.material ) {
  20891. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  20892. return;
  20893. }
  20894. if ( ! targetObject.material.map ) {
  20895. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  20896. return;
  20897. }
  20898. targetObject = targetObject.material.map;
  20899. break;
  20900. default:
  20901. if ( targetObject[ objectName ] === undefined ) {
  20902. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  20903. return;
  20904. }
  20905. targetObject = targetObject[ objectName ];
  20906. }
  20907. if ( objectIndex !== undefined ) {
  20908. if ( targetObject[ objectIndex ] === undefined ) {
  20909. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  20910. return;
  20911. }
  20912. targetObject = targetObject[ objectIndex ];
  20913. }
  20914. }
  20915. // resolve property
  20916. const nodeProperty = targetObject[ propertyName ];
  20917. if ( nodeProperty === undefined ) {
  20918. const nodeName = parsedPath.nodeName;
  20919. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  20920. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  20921. return;
  20922. }
  20923. // determine versioning scheme
  20924. let versioning = this.Versioning.None;
  20925. this.targetObject = targetObject;
  20926. if ( targetObject.isMaterial === true ) {
  20927. versioning = this.Versioning.NeedsUpdate;
  20928. } else if ( targetObject.isObject3D === true ) {
  20929. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  20930. }
  20931. // determine how the property gets bound
  20932. let bindingType = this.BindingType.Direct;
  20933. if ( propertyIndex !== undefined ) {
  20934. // access a sub element of the property array (only primitives are supported right now)
  20935. if ( propertyName === 'morphTargetInfluences' ) {
  20936. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  20937. // support resolving morphTarget names into indices.
  20938. if ( ! targetObject.geometry ) {
  20939. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  20940. return;
  20941. }
  20942. if ( ! targetObject.geometry.morphAttributes ) {
  20943. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  20944. return;
  20945. }
  20946. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  20947. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  20948. }
  20949. }
  20950. bindingType = this.BindingType.ArrayElement;
  20951. this.resolvedProperty = nodeProperty;
  20952. this.propertyIndex = propertyIndex;
  20953. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  20954. // must use copy for Object3D.Euler/Quaternion
  20955. bindingType = this.BindingType.HasFromToArray;
  20956. this.resolvedProperty = nodeProperty;
  20957. } else if ( Array.isArray( nodeProperty ) ) {
  20958. bindingType = this.BindingType.EntireArray;
  20959. this.resolvedProperty = nodeProperty;
  20960. } else {
  20961. this.propertyName = propertyName;
  20962. }
  20963. // select getter / setter
  20964. this.getValue = this.GetterByBindingType[ bindingType ];
  20965. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  20966. }
  20967. unbind() {
  20968. this.node = null;
  20969. // back to the prototype version of getValue / setValue
  20970. // note: avoiding to mutate the shape of 'this' via 'delete'
  20971. this.getValue = this._getValue_unbound;
  20972. this.setValue = this._setValue_unbound;
  20973. }
  20974. }
  20975. PropertyBinding.Composite = Composite;
  20976. PropertyBinding.prototype.BindingType = {
  20977. Direct: 0,
  20978. EntireArray: 1,
  20979. ArrayElement: 2,
  20980. HasFromToArray: 3
  20981. };
  20982. PropertyBinding.prototype.Versioning = {
  20983. None: 0,
  20984. NeedsUpdate: 1,
  20985. MatrixWorldNeedsUpdate: 2
  20986. };
  20987. PropertyBinding.prototype.GetterByBindingType = [
  20988. PropertyBinding.prototype._getValue_direct,
  20989. PropertyBinding.prototype._getValue_array,
  20990. PropertyBinding.prototype._getValue_arrayElement,
  20991. PropertyBinding.prototype._getValue_toArray,
  20992. ];
  20993. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  20994. [
  20995. // Direct
  20996. PropertyBinding.prototype._setValue_direct,
  20997. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  20998. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  20999. ], [
  21000. // EntireArray
  21001. PropertyBinding.prototype._setValue_array,
  21002. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  21003. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  21004. ], [
  21005. // ArrayElement
  21006. PropertyBinding.prototype._setValue_arrayElement,
  21007. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  21008. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  21009. ], [
  21010. // HasToFromArray
  21011. PropertyBinding.prototype._setValue_fromArray,
  21012. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  21013. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  21014. ]
  21015. ];
  21016. /**
  21017. *
  21018. * A group of objects that receives a shared animation state.
  21019. *
  21020. * Usage:
  21021. *
  21022. * - Add objects you would otherwise pass as 'root' to the
  21023. * constructor or the .clipAction method of AnimationMixer.
  21024. *
  21025. * - Instead pass this object as 'root'.
  21026. *
  21027. * - You can also add and remove objects later when the mixer
  21028. * is running.
  21029. *
  21030. * Note:
  21031. *
  21032. * Objects of this class appear as one object to the mixer,
  21033. * so cache control of the individual objects must be done
  21034. * on the group.
  21035. *
  21036. * Limitation:
  21037. *
  21038. * - The animated properties must be compatible among the
  21039. * all objects in the group.
  21040. *
  21041. * - A single property can either be controlled through a
  21042. * target group or directly, but not both.
  21043. */
  21044. class AnimationObjectGroup {
  21045. constructor() {
  21046. this.isAnimationObjectGroup = true;
  21047. this.uuid = generateUUID();
  21048. // cached objects followed by the active ones
  21049. this._objects = Array.prototype.slice.call( arguments );
  21050. this.nCachedObjects_ = 0; // threshold
  21051. // note: read by PropertyBinding.Composite
  21052. const indices = {};
  21053. this._indicesByUUID = indices; // for bookkeeping
  21054. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  21055. indices[ arguments[ i ].uuid ] = i;
  21056. }
  21057. this._paths = []; // inside: string
  21058. this._parsedPaths = []; // inside: { we don't care, here }
  21059. this._bindings = []; // inside: Array< PropertyBinding >
  21060. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  21061. const scope = this;
  21062. this.stats = {
  21063. objects: {
  21064. get total() {
  21065. return scope._objects.length;
  21066. },
  21067. get inUse() {
  21068. return this.total - scope.nCachedObjects_;
  21069. }
  21070. },
  21071. get bindingsPerObject() {
  21072. return scope._bindings.length;
  21073. }
  21074. };
  21075. }
  21076. add() {
  21077. const objects = this._objects,
  21078. indicesByUUID = this._indicesByUUID,
  21079. paths = this._paths,
  21080. parsedPaths = this._parsedPaths,
  21081. bindings = this._bindings,
  21082. nBindings = bindings.length;
  21083. let knownObject = undefined,
  21084. nObjects = objects.length,
  21085. nCachedObjects = this.nCachedObjects_;
  21086. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  21087. const object = arguments[ i ],
  21088. uuid = object.uuid;
  21089. let index = indicesByUUID[ uuid ];
  21090. if ( index === undefined ) {
  21091. // unknown object -> add it to the ACTIVE region
  21092. index = nObjects ++;
  21093. indicesByUUID[ uuid ] = index;
  21094. objects.push( object );
  21095. // accounting is done, now do the same for all bindings
  21096. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21097. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  21098. }
  21099. } else if ( index < nCachedObjects ) {
  21100. knownObject = objects[ index ];
  21101. // move existing object to the ACTIVE region
  21102. const firstActiveIndex = -- nCachedObjects,
  21103. lastCachedObject = objects[ firstActiveIndex ];
  21104. indicesByUUID[ lastCachedObject.uuid ] = index;
  21105. objects[ index ] = lastCachedObject;
  21106. indicesByUUID[ uuid ] = firstActiveIndex;
  21107. objects[ firstActiveIndex ] = object;
  21108. // accounting is done, now do the same for all bindings
  21109. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21110. const bindingsForPath = bindings[ j ],
  21111. lastCached = bindingsForPath[ firstActiveIndex ];
  21112. let binding = bindingsForPath[ index ];
  21113. bindingsForPath[ index ] = lastCached;
  21114. if ( binding === undefined ) {
  21115. // since we do not bother to create new bindings
  21116. // for objects that are cached, the binding may
  21117. // or may not exist
  21118. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  21119. }
  21120. bindingsForPath[ firstActiveIndex ] = binding;
  21121. }
  21122. } else if ( objects[ index ] !== knownObject ) {
  21123. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  21124. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  21125. } // else the object is already where we want it to be
  21126. } // for arguments
  21127. this.nCachedObjects_ = nCachedObjects;
  21128. }
  21129. remove() {
  21130. const objects = this._objects,
  21131. indicesByUUID = this._indicesByUUID,
  21132. bindings = this._bindings,
  21133. nBindings = bindings.length;
  21134. let nCachedObjects = this.nCachedObjects_;
  21135. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  21136. const object = arguments[ i ],
  21137. uuid = object.uuid,
  21138. index = indicesByUUID[ uuid ];
  21139. if ( index !== undefined && index >= nCachedObjects ) {
  21140. // move existing object into the CACHED region
  21141. const lastCachedIndex = nCachedObjects ++,
  21142. firstActiveObject = objects[ lastCachedIndex ];
  21143. indicesByUUID[ firstActiveObject.uuid ] = index;
  21144. objects[ index ] = firstActiveObject;
  21145. indicesByUUID[ uuid ] = lastCachedIndex;
  21146. objects[ lastCachedIndex ] = object;
  21147. // accounting is done, now do the same for all bindings
  21148. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21149. const bindingsForPath = bindings[ j ],
  21150. firstActive = bindingsForPath[ lastCachedIndex ],
  21151. binding = bindingsForPath[ index ];
  21152. bindingsForPath[ index ] = firstActive;
  21153. bindingsForPath[ lastCachedIndex ] = binding;
  21154. }
  21155. }
  21156. } // for arguments
  21157. this.nCachedObjects_ = nCachedObjects;
  21158. }
  21159. // remove & forget
  21160. uncache() {
  21161. const objects = this._objects,
  21162. indicesByUUID = this._indicesByUUID,
  21163. bindings = this._bindings,
  21164. nBindings = bindings.length;
  21165. let nCachedObjects = this.nCachedObjects_,
  21166. nObjects = objects.length;
  21167. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  21168. const object = arguments[ i ],
  21169. uuid = object.uuid,
  21170. index = indicesByUUID[ uuid ];
  21171. if ( index !== undefined ) {
  21172. delete indicesByUUID[ uuid ];
  21173. if ( index < nCachedObjects ) {
  21174. // object is cached, shrink the CACHED region
  21175. const firstActiveIndex = -- nCachedObjects,
  21176. lastCachedObject = objects[ firstActiveIndex ],
  21177. lastIndex = -- nObjects,
  21178. lastObject = objects[ lastIndex ];
  21179. // last cached object takes this object's place
  21180. indicesByUUID[ lastCachedObject.uuid ] = index;
  21181. objects[ index ] = lastCachedObject;
  21182. // last object goes to the activated slot and pop
  21183. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  21184. objects[ firstActiveIndex ] = lastObject;
  21185. objects.pop();
  21186. // accounting is done, now do the same for all bindings
  21187. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21188. const bindingsForPath = bindings[ j ],
  21189. lastCached = bindingsForPath[ firstActiveIndex ],
  21190. last = bindingsForPath[ lastIndex ];
  21191. bindingsForPath[ index ] = lastCached;
  21192. bindingsForPath[ firstActiveIndex ] = last;
  21193. bindingsForPath.pop();
  21194. }
  21195. } else {
  21196. // object is active, just swap with the last and pop
  21197. const lastIndex = -- nObjects,
  21198. lastObject = objects[ lastIndex ];
  21199. if ( lastIndex > 0 ) {
  21200. indicesByUUID[ lastObject.uuid ] = index;
  21201. }
  21202. objects[ index ] = lastObject;
  21203. objects.pop();
  21204. // accounting is done, now do the same for all bindings
  21205. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  21206. const bindingsForPath = bindings[ j ];
  21207. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  21208. bindingsForPath.pop();
  21209. }
  21210. } // cached or active
  21211. } // if object is known
  21212. } // for arguments
  21213. this.nCachedObjects_ = nCachedObjects;
  21214. }
  21215. // Internal interface used by befriended PropertyBinding.Composite:
  21216. subscribe_( path, parsedPath ) {
  21217. // returns an array of bindings for the given path that is changed
  21218. // according to the contained objects in the group
  21219. const indicesByPath = this._bindingsIndicesByPath;
  21220. let index = indicesByPath[ path ];
  21221. const bindings = this._bindings;
  21222. if ( index !== undefined ) return bindings[ index ];
  21223. const paths = this._paths,
  21224. parsedPaths = this._parsedPaths,
  21225. objects = this._objects,
  21226. nObjects = objects.length,
  21227. nCachedObjects = this.nCachedObjects_,
  21228. bindingsForPath = new Array( nObjects );
  21229. index = bindings.length;
  21230. indicesByPath[ path ] = index;
  21231. paths.push( path );
  21232. parsedPaths.push( parsedPath );
  21233. bindings.push( bindingsForPath );
  21234. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  21235. const object = objects[ i ];
  21236. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  21237. }
  21238. return bindingsForPath;
  21239. }
  21240. unsubscribe_( path ) {
  21241. // tells the group to forget about a property path and no longer
  21242. // update the array previously obtained with 'subscribe_'
  21243. const indicesByPath = this._bindingsIndicesByPath,
  21244. index = indicesByPath[ path ];
  21245. if ( index !== undefined ) {
  21246. const paths = this._paths,
  21247. parsedPaths = this._parsedPaths,
  21248. bindings = this._bindings,
  21249. lastBindingsIndex = bindings.length - 1,
  21250. lastBindings = bindings[ lastBindingsIndex ],
  21251. lastBindingsPath = path[ lastBindingsIndex ];
  21252. indicesByPath[ lastBindingsPath ] = index;
  21253. bindings[ index ] = lastBindings;
  21254. bindings.pop();
  21255. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  21256. parsedPaths.pop();
  21257. paths[ index ] = paths[ lastBindingsIndex ];
  21258. paths.pop();
  21259. }
  21260. }
  21261. }
  21262. class AnimationAction {
  21263. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  21264. this._mixer = mixer;
  21265. this._clip = clip;
  21266. this._localRoot = localRoot;
  21267. this.blendMode = blendMode;
  21268. const tracks = clip.tracks,
  21269. nTracks = tracks.length,
  21270. interpolants = new Array( nTracks );
  21271. const interpolantSettings = {
  21272. endingStart: ZeroCurvatureEnding,
  21273. endingEnd: ZeroCurvatureEnding
  21274. };
  21275. for ( let i = 0; i !== nTracks; ++ i ) {
  21276. const interpolant = tracks[ i ].createInterpolant( null );
  21277. interpolants[ i ] = interpolant;
  21278. interpolant.settings = interpolantSettings;
  21279. }
  21280. this._interpolantSettings = interpolantSettings;
  21281. this._interpolants = interpolants; // bound by the mixer
  21282. // inside: PropertyMixer (managed by the mixer)
  21283. this._propertyBindings = new Array( nTracks );
  21284. this._cacheIndex = null; // for the memory manager
  21285. this._byClipCacheIndex = null; // for the memory manager
  21286. this._timeScaleInterpolant = null;
  21287. this._weightInterpolant = null;
  21288. this.loop = LoopRepeat;
  21289. this._loopCount = -1;
  21290. // global mixer time when the action is to be started
  21291. // it's set back to 'null' upon start of the action
  21292. this._startTime = null;
  21293. // scaled local time of the action
  21294. // gets clamped or wrapped to 0..clip.duration according to loop
  21295. this.time = 0;
  21296. this.timeScale = 1;
  21297. this._effectiveTimeScale = 1;
  21298. this.weight = 1;
  21299. this._effectiveWeight = 1;
  21300. this.repetitions = Infinity; // no. of repetitions when looping
  21301. this.paused = false; // true -> zero effective time scale
  21302. this.enabled = true; // false -> zero effective weight
  21303. this.clampWhenFinished = false;// keep feeding the last frame?
  21304. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  21305. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  21306. }
  21307. // State & Scheduling
  21308. play() {
  21309. this._mixer._activateAction( this );
  21310. return this;
  21311. }
  21312. stop() {
  21313. this._mixer._deactivateAction( this );
  21314. return this.reset();
  21315. }
  21316. reset() {
  21317. this.paused = false;
  21318. this.enabled = true;
  21319. this.time = 0; // restart clip
  21320. this._loopCount = -1;// forget previous loops
  21321. this._startTime = null;// forget scheduling
  21322. return this.stopFading().stopWarping();
  21323. }
  21324. isRunning() {
  21325. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  21326. this._startTime === null && this._mixer._isActiveAction( this );
  21327. }
  21328. // return true when play has been called
  21329. isScheduled() {
  21330. return this._mixer._isActiveAction( this );
  21331. }
  21332. startAt( time ) {
  21333. this._startTime = time;
  21334. return this;
  21335. }
  21336. setLoop( mode, repetitions ) {
  21337. this.loop = mode;
  21338. this.repetitions = repetitions;
  21339. return this;
  21340. }
  21341. // Weight
  21342. // set the weight stopping any scheduled fading
  21343. // although .enabled = false yields an effective weight of zero, this
  21344. // method does *not* change .enabled, because it would be confusing
  21345. setEffectiveWeight( weight ) {
  21346. this.weight = weight;
  21347. // note: same logic as when updated at runtime
  21348. this._effectiveWeight = this.enabled ? weight : 0;
  21349. return this.stopFading();
  21350. }
  21351. // return the weight considering fading and .enabled
  21352. getEffectiveWeight() {
  21353. return this._effectiveWeight;
  21354. }
  21355. fadeIn( duration ) {
  21356. return this._scheduleFading( duration, 0, 1 );
  21357. }
  21358. fadeOut( duration ) {
  21359. return this._scheduleFading( duration, 1, 0 );
  21360. }
  21361. crossFadeFrom( fadeOutAction, duration, warp ) {
  21362. fadeOutAction.fadeOut( duration );
  21363. this.fadeIn( duration );
  21364. if ( warp ) {
  21365. const fadeInDuration = this._clip.duration,
  21366. fadeOutDuration = fadeOutAction._clip.duration,
  21367. startEndRatio = fadeOutDuration / fadeInDuration,
  21368. endStartRatio = fadeInDuration / fadeOutDuration;
  21369. fadeOutAction.warp( 1.0, startEndRatio, duration );
  21370. this.warp( endStartRatio, 1.0, duration );
  21371. }
  21372. return this;
  21373. }
  21374. crossFadeTo( fadeInAction, duration, warp ) {
  21375. return fadeInAction.crossFadeFrom( this, duration, warp );
  21376. }
  21377. stopFading() {
  21378. const weightInterpolant = this._weightInterpolant;
  21379. if ( weightInterpolant !== null ) {
  21380. this._weightInterpolant = null;
  21381. this._mixer._takeBackControlInterpolant( weightInterpolant );
  21382. }
  21383. return this;
  21384. }
  21385. // Time Scale Control
  21386. // set the time scale stopping any scheduled warping
  21387. // although .paused = true yields an effective time scale of zero, this
  21388. // method does *not* change .paused, because it would be confusing
  21389. setEffectiveTimeScale( timeScale ) {
  21390. this.timeScale = timeScale;
  21391. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  21392. return this.stopWarping();
  21393. }
  21394. // return the time scale considering warping and .paused
  21395. getEffectiveTimeScale() {
  21396. return this._effectiveTimeScale;
  21397. }
  21398. setDuration( duration ) {
  21399. this.timeScale = this._clip.duration / duration;
  21400. return this.stopWarping();
  21401. }
  21402. syncWith( action ) {
  21403. this.time = action.time;
  21404. this.timeScale = action.timeScale;
  21405. return this.stopWarping();
  21406. }
  21407. halt( duration ) {
  21408. return this.warp( this._effectiveTimeScale, 0, duration );
  21409. }
  21410. warp( startTimeScale, endTimeScale, duration ) {
  21411. const mixer = this._mixer,
  21412. now = mixer.time,
  21413. timeScale = this.timeScale;
  21414. let interpolant = this._timeScaleInterpolant;
  21415. if ( interpolant === null ) {
  21416. interpolant = mixer._lendControlInterpolant();
  21417. this._timeScaleInterpolant = interpolant;
  21418. }
  21419. const times = interpolant.parameterPositions,
  21420. values = interpolant.sampleValues;
  21421. times[ 0 ] = now;
  21422. times[ 1 ] = now + duration;
  21423. values[ 0 ] = startTimeScale / timeScale;
  21424. values[ 1 ] = endTimeScale / timeScale;
  21425. return this;
  21426. }
  21427. stopWarping() {
  21428. const timeScaleInterpolant = this._timeScaleInterpolant;
  21429. if ( timeScaleInterpolant !== null ) {
  21430. this._timeScaleInterpolant = null;
  21431. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  21432. }
  21433. return this;
  21434. }
  21435. // Object Accessors
  21436. getMixer() {
  21437. return this._mixer;
  21438. }
  21439. getClip() {
  21440. return this._clip;
  21441. }
  21442. getRoot() {
  21443. return this._localRoot || this._mixer._root;
  21444. }
  21445. // Interna
  21446. _update( time, deltaTime, timeDirection, accuIndex ) {
  21447. // called by the mixer
  21448. if ( ! this.enabled ) {
  21449. // call ._updateWeight() to update ._effectiveWeight
  21450. this._updateWeight( time );
  21451. return;
  21452. }
  21453. const startTime = this._startTime;
  21454. if ( startTime !== null ) {
  21455. // check for scheduled start of action
  21456. const timeRunning = ( time - startTime ) * timeDirection;
  21457. if ( timeRunning < 0 || timeDirection === 0 ) {
  21458. deltaTime = 0;
  21459. } else {
  21460. this._startTime = null; // unschedule
  21461. deltaTime = timeDirection * timeRunning;
  21462. }
  21463. }
  21464. // apply time scale and advance time
  21465. deltaTime *= this._updateTimeScale( time );
  21466. const clipTime = this._updateTime( deltaTime );
  21467. // note: _updateTime may disable the action resulting in
  21468. // an effective weight of 0
  21469. const weight = this._updateWeight( time );
  21470. if ( weight > 0 ) {
  21471. const interpolants = this._interpolants;
  21472. const propertyMixers = this._propertyBindings;
  21473. switch ( this.blendMode ) {
  21474. case AdditiveAnimationBlendMode:
  21475. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  21476. interpolants[ j ].evaluate( clipTime );
  21477. propertyMixers[ j ].accumulateAdditive( weight );
  21478. }
  21479. break;
  21480. case NormalAnimationBlendMode:
  21481. default:
  21482. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  21483. interpolants[ j ].evaluate( clipTime );
  21484. propertyMixers[ j ].accumulate( accuIndex, weight );
  21485. }
  21486. }
  21487. }
  21488. }
  21489. _updateWeight( time ) {
  21490. let weight = 0;
  21491. if ( this.enabled ) {
  21492. weight = this.weight;
  21493. const interpolant = this._weightInterpolant;
  21494. if ( interpolant !== null ) {
  21495. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  21496. weight *= interpolantValue;
  21497. if ( time > interpolant.parameterPositions[ 1 ] ) {
  21498. this.stopFading();
  21499. if ( interpolantValue === 0 ) {
  21500. // faded out, disable
  21501. this.enabled = false;
  21502. }
  21503. }
  21504. }
  21505. }
  21506. this._effectiveWeight = weight;
  21507. return weight;
  21508. }
  21509. _updateTimeScale( time ) {
  21510. let timeScale = 0;
  21511. if ( ! this.paused ) {
  21512. timeScale = this.timeScale;
  21513. const interpolant = this._timeScaleInterpolant;
  21514. if ( interpolant !== null ) {
  21515. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  21516. timeScale *= interpolantValue;
  21517. if ( time > interpolant.parameterPositions[ 1 ] ) {
  21518. this.stopWarping();
  21519. if ( timeScale === 0 ) {
  21520. // motion has halted, pause
  21521. this.paused = true;
  21522. } else {
  21523. // warp done - apply final time scale
  21524. this.timeScale = timeScale;
  21525. }
  21526. }
  21527. }
  21528. }
  21529. this._effectiveTimeScale = timeScale;
  21530. return timeScale;
  21531. }
  21532. _updateTime( deltaTime ) {
  21533. const duration = this._clip.duration;
  21534. const loop = this.loop;
  21535. let time = this.time + deltaTime;
  21536. let loopCount = this._loopCount;
  21537. const pingPong = ( loop === LoopPingPong );
  21538. if ( deltaTime === 0 ) {
  21539. if ( loopCount === -1 ) return time;
  21540. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  21541. }
  21542. if ( loop === LoopOnce ) {
  21543. if ( loopCount === -1 ) {
  21544. // just started
  21545. this._loopCount = 0;
  21546. this._setEndings( true, true, false );
  21547. }
  21548. handle_stop: {
  21549. if ( time >= duration ) {
  21550. time = duration;
  21551. } else if ( time < 0 ) {
  21552. time = 0;
  21553. } else {
  21554. this.time = time;
  21555. break handle_stop;
  21556. }
  21557. if ( this.clampWhenFinished ) this.paused = true;
  21558. else this.enabled = false;
  21559. this.time = time;
  21560. this._mixer.dispatchEvent( {
  21561. type: 'finished', action: this,
  21562. direction: deltaTime < 0 ? -1 : 1
  21563. } );
  21564. }
  21565. } else { // repetitive Repeat or PingPong
  21566. if ( loopCount === -1 ) {
  21567. // just started
  21568. if ( deltaTime >= 0 ) {
  21569. loopCount = 0;
  21570. this._setEndings( true, this.repetitions === 0, pingPong );
  21571. } else {
  21572. // when looping in reverse direction, the initial
  21573. // transition through zero counts as a repetition,
  21574. // so leave loopCount at -1
  21575. this._setEndings( this.repetitions === 0, true, pingPong );
  21576. }
  21577. }
  21578. if ( time >= duration || time < 0 ) {
  21579. // wrap around
  21580. const loopDelta = Math.floor( time / duration ); // signed
  21581. time -= duration * loopDelta;
  21582. loopCount += Math.abs( loopDelta );
  21583. const pending = this.repetitions - loopCount;
  21584. if ( pending <= 0 ) {
  21585. // have to stop (switch state, clamp time, fire event)
  21586. if ( this.clampWhenFinished ) this.paused = true;
  21587. else this.enabled = false;
  21588. time = deltaTime > 0 ? duration : 0;
  21589. this.time = time;
  21590. this._mixer.dispatchEvent( {
  21591. type: 'finished', action: this,
  21592. direction: deltaTime > 0 ? 1 : -1
  21593. } );
  21594. } else {
  21595. // keep running
  21596. if ( pending === 1 ) {
  21597. // entering the last round
  21598. const atStart = deltaTime < 0;
  21599. this._setEndings( atStart, ! atStart, pingPong );
  21600. } else {
  21601. this._setEndings( false, false, pingPong );
  21602. }
  21603. this._loopCount = loopCount;
  21604. this.time = time;
  21605. this._mixer.dispatchEvent( {
  21606. type: 'loop', action: this, loopDelta: loopDelta
  21607. } );
  21608. }
  21609. } else {
  21610. this.time = time;
  21611. }
  21612. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  21613. // invert time for the "pong round"
  21614. return duration - time;
  21615. }
  21616. }
  21617. return time;
  21618. }
  21619. _setEndings( atStart, atEnd, pingPong ) {
  21620. const settings = this._interpolantSettings;
  21621. if ( pingPong ) {
  21622. settings.endingStart = ZeroSlopeEnding;
  21623. settings.endingEnd = ZeroSlopeEnding;
  21624. } else {
  21625. // assuming for LoopOnce atStart == atEnd == true
  21626. if ( atStart ) {
  21627. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  21628. } else {
  21629. settings.endingStart = WrapAroundEnding;
  21630. }
  21631. if ( atEnd ) {
  21632. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  21633. } else {
  21634. settings.endingEnd = WrapAroundEnding;
  21635. }
  21636. }
  21637. }
  21638. _scheduleFading( duration, weightNow, weightThen ) {
  21639. const mixer = this._mixer, now = mixer.time;
  21640. let interpolant = this._weightInterpolant;
  21641. if ( interpolant === null ) {
  21642. interpolant = mixer._lendControlInterpolant();
  21643. this._weightInterpolant = interpolant;
  21644. }
  21645. const times = interpolant.parameterPositions,
  21646. values = interpolant.sampleValues;
  21647. times[ 0 ] = now;
  21648. values[ 0 ] = weightNow;
  21649. times[ 1 ] = now + duration;
  21650. values[ 1 ] = weightThen;
  21651. return this;
  21652. }
  21653. }
  21654. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  21655. class AnimationMixer extends EventDispatcher {
  21656. constructor( root ) {
  21657. super();
  21658. this._root = root;
  21659. this._initMemoryManager();
  21660. this._accuIndex = 0;
  21661. this.time = 0;
  21662. this.timeScale = 1.0;
  21663. }
  21664. _bindAction( action, prototypeAction ) {
  21665. const root = action._localRoot || this._root,
  21666. tracks = action._clip.tracks,
  21667. nTracks = tracks.length,
  21668. bindings = action._propertyBindings,
  21669. interpolants = action._interpolants,
  21670. rootUuid = root.uuid,
  21671. bindingsByRoot = this._bindingsByRootAndName;
  21672. let bindingsByName = bindingsByRoot[ rootUuid ];
  21673. if ( bindingsByName === undefined ) {
  21674. bindingsByName = {};
  21675. bindingsByRoot[ rootUuid ] = bindingsByName;
  21676. }
  21677. for ( let i = 0; i !== nTracks; ++ i ) {
  21678. const track = tracks[ i ],
  21679. trackName = track.name;
  21680. let binding = bindingsByName[ trackName ];
  21681. if ( binding !== undefined ) {
  21682. ++ binding.referenceCount;
  21683. bindings[ i ] = binding;
  21684. } else {
  21685. binding = bindings[ i ];
  21686. if ( binding !== undefined ) {
  21687. // existing binding, make sure the cache knows
  21688. if ( binding._cacheIndex === null ) {
  21689. ++ binding.referenceCount;
  21690. this._addInactiveBinding( binding, rootUuid, trackName );
  21691. }
  21692. continue;
  21693. }
  21694. const path = prototypeAction && prototypeAction.
  21695. _propertyBindings[ i ].binding.parsedPath;
  21696. binding = new PropertyMixer(
  21697. PropertyBinding.create( root, trackName, path ),
  21698. track.ValueTypeName, track.getValueSize() );
  21699. ++ binding.referenceCount;
  21700. this._addInactiveBinding( binding, rootUuid, trackName );
  21701. bindings[ i ] = binding;
  21702. }
  21703. interpolants[ i ].resultBuffer = binding.buffer;
  21704. }
  21705. }
  21706. _activateAction( action ) {
  21707. if ( ! this._isActiveAction( action ) ) {
  21708. if ( action._cacheIndex === null ) {
  21709. // this action has been forgotten by the cache, but the user
  21710. // appears to be still using it -> rebind
  21711. const rootUuid = ( action._localRoot || this._root ).uuid,
  21712. clipUuid = action._clip.uuid,
  21713. actionsForClip = this._actionsByClip[ clipUuid ];
  21714. this._bindAction( action,
  21715. actionsForClip && actionsForClip.knownActions[ 0 ] );
  21716. this._addInactiveAction( action, clipUuid, rootUuid );
  21717. }
  21718. const bindings = action._propertyBindings;
  21719. // increment reference counts / sort out state
  21720. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  21721. const binding = bindings[ i ];
  21722. if ( binding.useCount ++ === 0 ) {
  21723. this._lendBinding( binding );
  21724. binding.saveOriginalState();
  21725. }
  21726. }
  21727. this._lendAction( action );
  21728. }
  21729. }
  21730. _deactivateAction( action ) {
  21731. if ( this._isActiveAction( action ) ) {
  21732. const bindings = action._propertyBindings;
  21733. // decrement reference counts / sort out state
  21734. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  21735. const binding = bindings[ i ];
  21736. if ( -- binding.useCount === 0 ) {
  21737. binding.restoreOriginalState();
  21738. this._takeBackBinding( binding );
  21739. }
  21740. }
  21741. this._takeBackAction( action );
  21742. }
  21743. }
  21744. // Memory manager
  21745. _initMemoryManager() {
  21746. this._actions = []; // 'nActiveActions' followed by inactive ones
  21747. this._nActiveActions = 0;
  21748. this._actionsByClip = {};
  21749. // inside:
  21750. // {
  21751. // knownActions: Array< AnimationAction > - used as prototypes
  21752. // actionByRoot: AnimationAction - lookup
  21753. // }
  21754. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  21755. this._nActiveBindings = 0;
  21756. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  21757. this._controlInterpolants = []; // same game as above
  21758. this._nActiveControlInterpolants = 0;
  21759. const scope = this;
  21760. this.stats = {
  21761. actions: {
  21762. get total() {
  21763. return scope._actions.length;
  21764. },
  21765. get inUse() {
  21766. return scope._nActiveActions;
  21767. }
  21768. },
  21769. bindings: {
  21770. get total() {
  21771. return scope._bindings.length;
  21772. },
  21773. get inUse() {
  21774. return scope._nActiveBindings;
  21775. }
  21776. },
  21777. controlInterpolants: {
  21778. get total() {
  21779. return scope._controlInterpolants.length;
  21780. },
  21781. get inUse() {
  21782. return scope._nActiveControlInterpolants;
  21783. }
  21784. }
  21785. };
  21786. }
  21787. // Memory management for AnimationAction objects
  21788. _isActiveAction( action ) {
  21789. const index = action._cacheIndex;
  21790. return index !== null && index < this._nActiveActions;
  21791. }
  21792. _addInactiveAction( action, clipUuid, rootUuid ) {
  21793. const actions = this._actions,
  21794. actionsByClip = this._actionsByClip;
  21795. let actionsForClip = actionsByClip[ clipUuid ];
  21796. if ( actionsForClip === undefined ) {
  21797. actionsForClip = {
  21798. knownActions: [ action ],
  21799. actionByRoot: {}
  21800. };
  21801. action._byClipCacheIndex = 0;
  21802. actionsByClip[ clipUuid ] = actionsForClip;
  21803. } else {
  21804. const knownActions = actionsForClip.knownActions;
  21805. action._byClipCacheIndex = knownActions.length;
  21806. knownActions.push( action );
  21807. }
  21808. action._cacheIndex = actions.length;
  21809. actions.push( action );
  21810. actionsForClip.actionByRoot[ rootUuid ] = action;
  21811. }
  21812. _removeInactiveAction( action ) {
  21813. const actions = this._actions,
  21814. lastInactiveAction = actions[ actions.length - 1 ],
  21815. cacheIndex = action._cacheIndex;
  21816. lastInactiveAction._cacheIndex = cacheIndex;
  21817. actions[ cacheIndex ] = lastInactiveAction;
  21818. actions.pop();
  21819. action._cacheIndex = null;
  21820. const clipUuid = action._clip.uuid,
  21821. actionsByClip = this._actionsByClip,
  21822. actionsForClip = actionsByClip[ clipUuid ],
  21823. knownActionsForClip = actionsForClip.knownActions,
  21824. lastKnownAction =
  21825. knownActionsForClip[ knownActionsForClip.length - 1 ],
  21826. byClipCacheIndex = action._byClipCacheIndex;
  21827. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  21828. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  21829. knownActionsForClip.pop();
  21830. action._byClipCacheIndex = null;
  21831. const actionByRoot = actionsForClip.actionByRoot,
  21832. rootUuid = ( action._localRoot || this._root ).uuid;
  21833. delete actionByRoot[ rootUuid ];
  21834. if ( knownActionsForClip.length === 0 ) {
  21835. delete actionsByClip[ clipUuid ];
  21836. }
  21837. this._removeInactiveBindingsForAction( action );
  21838. }
  21839. _removeInactiveBindingsForAction( action ) {
  21840. const bindings = action._propertyBindings;
  21841. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  21842. const binding = bindings[ i ];
  21843. if ( -- binding.referenceCount === 0 ) {
  21844. this._removeInactiveBinding( binding );
  21845. }
  21846. }
  21847. }
  21848. _lendAction( action ) {
  21849. // [ active actions | inactive actions ]
  21850. // [ active actions >| inactive actions ]
  21851. // s a
  21852. // <-swap->
  21853. // a s
  21854. const actions = this._actions,
  21855. prevIndex = action._cacheIndex,
  21856. lastActiveIndex = this._nActiveActions ++,
  21857. firstInactiveAction = actions[ lastActiveIndex ];
  21858. action._cacheIndex = lastActiveIndex;
  21859. actions[ lastActiveIndex ] = action;
  21860. firstInactiveAction._cacheIndex = prevIndex;
  21861. actions[ prevIndex ] = firstInactiveAction;
  21862. }
  21863. _takeBackAction( action ) {
  21864. // [ active actions | inactive actions ]
  21865. // [ active actions |< inactive actions ]
  21866. // a s
  21867. // <-swap->
  21868. // s a
  21869. const actions = this._actions,
  21870. prevIndex = action._cacheIndex,
  21871. firstInactiveIndex = -- this._nActiveActions,
  21872. lastActiveAction = actions[ firstInactiveIndex ];
  21873. action._cacheIndex = firstInactiveIndex;
  21874. actions[ firstInactiveIndex ] = action;
  21875. lastActiveAction._cacheIndex = prevIndex;
  21876. actions[ prevIndex ] = lastActiveAction;
  21877. }
  21878. // Memory management for PropertyMixer objects
  21879. _addInactiveBinding( binding, rootUuid, trackName ) {
  21880. const bindingsByRoot = this._bindingsByRootAndName,
  21881. bindings = this._bindings;
  21882. let bindingByName = bindingsByRoot[ rootUuid ];
  21883. if ( bindingByName === undefined ) {
  21884. bindingByName = {};
  21885. bindingsByRoot[ rootUuid ] = bindingByName;
  21886. }
  21887. bindingByName[ trackName ] = binding;
  21888. binding._cacheIndex = bindings.length;
  21889. bindings.push( binding );
  21890. }
  21891. _removeInactiveBinding( binding ) {
  21892. const bindings = this._bindings,
  21893. propBinding = binding.binding,
  21894. rootUuid = propBinding.rootNode.uuid,
  21895. trackName = propBinding.path,
  21896. bindingsByRoot = this._bindingsByRootAndName,
  21897. bindingByName = bindingsByRoot[ rootUuid ],
  21898. lastInactiveBinding = bindings[ bindings.length - 1 ],
  21899. cacheIndex = binding._cacheIndex;
  21900. lastInactiveBinding._cacheIndex = cacheIndex;
  21901. bindings[ cacheIndex ] = lastInactiveBinding;
  21902. bindings.pop();
  21903. delete bindingByName[ trackName ];
  21904. if ( Object.keys( bindingByName ).length === 0 ) {
  21905. delete bindingsByRoot[ rootUuid ];
  21906. }
  21907. }
  21908. _lendBinding( binding ) {
  21909. const bindings = this._bindings,
  21910. prevIndex = binding._cacheIndex,
  21911. lastActiveIndex = this._nActiveBindings ++,
  21912. firstInactiveBinding = bindings[ lastActiveIndex ];
  21913. binding._cacheIndex = lastActiveIndex;
  21914. bindings[ lastActiveIndex ] = binding;
  21915. firstInactiveBinding._cacheIndex = prevIndex;
  21916. bindings[ prevIndex ] = firstInactiveBinding;
  21917. }
  21918. _takeBackBinding( binding ) {
  21919. const bindings = this._bindings,
  21920. prevIndex = binding._cacheIndex,
  21921. firstInactiveIndex = -- this._nActiveBindings,
  21922. lastActiveBinding = bindings[ firstInactiveIndex ];
  21923. binding._cacheIndex = firstInactiveIndex;
  21924. bindings[ firstInactiveIndex ] = binding;
  21925. lastActiveBinding._cacheIndex = prevIndex;
  21926. bindings[ prevIndex ] = lastActiveBinding;
  21927. }
  21928. // Memory management of Interpolants for weight and time scale
  21929. _lendControlInterpolant() {
  21930. const interpolants = this._controlInterpolants,
  21931. lastActiveIndex = this._nActiveControlInterpolants ++;
  21932. let interpolant = interpolants[ lastActiveIndex ];
  21933. if ( interpolant === undefined ) {
  21934. interpolant = new LinearInterpolant(
  21935. new Float32Array( 2 ), new Float32Array( 2 ),
  21936. 1, _controlInterpolantsResultBuffer );
  21937. interpolant.__cacheIndex = lastActiveIndex;
  21938. interpolants[ lastActiveIndex ] = interpolant;
  21939. }
  21940. return interpolant;
  21941. }
  21942. _takeBackControlInterpolant( interpolant ) {
  21943. const interpolants = this._controlInterpolants,
  21944. prevIndex = interpolant.__cacheIndex,
  21945. firstInactiveIndex = -- this._nActiveControlInterpolants,
  21946. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  21947. interpolant.__cacheIndex = firstInactiveIndex;
  21948. interpolants[ firstInactiveIndex ] = interpolant;
  21949. lastActiveInterpolant.__cacheIndex = prevIndex;
  21950. interpolants[ prevIndex ] = lastActiveInterpolant;
  21951. }
  21952. // return an action for a clip optionally using a custom root target
  21953. // object (this method allocates a lot of dynamic memory in case a
  21954. // previously unknown clip/root combination is specified)
  21955. clipAction( clip, optionalRoot, blendMode ) {
  21956. const root = optionalRoot || this._root,
  21957. rootUuid = root.uuid;
  21958. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  21959. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  21960. const actionsForClip = this._actionsByClip[ clipUuid ];
  21961. let prototypeAction = null;
  21962. if ( blendMode === undefined ) {
  21963. if ( clipObject !== null ) {
  21964. blendMode = clipObject.blendMode;
  21965. } else {
  21966. blendMode = NormalAnimationBlendMode;
  21967. }
  21968. }
  21969. if ( actionsForClip !== undefined ) {
  21970. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  21971. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  21972. return existingAction;
  21973. }
  21974. // we know the clip, so we don't have to parse all
  21975. // the bindings again but can just copy
  21976. prototypeAction = actionsForClip.knownActions[ 0 ];
  21977. // also, take the clip from the prototype action
  21978. if ( clipObject === null )
  21979. clipObject = prototypeAction._clip;
  21980. }
  21981. // clip must be known when specified via string
  21982. if ( clipObject === null ) return null;
  21983. // allocate all resources required to run it
  21984. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  21985. this._bindAction( newAction, prototypeAction );
  21986. // and make the action known to the memory manager
  21987. this._addInactiveAction( newAction, clipUuid, rootUuid );
  21988. return newAction;
  21989. }
  21990. // get an existing action
  21991. existingAction( clip, optionalRoot ) {
  21992. const root = optionalRoot || this._root,
  21993. rootUuid = root.uuid,
  21994. clipObject = typeof clip === 'string' ?
  21995. AnimationClip.findByName( root, clip ) : clip,
  21996. clipUuid = clipObject ? clipObject.uuid : clip,
  21997. actionsForClip = this._actionsByClip[ clipUuid ];
  21998. if ( actionsForClip !== undefined ) {
  21999. return actionsForClip.actionByRoot[ rootUuid ] || null;
  22000. }
  22001. return null;
  22002. }
  22003. // deactivates all previously scheduled actions
  22004. stopAllAction() {
  22005. const actions = this._actions,
  22006. nActions = this._nActiveActions;
  22007. for ( let i = nActions - 1; i >= 0; -- i ) {
  22008. actions[ i ].stop();
  22009. }
  22010. return this;
  22011. }
  22012. // advance the time and update apply the animation
  22013. update( deltaTime ) {
  22014. deltaTime *= this.timeScale;
  22015. const actions = this._actions,
  22016. nActions = this._nActiveActions,
  22017. time = this.time += deltaTime,
  22018. timeDirection = Math.sign( deltaTime ),
  22019. accuIndex = this._accuIndex ^= 1;
  22020. // run active actions
  22021. for ( let i = 0; i !== nActions; ++ i ) {
  22022. const action = actions[ i ];
  22023. action._update( time, deltaTime, timeDirection, accuIndex );
  22024. }
  22025. // update scene graph
  22026. const bindings = this._bindings,
  22027. nBindings = this._nActiveBindings;
  22028. for ( let i = 0; i !== nBindings; ++ i ) {
  22029. bindings[ i ].apply( accuIndex );
  22030. }
  22031. return this;
  22032. }
  22033. // Allows you to seek to a specific time in an animation.
  22034. setTime( timeInSeconds ) {
  22035. this.time = 0; // Zero out time attribute for AnimationMixer object;
  22036. for ( let i = 0; i < this._actions.length; i ++ ) {
  22037. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  22038. }
  22039. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  22040. }
  22041. // return this mixer's root target object
  22042. getRoot() {
  22043. return this._root;
  22044. }
  22045. // free all resources specific to a particular clip
  22046. uncacheClip( clip ) {
  22047. const actions = this._actions,
  22048. clipUuid = clip.uuid,
  22049. actionsByClip = this._actionsByClip,
  22050. actionsForClip = actionsByClip[ clipUuid ];
  22051. if ( actionsForClip !== undefined ) {
  22052. // note: just calling _removeInactiveAction would mess up the
  22053. // iteration state and also require updating the state we can
  22054. // just throw away
  22055. const actionsToRemove = actionsForClip.knownActions;
  22056. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  22057. const action = actionsToRemove[ i ];
  22058. this._deactivateAction( action );
  22059. const cacheIndex = action._cacheIndex,
  22060. lastInactiveAction = actions[ actions.length - 1 ];
  22061. action._cacheIndex = null;
  22062. action._byClipCacheIndex = null;
  22063. lastInactiveAction._cacheIndex = cacheIndex;
  22064. actions[ cacheIndex ] = lastInactiveAction;
  22065. actions.pop();
  22066. this._removeInactiveBindingsForAction( action );
  22067. }
  22068. delete actionsByClip[ clipUuid ];
  22069. }
  22070. }
  22071. // free all resources specific to a particular root target object
  22072. uncacheRoot( root ) {
  22073. const rootUuid = root.uuid,
  22074. actionsByClip = this._actionsByClip;
  22075. for ( const clipUuid in actionsByClip ) {
  22076. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  22077. action = actionByRoot[ rootUuid ];
  22078. if ( action !== undefined ) {
  22079. this._deactivateAction( action );
  22080. this._removeInactiveAction( action );
  22081. }
  22082. }
  22083. const bindingsByRoot = this._bindingsByRootAndName,
  22084. bindingByName = bindingsByRoot[ rootUuid ];
  22085. if ( bindingByName !== undefined ) {
  22086. for ( const trackName in bindingByName ) {
  22087. const binding = bindingByName[ trackName ];
  22088. binding.restoreOriginalState();
  22089. this._removeInactiveBinding( binding );
  22090. }
  22091. }
  22092. }
  22093. // remove a targeted clip from the cache
  22094. uncacheAction( clip, optionalRoot ) {
  22095. const action = this.existingAction( clip, optionalRoot );
  22096. if ( action !== null ) {
  22097. this._deactivateAction( action );
  22098. this._removeInactiveAction( action );
  22099. }
  22100. }
  22101. }
  22102. class RenderTarget3D extends RenderTarget {
  22103. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  22104. super( width, height, options );
  22105. this.isRenderTarget3D = true;
  22106. this.depth = depth;
  22107. this.texture = new Data3DTexture( null, width, height, depth );
  22108. this.texture.isRenderTargetTexture = true;
  22109. }
  22110. }
  22111. class RenderTargetArray extends RenderTarget {
  22112. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  22113. super( width, height, options );
  22114. this.isRenderTargetArray = true;
  22115. this.depth = depth;
  22116. this.texture = new DataArrayTexture( null, width, height, depth );
  22117. this.texture.isRenderTargetTexture = true;
  22118. }
  22119. }
  22120. class Uniform {
  22121. constructor( value ) {
  22122. this.value = value;
  22123. }
  22124. clone() {
  22125. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  22126. }
  22127. }
  22128. let _id$1 = 0;
  22129. class UniformsGroup extends EventDispatcher {
  22130. constructor() {
  22131. super();
  22132. this.isUniformsGroup = true;
  22133. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  22134. this.name = '';
  22135. this.usage = StaticDrawUsage;
  22136. this.uniforms = [];
  22137. }
  22138. add( uniform ) {
  22139. this.uniforms.push( uniform );
  22140. return this;
  22141. }
  22142. remove( uniform ) {
  22143. const index = this.uniforms.indexOf( uniform );
  22144. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  22145. return this;
  22146. }
  22147. setName( name ) {
  22148. this.name = name;
  22149. return this;
  22150. }
  22151. setUsage( value ) {
  22152. this.usage = value;
  22153. return this;
  22154. }
  22155. dispose() {
  22156. this.dispatchEvent( { type: 'dispose' } );
  22157. return this;
  22158. }
  22159. copy( source ) {
  22160. this.name = source.name;
  22161. this.usage = source.usage;
  22162. const uniformsSource = source.uniforms;
  22163. this.uniforms.length = 0;
  22164. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  22165. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  22166. for ( let j = 0; j < uniforms.length; j ++ ) {
  22167. this.uniforms.push( uniforms[ j ].clone() );
  22168. }
  22169. }
  22170. return this;
  22171. }
  22172. clone() {
  22173. return new this.constructor().copy( this );
  22174. }
  22175. }
  22176. class InstancedInterleavedBuffer extends InterleavedBuffer {
  22177. constructor( array, stride, meshPerAttribute = 1 ) {
  22178. super( array, stride );
  22179. this.isInstancedInterleavedBuffer = true;
  22180. this.meshPerAttribute = meshPerAttribute;
  22181. }
  22182. copy( source ) {
  22183. super.copy( source );
  22184. this.meshPerAttribute = source.meshPerAttribute;
  22185. return this;
  22186. }
  22187. clone( data ) {
  22188. const ib = super.clone( data );
  22189. ib.meshPerAttribute = this.meshPerAttribute;
  22190. return ib;
  22191. }
  22192. toJSON( data ) {
  22193. const json = super.toJSON( data );
  22194. json.isInstancedInterleavedBuffer = true;
  22195. json.meshPerAttribute = this.meshPerAttribute;
  22196. return json;
  22197. }
  22198. }
  22199. class GLBufferAttribute {
  22200. constructor( buffer, type, itemSize, elementSize, count ) {
  22201. this.isGLBufferAttribute = true;
  22202. this.name = '';
  22203. this.buffer = buffer;
  22204. this.type = type;
  22205. this.itemSize = itemSize;
  22206. this.elementSize = elementSize;
  22207. this.count = count;
  22208. this.version = 0;
  22209. }
  22210. set needsUpdate( value ) {
  22211. if ( value === true ) this.version ++;
  22212. }
  22213. setBuffer( buffer ) {
  22214. this.buffer = buffer;
  22215. return this;
  22216. }
  22217. setType( type, elementSize ) {
  22218. this.type = type;
  22219. this.elementSize = elementSize;
  22220. return this;
  22221. }
  22222. setItemSize( itemSize ) {
  22223. this.itemSize = itemSize;
  22224. return this;
  22225. }
  22226. setCount( count ) {
  22227. this.count = count;
  22228. return this;
  22229. }
  22230. }
  22231. const _matrix = /*@__PURE__*/ new Matrix4();
  22232. class Raycaster {
  22233. constructor( origin, direction, near = 0, far = Infinity ) {
  22234. this.ray = new Ray( origin, direction );
  22235. // direction is assumed to be normalized (for accurate distance calculations)
  22236. this.near = near;
  22237. this.far = far;
  22238. this.camera = null;
  22239. this.layers = new Layers();
  22240. this.params = {
  22241. Mesh: {},
  22242. Line: { threshold: 1 },
  22243. LOD: {},
  22244. Points: { threshold: 1 },
  22245. Sprite: {}
  22246. };
  22247. }
  22248. set( origin, direction ) {
  22249. // direction is assumed to be normalized (for accurate distance calculations)
  22250. this.ray.set( origin, direction );
  22251. }
  22252. setFromCamera( coords, camera ) {
  22253. if ( camera.isPerspectiveCamera ) {
  22254. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  22255. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  22256. this.camera = camera;
  22257. } else if ( camera.isOrthographicCamera ) {
  22258. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  22259. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  22260. this.camera = camera;
  22261. } else {
  22262. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  22263. }
  22264. }
  22265. setFromXRController( controller ) {
  22266. _matrix.identity().extractRotation( controller.matrixWorld );
  22267. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  22268. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  22269. return this;
  22270. }
  22271. intersectObject( object, recursive = true, intersects = [] ) {
  22272. intersect( object, this, intersects, recursive );
  22273. intersects.sort( ascSort );
  22274. return intersects;
  22275. }
  22276. intersectObjects( objects, recursive = true, intersects = [] ) {
  22277. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  22278. intersect( objects[ i ], this, intersects, recursive );
  22279. }
  22280. intersects.sort( ascSort );
  22281. return intersects;
  22282. }
  22283. }
  22284. function ascSort( a, b ) {
  22285. return a.distance - b.distance;
  22286. }
  22287. function intersect( object, raycaster, intersects, recursive ) {
  22288. let propagate = true;
  22289. if ( object.layers.test( raycaster.layers ) ) {
  22290. const result = object.raycast( raycaster, intersects );
  22291. if ( result === false ) propagate = false;
  22292. }
  22293. if ( propagate === true && recursive === true ) {
  22294. const children = object.children;
  22295. for ( let i = 0, l = children.length; i < l; i ++ ) {
  22296. intersect( children[ i ], raycaster, intersects, true );
  22297. }
  22298. }
  22299. }
  22300. /**
  22301. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  22302. *
  22303. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  22304. * theta (the azimuthal angle) is measured from the positive z-axis.
  22305. */
  22306. class Spherical {
  22307. constructor( radius = 1, phi = 0, theta = 0 ) {
  22308. this.radius = radius;
  22309. this.phi = phi; // polar angle
  22310. this.theta = theta; // azimuthal angle
  22311. return this;
  22312. }
  22313. set( radius, phi, theta ) {
  22314. this.radius = radius;
  22315. this.phi = phi;
  22316. this.theta = theta;
  22317. return this;
  22318. }
  22319. copy( other ) {
  22320. this.radius = other.radius;
  22321. this.phi = other.phi;
  22322. this.theta = other.theta;
  22323. return this;
  22324. }
  22325. // restrict phi to be between EPS and PI-EPS
  22326. makeSafe() {
  22327. const EPS = 0.000001;
  22328. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  22329. return this;
  22330. }
  22331. setFromVector3( v ) {
  22332. return this.setFromCartesianCoords( v.x, v.y, v.z );
  22333. }
  22334. setFromCartesianCoords( x, y, z ) {
  22335. this.radius = Math.sqrt( x * x + y * y + z * z );
  22336. if ( this.radius === 0 ) {
  22337. this.theta = 0;
  22338. this.phi = 0;
  22339. } else {
  22340. this.theta = Math.atan2( x, z );
  22341. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  22342. }
  22343. return this;
  22344. }
  22345. clone() {
  22346. return new this.constructor().copy( this );
  22347. }
  22348. }
  22349. /**
  22350. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  22351. */
  22352. class Cylindrical {
  22353. constructor( radius = 1, theta = 0, y = 0 ) {
  22354. this.radius = radius; // distance from the origin to a point in the x-z plane
  22355. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  22356. this.y = y; // height above the x-z plane
  22357. return this;
  22358. }
  22359. set( radius, theta, y ) {
  22360. this.radius = radius;
  22361. this.theta = theta;
  22362. this.y = y;
  22363. return this;
  22364. }
  22365. copy( other ) {
  22366. this.radius = other.radius;
  22367. this.theta = other.theta;
  22368. this.y = other.y;
  22369. return this;
  22370. }
  22371. setFromVector3( v ) {
  22372. return this.setFromCartesianCoords( v.x, v.y, v.z );
  22373. }
  22374. setFromCartesianCoords( x, y, z ) {
  22375. this.radius = Math.sqrt( x * x + z * z );
  22376. this.theta = Math.atan2( x, z );
  22377. this.y = y;
  22378. return this;
  22379. }
  22380. clone() {
  22381. return new this.constructor().copy( this );
  22382. }
  22383. }
  22384. class Matrix2 {
  22385. constructor( n11, n12, n21, n22 ) {
  22386. Matrix2.prototype.isMatrix2 = true;
  22387. this.elements = [
  22388. 1, 0,
  22389. 0, 1,
  22390. ];
  22391. if ( n11 !== undefined ) {
  22392. this.set( n11, n12, n21, n22 );
  22393. }
  22394. }
  22395. identity() {
  22396. this.set(
  22397. 1, 0,
  22398. 0, 1,
  22399. );
  22400. return this;
  22401. }
  22402. fromArray( array, offset = 0 ) {
  22403. for ( let i = 0; i < 4; i ++ ) {
  22404. this.elements[ i ] = array[ i + offset ];
  22405. }
  22406. return this;
  22407. }
  22408. set( n11, n12, n21, n22 ) {
  22409. const te = this.elements;
  22410. te[ 0 ] = n11; te[ 2 ] = n12;
  22411. te[ 1 ] = n21; te[ 3 ] = n22;
  22412. return this;
  22413. }
  22414. }
  22415. const _vector$4 = /*@__PURE__*/ new Vector2();
  22416. class Box2 {
  22417. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  22418. this.isBox2 = true;
  22419. this.min = min;
  22420. this.max = max;
  22421. }
  22422. set( min, max ) {
  22423. this.min.copy( min );
  22424. this.max.copy( max );
  22425. return this;
  22426. }
  22427. setFromPoints( points ) {
  22428. this.makeEmpty();
  22429. for ( let i = 0, il = points.length; i < il; i ++ ) {
  22430. this.expandByPoint( points[ i ] );
  22431. }
  22432. return this;
  22433. }
  22434. setFromCenterAndSize( center, size ) {
  22435. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  22436. this.min.copy( center ).sub( halfSize );
  22437. this.max.copy( center ).add( halfSize );
  22438. return this;
  22439. }
  22440. clone() {
  22441. return new this.constructor().copy( this );
  22442. }
  22443. copy( box ) {
  22444. this.min.copy( box.min );
  22445. this.max.copy( box.max );
  22446. return this;
  22447. }
  22448. makeEmpty() {
  22449. this.min.x = this.min.y = + Infinity;
  22450. this.max.x = this.max.y = - Infinity;
  22451. return this;
  22452. }
  22453. isEmpty() {
  22454. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  22455. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  22456. }
  22457. getCenter( target ) {
  22458. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  22459. }
  22460. getSize( target ) {
  22461. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  22462. }
  22463. expandByPoint( point ) {
  22464. this.min.min( point );
  22465. this.max.max( point );
  22466. return this;
  22467. }
  22468. expandByVector( vector ) {
  22469. this.min.sub( vector );
  22470. this.max.add( vector );
  22471. return this;
  22472. }
  22473. expandByScalar( scalar ) {
  22474. this.min.addScalar( - scalar );
  22475. this.max.addScalar( scalar );
  22476. return this;
  22477. }
  22478. containsPoint( point ) {
  22479. return point.x >= this.min.x && point.x <= this.max.x &&
  22480. point.y >= this.min.y && point.y <= this.max.y;
  22481. }
  22482. containsBox( box ) {
  22483. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  22484. this.min.y <= box.min.y && box.max.y <= this.max.y;
  22485. }
  22486. getParameter( point, target ) {
  22487. // This can potentially have a divide by zero if the box
  22488. // has a size dimension of 0.
  22489. return target.set(
  22490. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  22491. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  22492. );
  22493. }
  22494. intersectsBox( box ) {
  22495. // using 4 splitting planes to rule out intersections
  22496. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  22497. box.max.y >= this.min.y && box.min.y <= this.max.y;
  22498. }
  22499. clampPoint( point, target ) {
  22500. return target.copy( point ).clamp( this.min, this.max );
  22501. }
  22502. distanceToPoint( point ) {
  22503. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  22504. }
  22505. intersect( box ) {
  22506. this.min.max( box.min );
  22507. this.max.min( box.max );
  22508. if ( this.isEmpty() ) this.makeEmpty();
  22509. return this;
  22510. }
  22511. union( box ) {
  22512. this.min.min( box.min );
  22513. this.max.max( box.max );
  22514. return this;
  22515. }
  22516. translate( offset ) {
  22517. this.min.add( offset );
  22518. this.max.add( offset );
  22519. return this;
  22520. }
  22521. equals( box ) {
  22522. return box.min.equals( this.min ) && box.max.equals( this.max );
  22523. }
  22524. }
  22525. const _startP = /*@__PURE__*/ new Vector3();
  22526. const _startEnd = /*@__PURE__*/ new Vector3();
  22527. class Line3 {
  22528. constructor( start = new Vector3(), end = new Vector3() ) {
  22529. this.start = start;
  22530. this.end = end;
  22531. }
  22532. set( start, end ) {
  22533. this.start.copy( start );
  22534. this.end.copy( end );
  22535. return this;
  22536. }
  22537. copy( line ) {
  22538. this.start.copy( line.start );
  22539. this.end.copy( line.end );
  22540. return this;
  22541. }
  22542. getCenter( target ) {
  22543. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  22544. }
  22545. delta( target ) {
  22546. return target.subVectors( this.end, this.start );
  22547. }
  22548. distanceSq() {
  22549. return this.start.distanceToSquared( this.end );
  22550. }
  22551. distance() {
  22552. return this.start.distanceTo( this.end );
  22553. }
  22554. at( t, target ) {
  22555. return this.delta( target ).multiplyScalar( t ).add( this.start );
  22556. }
  22557. closestPointToPointParameter( point, clampToLine ) {
  22558. _startP.subVectors( point, this.start );
  22559. _startEnd.subVectors( this.end, this.start );
  22560. const startEnd2 = _startEnd.dot( _startEnd );
  22561. const startEnd_startP = _startEnd.dot( _startP );
  22562. let t = startEnd_startP / startEnd2;
  22563. if ( clampToLine ) {
  22564. t = clamp( t, 0, 1 );
  22565. }
  22566. return t;
  22567. }
  22568. closestPointToPoint( point, clampToLine, target ) {
  22569. const t = this.closestPointToPointParameter( point, clampToLine );
  22570. return this.delta( target ).multiplyScalar( t ).add( this.start );
  22571. }
  22572. applyMatrix4( matrix ) {
  22573. this.start.applyMatrix4( matrix );
  22574. this.end.applyMatrix4( matrix );
  22575. return this;
  22576. }
  22577. equals( line ) {
  22578. return line.start.equals( this.start ) && line.end.equals( this.end );
  22579. }
  22580. clone() {
  22581. return new this.constructor().copy( this );
  22582. }
  22583. }
  22584. const _vector$3 = /*@__PURE__*/ new Vector3();
  22585. class SpotLightHelper extends Object3D {
  22586. constructor( light, color ) {
  22587. super();
  22588. this.light = light;
  22589. this.matrixAutoUpdate = false;
  22590. this.color = color;
  22591. this.type = 'SpotLightHelper';
  22592. const geometry = new BufferGeometry();
  22593. const positions = [
  22594. 0, 0, 0, 0, 0, 1,
  22595. 0, 0, 0, 1, 0, 1,
  22596. 0, 0, 0, -1, 0, 1,
  22597. 0, 0, 0, 0, 1, 1,
  22598. 0, 0, 0, 0, -1, 1
  22599. ];
  22600. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  22601. const p1 = ( i / l ) * Math.PI * 2;
  22602. const p2 = ( j / l ) * Math.PI * 2;
  22603. positions.push(
  22604. Math.cos( p1 ), Math.sin( p1 ), 1,
  22605. Math.cos( p2 ), Math.sin( p2 ), 1
  22606. );
  22607. }
  22608. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  22609. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  22610. this.cone = new LineSegments( geometry, material );
  22611. this.add( this.cone );
  22612. this.update();
  22613. }
  22614. dispose() {
  22615. this.cone.geometry.dispose();
  22616. this.cone.material.dispose();
  22617. }
  22618. update() {
  22619. this.light.updateWorldMatrix( true, false );
  22620. this.light.target.updateWorldMatrix( true, false );
  22621. // update the local matrix based on the parent and light target transforms
  22622. if ( this.parent ) {
  22623. this.parent.updateWorldMatrix( true );
  22624. this.matrix
  22625. .copy( this.parent.matrixWorld )
  22626. .invert()
  22627. .multiply( this.light.matrixWorld );
  22628. } else {
  22629. this.matrix.copy( this.light.matrixWorld );
  22630. }
  22631. this.matrixWorld.copy( this.light.matrixWorld );
  22632. const coneLength = this.light.distance ? this.light.distance : 1000;
  22633. const coneWidth = coneLength * Math.tan( this.light.angle );
  22634. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  22635. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  22636. this.cone.lookAt( _vector$3 );
  22637. if ( this.color !== undefined ) {
  22638. this.cone.material.color.set( this.color );
  22639. } else {
  22640. this.cone.material.color.copy( this.light.color );
  22641. }
  22642. }
  22643. }
  22644. const _vector$2 = /*@__PURE__*/ new Vector3();
  22645. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  22646. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  22647. class SkeletonHelper extends LineSegments {
  22648. constructor( object ) {
  22649. const bones = getBoneList( object );
  22650. const geometry = new BufferGeometry();
  22651. const vertices = [];
  22652. const colors = [];
  22653. const color1 = new Color( 0, 0, 1 );
  22654. const color2 = new Color( 0, 1, 0 );
  22655. for ( let i = 0; i < bones.length; i ++ ) {
  22656. const bone = bones[ i ];
  22657. if ( bone.parent && bone.parent.isBone ) {
  22658. vertices.push( 0, 0, 0 );
  22659. vertices.push( 0, 0, 0 );
  22660. colors.push( color1.r, color1.g, color1.b );
  22661. colors.push( color2.r, color2.g, color2.b );
  22662. }
  22663. }
  22664. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22665. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22666. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  22667. super( geometry, material );
  22668. this.isSkeletonHelper = true;
  22669. this.type = 'SkeletonHelper';
  22670. this.root = object;
  22671. this.bones = bones;
  22672. this.matrix = object.matrixWorld;
  22673. this.matrixAutoUpdate = false;
  22674. }
  22675. updateMatrixWorld( force ) {
  22676. const bones = this.bones;
  22677. const geometry = this.geometry;
  22678. const position = geometry.getAttribute( 'position' );
  22679. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  22680. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  22681. const bone = bones[ i ];
  22682. if ( bone.parent && bone.parent.isBone ) {
  22683. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  22684. _vector$2.setFromMatrixPosition( _boneMatrix );
  22685. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  22686. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  22687. _vector$2.setFromMatrixPosition( _boneMatrix );
  22688. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  22689. j += 2;
  22690. }
  22691. }
  22692. geometry.getAttribute( 'position' ).needsUpdate = true;
  22693. super.updateMatrixWorld( force );
  22694. }
  22695. dispose() {
  22696. this.geometry.dispose();
  22697. this.material.dispose();
  22698. }
  22699. }
  22700. function getBoneList( object ) {
  22701. const boneList = [];
  22702. if ( object.isBone === true ) {
  22703. boneList.push( object );
  22704. }
  22705. for ( let i = 0; i < object.children.length; i ++ ) {
  22706. boneList.push( ...getBoneList( object.children[ i ] ) );
  22707. }
  22708. return boneList;
  22709. }
  22710. class PointLightHelper extends Mesh {
  22711. constructor( light, sphereSize, color ) {
  22712. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  22713. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  22714. super( geometry, material );
  22715. this.light = light;
  22716. this.color = color;
  22717. this.type = 'PointLightHelper';
  22718. this.matrix = this.light.matrixWorld;
  22719. this.matrixAutoUpdate = false;
  22720. this.update();
  22721. /*
  22722. // TODO: delete this comment?
  22723. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  22724. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  22725. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  22726. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  22727. const d = light.distance;
  22728. if ( d === 0.0 ) {
  22729. this.lightDistance.visible = false;
  22730. } else {
  22731. this.lightDistance.scale.set( d, d, d );
  22732. }
  22733. this.add( this.lightDistance );
  22734. */
  22735. }
  22736. dispose() {
  22737. this.geometry.dispose();
  22738. this.material.dispose();
  22739. }
  22740. update() {
  22741. this.light.updateWorldMatrix( true, false );
  22742. if ( this.color !== undefined ) {
  22743. this.material.color.set( this.color );
  22744. } else {
  22745. this.material.color.copy( this.light.color );
  22746. }
  22747. /*
  22748. const d = this.light.distance;
  22749. if ( d === 0.0 ) {
  22750. this.lightDistance.visible = false;
  22751. } else {
  22752. this.lightDistance.visible = true;
  22753. this.lightDistance.scale.set( d, d, d );
  22754. }
  22755. */
  22756. }
  22757. }
  22758. const _vector$1 = /*@__PURE__*/ new Vector3();
  22759. const _color1 = /*@__PURE__*/ new Color();
  22760. const _color2 = /*@__PURE__*/ new Color();
  22761. class HemisphereLightHelper extends Object3D {
  22762. constructor( light, size, color ) {
  22763. super();
  22764. this.light = light;
  22765. this.matrix = light.matrixWorld;
  22766. this.matrixAutoUpdate = false;
  22767. this.color = color;
  22768. this.type = 'HemisphereLightHelper';
  22769. const geometry = new OctahedronGeometry( size );
  22770. geometry.rotateY( Math.PI * 0.5 );
  22771. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  22772. if ( this.color === undefined ) this.material.vertexColors = true;
  22773. const position = geometry.getAttribute( 'position' );
  22774. const colors = new Float32Array( position.count * 3 );
  22775. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  22776. this.add( new Mesh( geometry, this.material ) );
  22777. this.update();
  22778. }
  22779. dispose() {
  22780. this.children[ 0 ].geometry.dispose();
  22781. this.children[ 0 ].material.dispose();
  22782. }
  22783. update() {
  22784. const mesh = this.children[ 0 ];
  22785. if ( this.color !== undefined ) {
  22786. this.material.color.set( this.color );
  22787. } else {
  22788. const colors = mesh.geometry.getAttribute( 'color' );
  22789. _color1.copy( this.light.color );
  22790. _color2.copy( this.light.groundColor );
  22791. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  22792. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  22793. colors.setXYZ( i, color.r, color.g, color.b );
  22794. }
  22795. colors.needsUpdate = true;
  22796. }
  22797. this.light.updateWorldMatrix( true, false );
  22798. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  22799. }
  22800. }
  22801. class GridHelper extends LineSegments {
  22802. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  22803. color1 = new Color( color1 );
  22804. color2 = new Color( color2 );
  22805. const center = divisions / 2;
  22806. const step = size / divisions;
  22807. const halfSize = size / 2;
  22808. const vertices = [], colors = [];
  22809. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  22810. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  22811. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  22812. const color = i === center ? color1 : color2;
  22813. color.toArray( colors, j ); j += 3;
  22814. color.toArray( colors, j ); j += 3;
  22815. color.toArray( colors, j ); j += 3;
  22816. color.toArray( colors, j ); j += 3;
  22817. }
  22818. const geometry = new BufferGeometry();
  22819. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22820. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22821. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  22822. super( geometry, material );
  22823. this.type = 'GridHelper';
  22824. }
  22825. dispose() {
  22826. this.geometry.dispose();
  22827. this.material.dispose();
  22828. }
  22829. }
  22830. class PolarGridHelper extends LineSegments {
  22831. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  22832. color1 = new Color( color1 );
  22833. color2 = new Color( color2 );
  22834. const vertices = [];
  22835. const colors = [];
  22836. // create the sectors
  22837. if ( sectors > 1 ) {
  22838. for ( let i = 0; i < sectors; i ++ ) {
  22839. const v = ( i / sectors ) * ( Math.PI * 2 );
  22840. const x = Math.sin( v ) * radius;
  22841. const z = Math.cos( v ) * radius;
  22842. vertices.push( 0, 0, 0 );
  22843. vertices.push( x, 0, z );
  22844. const color = ( i & 1 ) ? color1 : color2;
  22845. colors.push( color.r, color.g, color.b );
  22846. colors.push( color.r, color.g, color.b );
  22847. }
  22848. }
  22849. // create the rings
  22850. for ( let i = 0; i < rings; i ++ ) {
  22851. const color = ( i & 1 ) ? color1 : color2;
  22852. const r = radius - ( radius / rings * i );
  22853. for ( let j = 0; j < divisions; j ++ ) {
  22854. // first vertex
  22855. let v = ( j / divisions ) * ( Math.PI * 2 );
  22856. let x = Math.sin( v ) * r;
  22857. let z = Math.cos( v ) * r;
  22858. vertices.push( x, 0, z );
  22859. colors.push( color.r, color.g, color.b );
  22860. // second vertex
  22861. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  22862. x = Math.sin( v ) * r;
  22863. z = Math.cos( v ) * r;
  22864. vertices.push( x, 0, z );
  22865. colors.push( color.r, color.g, color.b );
  22866. }
  22867. }
  22868. const geometry = new BufferGeometry();
  22869. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22870. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22871. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  22872. super( geometry, material );
  22873. this.type = 'PolarGridHelper';
  22874. }
  22875. dispose() {
  22876. this.geometry.dispose();
  22877. this.material.dispose();
  22878. }
  22879. }
  22880. const _v1 = /*@__PURE__*/ new Vector3();
  22881. const _v2 = /*@__PURE__*/ new Vector3();
  22882. const _v3 = /*@__PURE__*/ new Vector3();
  22883. class DirectionalLightHelper extends Object3D {
  22884. constructor( light, size, color ) {
  22885. super();
  22886. this.light = light;
  22887. this.matrix = light.matrixWorld;
  22888. this.matrixAutoUpdate = false;
  22889. this.color = color;
  22890. this.type = 'DirectionalLightHelper';
  22891. if ( size === undefined ) size = 1;
  22892. let geometry = new BufferGeometry();
  22893. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  22894. - size, size, 0,
  22895. size, size, 0,
  22896. size, - size, 0,
  22897. - size, - size, 0,
  22898. - size, size, 0
  22899. ], 3 ) );
  22900. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  22901. this.lightPlane = new Line( geometry, material );
  22902. this.add( this.lightPlane );
  22903. geometry = new BufferGeometry();
  22904. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  22905. this.targetLine = new Line( geometry, material );
  22906. this.add( this.targetLine );
  22907. this.update();
  22908. }
  22909. dispose() {
  22910. this.lightPlane.geometry.dispose();
  22911. this.lightPlane.material.dispose();
  22912. this.targetLine.geometry.dispose();
  22913. this.targetLine.material.dispose();
  22914. }
  22915. update() {
  22916. this.light.updateWorldMatrix( true, false );
  22917. this.light.target.updateWorldMatrix( true, false );
  22918. _v1.setFromMatrixPosition( this.light.matrixWorld );
  22919. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  22920. _v3.subVectors( _v2, _v1 );
  22921. this.lightPlane.lookAt( _v2 );
  22922. if ( this.color !== undefined ) {
  22923. this.lightPlane.material.color.set( this.color );
  22924. this.targetLine.material.color.set( this.color );
  22925. } else {
  22926. this.lightPlane.material.color.copy( this.light.color );
  22927. this.targetLine.material.color.copy( this.light.color );
  22928. }
  22929. this.targetLine.lookAt( _v2 );
  22930. this.targetLine.scale.z = _v3.length();
  22931. }
  22932. }
  22933. const _vector = /*@__PURE__*/ new Vector3();
  22934. const _camera = /*@__PURE__*/ new Camera();
  22935. /**
  22936. * - shows frustum, line of sight and up of the camera
  22937. * - suitable for fast updates
  22938. * - based on frustum visualization in lightgl.js shadowmap example
  22939. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  22940. */
  22941. class CameraHelper extends LineSegments {
  22942. constructor( camera ) {
  22943. const geometry = new BufferGeometry();
  22944. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  22945. const vertices = [];
  22946. const colors = [];
  22947. const pointMap = {};
  22948. // near
  22949. addLine( 'n1', 'n2' );
  22950. addLine( 'n2', 'n4' );
  22951. addLine( 'n4', 'n3' );
  22952. addLine( 'n3', 'n1' );
  22953. // far
  22954. addLine( 'f1', 'f2' );
  22955. addLine( 'f2', 'f4' );
  22956. addLine( 'f4', 'f3' );
  22957. addLine( 'f3', 'f1' );
  22958. // sides
  22959. addLine( 'n1', 'f1' );
  22960. addLine( 'n2', 'f2' );
  22961. addLine( 'n3', 'f3' );
  22962. addLine( 'n4', 'f4' );
  22963. // cone
  22964. addLine( 'p', 'n1' );
  22965. addLine( 'p', 'n2' );
  22966. addLine( 'p', 'n3' );
  22967. addLine( 'p', 'n4' );
  22968. // up
  22969. addLine( 'u1', 'u2' );
  22970. addLine( 'u2', 'u3' );
  22971. addLine( 'u3', 'u1' );
  22972. // target
  22973. addLine( 'c', 't' );
  22974. addLine( 'p', 'c' );
  22975. // cross
  22976. addLine( 'cn1', 'cn2' );
  22977. addLine( 'cn3', 'cn4' );
  22978. addLine( 'cf1', 'cf2' );
  22979. addLine( 'cf3', 'cf4' );
  22980. function addLine( a, b ) {
  22981. addPoint( a );
  22982. addPoint( b );
  22983. }
  22984. function addPoint( id ) {
  22985. vertices.push( 0, 0, 0 );
  22986. colors.push( 0, 0, 0 );
  22987. if ( pointMap[ id ] === undefined ) {
  22988. pointMap[ id ] = [];
  22989. }
  22990. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  22991. }
  22992. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22993. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  22994. super( geometry, material );
  22995. this.type = 'CameraHelper';
  22996. this.camera = camera;
  22997. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  22998. this.matrix = camera.matrixWorld;
  22999. this.matrixAutoUpdate = false;
  23000. this.pointMap = pointMap;
  23001. this.update();
  23002. // colors
  23003. const colorFrustum = new Color( 0xffaa00 );
  23004. const colorCone = new Color( 0xff0000 );
  23005. const colorUp = new Color( 0x00aaff );
  23006. const colorTarget = new Color( 0xffffff );
  23007. const colorCross = new Color( 0x333333 );
  23008. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  23009. }
  23010. setColors( frustum, cone, up, target, cross ) {
  23011. const geometry = this.geometry;
  23012. const colorAttribute = geometry.getAttribute( 'color' );
  23013. // near
  23014. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  23015. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  23016. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  23017. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  23018. // far
  23019. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  23020. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  23021. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  23022. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  23023. // sides
  23024. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  23025. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  23026. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  23027. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  23028. // cone
  23029. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  23030. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  23031. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  23032. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  23033. // up
  23034. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  23035. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  23036. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  23037. // target
  23038. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  23039. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  23040. // cross
  23041. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  23042. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  23043. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  23044. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  23045. colorAttribute.needsUpdate = true;
  23046. }
  23047. update() {
  23048. const geometry = this.geometry;
  23049. const pointMap = this.pointMap;
  23050. const w = 1, h = 1;
  23051. // we need just camera projection matrix inverse
  23052. // world matrix must be identity
  23053. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  23054. // Adjust z values based on coordinate system
  23055. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0;
  23056. // center / target
  23057. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  23058. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  23059. // near
  23060. setPoint( 'n1', pointMap, geometry, _camera, -1, -1, nearZ );
  23061. setPoint( 'n2', pointMap, geometry, _camera, w, -1, nearZ );
  23062. setPoint( 'n3', pointMap, geometry, _camera, -1, h, nearZ );
  23063. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  23064. // far
  23065. setPoint( 'f1', pointMap, geometry, _camera, -1, -1, 1 );
  23066. setPoint( 'f2', pointMap, geometry, _camera, w, -1, 1 );
  23067. setPoint( 'f3', pointMap, geometry, _camera, -1, h, 1 );
  23068. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  23069. // up
  23070. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  23071. setPoint( 'u2', pointMap, geometry, _camera, -1 * 0.7, h * 1.1, nearZ );
  23072. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  23073. // cross
  23074. setPoint( 'cf1', pointMap, geometry, _camera, -1, 0, 1 );
  23075. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  23076. setPoint( 'cf3', pointMap, geometry, _camera, 0, -1, 1 );
  23077. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  23078. setPoint( 'cn1', pointMap, geometry, _camera, -1, 0, nearZ );
  23079. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  23080. setPoint( 'cn3', pointMap, geometry, _camera, 0, -1, nearZ );
  23081. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  23082. geometry.getAttribute( 'position' ).needsUpdate = true;
  23083. }
  23084. dispose() {
  23085. this.geometry.dispose();
  23086. this.material.dispose();
  23087. }
  23088. }
  23089. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  23090. _vector.set( x, y, z ).unproject( camera );
  23091. const points = pointMap[ point ];
  23092. if ( points !== undefined ) {
  23093. const position = geometry.getAttribute( 'position' );
  23094. for ( let i = 0, l = points.length; i < l; i ++ ) {
  23095. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  23096. }
  23097. }
  23098. }
  23099. const _box = /*@__PURE__*/ new Box3();
  23100. class BoxHelper extends LineSegments {
  23101. constructor( object, color = 0xffff00 ) {
  23102. 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 ] );
  23103. const positions = new Float32Array( 8 * 3 );
  23104. const geometry = new BufferGeometry();
  23105. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  23106. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  23107. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  23108. this.object = object;
  23109. this.type = 'BoxHelper';
  23110. this.matrixAutoUpdate = false;
  23111. this.update();
  23112. }
  23113. update( object ) {
  23114. if ( object !== undefined ) {
  23115. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  23116. }
  23117. if ( this.object !== undefined ) {
  23118. _box.setFromObject( this.object );
  23119. }
  23120. if ( _box.isEmpty() ) return;
  23121. const min = _box.min;
  23122. const max = _box.max;
  23123. /*
  23124. 5____4
  23125. 1/___0/|
  23126. | 6__|_7
  23127. 2/___3/
  23128. 0: max.x, max.y, max.z
  23129. 1: min.x, max.y, max.z
  23130. 2: min.x, min.y, max.z
  23131. 3: max.x, min.y, max.z
  23132. 4: max.x, max.y, min.z
  23133. 5: min.x, max.y, min.z
  23134. 6: min.x, min.y, min.z
  23135. 7: max.x, min.y, min.z
  23136. */
  23137. const position = this.geometry.attributes.position;
  23138. const array = position.array;
  23139. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  23140. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  23141. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  23142. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  23143. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  23144. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  23145. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  23146. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  23147. position.needsUpdate = true;
  23148. this.geometry.computeBoundingSphere();
  23149. }
  23150. setFromObject( object ) {
  23151. this.object = object;
  23152. this.update();
  23153. return this;
  23154. }
  23155. copy( source, recursive ) {
  23156. super.copy( source, recursive );
  23157. this.object = source.object;
  23158. return this;
  23159. }
  23160. dispose() {
  23161. this.geometry.dispose();
  23162. this.material.dispose();
  23163. }
  23164. }
  23165. class Box3Helper extends LineSegments {
  23166. constructor( box, color = 0xffff00 ) {
  23167. 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 ] );
  23168. 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 ];
  23169. const geometry = new BufferGeometry();
  23170. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  23171. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  23172. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  23173. this.box = box;
  23174. this.type = 'Box3Helper';
  23175. this.geometry.computeBoundingSphere();
  23176. }
  23177. updateMatrixWorld( force ) {
  23178. const box = this.box;
  23179. if ( box.isEmpty() ) return;
  23180. box.getCenter( this.position );
  23181. box.getSize( this.scale );
  23182. this.scale.multiplyScalar( 0.5 );
  23183. super.updateMatrixWorld( force );
  23184. }
  23185. dispose() {
  23186. this.geometry.dispose();
  23187. this.material.dispose();
  23188. }
  23189. }
  23190. class PlaneHelper extends Line {
  23191. constructor( plane, size = 1, hex = 0xffff00 ) {
  23192. const color = hex;
  23193. 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 ];
  23194. const geometry = new BufferGeometry();
  23195. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  23196. geometry.computeBoundingSphere();
  23197. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  23198. this.type = 'PlaneHelper';
  23199. this.plane = plane;
  23200. this.size = size;
  23201. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  23202. const geometry2 = new BufferGeometry();
  23203. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  23204. geometry2.computeBoundingSphere();
  23205. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  23206. }
  23207. updateMatrixWorld( force ) {
  23208. this.position.set( 0, 0, 0 );
  23209. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  23210. this.lookAt( this.plane.normal );
  23211. this.translateZ( - this.plane.constant );
  23212. super.updateMatrixWorld( force );
  23213. }
  23214. dispose() {
  23215. this.geometry.dispose();
  23216. this.material.dispose();
  23217. this.children[ 0 ].geometry.dispose();
  23218. this.children[ 0 ].material.dispose();
  23219. }
  23220. }
  23221. const _axis = /*@__PURE__*/ new Vector3();
  23222. let _lineGeometry, _coneGeometry;
  23223. class ArrowHelper extends Object3D {
  23224. // dir is assumed to be normalized
  23225. 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 ) {
  23226. super();
  23227. this.type = 'ArrowHelper';
  23228. if ( _lineGeometry === undefined ) {
  23229. _lineGeometry = new BufferGeometry();
  23230. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  23231. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  23232. _coneGeometry.translate( 0, -0.5, 0 );
  23233. }
  23234. this.position.copy( origin );
  23235. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  23236. this.line.matrixAutoUpdate = false;
  23237. this.add( this.line );
  23238. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  23239. this.cone.matrixAutoUpdate = false;
  23240. this.add( this.cone );
  23241. this.setDirection( dir );
  23242. this.setLength( length, headLength, headWidth );
  23243. }
  23244. setDirection( dir ) {
  23245. // dir is assumed to be normalized
  23246. if ( dir.y > 0.99999 ) {
  23247. this.quaternion.set( 0, 0, 0, 1 );
  23248. } else if ( dir.y < -0.99999 ) {
  23249. this.quaternion.set( 1, 0, 0, 0 );
  23250. } else {
  23251. _axis.set( dir.z, 0, - dir.x ).normalize();
  23252. const radians = Math.acos( dir.y );
  23253. this.quaternion.setFromAxisAngle( _axis, radians );
  23254. }
  23255. }
  23256. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  23257. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  23258. this.line.updateMatrix();
  23259. this.cone.scale.set( headWidth, headLength, headWidth );
  23260. this.cone.position.y = length;
  23261. this.cone.updateMatrix();
  23262. }
  23263. setColor( color ) {
  23264. this.line.material.color.set( color );
  23265. this.cone.material.color.set( color );
  23266. }
  23267. copy( source ) {
  23268. super.copy( source, false );
  23269. this.line.copy( source.line );
  23270. this.cone.copy( source.cone );
  23271. return this;
  23272. }
  23273. dispose() {
  23274. this.line.geometry.dispose();
  23275. this.line.material.dispose();
  23276. this.cone.geometry.dispose();
  23277. this.cone.material.dispose();
  23278. }
  23279. }
  23280. class AxesHelper extends LineSegments {
  23281. constructor( size = 1 ) {
  23282. const vertices = [
  23283. 0, 0, 0, size, 0, 0,
  23284. 0, 0, 0, 0, size, 0,
  23285. 0, 0, 0, 0, 0, size
  23286. ];
  23287. const colors = [
  23288. 1, 0, 0, 1, 0.6, 0,
  23289. 0, 1, 0, 0.6, 1, 0,
  23290. 0, 0, 1, 0, 0.6, 1
  23291. ];
  23292. const geometry = new BufferGeometry();
  23293. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23294. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  23295. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  23296. super( geometry, material );
  23297. this.type = 'AxesHelper';
  23298. }
  23299. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  23300. const color = new Color();
  23301. const array = this.geometry.attributes.color.array;
  23302. color.set( xAxisColor );
  23303. color.toArray( array, 0 );
  23304. color.toArray( array, 3 );
  23305. color.set( yAxisColor );
  23306. color.toArray( array, 6 );
  23307. color.toArray( array, 9 );
  23308. color.set( zAxisColor );
  23309. color.toArray( array, 12 );
  23310. color.toArray( array, 15 );
  23311. this.geometry.attributes.color.needsUpdate = true;
  23312. return this;
  23313. }
  23314. dispose() {
  23315. this.geometry.dispose();
  23316. this.material.dispose();
  23317. }
  23318. }
  23319. class ShapePath {
  23320. constructor() {
  23321. this.type = 'ShapePath';
  23322. this.color = new Color();
  23323. this.subPaths = [];
  23324. this.currentPath = null;
  23325. }
  23326. moveTo( x, y ) {
  23327. this.currentPath = new Path();
  23328. this.subPaths.push( this.currentPath );
  23329. this.currentPath.moveTo( x, y );
  23330. return this;
  23331. }
  23332. lineTo( x, y ) {
  23333. this.currentPath.lineTo( x, y );
  23334. return this;
  23335. }
  23336. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  23337. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  23338. return this;
  23339. }
  23340. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23341. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  23342. return this;
  23343. }
  23344. splineThru( pts ) {
  23345. this.currentPath.splineThru( pts );
  23346. return this;
  23347. }
  23348. toShapes( isCCW ) {
  23349. function toShapesNoHoles( inSubpaths ) {
  23350. const shapes = [];
  23351. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  23352. const tmpPath = inSubpaths[ i ];
  23353. const tmpShape = new Shape();
  23354. tmpShape.curves = tmpPath.curves;
  23355. shapes.push( tmpShape );
  23356. }
  23357. return shapes;
  23358. }
  23359. function isPointInsidePolygon( inPt, inPolygon ) {
  23360. const polyLen = inPolygon.length;
  23361. // inPt on polygon contour => immediate success or
  23362. // toggling of inside/outside at every single! intersection point of an edge
  23363. // with the horizontal line through inPt, left of inPt
  23364. // not counting lowerY endpoints of edges and whole edges on that line
  23365. let inside = false;
  23366. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  23367. let edgeLowPt = inPolygon[ p ];
  23368. let edgeHighPt = inPolygon[ q ];
  23369. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23370. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23371. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  23372. // not parallel
  23373. if ( edgeDy < 0 ) {
  23374. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  23375. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  23376. }
  23377. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  23378. if ( inPt.y === edgeLowPt.y ) {
  23379. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  23380. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23381. } else {
  23382. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  23383. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  23384. if ( perpEdge < 0 ) continue;
  23385. inside = ! inside; // true intersection left of inPt
  23386. }
  23387. } else {
  23388. // parallel or collinear
  23389. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  23390. // edge lies on the same horizontal line as inPt
  23391. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  23392. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  23393. // continue;
  23394. }
  23395. }
  23396. return inside;
  23397. }
  23398. const isClockWise = ShapeUtils.isClockWise;
  23399. const subPaths = this.subPaths;
  23400. if ( subPaths.length === 0 ) return [];
  23401. let solid, tmpPath, tmpShape;
  23402. const shapes = [];
  23403. if ( subPaths.length === 1 ) {
  23404. tmpPath = subPaths[ 0 ];
  23405. tmpShape = new Shape();
  23406. tmpShape.curves = tmpPath.curves;
  23407. shapes.push( tmpShape );
  23408. return shapes;
  23409. }
  23410. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  23411. holesFirst = isCCW ? ! holesFirst : holesFirst;
  23412. // console.log("Holes first", holesFirst);
  23413. const betterShapeHoles = [];
  23414. const newShapes = [];
  23415. let newShapeHoles = [];
  23416. let mainIdx = 0;
  23417. let tmpPoints;
  23418. newShapes[ mainIdx ] = undefined;
  23419. newShapeHoles[ mainIdx ] = [];
  23420. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  23421. tmpPath = subPaths[ i ];
  23422. tmpPoints = tmpPath.getPoints();
  23423. solid = isClockWise( tmpPoints );
  23424. solid = isCCW ? ! solid : solid;
  23425. if ( solid ) {
  23426. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  23427. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  23428. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  23429. if ( holesFirst ) mainIdx ++;
  23430. newShapeHoles[ mainIdx ] = [];
  23431. //console.log('cw', i);
  23432. } else {
  23433. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  23434. //console.log('ccw', i);
  23435. }
  23436. }
  23437. // only Holes? -> probably all Shapes with wrong orientation
  23438. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  23439. if ( newShapes.length > 1 ) {
  23440. let ambiguous = false;
  23441. let toChange = 0;
  23442. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  23443. betterShapeHoles[ sIdx ] = [];
  23444. }
  23445. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  23446. const sho = newShapeHoles[ sIdx ];
  23447. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  23448. const ho = sho[ hIdx ];
  23449. let hole_unassigned = true;
  23450. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  23451. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  23452. if ( sIdx !== s2Idx ) toChange ++;
  23453. if ( hole_unassigned ) {
  23454. hole_unassigned = false;
  23455. betterShapeHoles[ s2Idx ].push( ho );
  23456. } else {
  23457. ambiguous = true;
  23458. }
  23459. }
  23460. }
  23461. if ( hole_unassigned ) {
  23462. betterShapeHoles[ sIdx ].push( ho );
  23463. }
  23464. }
  23465. }
  23466. if ( toChange > 0 && ambiguous === false ) {
  23467. newShapeHoles = betterShapeHoles;
  23468. }
  23469. }
  23470. let tmpHoles;
  23471. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  23472. tmpShape = newShapes[ i ].s;
  23473. shapes.push( tmpShape );
  23474. tmpHoles = newShapeHoles[ i ];
  23475. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  23476. tmpShape.holes.push( tmpHoles[ j ].h );
  23477. }
  23478. }
  23479. //console.log("shape", shapes);
  23480. return shapes;
  23481. }
  23482. }
  23483. class Controls extends EventDispatcher {
  23484. constructor( object, domElement = null ) {
  23485. super();
  23486. this.object = object;
  23487. this.domElement = domElement;
  23488. this.enabled = true;
  23489. this.state = -1;
  23490. this.keys = {};
  23491. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  23492. this.touches = { ONE: null, TWO: null };
  23493. }
  23494. connect() {}
  23495. disconnect() {}
  23496. dispose() {}
  23497. update( /* delta */ ) {}
  23498. }
  23499. function contain( texture, aspect ) {
  23500. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  23501. if ( imageAspect > aspect ) {
  23502. texture.repeat.x = 1;
  23503. texture.repeat.y = imageAspect / aspect;
  23504. texture.offset.x = 0;
  23505. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  23506. } else {
  23507. texture.repeat.x = aspect / imageAspect;
  23508. texture.repeat.y = 1;
  23509. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  23510. texture.offset.y = 0;
  23511. }
  23512. return texture;
  23513. }
  23514. function cover( texture, aspect ) {
  23515. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  23516. if ( imageAspect > aspect ) {
  23517. texture.repeat.x = aspect / imageAspect;
  23518. texture.repeat.y = 1;
  23519. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  23520. texture.offset.y = 0;
  23521. } else {
  23522. texture.repeat.x = 1;
  23523. texture.repeat.y = imageAspect / aspect;
  23524. texture.offset.x = 0;
  23525. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  23526. }
  23527. return texture;
  23528. }
  23529. function fill( texture ) {
  23530. texture.repeat.x = 1;
  23531. texture.repeat.y = 1;
  23532. texture.offset.x = 0;
  23533. texture.offset.y = 0;
  23534. return texture;
  23535. }
  23536. /**
  23537. * Given the width, height, format, and type of a texture. Determines how many
  23538. * bytes must be used to represent the texture.
  23539. *
  23540. * @param {number} width
  23541. * @param {number} height
  23542. * @param {number} format
  23543. * @param {number} type
  23544. * @return {number} The number of bytes required to represent the texture.
  23545. */
  23546. function getByteLength( width, height, format, type ) {
  23547. const typeByteLength = getTextureTypeByteLength( type );
  23548. switch ( format ) {
  23549. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  23550. case AlphaFormat:
  23551. return width * height;
  23552. case LuminanceFormat:
  23553. return width * height;
  23554. case LuminanceAlphaFormat:
  23555. return width * height * 2;
  23556. case RedFormat:
  23557. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  23558. case RedIntegerFormat:
  23559. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  23560. case RGFormat:
  23561. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23562. case RGIntegerFormat:
  23563. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23564. case RGBFormat:
  23565. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23566. case RGBAFormat:
  23567. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23568. case RGBAIntegerFormat:
  23569. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  23570. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  23571. case RGB_S3TC_DXT1_Format:
  23572. case RGBA_S3TC_DXT1_Format:
  23573. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  23574. case RGBA_S3TC_DXT3_Format:
  23575. case RGBA_S3TC_DXT5_Format:
  23576. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  23577. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  23578. case RGB_PVRTC_2BPPV1_Format:
  23579. case RGBA_PVRTC_2BPPV1_Format:
  23580. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  23581. case RGB_PVRTC_4BPPV1_Format:
  23582. case RGBA_PVRTC_4BPPV1_Format:
  23583. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  23584. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  23585. case RGB_ETC1_Format:
  23586. case RGB_ETC2_Format:
  23587. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  23588. case RGBA_ETC2_EAC_Format:
  23589. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  23590. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  23591. case RGBA_ASTC_4x4_Format:
  23592. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  23593. case RGBA_ASTC_5x4_Format:
  23594. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  23595. case RGBA_ASTC_5x5_Format:
  23596. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  23597. case RGBA_ASTC_6x5_Format:
  23598. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  23599. case RGBA_ASTC_6x6_Format:
  23600. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  23601. case RGBA_ASTC_8x5_Format:
  23602. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  23603. case RGBA_ASTC_8x6_Format:
  23604. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  23605. case RGBA_ASTC_8x8_Format:
  23606. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  23607. case RGBA_ASTC_10x5_Format:
  23608. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  23609. case RGBA_ASTC_10x6_Format:
  23610. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  23611. case RGBA_ASTC_10x8_Format:
  23612. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  23613. case RGBA_ASTC_10x10_Format:
  23614. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  23615. case RGBA_ASTC_12x10_Format:
  23616. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  23617. case RGBA_ASTC_12x12_Format:
  23618. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  23619. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  23620. case RGBA_BPTC_Format:
  23621. case RGB_BPTC_SIGNED_Format:
  23622. case RGB_BPTC_UNSIGNED_Format:
  23623. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  23624. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  23625. case RED_RGTC1_Format:
  23626. case SIGNED_RED_RGTC1_Format:
  23627. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  23628. case RED_GREEN_RGTC2_Format:
  23629. case SIGNED_RED_GREEN_RGTC2_Format:
  23630. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  23631. }
  23632. throw new Error(
  23633. `Unable to determine texture byte length for ${format} format.`,
  23634. );
  23635. }
  23636. function getTextureTypeByteLength( type ) {
  23637. switch ( type ) {
  23638. case UnsignedByteType:
  23639. case ByteType:
  23640. return { byteLength: 1, components: 1 };
  23641. case UnsignedShortType:
  23642. case ShortType:
  23643. case HalfFloatType:
  23644. return { byteLength: 2, components: 1 };
  23645. case UnsignedShort4444Type:
  23646. case UnsignedShort5551Type:
  23647. return { byteLength: 2, components: 4 };
  23648. case UnsignedIntType:
  23649. case IntType:
  23650. case FloatType:
  23651. return { byteLength: 4, components: 1 };
  23652. case UnsignedInt5999Type:
  23653. return { byteLength: 4, components: 3 };
  23654. }
  23655. throw new Error( `Unknown texture type ${type}.` );
  23656. }
  23657. const TextureUtils = {
  23658. contain,
  23659. cover,
  23660. fill,
  23661. getByteLength
  23662. };
  23663. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  23664. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  23665. revision: REVISION,
  23666. } } ) );
  23667. }
  23668. if ( typeof window !== 'undefined' ) {
  23669. if ( window.__THREE__ ) {
  23670. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  23671. } else {
  23672. window.__THREE__ = REVISION;
  23673. }
  23674. }
  23675. function WebGLAnimation() {
  23676. let context = null;
  23677. let isAnimating = false;
  23678. let animationLoop = null;
  23679. let requestId = null;
  23680. function onAnimationFrame( time, frame ) {
  23681. animationLoop( time, frame );
  23682. requestId = context.requestAnimationFrame( onAnimationFrame );
  23683. }
  23684. return {
  23685. start: function () {
  23686. if ( isAnimating === true ) return;
  23687. if ( animationLoop === null ) return;
  23688. requestId = context.requestAnimationFrame( onAnimationFrame );
  23689. isAnimating = true;
  23690. },
  23691. stop: function () {
  23692. context.cancelAnimationFrame( requestId );
  23693. isAnimating = false;
  23694. },
  23695. setAnimationLoop: function ( callback ) {
  23696. animationLoop = callback;
  23697. },
  23698. setContext: function ( value ) {
  23699. context = value;
  23700. }
  23701. };
  23702. }
  23703. function WebGLAttributes( gl ) {
  23704. const buffers = new WeakMap();
  23705. function createBuffer( attribute, bufferType ) {
  23706. const array = attribute.array;
  23707. const usage = attribute.usage;
  23708. const size = array.byteLength;
  23709. const buffer = gl.createBuffer();
  23710. gl.bindBuffer( bufferType, buffer );
  23711. gl.bufferData( bufferType, array, usage );
  23712. attribute.onUploadCallback();
  23713. let type;
  23714. if ( array instanceof Float32Array ) {
  23715. type = gl.FLOAT;
  23716. } else if ( array instanceof Uint16Array ) {
  23717. if ( attribute.isFloat16BufferAttribute ) {
  23718. type = gl.HALF_FLOAT;
  23719. } else {
  23720. type = gl.UNSIGNED_SHORT;
  23721. }
  23722. } else if ( array instanceof Int16Array ) {
  23723. type = gl.SHORT;
  23724. } else if ( array instanceof Uint32Array ) {
  23725. type = gl.UNSIGNED_INT;
  23726. } else if ( array instanceof Int32Array ) {
  23727. type = gl.INT;
  23728. } else if ( array instanceof Int8Array ) {
  23729. type = gl.BYTE;
  23730. } else if ( array instanceof Uint8Array ) {
  23731. type = gl.UNSIGNED_BYTE;
  23732. } else if ( array instanceof Uint8ClampedArray ) {
  23733. type = gl.UNSIGNED_BYTE;
  23734. } else {
  23735. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  23736. }
  23737. return {
  23738. buffer: buffer,
  23739. type: type,
  23740. bytesPerElement: array.BYTES_PER_ELEMENT,
  23741. version: attribute.version,
  23742. size: size
  23743. };
  23744. }
  23745. function updateBuffer( buffer, attribute, bufferType ) {
  23746. const array = attribute.array;
  23747. const updateRanges = attribute.updateRanges;
  23748. gl.bindBuffer( bufferType, buffer );
  23749. if ( updateRanges.length === 0 ) {
  23750. // Not using update ranges
  23751. gl.bufferSubData( bufferType, 0, array );
  23752. } else {
  23753. // Before applying update ranges, we merge any adjacent / overlapping
  23754. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  23755. // to performance improvements for applications which make heavy use of
  23756. // update ranges. Likely due to GPU command overhead.
  23757. //
  23758. // Note that to reduce garbage collection between frames, we merge the
  23759. // update ranges in-place. This is safe because this method will clear the
  23760. // update ranges once updated.
  23761. updateRanges.sort( ( a, b ) => a.start - b.start );
  23762. // To merge the update ranges in-place, we work from left to right in the
  23763. // existing updateRanges array, merging ranges. This may result in a final
  23764. // array which is smaller than the original. This index tracks the last
  23765. // index representing a merged range, any data after this index can be
  23766. // trimmed once the merge algorithm is completed.
  23767. let mergeIndex = 0;
  23768. for ( let i = 1; i < updateRanges.length; i ++ ) {
  23769. const previousRange = updateRanges[ mergeIndex ];
  23770. const range = updateRanges[ i ];
  23771. // We add one here to merge adjacent ranges. This is safe because ranges
  23772. // operate over positive integers.
  23773. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  23774. previousRange.count = Math.max(
  23775. previousRange.count,
  23776. range.start + range.count - previousRange.start
  23777. );
  23778. } else {
  23779. ++ mergeIndex;
  23780. updateRanges[ mergeIndex ] = range;
  23781. }
  23782. }
  23783. // Trim the array to only contain the merged ranges.
  23784. updateRanges.length = mergeIndex + 1;
  23785. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  23786. const range = updateRanges[ i ];
  23787. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  23788. array, range.start, range.count );
  23789. }
  23790. attribute.clearUpdateRanges();
  23791. }
  23792. attribute.onUploadCallback();
  23793. }
  23794. //
  23795. function get( attribute ) {
  23796. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  23797. return buffers.get( attribute );
  23798. }
  23799. function remove( attribute ) {
  23800. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  23801. const data = buffers.get( attribute );
  23802. if ( data ) {
  23803. gl.deleteBuffer( data.buffer );
  23804. buffers.delete( attribute );
  23805. }
  23806. }
  23807. function update( attribute, bufferType ) {
  23808. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  23809. if ( attribute.isGLBufferAttribute ) {
  23810. const cached = buffers.get( attribute );
  23811. if ( ! cached || cached.version < attribute.version ) {
  23812. buffers.set( attribute, {
  23813. buffer: attribute.buffer,
  23814. type: attribute.type,
  23815. bytesPerElement: attribute.elementSize,
  23816. version: attribute.version
  23817. } );
  23818. }
  23819. return;
  23820. }
  23821. const data = buffers.get( attribute );
  23822. if ( data === undefined ) {
  23823. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  23824. } else if ( data.version < attribute.version ) {
  23825. if ( data.size !== attribute.array.byteLength ) {
  23826. 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.' );
  23827. }
  23828. updateBuffer( data.buffer, attribute, bufferType );
  23829. data.version = attribute.version;
  23830. }
  23831. }
  23832. return {
  23833. get: get,
  23834. remove: remove,
  23835. update: update
  23836. };
  23837. }
  23838. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  23839. 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";
  23840. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  23841. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  23842. 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";
  23843. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  23844. 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";
  23845. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  23846. 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";
  23847. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  23848. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  23849. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  23850. 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";
  23851. 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";
  23852. 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";
  23853. 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";
  23854. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  23855. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  23856. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  23857. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  23858. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  23859. 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";
  23860. 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";
  23861. 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";
  23862. 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";
  23863. 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";
  23864. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  23865. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  23866. 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";
  23867. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  23868. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  23869. 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}";
  23870. 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";
  23871. 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";
  23872. 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";
  23873. 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";
  23874. 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";
  23875. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  23876. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  23877. 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";
  23878. 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";
  23879. 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}";
  23880. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  23881. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  23882. 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";
  23883. 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";
  23884. 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";
  23885. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  23886. 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";
  23887. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  23888. 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";
  23889. 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";
  23890. 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}";
  23891. 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";
  23892. 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";
  23893. 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";
  23894. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  23895. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  23896. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  23897. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  23898. 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";
  23899. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  23900. 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";
  23901. 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";
  23902. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  23903. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  23904. 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";
  23905. 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";
  23906. 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";
  23907. 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";
  23908. 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";
  23909. 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;";
  23910. 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";
  23911. 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";
  23912. 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";
  23913. 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";
  23914. 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";
  23915. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  23916. 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";
  23917. 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";
  23918. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  23919. 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 );";
  23920. 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}";
  23921. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  23922. 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;";
  23923. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  23924. 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";
  23925. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  23926. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  23927. 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";
  23928. 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";
  23929. 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";
  23930. 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}";
  23931. 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";
  23932. 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";
  23933. 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";
  23934. 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";
  23935. 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";
  23936. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  23937. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  23938. 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; }";
  23939. 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";
  23940. 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\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\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#else\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#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";
  23941. 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";
  23942. 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";
  23943. 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";
  23944. 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";
  23945. 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}";
  23946. 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}";
  23947. 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}";
  23948. 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}";
  23949. 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}";
  23950. 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}";
  23951. 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}";
  23952. 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}";
  23953. 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}";
  23954. 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}";
  23955. 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}";
  23956. 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}";
  23957. 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}";
  23958. 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}";
  23959. 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}";
  23960. 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}";
  23961. 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}";
  23962. 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}";
  23963. 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}";
  23964. 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}";
  23965. 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}";
  23966. 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}";
  23967. 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}";
  23968. 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}";
  23969. 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}";
  23970. 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}";
  23971. 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}";
  23972. 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}";
  23973. 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}";
  23974. 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}";
  23975. 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}";
  23976. 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}";
  23977. 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}";
  23978. 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}";
  23979. const ShaderChunk = {
  23980. alphahash_fragment: alphahash_fragment,
  23981. alphahash_pars_fragment: alphahash_pars_fragment,
  23982. alphamap_fragment: alphamap_fragment,
  23983. alphamap_pars_fragment: alphamap_pars_fragment,
  23984. alphatest_fragment: alphatest_fragment,
  23985. alphatest_pars_fragment: alphatest_pars_fragment,
  23986. aomap_fragment: aomap_fragment,
  23987. aomap_pars_fragment: aomap_pars_fragment,
  23988. batching_pars_vertex: batching_pars_vertex,
  23989. batching_vertex: batching_vertex,
  23990. begin_vertex: begin_vertex,
  23991. beginnormal_vertex: beginnormal_vertex,
  23992. bsdfs: bsdfs,
  23993. iridescence_fragment: iridescence_fragment,
  23994. bumpmap_pars_fragment: bumpmap_pars_fragment,
  23995. clipping_planes_fragment: clipping_planes_fragment,
  23996. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  23997. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  23998. clipping_planes_vertex: clipping_planes_vertex,
  23999. color_fragment: color_fragment,
  24000. color_pars_fragment: color_pars_fragment,
  24001. color_pars_vertex: color_pars_vertex,
  24002. color_vertex: color_vertex,
  24003. common: common,
  24004. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  24005. defaultnormal_vertex: defaultnormal_vertex,
  24006. displacementmap_pars_vertex: displacementmap_pars_vertex,
  24007. displacementmap_vertex: displacementmap_vertex,
  24008. emissivemap_fragment: emissivemap_fragment,
  24009. emissivemap_pars_fragment: emissivemap_pars_fragment,
  24010. colorspace_fragment: colorspace_fragment,
  24011. colorspace_pars_fragment: colorspace_pars_fragment,
  24012. envmap_fragment: envmap_fragment,
  24013. envmap_common_pars_fragment: envmap_common_pars_fragment,
  24014. envmap_pars_fragment: envmap_pars_fragment,
  24015. envmap_pars_vertex: envmap_pars_vertex,
  24016. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  24017. envmap_vertex: envmap_vertex,
  24018. fog_vertex: fog_vertex,
  24019. fog_pars_vertex: fog_pars_vertex,
  24020. fog_fragment: fog_fragment,
  24021. fog_pars_fragment: fog_pars_fragment,
  24022. gradientmap_pars_fragment: gradientmap_pars_fragment,
  24023. lightmap_pars_fragment: lightmap_pars_fragment,
  24024. lights_lambert_fragment: lights_lambert_fragment,
  24025. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  24026. lights_pars_begin: lights_pars_begin,
  24027. lights_toon_fragment: lights_toon_fragment,
  24028. lights_toon_pars_fragment: lights_toon_pars_fragment,
  24029. lights_phong_fragment: lights_phong_fragment,
  24030. lights_phong_pars_fragment: lights_phong_pars_fragment,
  24031. lights_physical_fragment: lights_physical_fragment,
  24032. lights_physical_pars_fragment: lights_physical_pars_fragment,
  24033. lights_fragment_begin: lights_fragment_begin,
  24034. lights_fragment_maps: lights_fragment_maps,
  24035. lights_fragment_end: lights_fragment_end,
  24036. logdepthbuf_fragment: logdepthbuf_fragment,
  24037. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  24038. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  24039. logdepthbuf_vertex: logdepthbuf_vertex,
  24040. map_fragment: map_fragment,
  24041. map_pars_fragment: map_pars_fragment,
  24042. map_particle_fragment: map_particle_fragment,
  24043. map_particle_pars_fragment: map_particle_pars_fragment,
  24044. metalnessmap_fragment: metalnessmap_fragment,
  24045. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  24046. morphinstance_vertex: morphinstance_vertex,
  24047. morphcolor_vertex: morphcolor_vertex,
  24048. morphnormal_vertex: morphnormal_vertex,
  24049. morphtarget_pars_vertex: morphtarget_pars_vertex,
  24050. morphtarget_vertex: morphtarget_vertex,
  24051. normal_fragment_begin: normal_fragment_begin,
  24052. normal_fragment_maps: normal_fragment_maps,
  24053. normal_pars_fragment: normal_pars_fragment,
  24054. normal_pars_vertex: normal_pars_vertex,
  24055. normal_vertex: normal_vertex,
  24056. normalmap_pars_fragment: normalmap_pars_fragment,
  24057. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  24058. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  24059. clearcoat_pars_fragment: clearcoat_pars_fragment,
  24060. iridescence_pars_fragment: iridescence_pars_fragment,
  24061. opaque_fragment: opaque_fragment,
  24062. packing: packing,
  24063. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  24064. project_vertex: project_vertex,
  24065. dithering_fragment: dithering_fragment,
  24066. dithering_pars_fragment: dithering_pars_fragment,
  24067. roughnessmap_fragment: roughnessmap_fragment,
  24068. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  24069. shadowmap_pars_fragment: shadowmap_pars_fragment,
  24070. shadowmap_pars_vertex: shadowmap_pars_vertex,
  24071. shadowmap_vertex: shadowmap_vertex,
  24072. shadowmask_pars_fragment: shadowmask_pars_fragment,
  24073. skinbase_vertex: skinbase_vertex,
  24074. skinning_pars_vertex: skinning_pars_vertex,
  24075. skinning_vertex: skinning_vertex,
  24076. skinnormal_vertex: skinnormal_vertex,
  24077. specularmap_fragment: specularmap_fragment,
  24078. specularmap_pars_fragment: specularmap_pars_fragment,
  24079. tonemapping_fragment: tonemapping_fragment,
  24080. tonemapping_pars_fragment: tonemapping_pars_fragment,
  24081. transmission_fragment: transmission_fragment,
  24082. transmission_pars_fragment: transmission_pars_fragment,
  24083. uv_pars_fragment: uv_pars_fragment,
  24084. uv_pars_vertex: uv_pars_vertex,
  24085. uv_vertex: uv_vertex,
  24086. worldpos_vertex: worldpos_vertex,
  24087. background_vert: vertex$h,
  24088. background_frag: fragment$h,
  24089. backgroundCube_vert: vertex$g,
  24090. backgroundCube_frag: fragment$g,
  24091. cube_vert: vertex$f,
  24092. cube_frag: fragment$f,
  24093. depth_vert: vertex$e,
  24094. depth_frag: fragment$e,
  24095. distanceRGBA_vert: vertex$d,
  24096. distanceRGBA_frag: fragment$d,
  24097. equirect_vert: vertex$c,
  24098. equirect_frag: fragment$c,
  24099. linedashed_vert: vertex$b,
  24100. linedashed_frag: fragment$b,
  24101. meshbasic_vert: vertex$a,
  24102. meshbasic_frag: fragment$a,
  24103. meshlambert_vert: vertex$9,
  24104. meshlambert_frag: fragment$9,
  24105. meshmatcap_vert: vertex$8,
  24106. meshmatcap_frag: fragment$8,
  24107. meshnormal_vert: vertex$7,
  24108. meshnormal_frag: fragment$7,
  24109. meshphong_vert: vertex$6,
  24110. meshphong_frag: fragment$6,
  24111. meshphysical_vert: vertex$5,
  24112. meshphysical_frag: fragment$5,
  24113. meshtoon_vert: vertex$4,
  24114. meshtoon_frag: fragment$4,
  24115. points_vert: vertex$3,
  24116. points_frag: fragment$3,
  24117. shadow_vert: vertex$2,
  24118. shadow_frag: fragment$2,
  24119. sprite_vert: vertex$1,
  24120. sprite_frag: fragment$1
  24121. };
  24122. /**
  24123. * Uniforms library for shared webgl shaders
  24124. */
  24125. const UniformsLib = {
  24126. common: {
  24127. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  24128. opacity: { value: 1.0 },
  24129. map: { value: null },
  24130. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24131. alphaMap: { value: null },
  24132. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24133. alphaTest: { value: 0 }
  24134. },
  24135. specularmap: {
  24136. specularMap: { value: null },
  24137. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  24138. },
  24139. envmap: {
  24140. envMap: { value: null },
  24141. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  24142. flipEnvMap: { value: -1 },
  24143. reflectivity: { value: 1.0 }, // basic, lambert, phong
  24144. ior: { value: 1.5 }, // physical
  24145. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  24146. },
  24147. aomap: {
  24148. aoMap: { value: null },
  24149. aoMapIntensity: { value: 1 },
  24150. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  24151. },
  24152. lightmap: {
  24153. lightMap: { value: null },
  24154. lightMapIntensity: { value: 1 },
  24155. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  24156. },
  24157. bumpmap: {
  24158. bumpMap: { value: null },
  24159. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24160. bumpScale: { value: 1 }
  24161. },
  24162. normalmap: {
  24163. normalMap: { value: null },
  24164. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24165. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  24166. },
  24167. displacementmap: {
  24168. displacementMap: { value: null },
  24169. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24170. displacementScale: { value: 1 },
  24171. displacementBias: { value: 0 }
  24172. },
  24173. emissivemap: {
  24174. emissiveMap: { value: null },
  24175. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  24176. },
  24177. metalnessmap: {
  24178. metalnessMap: { value: null },
  24179. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  24180. },
  24181. roughnessmap: {
  24182. roughnessMap: { value: null },
  24183. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  24184. },
  24185. gradientmap: {
  24186. gradientMap: { value: null }
  24187. },
  24188. fog: {
  24189. fogDensity: { value: 0.00025 },
  24190. fogNear: { value: 1 },
  24191. fogFar: { value: 2000 },
  24192. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  24193. },
  24194. lights: {
  24195. ambientLightColor: { value: [] },
  24196. lightProbe: { value: [] },
  24197. directionalLights: { value: [], properties: {
  24198. direction: {},
  24199. color: {}
  24200. } },
  24201. directionalLightShadows: { value: [], properties: {
  24202. shadowIntensity: 1,
  24203. shadowBias: {},
  24204. shadowNormalBias: {},
  24205. shadowRadius: {},
  24206. shadowMapSize: {}
  24207. } },
  24208. directionalShadowMap: { value: [] },
  24209. directionalShadowMatrix: { value: [] },
  24210. spotLights: { value: [], properties: {
  24211. color: {},
  24212. position: {},
  24213. direction: {},
  24214. distance: {},
  24215. coneCos: {},
  24216. penumbraCos: {},
  24217. decay: {}
  24218. } },
  24219. spotLightShadows: { value: [], properties: {
  24220. shadowIntensity: 1,
  24221. shadowBias: {},
  24222. shadowNormalBias: {},
  24223. shadowRadius: {},
  24224. shadowMapSize: {}
  24225. } },
  24226. spotLightMap: { value: [] },
  24227. spotShadowMap: { value: [] },
  24228. spotLightMatrix: { value: [] },
  24229. pointLights: { value: [], properties: {
  24230. color: {},
  24231. position: {},
  24232. decay: {},
  24233. distance: {}
  24234. } },
  24235. pointLightShadows: { value: [], properties: {
  24236. shadowIntensity: 1,
  24237. shadowBias: {},
  24238. shadowNormalBias: {},
  24239. shadowRadius: {},
  24240. shadowMapSize: {},
  24241. shadowCameraNear: {},
  24242. shadowCameraFar: {}
  24243. } },
  24244. pointShadowMap: { value: [] },
  24245. pointShadowMatrix: { value: [] },
  24246. hemisphereLights: { value: [], properties: {
  24247. direction: {},
  24248. skyColor: {},
  24249. groundColor: {}
  24250. } },
  24251. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  24252. rectAreaLights: { value: [], properties: {
  24253. color: {},
  24254. position: {},
  24255. width: {},
  24256. height: {}
  24257. } },
  24258. ltc_1: { value: null },
  24259. ltc_2: { value: null }
  24260. },
  24261. points: {
  24262. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  24263. opacity: { value: 1.0 },
  24264. size: { value: 1.0 },
  24265. scale: { value: 1.0 },
  24266. map: { value: null },
  24267. alphaMap: { value: null },
  24268. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24269. alphaTest: { value: 0 },
  24270. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  24271. },
  24272. sprite: {
  24273. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  24274. opacity: { value: 1.0 },
  24275. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  24276. rotation: { value: 0.0 },
  24277. map: { value: null },
  24278. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24279. alphaMap: { value: null },
  24280. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24281. alphaTest: { value: 0 }
  24282. }
  24283. };
  24284. const ShaderLib = {
  24285. basic: {
  24286. uniforms: /*@__PURE__*/ mergeUniforms( [
  24287. UniformsLib.common,
  24288. UniformsLib.specularmap,
  24289. UniformsLib.envmap,
  24290. UniformsLib.aomap,
  24291. UniformsLib.lightmap,
  24292. UniformsLib.fog
  24293. ] ),
  24294. vertexShader: ShaderChunk.meshbasic_vert,
  24295. fragmentShader: ShaderChunk.meshbasic_frag
  24296. },
  24297. lambert: {
  24298. uniforms: /*@__PURE__*/ mergeUniforms( [
  24299. UniformsLib.common,
  24300. UniformsLib.specularmap,
  24301. UniformsLib.envmap,
  24302. UniformsLib.aomap,
  24303. UniformsLib.lightmap,
  24304. UniformsLib.emissivemap,
  24305. UniformsLib.bumpmap,
  24306. UniformsLib.normalmap,
  24307. UniformsLib.displacementmap,
  24308. UniformsLib.fog,
  24309. UniformsLib.lights,
  24310. {
  24311. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  24312. }
  24313. ] ),
  24314. vertexShader: ShaderChunk.meshlambert_vert,
  24315. fragmentShader: ShaderChunk.meshlambert_frag
  24316. },
  24317. phong: {
  24318. uniforms: /*@__PURE__*/ mergeUniforms( [
  24319. UniformsLib.common,
  24320. UniformsLib.specularmap,
  24321. UniformsLib.envmap,
  24322. UniformsLib.aomap,
  24323. UniformsLib.lightmap,
  24324. UniformsLib.emissivemap,
  24325. UniformsLib.bumpmap,
  24326. UniformsLib.normalmap,
  24327. UniformsLib.displacementmap,
  24328. UniformsLib.fog,
  24329. UniformsLib.lights,
  24330. {
  24331. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  24332. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  24333. shininess: { value: 30 }
  24334. }
  24335. ] ),
  24336. vertexShader: ShaderChunk.meshphong_vert,
  24337. fragmentShader: ShaderChunk.meshphong_frag
  24338. },
  24339. standard: {
  24340. uniforms: /*@__PURE__*/ mergeUniforms( [
  24341. UniformsLib.common,
  24342. UniformsLib.envmap,
  24343. UniformsLib.aomap,
  24344. UniformsLib.lightmap,
  24345. UniformsLib.emissivemap,
  24346. UniformsLib.bumpmap,
  24347. UniformsLib.normalmap,
  24348. UniformsLib.displacementmap,
  24349. UniformsLib.roughnessmap,
  24350. UniformsLib.metalnessmap,
  24351. UniformsLib.fog,
  24352. UniformsLib.lights,
  24353. {
  24354. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  24355. roughness: { value: 1.0 },
  24356. metalness: { value: 0.0 },
  24357. envMapIntensity: { value: 1 }
  24358. }
  24359. ] ),
  24360. vertexShader: ShaderChunk.meshphysical_vert,
  24361. fragmentShader: ShaderChunk.meshphysical_frag
  24362. },
  24363. toon: {
  24364. uniforms: /*@__PURE__*/ mergeUniforms( [
  24365. UniformsLib.common,
  24366. UniformsLib.aomap,
  24367. UniformsLib.lightmap,
  24368. UniformsLib.emissivemap,
  24369. UniformsLib.bumpmap,
  24370. UniformsLib.normalmap,
  24371. UniformsLib.displacementmap,
  24372. UniformsLib.gradientmap,
  24373. UniformsLib.fog,
  24374. UniformsLib.lights,
  24375. {
  24376. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  24377. }
  24378. ] ),
  24379. vertexShader: ShaderChunk.meshtoon_vert,
  24380. fragmentShader: ShaderChunk.meshtoon_frag
  24381. },
  24382. matcap: {
  24383. uniforms: /*@__PURE__*/ mergeUniforms( [
  24384. UniformsLib.common,
  24385. UniformsLib.bumpmap,
  24386. UniformsLib.normalmap,
  24387. UniformsLib.displacementmap,
  24388. UniformsLib.fog,
  24389. {
  24390. matcap: { value: null }
  24391. }
  24392. ] ),
  24393. vertexShader: ShaderChunk.meshmatcap_vert,
  24394. fragmentShader: ShaderChunk.meshmatcap_frag
  24395. },
  24396. points: {
  24397. uniforms: /*@__PURE__*/ mergeUniforms( [
  24398. UniformsLib.points,
  24399. UniformsLib.fog
  24400. ] ),
  24401. vertexShader: ShaderChunk.points_vert,
  24402. fragmentShader: ShaderChunk.points_frag
  24403. },
  24404. dashed: {
  24405. uniforms: /*@__PURE__*/ mergeUniforms( [
  24406. UniformsLib.common,
  24407. UniformsLib.fog,
  24408. {
  24409. scale: { value: 1 },
  24410. dashSize: { value: 1 },
  24411. totalSize: { value: 2 }
  24412. }
  24413. ] ),
  24414. vertexShader: ShaderChunk.linedashed_vert,
  24415. fragmentShader: ShaderChunk.linedashed_frag
  24416. },
  24417. depth: {
  24418. uniforms: /*@__PURE__*/ mergeUniforms( [
  24419. UniformsLib.common,
  24420. UniformsLib.displacementmap
  24421. ] ),
  24422. vertexShader: ShaderChunk.depth_vert,
  24423. fragmentShader: ShaderChunk.depth_frag
  24424. },
  24425. normal: {
  24426. uniforms: /*@__PURE__*/ mergeUniforms( [
  24427. UniformsLib.common,
  24428. UniformsLib.bumpmap,
  24429. UniformsLib.normalmap,
  24430. UniformsLib.displacementmap,
  24431. {
  24432. opacity: { value: 1.0 }
  24433. }
  24434. ] ),
  24435. vertexShader: ShaderChunk.meshnormal_vert,
  24436. fragmentShader: ShaderChunk.meshnormal_frag
  24437. },
  24438. sprite: {
  24439. uniforms: /*@__PURE__*/ mergeUniforms( [
  24440. UniformsLib.sprite,
  24441. UniformsLib.fog
  24442. ] ),
  24443. vertexShader: ShaderChunk.sprite_vert,
  24444. fragmentShader: ShaderChunk.sprite_frag
  24445. },
  24446. background: {
  24447. uniforms: {
  24448. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  24449. t2D: { value: null },
  24450. backgroundIntensity: { value: 1 }
  24451. },
  24452. vertexShader: ShaderChunk.background_vert,
  24453. fragmentShader: ShaderChunk.background_frag
  24454. },
  24455. backgroundCube: {
  24456. uniforms: {
  24457. envMap: { value: null },
  24458. flipEnvMap: { value: -1 },
  24459. backgroundBlurriness: { value: 0 },
  24460. backgroundIntensity: { value: 1 },
  24461. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  24462. },
  24463. vertexShader: ShaderChunk.backgroundCube_vert,
  24464. fragmentShader: ShaderChunk.backgroundCube_frag
  24465. },
  24466. cube: {
  24467. uniforms: {
  24468. tCube: { value: null },
  24469. tFlip: { value: -1 },
  24470. opacity: { value: 1.0 }
  24471. },
  24472. vertexShader: ShaderChunk.cube_vert,
  24473. fragmentShader: ShaderChunk.cube_frag
  24474. },
  24475. equirect: {
  24476. uniforms: {
  24477. tEquirect: { value: null },
  24478. },
  24479. vertexShader: ShaderChunk.equirect_vert,
  24480. fragmentShader: ShaderChunk.equirect_frag
  24481. },
  24482. distanceRGBA: {
  24483. uniforms: /*@__PURE__*/ mergeUniforms( [
  24484. UniformsLib.common,
  24485. UniformsLib.displacementmap,
  24486. {
  24487. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  24488. nearDistance: { value: 1 },
  24489. farDistance: { value: 1000 }
  24490. }
  24491. ] ),
  24492. vertexShader: ShaderChunk.distanceRGBA_vert,
  24493. fragmentShader: ShaderChunk.distanceRGBA_frag
  24494. },
  24495. shadow: {
  24496. uniforms: /*@__PURE__*/ mergeUniforms( [
  24497. UniformsLib.lights,
  24498. UniformsLib.fog,
  24499. {
  24500. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  24501. opacity: { value: 1.0 }
  24502. },
  24503. ] ),
  24504. vertexShader: ShaderChunk.shadow_vert,
  24505. fragmentShader: ShaderChunk.shadow_frag
  24506. }
  24507. };
  24508. ShaderLib.physical = {
  24509. uniforms: /*@__PURE__*/ mergeUniforms( [
  24510. ShaderLib.standard.uniforms,
  24511. {
  24512. clearcoat: { value: 0 },
  24513. clearcoatMap: { value: null },
  24514. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24515. clearcoatNormalMap: { value: null },
  24516. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24517. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  24518. clearcoatRoughness: { value: 0 },
  24519. clearcoatRoughnessMap: { value: null },
  24520. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24521. dispersion: { value: 0 },
  24522. iridescence: { value: 0 },
  24523. iridescenceMap: { value: null },
  24524. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24525. iridescenceIOR: { value: 1.3 },
  24526. iridescenceThicknessMinimum: { value: 100 },
  24527. iridescenceThicknessMaximum: { value: 400 },
  24528. iridescenceThicknessMap: { value: null },
  24529. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24530. sheen: { value: 0 },
  24531. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  24532. sheenColorMap: { value: null },
  24533. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24534. sheenRoughness: { value: 1 },
  24535. sheenRoughnessMap: { value: null },
  24536. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24537. transmission: { value: 0 },
  24538. transmissionMap: { value: null },
  24539. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24540. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  24541. transmissionSamplerMap: { value: null },
  24542. thickness: { value: 0 },
  24543. thicknessMap: { value: null },
  24544. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24545. attenuationDistance: { value: 0 },
  24546. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  24547. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  24548. specularColorMap: { value: null },
  24549. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24550. specularIntensity: { value: 1 },
  24551. specularIntensityMap: { value: null },
  24552. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24553. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  24554. anisotropyMap: { value: null },
  24555. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  24556. }
  24557. ] ),
  24558. vertexShader: ShaderChunk.meshphysical_vert,
  24559. fragmentShader: ShaderChunk.meshphysical_frag
  24560. };
  24561. const _rgb = { r: 0, b: 0, g: 0 };
  24562. const _e1$1 = /*@__PURE__*/ new Euler();
  24563. const _m1$1 = /*@__PURE__*/ new Matrix4();
  24564. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  24565. const clearColor = new Color( 0x000000 );
  24566. let clearAlpha = alpha === true ? 0 : 1;
  24567. let planeMesh;
  24568. let boxMesh;
  24569. let currentBackground = null;
  24570. let currentBackgroundVersion = 0;
  24571. let currentTonemapping = null;
  24572. function getBackground( scene ) {
  24573. let background = scene.isScene === true ? scene.background : null;
  24574. if ( background && background.isTexture ) {
  24575. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  24576. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  24577. }
  24578. return background;
  24579. }
  24580. function render( scene ) {
  24581. let forceClear = false;
  24582. const background = getBackground( scene );
  24583. if ( background === null ) {
  24584. setClear( clearColor, clearAlpha );
  24585. } else if ( background && background.isColor ) {
  24586. setClear( background, 1 );
  24587. forceClear = true;
  24588. }
  24589. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  24590. if ( environmentBlendMode === 'additive' ) {
  24591. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  24592. } else if ( environmentBlendMode === 'alpha-blend' ) {
  24593. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  24594. }
  24595. if ( renderer.autoClear || forceClear ) {
  24596. // buffers might not be writable which is required to ensure a correct clear
  24597. state.buffers.depth.setTest( true );
  24598. state.buffers.depth.setMask( true );
  24599. state.buffers.color.setMask( true );
  24600. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  24601. }
  24602. }
  24603. function addToRenderList( renderList, scene ) {
  24604. const background = getBackground( scene );
  24605. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  24606. if ( boxMesh === undefined ) {
  24607. boxMesh = new Mesh(
  24608. new BoxGeometry( 1, 1, 1 ),
  24609. new ShaderMaterial( {
  24610. name: 'BackgroundCubeMaterial',
  24611. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  24612. vertexShader: ShaderLib.backgroundCube.vertexShader,
  24613. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  24614. side: BackSide,
  24615. depthTest: false,
  24616. depthWrite: false,
  24617. fog: false
  24618. } )
  24619. );
  24620. boxMesh.geometry.deleteAttribute( 'normal' );
  24621. boxMesh.geometry.deleteAttribute( 'uv' );
  24622. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  24623. this.matrixWorld.copyPosition( camera.matrixWorld );
  24624. };
  24625. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  24626. Object.defineProperty( boxMesh.material, 'envMap', {
  24627. get: function () {
  24628. return this.uniforms.envMap.value;
  24629. }
  24630. } );
  24631. objects.update( boxMesh );
  24632. }
  24633. _e1$1.copy( scene.backgroundRotation );
  24634. // accommodate left-handed frame
  24635. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  24636. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  24637. // environment maps which are not cube render targets or PMREMs follow a different convention
  24638. _e1$1.y *= -1;
  24639. _e1$1.z *= -1;
  24640. }
  24641. boxMesh.material.uniforms.envMap.value = background;
  24642. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  24643. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  24644. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  24645. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  24646. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  24647. if ( currentBackground !== background ||
  24648. currentBackgroundVersion !== background.version ||
  24649. currentTonemapping !== renderer.toneMapping ) {
  24650. boxMesh.material.needsUpdate = true;
  24651. currentBackground = background;
  24652. currentBackgroundVersion = background.version;
  24653. currentTonemapping = renderer.toneMapping;
  24654. }
  24655. boxMesh.layers.enableAll();
  24656. // push to the pre-sorted opaque render list
  24657. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  24658. } else if ( background && background.isTexture ) {
  24659. if ( planeMesh === undefined ) {
  24660. planeMesh = new Mesh(
  24661. new PlaneGeometry( 2, 2 ),
  24662. new ShaderMaterial( {
  24663. name: 'BackgroundMaterial',
  24664. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  24665. vertexShader: ShaderLib.background.vertexShader,
  24666. fragmentShader: ShaderLib.background.fragmentShader,
  24667. side: FrontSide,
  24668. depthTest: false,
  24669. depthWrite: false,
  24670. fog: false
  24671. } )
  24672. );
  24673. planeMesh.geometry.deleteAttribute( 'normal' );
  24674. // add "map" material property so the renderer can evaluate it like for built-in materials
  24675. Object.defineProperty( planeMesh.material, 'map', {
  24676. get: function () {
  24677. return this.uniforms.t2D.value;
  24678. }
  24679. } );
  24680. objects.update( planeMesh );
  24681. }
  24682. planeMesh.material.uniforms.t2D.value = background;
  24683. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  24684. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  24685. if ( background.matrixAutoUpdate === true ) {
  24686. background.updateMatrix();
  24687. }
  24688. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  24689. if ( currentBackground !== background ||
  24690. currentBackgroundVersion !== background.version ||
  24691. currentTonemapping !== renderer.toneMapping ) {
  24692. planeMesh.material.needsUpdate = true;
  24693. currentBackground = background;
  24694. currentBackgroundVersion = background.version;
  24695. currentTonemapping = renderer.toneMapping;
  24696. }
  24697. planeMesh.layers.enableAll();
  24698. // push to the pre-sorted opaque render list
  24699. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  24700. }
  24701. }
  24702. function setClear( color, alpha ) {
  24703. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  24704. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  24705. }
  24706. function dispose() {
  24707. if ( boxMesh !== undefined ) {
  24708. boxMesh.geometry.dispose();
  24709. boxMesh.material.dispose();
  24710. boxMesh = undefined;
  24711. }
  24712. if ( planeMesh !== undefined ) {
  24713. planeMesh.geometry.dispose();
  24714. planeMesh.material.dispose();
  24715. planeMesh = undefined;
  24716. }
  24717. }
  24718. return {
  24719. getClearColor: function () {
  24720. return clearColor;
  24721. },
  24722. setClearColor: function ( color, alpha = 1 ) {
  24723. clearColor.set( color );
  24724. clearAlpha = alpha;
  24725. setClear( clearColor, clearAlpha );
  24726. },
  24727. getClearAlpha: function () {
  24728. return clearAlpha;
  24729. },
  24730. setClearAlpha: function ( alpha ) {
  24731. clearAlpha = alpha;
  24732. setClear( clearColor, clearAlpha );
  24733. },
  24734. render: render,
  24735. addToRenderList: addToRenderList,
  24736. dispose: dispose
  24737. };
  24738. }
  24739. function WebGLBindingStates( gl, attributes ) {
  24740. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  24741. const bindingStates = {};
  24742. const defaultState = createBindingState( null );
  24743. let currentState = defaultState;
  24744. let forceUpdate = false;
  24745. function setup( object, material, program, geometry, index ) {
  24746. let updateBuffers = false;
  24747. const state = getBindingState( geometry, program, material );
  24748. if ( currentState !== state ) {
  24749. currentState = state;
  24750. bindVertexArrayObject( currentState.object );
  24751. }
  24752. updateBuffers = needsUpdate( object, geometry, program, index );
  24753. if ( updateBuffers ) saveCache( object, geometry, program, index );
  24754. if ( index !== null ) {
  24755. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  24756. }
  24757. if ( updateBuffers || forceUpdate ) {
  24758. forceUpdate = false;
  24759. setupVertexAttributes( object, material, program, geometry );
  24760. if ( index !== null ) {
  24761. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  24762. }
  24763. }
  24764. }
  24765. function createVertexArrayObject() {
  24766. return gl.createVertexArray();
  24767. }
  24768. function bindVertexArrayObject( vao ) {
  24769. return gl.bindVertexArray( vao );
  24770. }
  24771. function deleteVertexArrayObject( vao ) {
  24772. return gl.deleteVertexArray( vao );
  24773. }
  24774. function getBindingState( geometry, program, material ) {
  24775. const wireframe = ( material.wireframe === true );
  24776. let programMap = bindingStates[ geometry.id ];
  24777. if ( programMap === undefined ) {
  24778. programMap = {};
  24779. bindingStates[ geometry.id ] = programMap;
  24780. }
  24781. let stateMap = programMap[ program.id ];
  24782. if ( stateMap === undefined ) {
  24783. stateMap = {};
  24784. programMap[ program.id ] = stateMap;
  24785. }
  24786. let state = stateMap[ wireframe ];
  24787. if ( state === undefined ) {
  24788. state = createBindingState( createVertexArrayObject() );
  24789. stateMap[ wireframe ] = state;
  24790. }
  24791. return state;
  24792. }
  24793. function createBindingState( vao ) {
  24794. const newAttributes = [];
  24795. const enabledAttributes = [];
  24796. const attributeDivisors = [];
  24797. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  24798. newAttributes[ i ] = 0;
  24799. enabledAttributes[ i ] = 0;
  24800. attributeDivisors[ i ] = 0;
  24801. }
  24802. return {
  24803. // for backward compatibility on non-VAO support browser
  24804. geometry: null,
  24805. program: null,
  24806. wireframe: false,
  24807. newAttributes: newAttributes,
  24808. enabledAttributes: enabledAttributes,
  24809. attributeDivisors: attributeDivisors,
  24810. object: vao,
  24811. attributes: {},
  24812. index: null
  24813. };
  24814. }
  24815. function needsUpdate( object, geometry, program, index ) {
  24816. const cachedAttributes = currentState.attributes;
  24817. const geometryAttributes = geometry.attributes;
  24818. let attributesNum = 0;
  24819. const programAttributes = program.getAttributes();
  24820. for ( const name in programAttributes ) {
  24821. const programAttribute = programAttributes[ name ];
  24822. if ( programAttribute.location >= 0 ) {
  24823. const cachedAttribute = cachedAttributes[ name ];
  24824. let geometryAttribute = geometryAttributes[ name ];
  24825. if ( geometryAttribute === undefined ) {
  24826. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  24827. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  24828. }
  24829. if ( cachedAttribute === undefined ) return true;
  24830. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  24831. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  24832. attributesNum ++;
  24833. }
  24834. }
  24835. if ( currentState.attributesNum !== attributesNum ) return true;
  24836. if ( currentState.index !== index ) return true;
  24837. return false;
  24838. }
  24839. function saveCache( object, geometry, program, index ) {
  24840. const cache = {};
  24841. const attributes = geometry.attributes;
  24842. let attributesNum = 0;
  24843. const programAttributes = program.getAttributes();
  24844. for ( const name in programAttributes ) {
  24845. const programAttribute = programAttributes[ name ];
  24846. if ( programAttribute.location >= 0 ) {
  24847. let attribute = attributes[ name ];
  24848. if ( attribute === undefined ) {
  24849. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  24850. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  24851. }
  24852. const data = {};
  24853. data.attribute = attribute;
  24854. if ( attribute && attribute.data ) {
  24855. data.data = attribute.data;
  24856. }
  24857. cache[ name ] = data;
  24858. attributesNum ++;
  24859. }
  24860. }
  24861. currentState.attributes = cache;
  24862. currentState.attributesNum = attributesNum;
  24863. currentState.index = index;
  24864. }
  24865. function initAttributes() {
  24866. const newAttributes = currentState.newAttributes;
  24867. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  24868. newAttributes[ i ] = 0;
  24869. }
  24870. }
  24871. function enableAttribute( attribute ) {
  24872. enableAttributeAndDivisor( attribute, 0 );
  24873. }
  24874. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  24875. const newAttributes = currentState.newAttributes;
  24876. const enabledAttributes = currentState.enabledAttributes;
  24877. const attributeDivisors = currentState.attributeDivisors;
  24878. newAttributes[ attribute ] = 1;
  24879. if ( enabledAttributes[ attribute ] === 0 ) {
  24880. gl.enableVertexAttribArray( attribute );
  24881. enabledAttributes[ attribute ] = 1;
  24882. }
  24883. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  24884. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  24885. attributeDivisors[ attribute ] = meshPerAttribute;
  24886. }
  24887. }
  24888. function disableUnusedAttributes() {
  24889. const newAttributes = currentState.newAttributes;
  24890. const enabledAttributes = currentState.enabledAttributes;
  24891. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  24892. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  24893. gl.disableVertexAttribArray( i );
  24894. enabledAttributes[ i ] = 0;
  24895. }
  24896. }
  24897. }
  24898. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  24899. if ( integer === true ) {
  24900. gl.vertexAttribIPointer( index, size, type, stride, offset );
  24901. } else {
  24902. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  24903. }
  24904. }
  24905. function setupVertexAttributes( object, material, program, geometry ) {
  24906. initAttributes();
  24907. const geometryAttributes = geometry.attributes;
  24908. const programAttributes = program.getAttributes();
  24909. const materialDefaultAttributeValues = material.defaultAttributeValues;
  24910. for ( const name in programAttributes ) {
  24911. const programAttribute = programAttributes[ name ];
  24912. if ( programAttribute.location >= 0 ) {
  24913. let geometryAttribute = geometryAttributes[ name ];
  24914. if ( geometryAttribute === undefined ) {
  24915. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  24916. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  24917. }
  24918. if ( geometryAttribute !== undefined ) {
  24919. const normalized = geometryAttribute.normalized;
  24920. const size = geometryAttribute.itemSize;
  24921. const attribute = attributes.get( geometryAttribute );
  24922. // TODO Attribute may not be available on context restore
  24923. if ( attribute === undefined ) continue;
  24924. const buffer = attribute.buffer;
  24925. const type = attribute.type;
  24926. const bytesPerElement = attribute.bytesPerElement;
  24927. // check for integer attributes
  24928. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  24929. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  24930. const data = geometryAttribute.data;
  24931. const stride = data.stride;
  24932. const offset = geometryAttribute.offset;
  24933. if ( data.isInstancedInterleavedBuffer ) {
  24934. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  24935. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  24936. }
  24937. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  24938. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  24939. }
  24940. } else {
  24941. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  24942. enableAttribute( programAttribute.location + i );
  24943. }
  24944. }
  24945. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  24946. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  24947. vertexAttribPointer(
  24948. programAttribute.location + i,
  24949. size / programAttribute.locationSize,
  24950. type,
  24951. normalized,
  24952. stride * bytesPerElement,
  24953. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  24954. integer
  24955. );
  24956. }
  24957. } else {
  24958. if ( geometryAttribute.isInstancedBufferAttribute ) {
  24959. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  24960. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  24961. }
  24962. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  24963. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  24964. }
  24965. } else {
  24966. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  24967. enableAttribute( programAttribute.location + i );
  24968. }
  24969. }
  24970. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  24971. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  24972. vertexAttribPointer(
  24973. programAttribute.location + i,
  24974. size / programAttribute.locationSize,
  24975. type,
  24976. normalized,
  24977. size * bytesPerElement,
  24978. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  24979. integer
  24980. );
  24981. }
  24982. }
  24983. } else if ( materialDefaultAttributeValues !== undefined ) {
  24984. const value = materialDefaultAttributeValues[ name ];
  24985. if ( value !== undefined ) {
  24986. switch ( value.length ) {
  24987. case 2:
  24988. gl.vertexAttrib2fv( programAttribute.location, value );
  24989. break;
  24990. case 3:
  24991. gl.vertexAttrib3fv( programAttribute.location, value );
  24992. break;
  24993. case 4:
  24994. gl.vertexAttrib4fv( programAttribute.location, value );
  24995. break;
  24996. default:
  24997. gl.vertexAttrib1fv( programAttribute.location, value );
  24998. }
  24999. }
  25000. }
  25001. }
  25002. }
  25003. disableUnusedAttributes();
  25004. }
  25005. function dispose() {
  25006. reset();
  25007. for ( const geometryId in bindingStates ) {
  25008. const programMap = bindingStates[ geometryId ];
  25009. for ( const programId in programMap ) {
  25010. const stateMap = programMap[ programId ];
  25011. for ( const wireframe in stateMap ) {
  25012. deleteVertexArrayObject( stateMap[ wireframe ].object );
  25013. delete stateMap[ wireframe ];
  25014. }
  25015. delete programMap[ programId ];
  25016. }
  25017. delete bindingStates[ geometryId ];
  25018. }
  25019. }
  25020. function releaseStatesOfGeometry( geometry ) {
  25021. if ( bindingStates[ geometry.id ] === undefined ) return;
  25022. const programMap = bindingStates[ geometry.id ];
  25023. for ( const programId in programMap ) {
  25024. const stateMap = programMap[ programId ];
  25025. for ( const wireframe in stateMap ) {
  25026. deleteVertexArrayObject( stateMap[ wireframe ].object );
  25027. delete stateMap[ wireframe ];
  25028. }
  25029. delete programMap[ programId ];
  25030. }
  25031. delete bindingStates[ geometry.id ];
  25032. }
  25033. function releaseStatesOfProgram( program ) {
  25034. for ( const geometryId in bindingStates ) {
  25035. const programMap = bindingStates[ geometryId ];
  25036. if ( programMap[ program.id ] === undefined ) continue;
  25037. const stateMap = programMap[ program.id ];
  25038. for ( const wireframe in stateMap ) {
  25039. deleteVertexArrayObject( stateMap[ wireframe ].object );
  25040. delete stateMap[ wireframe ];
  25041. }
  25042. delete programMap[ program.id ];
  25043. }
  25044. }
  25045. function reset() {
  25046. resetDefaultState();
  25047. forceUpdate = true;
  25048. if ( currentState === defaultState ) return;
  25049. currentState = defaultState;
  25050. bindVertexArrayObject( currentState.object );
  25051. }
  25052. // for backward-compatibility
  25053. function resetDefaultState() {
  25054. defaultState.geometry = null;
  25055. defaultState.program = null;
  25056. defaultState.wireframe = false;
  25057. }
  25058. return {
  25059. setup: setup,
  25060. reset: reset,
  25061. resetDefaultState: resetDefaultState,
  25062. dispose: dispose,
  25063. releaseStatesOfGeometry: releaseStatesOfGeometry,
  25064. releaseStatesOfProgram: releaseStatesOfProgram,
  25065. initAttributes: initAttributes,
  25066. enableAttribute: enableAttribute,
  25067. disableUnusedAttributes: disableUnusedAttributes
  25068. };
  25069. }
  25070. function WebGLBufferRenderer( gl, extensions, info ) {
  25071. let mode;
  25072. function setMode( value ) {
  25073. mode = value;
  25074. }
  25075. function render( start, count ) {
  25076. gl.drawArrays( mode, start, count );
  25077. info.update( count, mode, 1 );
  25078. }
  25079. function renderInstances( start, count, primcount ) {
  25080. if ( primcount === 0 ) return;
  25081. gl.drawArraysInstanced( mode, start, count, primcount );
  25082. info.update( count, mode, primcount );
  25083. }
  25084. function renderMultiDraw( starts, counts, drawCount ) {
  25085. if ( drawCount === 0 ) return;
  25086. const extension = extensions.get( 'WEBGL_multi_draw' );
  25087. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  25088. let elementCount = 0;
  25089. for ( let i = 0; i < drawCount; i ++ ) {
  25090. elementCount += counts[ i ];
  25091. }
  25092. info.update( elementCount, mode, 1 );
  25093. }
  25094. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  25095. if ( drawCount === 0 ) return;
  25096. const extension = extensions.get( 'WEBGL_multi_draw' );
  25097. if ( extension === null ) {
  25098. for ( let i = 0; i < starts.length; i ++ ) {
  25099. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  25100. }
  25101. } else {
  25102. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  25103. let elementCount = 0;
  25104. for ( let i = 0; i < drawCount; i ++ ) {
  25105. elementCount += counts[ i ] * primcount[ i ];
  25106. }
  25107. info.update( elementCount, mode, 1 );
  25108. }
  25109. }
  25110. //
  25111. this.setMode = setMode;
  25112. this.render = render;
  25113. this.renderInstances = renderInstances;
  25114. this.renderMultiDraw = renderMultiDraw;
  25115. this.renderMultiDrawInstances = renderMultiDrawInstances;
  25116. }
  25117. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  25118. let maxAnisotropy;
  25119. function getMaxAnisotropy() {
  25120. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  25121. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  25122. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  25123. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  25124. } else {
  25125. maxAnisotropy = 0;
  25126. }
  25127. return maxAnisotropy;
  25128. }
  25129. function textureFormatReadable( textureFormat ) {
  25130. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  25131. return false;
  25132. }
  25133. return true;
  25134. }
  25135. function textureTypeReadable( textureType ) {
  25136. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  25137. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  25138. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  25139. return false;
  25140. }
  25141. return true;
  25142. }
  25143. function getMaxPrecision( precision ) {
  25144. if ( precision === 'highp' ) {
  25145. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  25146. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  25147. return 'highp';
  25148. }
  25149. precision = 'mediump';
  25150. }
  25151. if ( precision === 'mediump' ) {
  25152. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  25153. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  25154. return 'mediump';
  25155. }
  25156. }
  25157. return 'lowp';
  25158. }
  25159. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  25160. const maxPrecision = getMaxPrecision( precision );
  25161. if ( maxPrecision !== precision ) {
  25162. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  25163. precision = maxPrecision;
  25164. }
  25165. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  25166. const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  25167. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  25168. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  25169. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  25170. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  25171. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  25172. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  25173. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  25174. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  25175. const vertexTextures = maxVertexTextures > 0;
  25176. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  25177. return {
  25178. isWebGL2: true, // keeping this for backwards compatibility
  25179. getMaxAnisotropy: getMaxAnisotropy,
  25180. getMaxPrecision: getMaxPrecision,
  25181. textureFormatReadable: textureFormatReadable,
  25182. textureTypeReadable: textureTypeReadable,
  25183. precision: precision,
  25184. logarithmicDepthBuffer: logarithmicDepthBuffer,
  25185. reverseDepthBuffer: reverseDepthBuffer,
  25186. maxTextures: maxTextures,
  25187. maxVertexTextures: maxVertexTextures,
  25188. maxTextureSize: maxTextureSize,
  25189. maxCubemapSize: maxCubemapSize,
  25190. maxAttributes: maxAttributes,
  25191. maxVertexUniforms: maxVertexUniforms,
  25192. maxVaryings: maxVaryings,
  25193. maxFragmentUniforms: maxFragmentUniforms,
  25194. vertexTextures: vertexTextures,
  25195. maxSamples: maxSamples
  25196. };
  25197. }
  25198. function WebGLClipping( properties ) {
  25199. const scope = this;
  25200. let globalState = null,
  25201. numGlobalPlanes = 0,
  25202. localClippingEnabled = false,
  25203. renderingShadows = false;
  25204. const plane = new Plane(),
  25205. viewNormalMatrix = new Matrix3(),
  25206. uniform = { value: null, needsUpdate: false };
  25207. this.uniform = uniform;
  25208. this.numPlanes = 0;
  25209. this.numIntersection = 0;
  25210. this.init = function ( planes, enableLocalClipping ) {
  25211. const enabled =
  25212. planes.length !== 0 ||
  25213. enableLocalClipping ||
  25214. // enable state of previous frame - the clipping code has to
  25215. // run another frame in order to reset the state:
  25216. numGlobalPlanes !== 0 ||
  25217. localClippingEnabled;
  25218. localClippingEnabled = enableLocalClipping;
  25219. numGlobalPlanes = planes.length;
  25220. return enabled;
  25221. };
  25222. this.beginShadows = function () {
  25223. renderingShadows = true;
  25224. projectPlanes( null );
  25225. };
  25226. this.endShadows = function () {
  25227. renderingShadows = false;
  25228. };
  25229. this.setGlobalState = function ( planes, camera ) {
  25230. globalState = projectPlanes( planes, camera, 0 );
  25231. };
  25232. this.setState = function ( material, camera, useCache ) {
  25233. const planes = material.clippingPlanes,
  25234. clipIntersection = material.clipIntersection,
  25235. clipShadows = material.clipShadows;
  25236. const materialProperties = properties.get( material );
  25237. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  25238. // there's no local clipping
  25239. if ( renderingShadows ) {
  25240. // there's no global clipping
  25241. projectPlanes( null );
  25242. } else {
  25243. resetGlobalState();
  25244. }
  25245. } else {
  25246. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  25247. lGlobal = nGlobal * 4;
  25248. let dstArray = materialProperties.clippingState || null;
  25249. uniform.value = dstArray; // ensure unique state
  25250. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  25251. for ( let i = 0; i !== lGlobal; ++ i ) {
  25252. dstArray[ i ] = globalState[ i ];
  25253. }
  25254. materialProperties.clippingState = dstArray;
  25255. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  25256. this.numPlanes += nGlobal;
  25257. }
  25258. };
  25259. function resetGlobalState() {
  25260. if ( uniform.value !== globalState ) {
  25261. uniform.value = globalState;
  25262. uniform.needsUpdate = numGlobalPlanes > 0;
  25263. }
  25264. scope.numPlanes = numGlobalPlanes;
  25265. scope.numIntersection = 0;
  25266. }
  25267. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  25268. const nPlanes = planes !== null ? planes.length : 0;
  25269. let dstArray = null;
  25270. if ( nPlanes !== 0 ) {
  25271. dstArray = uniform.value;
  25272. if ( skipTransform !== true || dstArray === null ) {
  25273. const flatSize = dstOffset + nPlanes * 4,
  25274. viewMatrix = camera.matrixWorldInverse;
  25275. viewNormalMatrix.getNormalMatrix( viewMatrix );
  25276. if ( dstArray === null || dstArray.length < flatSize ) {
  25277. dstArray = new Float32Array( flatSize );
  25278. }
  25279. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  25280. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  25281. plane.normal.toArray( dstArray, i4 );
  25282. dstArray[ i4 + 3 ] = plane.constant;
  25283. }
  25284. }
  25285. uniform.value = dstArray;
  25286. uniform.needsUpdate = true;
  25287. }
  25288. scope.numPlanes = nPlanes;
  25289. scope.numIntersection = 0;
  25290. return dstArray;
  25291. }
  25292. }
  25293. function WebGLCubeMaps( renderer ) {
  25294. let cubemaps = new WeakMap();
  25295. function mapTextureMapping( texture, mapping ) {
  25296. if ( mapping === EquirectangularReflectionMapping ) {
  25297. texture.mapping = CubeReflectionMapping;
  25298. } else if ( mapping === EquirectangularRefractionMapping ) {
  25299. texture.mapping = CubeRefractionMapping;
  25300. }
  25301. return texture;
  25302. }
  25303. function get( texture ) {
  25304. if ( texture && texture.isTexture ) {
  25305. const mapping = texture.mapping;
  25306. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  25307. if ( cubemaps.has( texture ) ) {
  25308. const cubemap = cubemaps.get( texture ).texture;
  25309. return mapTextureMapping( cubemap, texture.mapping );
  25310. } else {
  25311. const image = texture.image;
  25312. if ( image && image.height > 0 ) {
  25313. const renderTarget = new WebGLCubeRenderTarget( image.height );
  25314. renderTarget.fromEquirectangularTexture( renderer, texture );
  25315. cubemaps.set( texture, renderTarget );
  25316. texture.addEventListener( 'dispose', onTextureDispose );
  25317. return mapTextureMapping( renderTarget.texture, texture.mapping );
  25318. } else {
  25319. // image not yet ready. try the conversion next frame
  25320. return null;
  25321. }
  25322. }
  25323. }
  25324. }
  25325. return texture;
  25326. }
  25327. function onTextureDispose( event ) {
  25328. const texture = event.target;
  25329. texture.removeEventListener( 'dispose', onTextureDispose );
  25330. const cubemap = cubemaps.get( texture );
  25331. if ( cubemap !== undefined ) {
  25332. cubemaps.delete( texture );
  25333. cubemap.dispose();
  25334. }
  25335. }
  25336. function dispose() {
  25337. cubemaps = new WeakMap();
  25338. }
  25339. return {
  25340. get: get,
  25341. dispose: dispose
  25342. };
  25343. }
  25344. const LOD_MIN = 4;
  25345. // The standard deviations (radians) associated with the extra mips. These are
  25346. // chosen to approximate a Trowbridge-Reitz distribution function times the
  25347. // geometric shadowing function. These sigma values squared must match the
  25348. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  25349. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  25350. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  25351. // samples and exit early, but not recompile the shader.
  25352. const MAX_SAMPLES = 20;
  25353. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  25354. const _clearColor = /*@__PURE__*/ new Color();
  25355. let _oldTarget = null;
  25356. let _oldActiveCubeFace = 0;
  25357. let _oldActiveMipmapLevel = 0;
  25358. let _oldXrEnabled = false;
  25359. // Golden Ratio
  25360. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  25361. const INV_PHI = 1 / PHI;
  25362. // Vertices of a dodecahedron (except the opposites, which represent the
  25363. // same axis), used as axis directions evenly spread on a sphere.
  25364. const _axisDirections = [
  25365. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  25366. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  25367. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  25368. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  25369. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  25370. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  25371. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  25372. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  25373. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  25374. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  25375. const _origin = /*@__PURE__*/ new Vector3();
  25376. /**
  25377. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  25378. * (PMREM) from a cubeMap environment texture. This allows different levels of
  25379. * blur to be quickly accessed based on material roughness. It is packed into a
  25380. * special CubeUV format that allows us to perform custom interpolation so that
  25381. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  25382. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  25383. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  25384. * higher roughness levels. In this way we maintain resolution to smoothly
  25385. * interpolate diffuse lighting while limiting sampling computation.
  25386. *
  25387. * Paper: Fast, Accurate Image-Based Lighting
  25388. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  25389. */
  25390. class PMREMGenerator {
  25391. constructor( renderer ) {
  25392. this._renderer = renderer;
  25393. this._pingPongRenderTarget = null;
  25394. this._lodMax = 0;
  25395. this._cubeSize = 0;
  25396. this._lodPlanes = [];
  25397. this._sizeLods = [];
  25398. this._sigmas = [];
  25399. this._blurMaterial = null;
  25400. this._cubemapMaterial = null;
  25401. this._equirectMaterial = null;
  25402. this._compileMaterial( this._blurMaterial );
  25403. }
  25404. /**
  25405. * Generates a PMREM from a supplied Scene, which can be faster than using an
  25406. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  25407. * in radians to be applied to the scene before PMREM generation. Optional near
  25408. * and far planes ensure the scene is rendered in its entirety.
  25409. *
  25410. * @param {Scene} scene
  25411. * @param {number} sigma
  25412. * @param {number} near
  25413. * @param {number} far
  25414. * @param {?Object} [options={}]
  25415. * @return {WebGLRenderTarget}
  25416. */
  25417. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  25418. const {
  25419. size = 256,
  25420. position = _origin,
  25421. } = options;
  25422. _oldTarget = this._renderer.getRenderTarget();
  25423. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  25424. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  25425. _oldXrEnabled = this._renderer.xr.enabled;
  25426. this._renderer.xr.enabled = false;
  25427. this._setSize( size );
  25428. const cubeUVRenderTarget = this._allocateTargets();
  25429. cubeUVRenderTarget.depthBuffer = true;
  25430. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  25431. if ( sigma > 0 ) {
  25432. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  25433. }
  25434. this._applyPMREM( cubeUVRenderTarget );
  25435. this._cleanup( cubeUVRenderTarget );
  25436. return cubeUVRenderTarget;
  25437. }
  25438. /**
  25439. * Generates a PMREM from an equirectangular texture, which can be either LDR
  25440. * or HDR. The ideal input image size is 1k (1024 x 512),
  25441. * as this matches best with the 256 x 256 cubemap output.
  25442. * The smallest supported equirectangular image size is 64 x 32.
  25443. *
  25444. * @param {Texture} equirectangular
  25445. * @param {WebGLRenderTarget} [renderTarget=null] - Optional render target.
  25446. * @return {WebGLRenderTarget}
  25447. */
  25448. fromEquirectangular( equirectangular, renderTarget = null ) {
  25449. return this._fromTexture( equirectangular, renderTarget );
  25450. }
  25451. /**
  25452. * Generates a PMREM from an cubemap texture, which can be either LDR
  25453. * or HDR. The ideal input cube size is 256 x 256,
  25454. * as this matches best with the 256 x 256 cubemap output.
  25455. * The smallest supported cube size is 16 x 16.
  25456. *
  25457. * @param {Texture} cubemap
  25458. * @param {null} [renderTarget=null] - Optional render target.
  25459. * @return {WebGLRenderTarget}
  25460. */
  25461. fromCubemap( cubemap, renderTarget = null ) {
  25462. return this._fromTexture( cubemap, renderTarget );
  25463. }
  25464. /**
  25465. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  25466. * your texture's network fetch for increased concurrency.
  25467. */
  25468. compileCubemapShader() {
  25469. if ( this._cubemapMaterial === null ) {
  25470. this._cubemapMaterial = _getCubemapMaterial();
  25471. this._compileMaterial( this._cubemapMaterial );
  25472. }
  25473. }
  25474. /**
  25475. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  25476. * your texture's network fetch for increased concurrency.
  25477. */
  25478. compileEquirectangularShader() {
  25479. if ( this._equirectMaterial === null ) {
  25480. this._equirectMaterial = _getEquirectMaterial();
  25481. this._compileMaterial( this._equirectMaterial );
  25482. }
  25483. }
  25484. /**
  25485. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  25486. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  25487. * one of them will cause any others to also become unusable.
  25488. */
  25489. dispose() {
  25490. this._dispose();
  25491. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  25492. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  25493. }
  25494. // private interface
  25495. _setSize( cubeSize ) {
  25496. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  25497. this._cubeSize = Math.pow( 2, this._lodMax );
  25498. }
  25499. _dispose() {
  25500. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  25501. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  25502. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  25503. this._lodPlanes[ i ].dispose();
  25504. }
  25505. }
  25506. _cleanup( outputTarget ) {
  25507. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  25508. this._renderer.xr.enabled = _oldXrEnabled;
  25509. outputTarget.scissorTest = false;
  25510. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  25511. }
  25512. _fromTexture( texture, renderTarget ) {
  25513. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  25514. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  25515. } else { // Equirectangular
  25516. this._setSize( texture.image.width / 4 );
  25517. }
  25518. _oldTarget = this._renderer.getRenderTarget();
  25519. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  25520. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  25521. _oldXrEnabled = this._renderer.xr.enabled;
  25522. this._renderer.xr.enabled = false;
  25523. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  25524. this._textureToCubeUV( texture, cubeUVRenderTarget );
  25525. this._applyPMREM( cubeUVRenderTarget );
  25526. this._cleanup( cubeUVRenderTarget );
  25527. return cubeUVRenderTarget;
  25528. }
  25529. _allocateTargets() {
  25530. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  25531. const height = 4 * this._cubeSize;
  25532. const params = {
  25533. magFilter: LinearFilter,
  25534. minFilter: LinearFilter,
  25535. generateMipmaps: false,
  25536. type: HalfFloatType,
  25537. format: RGBAFormat,
  25538. colorSpace: LinearSRGBColorSpace,
  25539. depthBuffer: false
  25540. };
  25541. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  25542. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  25543. if ( this._pingPongRenderTarget !== null ) {
  25544. this._dispose();
  25545. }
  25546. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  25547. const { _lodMax } = this;
  25548. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  25549. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  25550. }
  25551. return cubeUVRenderTarget;
  25552. }
  25553. _compileMaterial( material ) {
  25554. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  25555. this._renderer.compile( tmpMesh, _flatCamera );
  25556. }
  25557. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  25558. const fov = 90;
  25559. const aspect = 1;
  25560. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  25561. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  25562. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  25563. const renderer = this._renderer;
  25564. const originalAutoClear = renderer.autoClear;
  25565. const toneMapping = renderer.toneMapping;
  25566. renderer.getClearColor( _clearColor );
  25567. renderer.toneMapping = NoToneMapping;
  25568. renderer.autoClear = false;
  25569. const backgroundMaterial = new MeshBasicMaterial( {
  25570. name: 'PMREM.Background',
  25571. side: BackSide,
  25572. depthWrite: false,
  25573. depthTest: false,
  25574. } );
  25575. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  25576. let useSolidColor = false;
  25577. const background = scene.background;
  25578. if ( background ) {
  25579. if ( background.isColor ) {
  25580. backgroundMaterial.color.copy( background );
  25581. scene.background = null;
  25582. useSolidColor = true;
  25583. }
  25584. } else {
  25585. backgroundMaterial.color.copy( _clearColor );
  25586. useSolidColor = true;
  25587. }
  25588. for ( let i = 0; i < 6; i ++ ) {
  25589. const col = i % 3;
  25590. if ( col === 0 ) {
  25591. cubeCamera.up.set( 0, upSign[ i ], 0 );
  25592. cubeCamera.position.set( position.x, position.y, position.z );
  25593. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  25594. } else if ( col === 1 ) {
  25595. cubeCamera.up.set( 0, 0, upSign[ i ] );
  25596. cubeCamera.position.set( position.x, position.y, position.z );
  25597. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  25598. } else {
  25599. cubeCamera.up.set( 0, upSign[ i ], 0 );
  25600. cubeCamera.position.set( position.x, position.y, position.z );
  25601. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  25602. }
  25603. const size = this._cubeSize;
  25604. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  25605. renderer.setRenderTarget( cubeUVRenderTarget );
  25606. if ( useSolidColor ) {
  25607. renderer.render( backgroundBox, cubeCamera );
  25608. }
  25609. renderer.render( scene, cubeCamera );
  25610. }
  25611. backgroundBox.geometry.dispose();
  25612. backgroundBox.material.dispose();
  25613. renderer.toneMapping = toneMapping;
  25614. renderer.autoClear = originalAutoClear;
  25615. scene.background = background;
  25616. }
  25617. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  25618. const renderer = this._renderer;
  25619. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  25620. if ( isCubeTexture ) {
  25621. if ( this._cubemapMaterial === null ) {
  25622. this._cubemapMaterial = _getCubemapMaterial();
  25623. }
  25624. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  25625. } else {
  25626. if ( this._equirectMaterial === null ) {
  25627. this._equirectMaterial = _getEquirectMaterial();
  25628. }
  25629. }
  25630. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  25631. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  25632. const uniforms = material.uniforms;
  25633. uniforms[ 'envMap' ].value = texture;
  25634. const size = this._cubeSize;
  25635. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  25636. renderer.setRenderTarget( cubeUVRenderTarget );
  25637. renderer.render( mesh, _flatCamera );
  25638. }
  25639. _applyPMREM( cubeUVRenderTarget ) {
  25640. const renderer = this._renderer;
  25641. const autoClear = renderer.autoClear;
  25642. renderer.autoClear = false;
  25643. const n = this._lodPlanes.length;
  25644. for ( let i = 1; i < n; i ++ ) {
  25645. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  25646. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  25647. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  25648. }
  25649. renderer.autoClear = autoClear;
  25650. }
  25651. /**
  25652. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  25653. * vertically and horizontally, but this breaks down on a cube. Here we apply
  25654. * the blur latitudinally (around the poles), and then longitudinally (towards
  25655. * the poles) to approximate the orthogonally-separable blur. It is least
  25656. * accurate at the poles, but still does a decent job.
  25657. *
  25658. * @param {WebGLRenderTarget} cubeUVRenderTarget
  25659. * @param {number} lodIn
  25660. * @param {number} lodOut
  25661. * @param {number} sigma
  25662. * @param {Vector3} [poleAxis]
  25663. */
  25664. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  25665. const pingPongRenderTarget = this._pingPongRenderTarget;
  25666. this._halfBlur(
  25667. cubeUVRenderTarget,
  25668. pingPongRenderTarget,
  25669. lodIn,
  25670. lodOut,
  25671. sigma,
  25672. 'latitudinal',
  25673. poleAxis );
  25674. this._halfBlur(
  25675. pingPongRenderTarget,
  25676. cubeUVRenderTarget,
  25677. lodOut,
  25678. lodOut,
  25679. sigma,
  25680. 'longitudinal',
  25681. poleAxis );
  25682. }
  25683. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  25684. const renderer = this._renderer;
  25685. const blurMaterial = this._blurMaterial;
  25686. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  25687. console.error(
  25688. 'blur direction must be either latitudinal or longitudinal!' );
  25689. }
  25690. // Number of standard deviations at which to cut off the discrete approximation.
  25691. const STANDARD_DEVIATIONS = 3;
  25692. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  25693. const blurUniforms = blurMaterial.uniforms;
  25694. const pixels = this._sizeLods[ lodIn ] - 1;
  25695. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  25696. const sigmaPixels = sigmaRadians / radiansPerPixel;
  25697. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  25698. if ( samples > MAX_SAMPLES ) {
  25699. console.warn( `sigmaRadians, ${
  25700. sigmaRadians}, is too large and will clip, as it requested ${
  25701. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  25702. }
  25703. const weights = [];
  25704. let sum = 0;
  25705. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  25706. const x = i / sigmaPixels;
  25707. const weight = Math.exp( - x * x / 2 );
  25708. weights.push( weight );
  25709. if ( i === 0 ) {
  25710. sum += weight;
  25711. } else if ( i < samples ) {
  25712. sum += 2 * weight;
  25713. }
  25714. }
  25715. for ( let i = 0; i < weights.length; i ++ ) {
  25716. weights[ i ] = weights[ i ] / sum;
  25717. }
  25718. blurUniforms[ 'envMap' ].value = targetIn.texture;
  25719. blurUniforms[ 'samples' ].value = samples;
  25720. blurUniforms[ 'weights' ].value = weights;
  25721. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  25722. if ( poleAxis ) {
  25723. blurUniforms[ 'poleAxis' ].value = poleAxis;
  25724. }
  25725. const { _lodMax } = this;
  25726. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  25727. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  25728. const outputSize = this._sizeLods[ lodOut ];
  25729. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  25730. const y = 4 * ( this._cubeSize - outputSize );
  25731. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  25732. renderer.setRenderTarget( targetOut );
  25733. renderer.render( blurMesh, _flatCamera );
  25734. }
  25735. }
  25736. function _createPlanes( lodMax ) {
  25737. const lodPlanes = [];
  25738. const sizeLods = [];
  25739. const sigmas = [];
  25740. let lod = lodMax;
  25741. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  25742. for ( let i = 0; i < totalLods; i ++ ) {
  25743. const sizeLod = Math.pow( 2, lod );
  25744. sizeLods.push( sizeLod );
  25745. let sigma = 1.0 / sizeLod;
  25746. if ( i > lodMax - LOD_MIN ) {
  25747. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  25748. } else if ( i === 0 ) {
  25749. sigma = 0;
  25750. }
  25751. sigmas.push( sigma );
  25752. const texelSize = 1.0 / ( sizeLod - 2 );
  25753. const min = - texelSize;
  25754. const max = 1 + texelSize;
  25755. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  25756. const cubeFaces = 6;
  25757. const vertices = 6;
  25758. const positionSize = 3;
  25759. const uvSize = 2;
  25760. const faceIndexSize = 1;
  25761. const position = new Float32Array( positionSize * vertices * cubeFaces );
  25762. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  25763. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  25764. for ( let face = 0; face < cubeFaces; face ++ ) {
  25765. const x = ( face % 3 ) * 2 / 3 - 1;
  25766. const y = face > 2 ? 0 : -1;
  25767. const coordinates = [
  25768. x, y, 0,
  25769. x + 2 / 3, y, 0,
  25770. x + 2 / 3, y + 1, 0,
  25771. x, y, 0,
  25772. x + 2 / 3, y + 1, 0,
  25773. x, y + 1, 0
  25774. ];
  25775. position.set( coordinates, positionSize * vertices * face );
  25776. uv.set( uv1, uvSize * vertices * face );
  25777. const fill = [ face, face, face, face, face, face ];
  25778. faceIndex.set( fill, faceIndexSize * vertices * face );
  25779. }
  25780. const planes = new BufferGeometry();
  25781. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  25782. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  25783. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  25784. lodPlanes.push( planes );
  25785. if ( lod > LOD_MIN ) {
  25786. lod --;
  25787. }
  25788. }
  25789. return { lodPlanes, sizeLods, sigmas };
  25790. }
  25791. function _createRenderTarget( width, height, params ) {
  25792. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  25793. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  25794. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  25795. cubeUVRenderTarget.scissorTest = true;
  25796. return cubeUVRenderTarget;
  25797. }
  25798. function _setViewport( target, x, y, width, height ) {
  25799. target.viewport.set( x, y, width, height );
  25800. target.scissor.set( x, y, width, height );
  25801. }
  25802. function _getBlurShader( lodMax, width, height ) {
  25803. const weights = new Float32Array( MAX_SAMPLES );
  25804. const poleAxis = new Vector3( 0, 1, 0 );
  25805. const shaderMaterial = new ShaderMaterial( {
  25806. name: 'SphericalGaussianBlur',
  25807. defines: {
  25808. 'n': MAX_SAMPLES,
  25809. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  25810. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  25811. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  25812. },
  25813. uniforms: {
  25814. 'envMap': { value: null },
  25815. 'samples': { value: 1 },
  25816. 'weights': { value: weights },
  25817. 'latitudinal': { value: false },
  25818. 'dTheta': { value: 0 },
  25819. 'mipInt': { value: 0 },
  25820. 'poleAxis': { value: poleAxis }
  25821. },
  25822. vertexShader: _getCommonVertexShader(),
  25823. fragmentShader: /* glsl */`
  25824. precision mediump float;
  25825. precision mediump int;
  25826. varying vec3 vOutputDirection;
  25827. uniform sampler2D envMap;
  25828. uniform int samples;
  25829. uniform float weights[ n ];
  25830. uniform bool latitudinal;
  25831. uniform float dTheta;
  25832. uniform float mipInt;
  25833. uniform vec3 poleAxis;
  25834. #define ENVMAP_TYPE_CUBE_UV
  25835. #include <cube_uv_reflection_fragment>
  25836. vec3 getSample( float theta, vec3 axis ) {
  25837. float cosTheta = cos( theta );
  25838. // Rodrigues' axis-angle rotation
  25839. vec3 sampleDirection = vOutputDirection * cosTheta
  25840. + cross( axis, vOutputDirection ) * sin( theta )
  25841. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  25842. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  25843. }
  25844. void main() {
  25845. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  25846. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  25847. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  25848. }
  25849. axis = normalize( axis );
  25850. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  25851. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  25852. for ( int i = 1; i < n; i++ ) {
  25853. if ( i >= samples ) {
  25854. break;
  25855. }
  25856. float theta = dTheta * float( i );
  25857. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  25858. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  25859. }
  25860. }
  25861. `,
  25862. blending: NoBlending,
  25863. depthTest: false,
  25864. depthWrite: false
  25865. } );
  25866. return shaderMaterial;
  25867. }
  25868. function _getEquirectMaterial() {
  25869. return new ShaderMaterial( {
  25870. name: 'EquirectangularToCubeUV',
  25871. uniforms: {
  25872. 'envMap': { value: null }
  25873. },
  25874. vertexShader: _getCommonVertexShader(),
  25875. fragmentShader: /* glsl */`
  25876. precision mediump float;
  25877. precision mediump int;
  25878. varying vec3 vOutputDirection;
  25879. uniform sampler2D envMap;
  25880. #include <common>
  25881. void main() {
  25882. vec3 outputDirection = normalize( vOutputDirection );
  25883. vec2 uv = equirectUv( outputDirection );
  25884. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  25885. }
  25886. `,
  25887. blending: NoBlending,
  25888. depthTest: false,
  25889. depthWrite: false
  25890. } );
  25891. }
  25892. function _getCubemapMaterial() {
  25893. return new ShaderMaterial( {
  25894. name: 'CubemapToCubeUV',
  25895. uniforms: {
  25896. 'envMap': { value: null },
  25897. 'flipEnvMap': { value: -1 }
  25898. },
  25899. vertexShader: _getCommonVertexShader(),
  25900. fragmentShader: /* glsl */`
  25901. precision mediump float;
  25902. precision mediump int;
  25903. uniform float flipEnvMap;
  25904. varying vec3 vOutputDirection;
  25905. uniform samplerCube envMap;
  25906. void main() {
  25907. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  25908. }
  25909. `,
  25910. blending: NoBlending,
  25911. depthTest: false,
  25912. depthWrite: false
  25913. } );
  25914. }
  25915. function _getCommonVertexShader() {
  25916. return /* glsl */`
  25917. precision mediump float;
  25918. precision mediump int;
  25919. attribute float faceIndex;
  25920. varying vec3 vOutputDirection;
  25921. // RH coordinate system; PMREM face-indexing convention
  25922. vec3 getDirection( vec2 uv, float face ) {
  25923. uv = 2.0 * uv - 1.0;
  25924. vec3 direction = vec3( uv, 1.0 );
  25925. if ( face == 0.0 ) {
  25926. direction = direction.zyx; // ( 1, v, u ) pos x
  25927. } else if ( face == 1.0 ) {
  25928. direction = direction.xzy;
  25929. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  25930. } else if ( face == 2.0 ) {
  25931. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  25932. } else if ( face == 3.0 ) {
  25933. direction = direction.zyx;
  25934. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  25935. } else if ( face == 4.0 ) {
  25936. direction = direction.xzy;
  25937. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  25938. } else if ( face == 5.0 ) {
  25939. direction.z *= -1.0; // ( u, v, -1 ) neg z
  25940. }
  25941. return direction;
  25942. }
  25943. void main() {
  25944. vOutputDirection = getDirection( uv, faceIndex );
  25945. gl_Position = vec4( position, 1.0 );
  25946. }
  25947. `;
  25948. }
  25949. function WebGLCubeUVMaps( renderer ) {
  25950. let cubeUVmaps = new WeakMap();
  25951. let pmremGenerator = null;
  25952. function get( texture ) {
  25953. if ( texture && texture.isTexture ) {
  25954. const mapping = texture.mapping;
  25955. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  25956. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  25957. // equirect/cube map to cubeUV conversion
  25958. if ( isEquirectMap || isCubeMap ) {
  25959. let renderTarget = cubeUVmaps.get( texture );
  25960. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  25961. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  25962. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  25963. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  25964. renderTarget.texture.pmremVersion = texture.pmremVersion;
  25965. cubeUVmaps.set( texture, renderTarget );
  25966. return renderTarget.texture;
  25967. } else {
  25968. if ( renderTarget !== undefined ) {
  25969. return renderTarget.texture;
  25970. } else {
  25971. const image = texture.image;
  25972. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  25973. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  25974. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  25975. renderTarget.texture.pmremVersion = texture.pmremVersion;
  25976. cubeUVmaps.set( texture, renderTarget );
  25977. texture.addEventListener( 'dispose', onTextureDispose );
  25978. return renderTarget.texture;
  25979. } else {
  25980. // image not yet ready. try the conversion next frame
  25981. return null;
  25982. }
  25983. }
  25984. }
  25985. }
  25986. }
  25987. return texture;
  25988. }
  25989. function isCubeTextureComplete( image ) {
  25990. let count = 0;
  25991. const length = 6;
  25992. for ( let i = 0; i < length; i ++ ) {
  25993. if ( image[ i ] !== undefined ) count ++;
  25994. }
  25995. return count === length;
  25996. }
  25997. function onTextureDispose( event ) {
  25998. const texture = event.target;
  25999. texture.removeEventListener( 'dispose', onTextureDispose );
  26000. const cubemapUV = cubeUVmaps.get( texture );
  26001. if ( cubemapUV !== undefined ) {
  26002. cubeUVmaps.delete( texture );
  26003. cubemapUV.dispose();
  26004. }
  26005. }
  26006. function dispose() {
  26007. cubeUVmaps = new WeakMap();
  26008. if ( pmremGenerator !== null ) {
  26009. pmremGenerator.dispose();
  26010. pmremGenerator = null;
  26011. }
  26012. }
  26013. return {
  26014. get: get,
  26015. dispose: dispose
  26016. };
  26017. }
  26018. function WebGLExtensions( gl ) {
  26019. const extensions = {};
  26020. function getExtension( name ) {
  26021. if ( extensions[ name ] !== undefined ) {
  26022. return extensions[ name ];
  26023. }
  26024. let extension;
  26025. switch ( name ) {
  26026. case 'WEBGL_depth_texture':
  26027. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  26028. break;
  26029. case 'EXT_texture_filter_anisotropic':
  26030. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  26031. break;
  26032. case 'WEBGL_compressed_texture_s3tc':
  26033. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  26034. break;
  26035. case 'WEBGL_compressed_texture_pvrtc':
  26036. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  26037. break;
  26038. default:
  26039. extension = gl.getExtension( name );
  26040. }
  26041. extensions[ name ] = extension;
  26042. return extension;
  26043. }
  26044. return {
  26045. has: function ( name ) {
  26046. return getExtension( name ) !== null;
  26047. },
  26048. init: function () {
  26049. getExtension( 'EXT_color_buffer_float' );
  26050. getExtension( 'WEBGL_clip_cull_distance' );
  26051. getExtension( 'OES_texture_float_linear' );
  26052. getExtension( 'EXT_color_buffer_half_float' );
  26053. getExtension( 'WEBGL_multisampled_render_to_texture' );
  26054. getExtension( 'WEBGL_render_shared_exponent' );
  26055. },
  26056. get: function ( name ) {
  26057. const extension = getExtension( name );
  26058. if ( extension === null ) {
  26059. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  26060. }
  26061. return extension;
  26062. }
  26063. };
  26064. }
  26065. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  26066. const geometries = {};
  26067. const wireframeAttributes = new WeakMap();
  26068. function onGeometryDispose( event ) {
  26069. const geometry = event.target;
  26070. if ( geometry.index !== null ) {
  26071. attributes.remove( geometry.index );
  26072. }
  26073. for ( const name in geometry.attributes ) {
  26074. attributes.remove( geometry.attributes[ name ] );
  26075. }
  26076. geometry.removeEventListener( 'dispose', onGeometryDispose );
  26077. delete geometries[ geometry.id ];
  26078. const attribute = wireframeAttributes.get( geometry );
  26079. if ( attribute ) {
  26080. attributes.remove( attribute );
  26081. wireframeAttributes.delete( geometry );
  26082. }
  26083. bindingStates.releaseStatesOfGeometry( geometry );
  26084. if ( geometry.isInstancedBufferGeometry === true ) {
  26085. delete geometry._maxInstanceCount;
  26086. }
  26087. //
  26088. info.memory.geometries --;
  26089. }
  26090. function get( object, geometry ) {
  26091. if ( geometries[ geometry.id ] === true ) return geometry;
  26092. geometry.addEventListener( 'dispose', onGeometryDispose );
  26093. geometries[ geometry.id ] = true;
  26094. info.memory.geometries ++;
  26095. return geometry;
  26096. }
  26097. function update( geometry ) {
  26098. const geometryAttributes = geometry.attributes;
  26099. // Updating index buffer in VAO now. See WebGLBindingStates.
  26100. for ( const name in geometryAttributes ) {
  26101. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  26102. }
  26103. }
  26104. function updateWireframeAttribute( geometry ) {
  26105. const indices = [];
  26106. const geometryIndex = geometry.index;
  26107. const geometryPosition = geometry.attributes.position;
  26108. let version = 0;
  26109. if ( geometryIndex !== null ) {
  26110. const array = geometryIndex.array;
  26111. version = geometryIndex.version;
  26112. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  26113. const a = array[ i + 0 ];
  26114. const b = array[ i + 1 ];
  26115. const c = array[ i + 2 ];
  26116. indices.push( a, b, b, c, c, a );
  26117. }
  26118. } else if ( geometryPosition !== undefined ) {
  26119. const array = geometryPosition.array;
  26120. version = geometryPosition.version;
  26121. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  26122. const a = i + 0;
  26123. const b = i + 1;
  26124. const c = i + 2;
  26125. indices.push( a, b, b, c, c, a );
  26126. }
  26127. } else {
  26128. return;
  26129. }
  26130. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  26131. attribute.version = version;
  26132. // Updating index buffer in VAO now. See WebGLBindingStates
  26133. //
  26134. const previousAttribute = wireframeAttributes.get( geometry );
  26135. if ( previousAttribute ) attributes.remove( previousAttribute );
  26136. //
  26137. wireframeAttributes.set( geometry, attribute );
  26138. }
  26139. function getWireframeAttribute( geometry ) {
  26140. const currentAttribute = wireframeAttributes.get( geometry );
  26141. if ( currentAttribute ) {
  26142. const geometryIndex = geometry.index;
  26143. if ( geometryIndex !== null ) {
  26144. // if the attribute is obsolete, create a new one
  26145. if ( currentAttribute.version < geometryIndex.version ) {
  26146. updateWireframeAttribute( geometry );
  26147. }
  26148. }
  26149. } else {
  26150. updateWireframeAttribute( geometry );
  26151. }
  26152. return wireframeAttributes.get( geometry );
  26153. }
  26154. return {
  26155. get: get,
  26156. update: update,
  26157. getWireframeAttribute: getWireframeAttribute
  26158. };
  26159. }
  26160. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  26161. let mode;
  26162. function setMode( value ) {
  26163. mode = value;
  26164. }
  26165. let type, bytesPerElement;
  26166. function setIndex( value ) {
  26167. type = value.type;
  26168. bytesPerElement = value.bytesPerElement;
  26169. }
  26170. function render( start, count ) {
  26171. gl.drawElements( mode, count, type, start * bytesPerElement );
  26172. info.update( count, mode, 1 );
  26173. }
  26174. function renderInstances( start, count, primcount ) {
  26175. if ( primcount === 0 ) return;
  26176. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  26177. info.update( count, mode, primcount );
  26178. }
  26179. function renderMultiDraw( starts, counts, drawCount ) {
  26180. if ( drawCount === 0 ) return;
  26181. const extension = extensions.get( 'WEBGL_multi_draw' );
  26182. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  26183. let elementCount = 0;
  26184. for ( let i = 0; i < drawCount; i ++ ) {
  26185. elementCount += counts[ i ];
  26186. }
  26187. info.update( elementCount, mode, 1 );
  26188. }
  26189. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  26190. if ( drawCount === 0 ) return;
  26191. const extension = extensions.get( 'WEBGL_multi_draw' );
  26192. if ( extension === null ) {
  26193. for ( let i = 0; i < starts.length; i ++ ) {
  26194. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  26195. }
  26196. } else {
  26197. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  26198. let elementCount = 0;
  26199. for ( let i = 0; i < drawCount; i ++ ) {
  26200. elementCount += counts[ i ] * primcount[ i ];
  26201. }
  26202. info.update( elementCount, mode, 1 );
  26203. }
  26204. }
  26205. //
  26206. this.setMode = setMode;
  26207. this.setIndex = setIndex;
  26208. this.render = render;
  26209. this.renderInstances = renderInstances;
  26210. this.renderMultiDraw = renderMultiDraw;
  26211. this.renderMultiDrawInstances = renderMultiDrawInstances;
  26212. }
  26213. function WebGLInfo( gl ) {
  26214. const memory = {
  26215. geometries: 0,
  26216. textures: 0
  26217. };
  26218. const render = {
  26219. frame: 0,
  26220. calls: 0,
  26221. triangles: 0,
  26222. points: 0,
  26223. lines: 0
  26224. };
  26225. function update( count, mode, instanceCount ) {
  26226. render.calls ++;
  26227. switch ( mode ) {
  26228. case gl.TRIANGLES:
  26229. render.triangles += instanceCount * ( count / 3 );
  26230. break;
  26231. case gl.LINES:
  26232. render.lines += instanceCount * ( count / 2 );
  26233. break;
  26234. case gl.LINE_STRIP:
  26235. render.lines += instanceCount * ( count - 1 );
  26236. break;
  26237. case gl.LINE_LOOP:
  26238. render.lines += instanceCount * count;
  26239. break;
  26240. case gl.POINTS:
  26241. render.points += instanceCount * count;
  26242. break;
  26243. default:
  26244. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  26245. break;
  26246. }
  26247. }
  26248. function reset() {
  26249. render.calls = 0;
  26250. render.triangles = 0;
  26251. render.points = 0;
  26252. render.lines = 0;
  26253. }
  26254. return {
  26255. memory: memory,
  26256. render: render,
  26257. programs: null,
  26258. autoReset: true,
  26259. reset: reset,
  26260. update: update
  26261. };
  26262. }
  26263. function WebGLMorphtargets( gl, capabilities, textures ) {
  26264. const morphTextures = new WeakMap();
  26265. const morph = new Vector4();
  26266. function update( object, geometry, program ) {
  26267. const objectInfluences = object.morphTargetInfluences;
  26268. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  26269. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  26270. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  26271. let entry = morphTextures.get( geometry );
  26272. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  26273. if ( entry !== undefined ) entry.texture.dispose();
  26274. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  26275. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  26276. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  26277. const morphTargets = geometry.morphAttributes.position || [];
  26278. const morphNormals = geometry.morphAttributes.normal || [];
  26279. const morphColors = geometry.morphAttributes.color || [];
  26280. let vertexDataCount = 0;
  26281. if ( hasMorphPosition === true ) vertexDataCount = 1;
  26282. if ( hasMorphNormals === true ) vertexDataCount = 2;
  26283. if ( hasMorphColors === true ) vertexDataCount = 3;
  26284. let width = geometry.attributes.position.count * vertexDataCount;
  26285. let height = 1;
  26286. if ( width > capabilities.maxTextureSize ) {
  26287. height = Math.ceil( width / capabilities.maxTextureSize );
  26288. width = capabilities.maxTextureSize;
  26289. }
  26290. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  26291. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  26292. texture.type = FloatType;
  26293. texture.needsUpdate = true;
  26294. // fill buffer
  26295. const vertexDataStride = vertexDataCount * 4;
  26296. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  26297. const morphTarget = morphTargets[ i ];
  26298. const morphNormal = morphNormals[ i ];
  26299. const morphColor = morphColors[ i ];
  26300. const offset = width * height * 4 * i;
  26301. for ( let j = 0; j < morphTarget.count; j ++ ) {
  26302. const stride = j * vertexDataStride;
  26303. if ( hasMorphPosition === true ) {
  26304. morph.fromBufferAttribute( morphTarget, j );
  26305. buffer[ offset + stride + 0 ] = morph.x;
  26306. buffer[ offset + stride + 1 ] = morph.y;
  26307. buffer[ offset + stride + 2 ] = morph.z;
  26308. buffer[ offset + stride + 3 ] = 0;
  26309. }
  26310. if ( hasMorphNormals === true ) {
  26311. morph.fromBufferAttribute( morphNormal, j );
  26312. buffer[ offset + stride + 4 ] = morph.x;
  26313. buffer[ offset + stride + 5 ] = morph.y;
  26314. buffer[ offset + stride + 6 ] = morph.z;
  26315. buffer[ offset + stride + 7 ] = 0;
  26316. }
  26317. if ( hasMorphColors === true ) {
  26318. morph.fromBufferAttribute( morphColor, j );
  26319. buffer[ offset + stride + 8 ] = morph.x;
  26320. buffer[ offset + stride + 9 ] = morph.y;
  26321. buffer[ offset + stride + 10 ] = morph.z;
  26322. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  26323. }
  26324. }
  26325. }
  26326. entry = {
  26327. count: morphTargetsCount,
  26328. texture: texture,
  26329. size: new Vector2( width, height )
  26330. };
  26331. morphTextures.set( geometry, entry );
  26332. function disposeTexture() {
  26333. texture.dispose();
  26334. morphTextures.delete( geometry );
  26335. geometry.removeEventListener( 'dispose', disposeTexture );
  26336. }
  26337. geometry.addEventListener( 'dispose', disposeTexture );
  26338. }
  26339. //
  26340. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  26341. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  26342. } else {
  26343. let morphInfluencesSum = 0;
  26344. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  26345. morphInfluencesSum += objectInfluences[ i ];
  26346. }
  26347. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  26348. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  26349. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  26350. }
  26351. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  26352. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  26353. }
  26354. return {
  26355. update: update
  26356. };
  26357. }
  26358. function WebGLObjects( gl, geometries, attributes, info ) {
  26359. let updateMap = new WeakMap();
  26360. function update( object ) {
  26361. const frame = info.render.frame;
  26362. const geometry = object.geometry;
  26363. const buffergeometry = geometries.get( object, geometry );
  26364. // Update once per frame
  26365. if ( updateMap.get( buffergeometry ) !== frame ) {
  26366. geometries.update( buffergeometry );
  26367. updateMap.set( buffergeometry, frame );
  26368. }
  26369. if ( object.isInstancedMesh ) {
  26370. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  26371. object.addEventListener( 'dispose', onInstancedMeshDispose );
  26372. }
  26373. if ( updateMap.get( object ) !== frame ) {
  26374. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  26375. if ( object.instanceColor !== null ) {
  26376. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  26377. }
  26378. updateMap.set( object, frame );
  26379. }
  26380. }
  26381. if ( object.isSkinnedMesh ) {
  26382. const skeleton = object.skeleton;
  26383. if ( updateMap.get( skeleton ) !== frame ) {
  26384. skeleton.update();
  26385. updateMap.set( skeleton, frame );
  26386. }
  26387. }
  26388. return buffergeometry;
  26389. }
  26390. function dispose() {
  26391. updateMap = new WeakMap();
  26392. }
  26393. function onInstancedMeshDispose( event ) {
  26394. const instancedMesh = event.target;
  26395. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  26396. attributes.remove( instancedMesh.instanceMatrix );
  26397. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  26398. }
  26399. return {
  26400. update: update,
  26401. dispose: dispose
  26402. };
  26403. }
  26404. /**
  26405. * Uniforms of a program.
  26406. * Those form a tree structure with a special top-level container for the root,
  26407. * which you get by calling 'new WebGLUniforms( gl, program )'.
  26408. *
  26409. *
  26410. * Properties of inner nodes including the top-level container:
  26411. *
  26412. * .seq - array of nested uniforms
  26413. * .map - nested uniforms by name
  26414. *
  26415. *
  26416. * Methods of all nodes except the top-level container:
  26417. *
  26418. * .setValue( gl, value, [textures] )
  26419. *
  26420. * uploads a uniform value(s)
  26421. * the 'textures' parameter is needed for sampler uniforms
  26422. *
  26423. *
  26424. * Static methods of the top-level container (textures factorizations):
  26425. *
  26426. * .upload( gl, seq, values, textures )
  26427. *
  26428. * sets uniforms in 'seq' to 'values[id].value'
  26429. *
  26430. * .seqWithValue( seq, values ) : filteredSeq
  26431. *
  26432. * filters 'seq' entries with corresponding entry in values
  26433. *
  26434. *
  26435. * Methods of the top-level container (textures factorizations):
  26436. *
  26437. * .setValue( gl, name, value, textures )
  26438. *
  26439. * sets uniform with name 'name' to 'value'
  26440. *
  26441. * .setOptional( gl, obj, prop )
  26442. *
  26443. * like .set for an optional property of the object
  26444. *
  26445. */
  26446. const emptyTexture = /*@__PURE__*/ new Texture();
  26447. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  26448. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  26449. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  26450. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  26451. // --- Utilities ---
  26452. // Array Caches (provide typed arrays for temporary by size)
  26453. const arrayCacheF32 = [];
  26454. const arrayCacheI32 = [];
  26455. // Float32Array caches used for uploading Matrix uniforms
  26456. const mat4array = new Float32Array( 16 );
  26457. const mat3array = new Float32Array( 9 );
  26458. const mat2array = new Float32Array( 4 );
  26459. // Flattening for arrays of vectors and matrices
  26460. function flatten( array, nBlocks, blockSize ) {
  26461. const firstElem = array[ 0 ];
  26462. if ( firstElem <= 0 || firstElem > 0 ) return array;
  26463. // unoptimized: ! isNaN( firstElem )
  26464. // see http://jacksondunstan.com/articles/983
  26465. const n = nBlocks * blockSize;
  26466. let r = arrayCacheF32[ n ];
  26467. if ( r === undefined ) {
  26468. r = new Float32Array( n );
  26469. arrayCacheF32[ n ] = r;
  26470. }
  26471. if ( nBlocks !== 0 ) {
  26472. firstElem.toArray( r, 0 );
  26473. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  26474. offset += blockSize;
  26475. array[ i ].toArray( r, offset );
  26476. }
  26477. }
  26478. return r;
  26479. }
  26480. function arraysEqual( a, b ) {
  26481. if ( a.length !== b.length ) return false;
  26482. for ( let i = 0, l = a.length; i < l; i ++ ) {
  26483. if ( a[ i ] !== b[ i ] ) return false;
  26484. }
  26485. return true;
  26486. }
  26487. function copyArray( a, b ) {
  26488. for ( let i = 0, l = b.length; i < l; i ++ ) {
  26489. a[ i ] = b[ i ];
  26490. }
  26491. }
  26492. // Texture unit allocation
  26493. function allocTexUnits( textures, n ) {
  26494. let r = arrayCacheI32[ n ];
  26495. if ( r === undefined ) {
  26496. r = new Int32Array( n );
  26497. arrayCacheI32[ n ] = r;
  26498. }
  26499. for ( let i = 0; i !== n; ++ i ) {
  26500. r[ i ] = textures.allocateTextureUnit();
  26501. }
  26502. return r;
  26503. }
  26504. // --- Setters ---
  26505. // Note: Defining these methods externally, because they come in a bunch
  26506. // and this way their names minify.
  26507. // Single scalar
  26508. function setValueV1f( gl, v ) {
  26509. const cache = this.cache;
  26510. if ( cache[ 0 ] === v ) return;
  26511. gl.uniform1f( this.addr, v );
  26512. cache[ 0 ] = v;
  26513. }
  26514. // Single float vector (from flat array or THREE.VectorN)
  26515. function setValueV2f( gl, v ) {
  26516. const cache = this.cache;
  26517. if ( v.x !== undefined ) {
  26518. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  26519. gl.uniform2f( this.addr, v.x, v.y );
  26520. cache[ 0 ] = v.x;
  26521. cache[ 1 ] = v.y;
  26522. }
  26523. } else {
  26524. if ( arraysEqual( cache, v ) ) return;
  26525. gl.uniform2fv( this.addr, v );
  26526. copyArray( cache, v );
  26527. }
  26528. }
  26529. function setValueV3f( gl, v ) {
  26530. const cache = this.cache;
  26531. if ( v.x !== undefined ) {
  26532. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  26533. gl.uniform3f( this.addr, v.x, v.y, v.z );
  26534. cache[ 0 ] = v.x;
  26535. cache[ 1 ] = v.y;
  26536. cache[ 2 ] = v.z;
  26537. }
  26538. } else if ( v.r !== undefined ) {
  26539. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  26540. gl.uniform3f( this.addr, v.r, v.g, v.b );
  26541. cache[ 0 ] = v.r;
  26542. cache[ 1 ] = v.g;
  26543. cache[ 2 ] = v.b;
  26544. }
  26545. } else {
  26546. if ( arraysEqual( cache, v ) ) return;
  26547. gl.uniform3fv( this.addr, v );
  26548. copyArray( cache, v );
  26549. }
  26550. }
  26551. function setValueV4f( gl, v ) {
  26552. const cache = this.cache;
  26553. if ( v.x !== undefined ) {
  26554. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  26555. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  26556. cache[ 0 ] = v.x;
  26557. cache[ 1 ] = v.y;
  26558. cache[ 2 ] = v.z;
  26559. cache[ 3 ] = v.w;
  26560. }
  26561. } else {
  26562. if ( arraysEqual( cache, v ) ) return;
  26563. gl.uniform4fv( this.addr, v );
  26564. copyArray( cache, v );
  26565. }
  26566. }
  26567. // Single matrix (from flat array or THREE.MatrixN)
  26568. function setValueM2( gl, v ) {
  26569. const cache = this.cache;
  26570. const elements = v.elements;
  26571. if ( elements === undefined ) {
  26572. if ( arraysEqual( cache, v ) ) return;
  26573. gl.uniformMatrix2fv( this.addr, false, v );
  26574. copyArray( cache, v );
  26575. } else {
  26576. if ( arraysEqual( cache, elements ) ) return;
  26577. mat2array.set( elements );
  26578. gl.uniformMatrix2fv( this.addr, false, mat2array );
  26579. copyArray( cache, elements );
  26580. }
  26581. }
  26582. function setValueM3( gl, v ) {
  26583. const cache = this.cache;
  26584. const elements = v.elements;
  26585. if ( elements === undefined ) {
  26586. if ( arraysEqual( cache, v ) ) return;
  26587. gl.uniformMatrix3fv( this.addr, false, v );
  26588. copyArray( cache, v );
  26589. } else {
  26590. if ( arraysEqual( cache, elements ) ) return;
  26591. mat3array.set( elements );
  26592. gl.uniformMatrix3fv( this.addr, false, mat3array );
  26593. copyArray( cache, elements );
  26594. }
  26595. }
  26596. function setValueM4( gl, v ) {
  26597. const cache = this.cache;
  26598. const elements = v.elements;
  26599. if ( elements === undefined ) {
  26600. if ( arraysEqual( cache, v ) ) return;
  26601. gl.uniformMatrix4fv( this.addr, false, v );
  26602. copyArray( cache, v );
  26603. } else {
  26604. if ( arraysEqual( cache, elements ) ) return;
  26605. mat4array.set( elements );
  26606. gl.uniformMatrix4fv( this.addr, false, mat4array );
  26607. copyArray( cache, elements );
  26608. }
  26609. }
  26610. // Single integer / boolean
  26611. function setValueV1i( gl, v ) {
  26612. const cache = this.cache;
  26613. if ( cache[ 0 ] === v ) return;
  26614. gl.uniform1i( this.addr, v );
  26615. cache[ 0 ] = v;
  26616. }
  26617. // Single integer / boolean vector (from flat array or THREE.VectorN)
  26618. function setValueV2i( gl, v ) {
  26619. const cache = this.cache;
  26620. if ( v.x !== undefined ) {
  26621. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  26622. gl.uniform2i( this.addr, v.x, v.y );
  26623. cache[ 0 ] = v.x;
  26624. cache[ 1 ] = v.y;
  26625. }
  26626. } else {
  26627. if ( arraysEqual( cache, v ) ) return;
  26628. gl.uniform2iv( this.addr, v );
  26629. copyArray( cache, v );
  26630. }
  26631. }
  26632. function setValueV3i( gl, v ) {
  26633. const cache = this.cache;
  26634. if ( v.x !== undefined ) {
  26635. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  26636. gl.uniform3i( this.addr, v.x, v.y, v.z );
  26637. cache[ 0 ] = v.x;
  26638. cache[ 1 ] = v.y;
  26639. cache[ 2 ] = v.z;
  26640. }
  26641. } else {
  26642. if ( arraysEqual( cache, v ) ) return;
  26643. gl.uniform3iv( this.addr, v );
  26644. copyArray( cache, v );
  26645. }
  26646. }
  26647. function setValueV4i( gl, v ) {
  26648. const cache = this.cache;
  26649. if ( v.x !== undefined ) {
  26650. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  26651. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  26652. cache[ 0 ] = v.x;
  26653. cache[ 1 ] = v.y;
  26654. cache[ 2 ] = v.z;
  26655. cache[ 3 ] = v.w;
  26656. }
  26657. } else {
  26658. if ( arraysEqual( cache, v ) ) return;
  26659. gl.uniform4iv( this.addr, v );
  26660. copyArray( cache, v );
  26661. }
  26662. }
  26663. // Single unsigned integer
  26664. function setValueV1ui( gl, v ) {
  26665. const cache = this.cache;
  26666. if ( cache[ 0 ] === v ) return;
  26667. gl.uniform1ui( this.addr, v );
  26668. cache[ 0 ] = v;
  26669. }
  26670. // Single unsigned integer vector (from flat array or THREE.VectorN)
  26671. function setValueV2ui( gl, v ) {
  26672. const cache = this.cache;
  26673. if ( v.x !== undefined ) {
  26674. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  26675. gl.uniform2ui( this.addr, v.x, v.y );
  26676. cache[ 0 ] = v.x;
  26677. cache[ 1 ] = v.y;
  26678. }
  26679. } else {
  26680. if ( arraysEqual( cache, v ) ) return;
  26681. gl.uniform2uiv( this.addr, v );
  26682. copyArray( cache, v );
  26683. }
  26684. }
  26685. function setValueV3ui( gl, v ) {
  26686. const cache = this.cache;
  26687. if ( v.x !== undefined ) {
  26688. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  26689. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  26690. cache[ 0 ] = v.x;
  26691. cache[ 1 ] = v.y;
  26692. cache[ 2 ] = v.z;
  26693. }
  26694. } else {
  26695. if ( arraysEqual( cache, v ) ) return;
  26696. gl.uniform3uiv( this.addr, v );
  26697. copyArray( cache, v );
  26698. }
  26699. }
  26700. function setValueV4ui( gl, v ) {
  26701. const cache = this.cache;
  26702. if ( v.x !== undefined ) {
  26703. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  26704. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  26705. cache[ 0 ] = v.x;
  26706. cache[ 1 ] = v.y;
  26707. cache[ 2 ] = v.z;
  26708. cache[ 3 ] = v.w;
  26709. }
  26710. } else {
  26711. if ( arraysEqual( cache, v ) ) return;
  26712. gl.uniform4uiv( this.addr, v );
  26713. copyArray( cache, v );
  26714. }
  26715. }
  26716. // Single texture (2D / Cube)
  26717. function setValueT1( gl, v, textures ) {
  26718. const cache = this.cache;
  26719. const unit = textures.allocateTextureUnit();
  26720. if ( cache[ 0 ] !== unit ) {
  26721. gl.uniform1i( this.addr, unit );
  26722. cache[ 0 ] = unit;
  26723. }
  26724. let emptyTexture2D;
  26725. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  26726. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  26727. emptyTexture2D = emptyShadowTexture;
  26728. } else {
  26729. emptyTexture2D = emptyTexture;
  26730. }
  26731. textures.setTexture2D( v || emptyTexture2D, unit );
  26732. }
  26733. function setValueT3D1( gl, v, textures ) {
  26734. const cache = this.cache;
  26735. const unit = textures.allocateTextureUnit();
  26736. if ( cache[ 0 ] !== unit ) {
  26737. gl.uniform1i( this.addr, unit );
  26738. cache[ 0 ] = unit;
  26739. }
  26740. textures.setTexture3D( v || empty3dTexture, unit );
  26741. }
  26742. function setValueT6( gl, v, textures ) {
  26743. const cache = this.cache;
  26744. const unit = textures.allocateTextureUnit();
  26745. if ( cache[ 0 ] !== unit ) {
  26746. gl.uniform1i( this.addr, unit );
  26747. cache[ 0 ] = unit;
  26748. }
  26749. textures.setTextureCube( v || emptyCubeTexture, unit );
  26750. }
  26751. function setValueT2DArray1( gl, v, textures ) {
  26752. const cache = this.cache;
  26753. const unit = textures.allocateTextureUnit();
  26754. if ( cache[ 0 ] !== unit ) {
  26755. gl.uniform1i( this.addr, unit );
  26756. cache[ 0 ] = unit;
  26757. }
  26758. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  26759. }
  26760. // Helper to pick the right setter for the singular case
  26761. function getSingularSetter( type ) {
  26762. switch ( type ) {
  26763. case 0x1406: return setValueV1f; // FLOAT
  26764. case 0x8b50: return setValueV2f; // _VEC2
  26765. case 0x8b51: return setValueV3f; // _VEC3
  26766. case 0x8b52: return setValueV4f; // _VEC4
  26767. case 0x8b5a: return setValueM2; // _MAT2
  26768. case 0x8b5b: return setValueM3; // _MAT3
  26769. case 0x8b5c: return setValueM4; // _MAT4
  26770. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  26771. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  26772. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  26773. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  26774. case 0x1405: return setValueV1ui; // UINT
  26775. case 0x8dc6: return setValueV2ui; // _VEC2
  26776. case 0x8dc7: return setValueV3ui; // _VEC3
  26777. case 0x8dc8: return setValueV4ui; // _VEC4
  26778. case 0x8b5e: // SAMPLER_2D
  26779. case 0x8d66: // SAMPLER_EXTERNAL_OES
  26780. case 0x8dca: // INT_SAMPLER_2D
  26781. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  26782. case 0x8b62: // SAMPLER_2D_SHADOW
  26783. return setValueT1;
  26784. case 0x8b5f: // SAMPLER_3D
  26785. case 0x8dcb: // INT_SAMPLER_3D
  26786. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  26787. return setValueT3D1;
  26788. case 0x8b60: // SAMPLER_CUBE
  26789. case 0x8dcc: // INT_SAMPLER_CUBE
  26790. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  26791. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  26792. return setValueT6;
  26793. case 0x8dc1: // SAMPLER_2D_ARRAY
  26794. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  26795. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  26796. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  26797. return setValueT2DArray1;
  26798. }
  26799. }
  26800. // Array of scalars
  26801. function setValueV1fArray( gl, v ) {
  26802. gl.uniform1fv( this.addr, v );
  26803. }
  26804. // Array of vectors (from flat array or array of THREE.VectorN)
  26805. function setValueV2fArray( gl, v ) {
  26806. const data = flatten( v, this.size, 2 );
  26807. gl.uniform2fv( this.addr, data );
  26808. }
  26809. function setValueV3fArray( gl, v ) {
  26810. const data = flatten( v, this.size, 3 );
  26811. gl.uniform3fv( this.addr, data );
  26812. }
  26813. function setValueV4fArray( gl, v ) {
  26814. const data = flatten( v, this.size, 4 );
  26815. gl.uniform4fv( this.addr, data );
  26816. }
  26817. // Array of matrices (from flat array or array of THREE.MatrixN)
  26818. function setValueM2Array( gl, v ) {
  26819. const data = flatten( v, this.size, 4 );
  26820. gl.uniformMatrix2fv( this.addr, false, data );
  26821. }
  26822. function setValueM3Array( gl, v ) {
  26823. const data = flatten( v, this.size, 9 );
  26824. gl.uniformMatrix3fv( this.addr, false, data );
  26825. }
  26826. function setValueM4Array( gl, v ) {
  26827. const data = flatten( v, this.size, 16 );
  26828. gl.uniformMatrix4fv( this.addr, false, data );
  26829. }
  26830. // Array of integer / boolean
  26831. function setValueV1iArray( gl, v ) {
  26832. gl.uniform1iv( this.addr, v );
  26833. }
  26834. // Array of integer / boolean vectors (from flat array)
  26835. function setValueV2iArray( gl, v ) {
  26836. gl.uniform2iv( this.addr, v );
  26837. }
  26838. function setValueV3iArray( gl, v ) {
  26839. gl.uniform3iv( this.addr, v );
  26840. }
  26841. function setValueV4iArray( gl, v ) {
  26842. gl.uniform4iv( this.addr, v );
  26843. }
  26844. // Array of unsigned integer
  26845. function setValueV1uiArray( gl, v ) {
  26846. gl.uniform1uiv( this.addr, v );
  26847. }
  26848. // Array of unsigned integer vectors (from flat array)
  26849. function setValueV2uiArray( gl, v ) {
  26850. gl.uniform2uiv( this.addr, v );
  26851. }
  26852. function setValueV3uiArray( gl, v ) {
  26853. gl.uniform3uiv( this.addr, v );
  26854. }
  26855. function setValueV4uiArray( gl, v ) {
  26856. gl.uniform4uiv( this.addr, v );
  26857. }
  26858. // Array of textures (2D / 3D / Cube / 2DArray)
  26859. function setValueT1Array( gl, v, textures ) {
  26860. const cache = this.cache;
  26861. const n = v.length;
  26862. const units = allocTexUnits( textures, n );
  26863. if ( ! arraysEqual( cache, units ) ) {
  26864. gl.uniform1iv( this.addr, units );
  26865. copyArray( cache, units );
  26866. }
  26867. for ( let i = 0; i !== n; ++ i ) {
  26868. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  26869. }
  26870. }
  26871. function setValueT3DArray( gl, v, textures ) {
  26872. const cache = this.cache;
  26873. const n = v.length;
  26874. const units = allocTexUnits( textures, n );
  26875. if ( ! arraysEqual( cache, units ) ) {
  26876. gl.uniform1iv( this.addr, units );
  26877. copyArray( cache, units );
  26878. }
  26879. for ( let i = 0; i !== n; ++ i ) {
  26880. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  26881. }
  26882. }
  26883. function setValueT6Array( gl, v, textures ) {
  26884. const cache = this.cache;
  26885. const n = v.length;
  26886. const units = allocTexUnits( textures, n );
  26887. if ( ! arraysEqual( cache, units ) ) {
  26888. gl.uniform1iv( this.addr, units );
  26889. copyArray( cache, units );
  26890. }
  26891. for ( let i = 0; i !== n; ++ i ) {
  26892. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  26893. }
  26894. }
  26895. function setValueT2DArrayArray( gl, v, textures ) {
  26896. const cache = this.cache;
  26897. const n = v.length;
  26898. const units = allocTexUnits( textures, n );
  26899. if ( ! arraysEqual( cache, units ) ) {
  26900. gl.uniform1iv( this.addr, units );
  26901. copyArray( cache, units );
  26902. }
  26903. for ( let i = 0; i !== n; ++ i ) {
  26904. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  26905. }
  26906. }
  26907. // Helper to pick the right setter for a pure (bottom-level) array
  26908. function getPureArraySetter( type ) {
  26909. switch ( type ) {
  26910. case 0x1406: return setValueV1fArray; // FLOAT
  26911. case 0x8b50: return setValueV2fArray; // _VEC2
  26912. case 0x8b51: return setValueV3fArray; // _VEC3
  26913. case 0x8b52: return setValueV4fArray; // _VEC4
  26914. case 0x8b5a: return setValueM2Array; // _MAT2
  26915. case 0x8b5b: return setValueM3Array; // _MAT3
  26916. case 0x8b5c: return setValueM4Array; // _MAT4
  26917. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  26918. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  26919. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  26920. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  26921. case 0x1405: return setValueV1uiArray; // UINT
  26922. case 0x8dc6: return setValueV2uiArray; // _VEC2
  26923. case 0x8dc7: return setValueV3uiArray; // _VEC3
  26924. case 0x8dc8: return setValueV4uiArray; // _VEC4
  26925. case 0x8b5e: // SAMPLER_2D
  26926. case 0x8d66: // SAMPLER_EXTERNAL_OES
  26927. case 0x8dca: // INT_SAMPLER_2D
  26928. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  26929. case 0x8b62: // SAMPLER_2D_SHADOW
  26930. return setValueT1Array;
  26931. case 0x8b5f: // SAMPLER_3D
  26932. case 0x8dcb: // INT_SAMPLER_3D
  26933. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  26934. return setValueT3DArray;
  26935. case 0x8b60: // SAMPLER_CUBE
  26936. case 0x8dcc: // INT_SAMPLER_CUBE
  26937. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  26938. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  26939. return setValueT6Array;
  26940. case 0x8dc1: // SAMPLER_2D_ARRAY
  26941. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  26942. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  26943. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  26944. return setValueT2DArrayArray;
  26945. }
  26946. }
  26947. // --- Uniform Classes ---
  26948. class SingleUniform {
  26949. constructor( id, activeInfo, addr ) {
  26950. this.id = id;
  26951. this.addr = addr;
  26952. this.cache = [];
  26953. this.type = activeInfo.type;
  26954. this.setValue = getSingularSetter( activeInfo.type );
  26955. // this.path = activeInfo.name; // DEBUG
  26956. }
  26957. }
  26958. class PureArrayUniform {
  26959. constructor( id, activeInfo, addr ) {
  26960. this.id = id;
  26961. this.addr = addr;
  26962. this.cache = [];
  26963. this.type = activeInfo.type;
  26964. this.size = activeInfo.size;
  26965. this.setValue = getPureArraySetter( activeInfo.type );
  26966. // this.path = activeInfo.name; // DEBUG
  26967. }
  26968. }
  26969. class StructuredUniform {
  26970. constructor( id ) {
  26971. this.id = id;
  26972. this.seq = [];
  26973. this.map = {};
  26974. }
  26975. setValue( gl, value, textures ) {
  26976. const seq = this.seq;
  26977. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  26978. const u = seq[ i ];
  26979. u.setValue( gl, value[ u.id ], textures );
  26980. }
  26981. }
  26982. }
  26983. // --- Top-level ---
  26984. // Parser - builds up the property tree from the path strings
  26985. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  26986. // extracts
  26987. // - the identifier (member name or array index)
  26988. // - followed by an optional right bracket (found when array index)
  26989. // - followed by an optional left bracket or dot (type of subscript)
  26990. //
  26991. // Note: These portions can be read in a non-overlapping fashion and
  26992. // allow straightforward parsing of the hierarchy that WebGL encodes
  26993. // in the uniform names.
  26994. function addUniform( container, uniformObject ) {
  26995. container.seq.push( uniformObject );
  26996. container.map[ uniformObject.id ] = uniformObject;
  26997. }
  26998. function parseUniform( activeInfo, addr, container ) {
  26999. const path = activeInfo.name,
  27000. pathLength = path.length;
  27001. // reset RegExp object, because of the early exit of a previous run
  27002. RePathPart.lastIndex = 0;
  27003. while ( true ) {
  27004. const match = RePathPart.exec( path ),
  27005. matchEnd = RePathPart.lastIndex;
  27006. let id = match[ 1 ];
  27007. const idIsIndex = match[ 2 ] === ']',
  27008. subscript = match[ 3 ];
  27009. if ( idIsIndex ) id = id | 0; // convert to integer
  27010. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  27011. // bare name or "pure" bottom-level array "[0]" suffix
  27012. addUniform( container, subscript === undefined ?
  27013. new SingleUniform( id, activeInfo, addr ) :
  27014. new PureArrayUniform( id, activeInfo, addr ) );
  27015. break;
  27016. } else {
  27017. // step into inner node / create it in case it doesn't exist
  27018. const map = container.map;
  27019. let next = map[ id ];
  27020. if ( next === undefined ) {
  27021. next = new StructuredUniform( id );
  27022. addUniform( container, next );
  27023. }
  27024. container = next;
  27025. }
  27026. }
  27027. }
  27028. // Root Container
  27029. class WebGLUniforms {
  27030. constructor( gl, program ) {
  27031. this.seq = [];
  27032. this.map = {};
  27033. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  27034. for ( let i = 0; i < n; ++ i ) {
  27035. const info = gl.getActiveUniform( program, i ),
  27036. addr = gl.getUniformLocation( program, info.name );
  27037. parseUniform( info, addr, this );
  27038. }
  27039. }
  27040. setValue( gl, name, value, textures ) {
  27041. const u = this.map[ name ];
  27042. if ( u !== undefined ) u.setValue( gl, value, textures );
  27043. }
  27044. setOptional( gl, object, name ) {
  27045. const v = object[ name ];
  27046. if ( v !== undefined ) this.setValue( gl, name, v );
  27047. }
  27048. static upload( gl, seq, values, textures ) {
  27049. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  27050. const u = seq[ i ],
  27051. v = values[ u.id ];
  27052. if ( v.needsUpdate !== false ) {
  27053. // note: always updating when .needsUpdate is undefined
  27054. u.setValue( gl, v.value, textures );
  27055. }
  27056. }
  27057. }
  27058. static seqWithValue( seq, values ) {
  27059. const r = [];
  27060. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  27061. const u = seq[ i ];
  27062. if ( u.id in values ) r.push( u );
  27063. }
  27064. return r;
  27065. }
  27066. }
  27067. function WebGLShader( gl, type, string ) {
  27068. const shader = gl.createShader( type );
  27069. gl.shaderSource( shader, string );
  27070. gl.compileShader( shader );
  27071. return shader;
  27072. }
  27073. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  27074. const COMPLETION_STATUS_KHR = 0x91B1;
  27075. let programIdCount = 0;
  27076. function handleSource( string, errorLine ) {
  27077. const lines = string.split( '\n' );
  27078. const lines2 = [];
  27079. const from = Math.max( errorLine - 6, 0 );
  27080. const to = Math.min( errorLine + 6, lines.length );
  27081. for ( let i = from; i < to; i ++ ) {
  27082. const line = i + 1;
  27083. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  27084. }
  27085. return lines2.join( '\n' );
  27086. }
  27087. const _m0 = /*@__PURE__*/ new Matrix3();
  27088. function getEncodingComponents( colorSpace ) {
  27089. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  27090. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  27091. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  27092. case LinearTransfer:
  27093. return [ encodingMatrix, 'LinearTransferOETF' ];
  27094. case SRGBTransfer:
  27095. return [ encodingMatrix, 'sRGBTransferOETF' ];
  27096. default:
  27097. console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace );
  27098. return [ encodingMatrix, 'LinearTransferOETF' ];
  27099. }
  27100. }
  27101. function getShaderErrors( gl, shader, type ) {
  27102. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  27103. const errors = gl.getShaderInfoLog( shader ).trim();
  27104. if ( status && errors === '' ) return '';
  27105. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  27106. if ( errorMatches ) {
  27107. // --enable-privileged-webgl-extension
  27108. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  27109. const errorLine = parseInt( errorMatches[ 1 ] );
  27110. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  27111. } else {
  27112. return errors;
  27113. }
  27114. }
  27115. function getTexelEncodingFunction( functionName, colorSpace ) {
  27116. const components = getEncodingComponents( colorSpace );
  27117. return [
  27118. `vec4 ${functionName}( vec4 value ) {`,
  27119. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  27120. '}',
  27121. ].join( '\n' );
  27122. }
  27123. function getToneMappingFunction( functionName, toneMapping ) {
  27124. let toneMappingName;
  27125. switch ( toneMapping ) {
  27126. case LinearToneMapping:
  27127. toneMappingName = 'Linear';
  27128. break;
  27129. case ReinhardToneMapping:
  27130. toneMappingName = 'Reinhard';
  27131. break;
  27132. case CineonToneMapping:
  27133. toneMappingName = 'Cineon';
  27134. break;
  27135. case ACESFilmicToneMapping:
  27136. toneMappingName = 'ACESFilmic';
  27137. break;
  27138. case AgXToneMapping:
  27139. toneMappingName = 'AgX';
  27140. break;
  27141. case NeutralToneMapping:
  27142. toneMappingName = 'Neutral';
  27143. break;
  27144. case CustomToneMapping:
  27145. toneMappingName = 'Custom';
  27146. break;
  27147. default:
  27148. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  27149. toneMappingName = 'Linear';
  27150. }
  27151. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  27152. }
  27153. const _v0 = /*@__PURE__*/ new Vector3();
  27154. function getLuminanceFunction() {
  27155. ColorManagement.getLuminanceCoefficients( _v0 );
  27156. const r = _v0.x.toFixed( 4 );
  27157. const g = _v0.y.toFixed( 4 );
  27158. const b = _v0.z.toFixed( 4 );
  27159. return [
  27160. 'float luminance( const in vec3 rgb ) {',
  27161. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  27162. ' return dot( weights, rgb );',
  27163. '}'
  27164. ].join( '\n' );
  27165. }
  27166. function generateVertexExtensions( parameters ) {
  27167. const chunks = [
  27168. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  27169. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  27170. ];
  27171. return chunks.filter( filterEmptyLine ).join( '\n' );
  27172. }
  27173. function generateDefines( defines ) {
  27174. const chunks = [];
  27175. for ( const name in defines ) {
  27176. const value = defines[ name ];
  27177. if ( value === false ) continue;
  27178. chunks.push( '#define ' + name + ' ' + value );
  27179. }
  27180. return chunks.join( '\n' );
  27181. }
  27182. function fetchAttributeLocations( gl, program ) {
  27183. const attributes = {};
  27184. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  27185. for ( let i = 0; i < n; i ++ ) {
  27186. const info = gl.getActiveAttrib( program, i );
  27187. const name = info.name;
  27188. let locationSize = 1;
  27189. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  27190. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  27191. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  27192. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  27193. attributes[ name ] = {
  27194. type: info.type,
  27195. location: gl.getAttribLocation( program, name ),
  27196. locationSize: locationSize
  27197. };
  27198. }
  27199. return attributes;
  27200. }
  27201. function filterEmptyLine( string ) {
  27202. return string !== '';
  27203. }
  27204. function replaceLightNums( string, parameters ) {
  27205. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  27206. return string
  27207. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  27208. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  27209. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  27210. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  27211. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  27212. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  27213. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  27214. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  27215. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  27216. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  27217. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  27218. }
  27219. function replaceClippingPlaneNums( string, parameters ) {
  27220. return string
  27221. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  27222. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  27223. }
  27224. // Resolve Includes
  27225. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  27226. function resolveIncludes( string ) {
  27227. return string.replace( includePattern, includeReplacer );
  27228. }
  27229. const shaderChunkMap = new Map();
  27230. function includeReplacer( match, include ) {
  27231. let string = ShaderChunk[ include ];
  27232. if ( string === undefined ) {
  27233. const newInclude = shaderChunkMap.get( include );
  27234. if ( newInclude !== undefined ) {
  27235. string = ShaderChunk[ newInclude ];
  27236. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  27237. } else {
  27238. throw new Error( 'Can not resolve #include <' + include + '>' );
  27239. }
  27240. }
  27241. return resolveIncludes( string );
  27242. }
  27243. // Unroll Loops
  27244. 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;
  27245. function unrollLoops( string ) {
  27246. return string.replace( unrollLoopPattern, loopReplacer );
  27247. }
  27248. function loopReplacer( match, start, end, snippet ) {
  27249. let string = '';
  27250. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  27251. string += snippet
  27252. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  27253. .replace( /UNROLLED_LOOP_INDEX/g, i );
  27254. }
  27255. return string;
  27256. }
  27257. //
  27258. function generatePrecision( parameters ) {
  27259. let precisionstring = `precision ${parameters.precision} float;
  27260. precision ${parameters.precision} int;
  27261. precision ${parameters.precision} sampler2D;
  27262. precision ${parameters.precision} samplerCube;
  27263. precision ${parameters.precision} sampler3D;
  27264. precision ${parameters.precision} sampler2DArray;
  27265. precision ${parameters.precision} sampler2DShadow;
  27266. precision ${parameters.precision} samplerCubeShadow;
  27267. precision ${parameters.precision} sampler2DArrayShadow;
  27268. precision ${parameters.precision} isampler2D;
  27269. precision ${parameters.precision} isampler3D;
  27270. precision ${parameters.precision} isamplerCube;
  27271. precision ${parameters.precision} isampler2DArray;
  27272. precision ${parameters.precision} usampler2D;
  27273. precision ${parameters.precision} usampler3D;
  27274. precision ${parameters.precision} usamplerCube;
  27275. precision ${parameters.precision} usampler2DArray;
  27276. `;
  27277. if ( parameters.precision === 'highp' ) {
  27278. precisionstring += '\n#define HIGH_PRECISION';
  27279. } else if ( parameters.precision === 'mediump' ) {
  27280. precisionstring += '\n#define MEDIUM_PRECISION';
  27281. } else if ( parameters.precision === 'lowp' ) {
  27282. precisionstring += '\n#define LOW_PRECISION';
  27283. }
  27284. return precisionstring;
  27285. }
  27286. function generateShadowMapTypeDefine( parameters ) {
  27287. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  27288. if ( parameters.shadowMapType === PCFShadowMap ) {
  27289. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  27290. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  27291. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  27292. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  27293. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  27294. }
  27295. return shadowMapTypeDefine;
  27296. }
  27297. function generateEnvMapTypeDefine( parameters ) {
  27298. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  27299. if ( parameters.envMap ) {
  27300. switch ( parameters.envMapMode ) {
  27301. case CubeReflectionMapping:
  27302. case CubeRefractionMapping:
  27303. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  27304. break;
  27305. case CubeUVReflectionMapping:
  27306. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  27307. break;
  27308. }
  27309. }
  27310. return envMapTypeDefine;
  27311. }
  27312. function generateEnvMapModeDefine( parameters ) {
  27313. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  27314. if ( parameters.envMap ) {
  27315. switch ( parameters.envMapMode ) {
  27316. case CubeRefractionMapping:
  27317. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  27318. break;
  27319. }
  27320. }
  27321. return envMapModeDefine;
  27322. }
  27323. function generateEnvMapBlendingDefine( parameters ) {
  27324. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  27325. if ( parameters.envMap ) {
  27326. switch ( parameters.combine ) {
  27327. case MultiplyOperation:
  27328. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  27329. break;
  27330. case MixOperation:
  27331. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  27332. break;
  27333. case AddOperation:
  27334. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  27335. break;
  27336. }
  27337. }
  27338. return envMapBlendingDefine;
  27339. }
  27340. function generateCubeUVSize( parameters ) {
  27341. const imageHeight = parameters.envMapCubeUVHeight;
  27342. if ( imageHeight === null ) return null;
  27343. const maxMip = Math.log2( imageHeight ) - 2;
  27344. const texelHeight = 1.0 / imageHeight;
  27345. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  27346. return { texelWidth, texelHeight, maxMip };
  27347. }
  27348. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  27349. // TODO Send this event to Three.js DevTools
  27350. // console.log( 'WebGLProgram', cacheKey );
  27351. const gl = renderer.getContext();
  27352. const defines = parameters.defines;
  27353. let vertexShader = parameters.vertexShader;
  27354. let fragmentShader = parameters.fragmentShader;
  27355. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  27356. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  27357. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  27358. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  27359. const envMapCubeUVSize = generateCubeUVSize( parameters );
  27360. const customVertexExtensions = generateVertexExtensions( parameters );
  27361. const customDefines = generateDefines( defines );
  27362. const program = gl.createProgram();
  27363. let prefixVertex, prefixFragment;
  27364. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  27365. if ( parameters.isRawShaderMaterial ) {
  27366. prefixVertex = [
  27367. '#define SHADER_TYPE ' + parameters.shaderType,
  27368. '#define SHADER_NAME ' + parameters.shaderName,
  27369. customDefines
  27370. ].filter( filterEmptyLine ).join( '\n' );
  27371. if ( prefixVertex.length > 0 ) {
  27372. prefixVertex += '\n';
  27373. }
  27374. prefixFragment = [
  27375. '#define SHADER_TYPE ' + parameters.shaderType,
  27376. '#define SHADER_NAME ' + parameters.shaderName,
  27377. customDefines
  27378. ].filter( filterEmptyLine ).join( '\n' );
  27379. if ( prefixFragment.length > 0 ) {
  27380. prefixFragment += '\n';
  27381. }
  27382. } else {
  27383. prefixVertex = [
  27384. generatePrecision( parameters ),
  27385. '#define SHADER_TYPE ' + parameters.shaderType,
  27386. '#define SHADER_NAME ' + parameters.shaderName,
  27387. customDefines,
  27388. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  27389. parameters.batching ? '#define USE_BATCHING' : '',
  27390. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  27391. parameters.instancing ? '#define USE_INSTANCING' : '',
  27392. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  27393. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  27394. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  27395. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  27396. parameters.map ? '#define USE_MAP' : '',
  27397. parameters.envMap ? '#define USE_ENVMAP' : '',
  27398. parameters.envMap ? '#define ' + envMapModeDefine : '',
  27399. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  27400. parameters.aoMap ? '#define USE_AOMAP' : '',
  27401. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  27402. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  27403. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  27404. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  27405. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  27406. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  27407. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  27408. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  27409. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  27410. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  27411. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  27412. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  27413. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  27414. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  27415. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  27416. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  27417. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  27418. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  27419. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  27420. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  27421. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  27422. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  27423. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  27424. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  27425. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  27426. //
  27427. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  27428. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  27429. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  27430. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  27431. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  27432. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  27433. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  27434. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  27435. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  27436. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  27437. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  27438. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  27439. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  27440. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  27441. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  27442. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  27443. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  27444. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  27445. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  27446. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  27447. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  27448. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  27449. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  27450. //
  27451. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  27452. parameters.vertexColors ? '#define USE_COLOR' : '',
  27453. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  27454. parameters.vertexUv1s ? '#define USE_UV1' : '',
  27455. parameters.vertexUv2s ? '#define USE_UV2' : '',
  27456. parameters.vertexUv3s ? '#define USE_UV3' : '',
  27457. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  27458. parameters.flatShading ? '#define FLAT_SHADED' : '',
  27459. parameters.skinning ? '#define USE_SKINNING' : '',
  27460. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  27461. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  27462. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  27463. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  27464. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  27465. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  27466. parameters.flipSided ? '#define FLIP_SIDED' : '',
  27467. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  27468. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  27469. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  27470. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  27471. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  27472. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  27473. 'uniform mat4 modelMatrix;',
  27474. 'uniform mat4 modelViewMatrix;',
  27475. 'uniform mat4 projectionMatrix;',
  27476. 'uniform mat4 viewMatrix;',
  27477. 'uniform mat3 normalMatrix;',
  27478. 'uniform vec3 cameraPosition;',
  27479. 'uniform bool isOrthographic;',
  27480. '#ifdef USE_INSTANCING',
  27481. ' attribute mat4 instanceMatrix;',
  27482. '#endif',
  27483. '#ifdef USE_INSTANCING_COLOR',
  27484. ' attribute vec3 instanceColor;',
  27485. '#endif',
  27486. '#ifdef USE_INSTANCING_MORPH',
  27487. ' uniform sampler2D morphTexture;',
  27488. '#endif',
  27489. 'attribute vec3 position;',
  27490. 'attribute vec3 normal;',
  27491. 'attribute vec2 uv;',
  27492. '#ifdef USE_UV1',
  27493. ' attribute vec2 uv1;',
  27494. '#endif',
  27495. '#ifdef USE_UV2',
  27496. ' attribute vec2 uv2;',
  27497. '#endif',
  27498. '#ifdef USE_UV3',
  27499. ' attribute vec2 uv3;',
  27500. '#endif',
  27501. '#ifdef USE_TANGENT',
  27502. ' attribute vec4 tangent;',
  27503. '#endif',
  27504. '#if defined( USE_COLOR_ALPHA )',
  27505. ' attribute vec4 color;',
  27506. '#elif defined( USE_COLOR )',
  27507. ' attribute vec3 color;',
  27508. '#endif',
  27509. '#ifdef USE_SKINNING',
  27510. ' attribute vec4 skinIndex;',
  27511. ' attribute vec4 skinWeight;',
  27512. '#endif',
  27513. '\n'
  27514. ].filter( filterEmptyLine ).join( '\n' );
  27515. prefixFragment = [
  27516. generatePrecision( parameters ),
  27517. '#define SHADER_TYPE ' + parameters.shaderType,
  27518. '#define SHADER_NAME ' + parameters.shaderName,
  27519. customDefines,
  27520. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  27521. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  27522. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  27523. parameters.map ? '#define USE_MAP' : '',
  27524. parameters.matcap ? '#define USE_MATCAP' : '',
  27525. parameters.envMap ? '#define USE_ENVMAP' : '',
  27526. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  27527. parameters.envMap ? '#define ' + envMapModeDefine : '',
  27528. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  27529. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  27530. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  27531. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  27532. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  27533. parameters.aoMap ? '#define USE_AOMAP' : '',
  27534. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  27535. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  27536. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  27537. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  27538. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  27539. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  27540. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  27541. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  27542. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  27543. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  27544. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  27545. parameters.dispersion ? '#define USE_DISPERSION' : '',
  27546. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  27547. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  27548. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  27549. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  27550. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  27551. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  27552. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  27553. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  27554. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  27555. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  27556. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  27557. parameters.sheen ? '#define USE_SHEEN' : '',
  27558. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  27559. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  27560. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  27561. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  27562. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  27563. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  27564. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  27565. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  27566. parameters.vertexUv1s ? '#define USE_UV1' : '',
  27567. parameters.vertexUv2s ? '#define USE_UV2' : '',
  27568. parameters.vertexUv3s ? '#define USE_UV3' : '',
  27569. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  27570. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  27571. parameters.flatShading ? '#define FLAT_SHADED' : '',
  27572. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  27573. parameters.flipSided ? '#define FLIP_SIDED' : '',
  27574. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  27575. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  27576. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  27577. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  27578. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  27579. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  27580. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  27581. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  27582. 'uniform mat4 viewMatrix;',
  27583. 'uniform vec3 cameraPosition;',
  27584. 'uniform bool isOrthographic;',
  27585. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  27586. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  27587. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  27588. parameters.dithering ? '#define DITHERING' : '',
  27589. parameters.opaque ? '#define OPAQUE' : '',
  27590. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  27591. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  27592. getLuminanceFunction(),
  27593. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  27594. '\n'
  27595. ].filter( filterEmptyLine ).join( '\n' );
  27596. }
  27597. vertexShader = resolveIncludes( vertexShader );
  27598. vertexShader = replaceLightNums( vertexShader, parameters );
  27599. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  27600. fragmentShader = resolveIncludes( fragmentShader );
  27601. fragmentShader = replaceLightNums( fragmentShader, parameters );
  27602. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  27603. vertexShader = unrollLoops( vertexShader );
  27604. fragmentShader = unrollLoops( fragmentShader );
  27605. if ( parameters.isRawShaderMaterial !== true ) {
  27606. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  27607. versionString = '#version 300 es\n';
  27608. prefixVertex = [
  27609. customVertexExtensions,
  27610. '#define attribute in',
  27611. '#define varying out',
  27612. '#define texture2D texture'
  27613. ].join( '\n' ) + '\n' + prefixVertex;
  27614. prefixFragment = [
  27615. '#define varying in',
  27616. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  27617. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  27618. '#define gl_FragDepthEXT gl_FragDepth',
  27619. '#define texture2D texture',
  27620. '#define textureCube texture',
  27621. '#define texture2DProj textureProj',
  27622. '#define texture2DLodEXT textureLod',
  27623. '#define texture2DProjLodEXT textureProjLod',
  27624. '#define textureCubeLodEXT textureLod',
  27625. '#define texture2DGradEXT textureGrad',
  27626. '#define texture2DProjGradEXT textureProjGrad',
  27627. '#define textureCubeGradEXT textureGrad'
  27628. ].join( '\n' ) + '\n' + prefixFragment;
  27629. }
  27630. const vertexGlsl = versionString + prefixVertex + vertexShader;
  27631. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  27632. // console.log( '*VERTEX*', vertexGlsl );
  27633. // console.log( '*FRAGMENT*', fragmentGlsl );
  27634. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  27635. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  27636. gl.attachShader( program, glVertexShader );
  27637. gl.attachShader( program, glFragmentShader );
  27638. // Force a particular attribute to index 0.
  27639. if ( parameters.index0AttributeName !== undefined ) {
  27640. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  27641. } else if ( parameters.morphTargets === true ) {
  27642. // programs with morphTargets displace position out of attribute 0
  27643. gl.bindAttribLocation( program, 0, 'position' );
  27644. }
  27645. gl.linkProgram( program );
  27646. function onFirstUse( self ) {
  27647. // check for link errors
  27648. if ( renderer.debug.checkShaderErrors ) {
  27649. const programLog = gl.getProgramInfoLog( program ).trim();
  27650. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  27651. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  27652. let runnable = true;
  27653. let haveDiagnostics = true;
  27654. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  27655. runnable = false;
  27656. if ( typeof renderer.debug.onShaderError === 'function' ) {
  27657. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  27658. } else {
  27659. // default error reporting
  27660. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  27661. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  27662. console.error(
  27663. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  27664. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  27665. 'Material Name: ' + self.name + '\n' +
  27666. 'Material Type: ' + self.type + '\n\n' +
  27667. 'Program Info Log: ' + programLog + '\n' +
  27668. vertexErrors + '\n' +
  27669. fragmentErrors
  27670. );
  27671. }
  27672. } else if ( programLog !== '' ) {
  27673. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  27674. } else if ( vertexLog === '' || fragmentLog === '' ) {
  27675. haveDiagnostics = false;
  27676. }
  27677. if ( haveDiagnostics ) {
  27678. self.diagnostics = {
  27679. runnable: runnable,
  27680. programLog: programLog,
  27681. vertexShader: {
  27682. log: vertexLog,
  27683. prefix: prefixVertex
  27684. },
  27685. fragmentShader: {
  27686. log: fragmentLog,
  27687. prefix: prefixFragment
  27688. }
  27689. };
  27690. }
  27691. }
  27692. // Clean up
  27693. // Crashes in iOS9 and iOS10. #18402
  27694. // gl.detachShader( program, glVertexShader );
  27695. // gl.detachShader( program, glFragmentShader );
  27696. gl.deleteShader( glVertexShader );
  27697. gl.deleteShader( glFragmentShader );
  27698. cachedUniforms = new WebGLUniforms( gl, program );
  27699. cachedAttributes = fetchAttributeLocations( gl, program );
  27700. }
  27701. // set up caching for uniform locations
  27702. let cachedUniforms;
  27703. this.getUniforms = function () {
  27704. if ( cachedUniforms === undefined ) {
  27705. // Populates cachedUniforms and cachedAttributes
  27706. onFirstUse( this );
  27707. }
  27708. return cachedUniforms;
  27709. };
  27710. // set up caching for attribute locations
  27711. let cachedAttributes;
  27712. this.getAttributes = function () {
  27713. if ( cachedAttributes === undefined ) {
  27714. // Populates cachedAttributes and cachedUniforms
  27715. onFirstUse( this );
  27716. }
  27717. return cachedAttributes;
  27718. };
  27719. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  27720. // flag the program as ready immediately. It may cause a stall when it's first used.
  27721. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  27722. this.isReady = function () {
  27723. if ( programReady === false ) {
  27724. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  27725. }
  27726. return programReady;
  27727. };
  27728. // free resource
  27729. this.destroy = function () {
  27730. bindingStates.releaseStatesOfProgram( this );
  27731. gl.deleteProgram( program );
  27732. this.program = undefined;
  27733. };
  27734. //
  27735. this.type = parameters.shaderType;
  27736. this.name = parameters.shaderName;
  27737. this.id = programIdCount ++;
  27738. this.cacheKey = cacheKey;
  27739. this.usedTimes = 1;
  27740. this.program = program;
  27741. this.vertexShader = glVertexShader;
  27742. this.fragmentShader = glFragmentShader;
  27743. return this;
  27744. }
  27745. let _id = 0;
  27746. class WebGLShaderCache {
  27747. constructor() {
  27748. this.shaderCache = new Map();
  27749. this.materialCache = new Map();
  27750. }
  27751. update( material ) {
  27752. const vertexShader = material.vertexShader;
  27753. const fragmentShader = material.fragmentShader;
  27754. const vertexShaderStage = this._getShaderStage( vertexShader );
  27755. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  27756. const materialShaders = this._getShaderCacheForMaterial( material );
  27757. if ( materialShaders.has( vertexShaderStage ) === false ) {
  27758. materialShaders.add( vertexShaderStage );
  27759. vertexShaderStage.usedTimes ++;
  27760. }
  27761. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  27762. materialShaders.add( fragmentShaderStage );
  27763. fragmentShaderStage.usedTimes ++;
  27764. }
  27765. return this;
  27766. }
  27767. remove( material ) {
  27768. const materialShaders = this.materialCache.get( material );
  27769. for ( const shaderStage of materialShaders ) {
  27770. shaderStage.usedTimes --;
  27771. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  27772. }
  27773. this.materialCache.delete( material );
  27774. return this;
  27775. }
  27776. getVertexShaderID( material ) {
  27777. return this._getShaderStage( material.vertexShader ).id;
  27778. }
  27779. getFragmentShaderID( material ) {
  27780. return this._getShaderStage( material.fragmentShader ).id;
  27781. }
  27782. dispose() {
  27783. this.shaderCache.clear();
  27784. this.materialCache.clear();
  27785. }
  27786. _getShaderCacheForMaterial( material ) {
  27787. const cache = this.materialCache;
  27788. let set = cache.get( material );
  27789. if ( set === undefined ) {
  27790. set = new Set();
  27791. cache.set( material, set );
  27792. }
  27793. return set;
  27794. }
  27795. _getShaderStage( code ) {
  27796. const cache = this.shaderCache;
  27797. let stage = cache.get( code );
  27798. if ( stage === undefined ) {
  27799. stage = new WebGLShaderStage( code );
  27800. cache.set( code, stage );
  27801. }
  27802. return stage;
  27803. }
  27804. }
  27805. class WebGLShaderStage {
  27806. constructor( code ) {
  27807. this.id = _id ++;
  27808. this.code = code;
  27809. this.usedTimes = 0;
  27810. }
  27811. }
  27812. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  27813. const _programLayers = new Layers();
  27814. const _customShaders = new WebGLShaderCache();
  27815. const _activeChannels = new Set();
  27816. const programs = [];
  27817. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  27818. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  27819. let precision = capabilities.precision;
  27820. const shaderIDs = {
  27821. MeshDepthMaterial: 'depth',
  27822. MeshDistanceMaterial: 'distanceRGBA',
  27823. MeshNormalMaterial: 'normal',
  27824. MeshBasicMaterial: 'basic',
  27825. MeshLambertMaterial: 'lambert',
  27826. MeshPhongMaterial: 'phong',
  27827. MeshToonMaterial: 'toon',
  27828. MeshStandardMaterial: 'physical',
  27829. MeshPhysicalMaterial: 'physical',
  27830. MeshMatcapMaterial: 'matcap',
  27831. LineBasicMaterial: 'basic',
  27832. LineDashedMaterial: 'dashed',
  27833. PointsMaterial: 'points',
  27834. ShadowMaterial: 'shadow',
  27835. SpriteMaterial: 'sprite'
  27836. };
  27837. function getChannel( value ) {
  27838. _activeChannels.add( value );
  27839. if ( value === 0 ) return 'uv';
  27840. return `uv${ value }`;
  27841. }
  27842. function getParameters( material, lights, shadows, scene, object ) {
  27843. const fog = scene.fog;
  27844. const geometry = object.geometry;
  27845. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  27846. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  27847. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  27848. const shaderID = shaderIDs[ material.type ];
  27849. // heuristics to create shader parameters according to lights in the scene
  27850. // (not to blow over maxLights budget)
  27851. if ( material.precision !== null ) {
  27852. precision = capabilities.getMaxPrecision( material.precision );
  27853. if ( precision !== material.precision ) {
  27854. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  27855. }
  27856. }
  27857. //
  27858. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  27859. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  27860. let morphTextureStride = 0;
  27861. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  27862. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  27863. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  27864. //
  27865. let vertexShader, fragmentShader;
  27866. let customVertexShaderID, customFragmentShaderID;
  27867. if ( shaderID ) {
  27868. const shader = ShaderLib[ shaderID ];
  27869. vertexShader = shader.vertexShader;
  27870. fragmentShader = shader.fragmentShader;
  27871. } else {
  27872. vertexShader = material.vertexShader;
  27873. fragmentShader = material.fragmentShader;
  27874. _customShaders.update( material );
  27875. customVertexShaderID = _customShaders.getVertexShaderID( material );
  27876. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  27877. }
  27878. const currentRenderTarget = renderer.getRenderTarget();
  27879. const reverseDepthBuffer = renderer.state.buffers.depth.getReversed();
  27880. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  27881. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  27882. const HAS_MAP = !! material.map;
  27883. const HAS_MATCAP = !! material.matcap;
  27884. const HAS_ENVMAP = !! envMap;
  27885. const HAS_AOMAP = !! material.aoMap;
  27886. const HAS_LIGHTMAP = !! material.lightMap;
  27887. const HAS_BUMPMAP = !! material.bumpMap;
  27888. const HAS_NORMALMAP = !! material.normalMap;
  27889. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  27890. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  27891. const HAS_METALNESSMAP = !! material.metalnessMap;
  27892. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  27893. const HAS_ANISOTROPY = material.anisotropy > 0;
  27894. const HAS_CLEARCOAT = material.clearcoat > 0;
  27895. const HAS_DISPERSION = material.dispersion > 0;
  27896. const HAS_IRIDESCENCE = material.iridescence > 0;
  27897. const HAS_SHEEN = material.sheen > 0;
  27898. const HAS_TRANSMISSION = material.transmission > 0;
  27899. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  27900. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  27901. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  27902. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  27903. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  27904. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  27905. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  27906. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  27907. const HAS_SPECULARMAP = !! material.specularMap;
  27908. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  27909. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  27910. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  27911. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  27912. const HAS_GRADIENTMAP = !! material.gradientMap;
  27913. const HAS_ALPHAMAP = !! material.alphaMap;
  27914. const HAS_ALPHATEST = material.alphaTest > 0;
  27915. const HAS_ALPHAHASH = !! material.alphaHash;
  27916. const HAS_EXTENSIONS = !! material.extensions;
  27917. let toneMapping = NoToneMapping;
  27918. if ( material.toneMapped ) {
  27919. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  27920. toneMapping = renderer.toneMapping;
  27921. }
  27922. }
  27923. const parameters = {
  27924. shaderID: shaderID,
  27925. shaderType: material.type,
  27926. shaderName: material.name,
  27927. vertexShader: vertexShader,
  27928. fragmentShader: fragmentShader,
  27929. defines: material.defines,
  27930. customVertexShaderID: customVertexShaderID,
  27931. customFragmentShaderID: customFragmentShaderID,
  27932. isRawShaderMaterial: material.isRawShaderMaterial === true,
  27933. glslVersion: material.glslVersion,
  27934. precision: precision,
  27935. batching: IS_BATCHEDMESH,
  27936. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  27937. instancing: IS_INSTANCEDMESH,
  27938. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  27939. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  27940. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  27941. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  27942. alphaToCoverage: !! material.alphaToCoverage,
  27943. map: HAS_MAP,
  27944. matcap: HAS_MATCAP,
  27945. envMap: HAS_ENVMAP,
  27946. envMapMode: HAS_ENVMAP && envMap.mapping,
  27947. envMapCubeUVHeight: envMapCubeUVHeight,
  27948. aoMap: HAS_AOMAP,
  27949. lightMap: HAS_LIGHTMAP,
  27950. bumpMap: HAS_BUMPMAP,
  27951. normalMap: HAS_NORMALMAP,
  27952. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  27953. emissiveMap: HAS_EMISSIVEMAP,
  27954. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  27955. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  27956. metalnessMap: HAS_METALNESSMAP,
  27957. roughnessMap: HAS_ROUGHNESSMAP,
  27958. anisotropy: HAS_ANISOTROPY,
  27959. anisotropyMap: HAS_ANISOTROPYMAP,
  27960. clearcoat: HAS_CLEARCOAT,
  27961. clearcoatMap: HAS_CLEARCOATMAP,
  27962. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  27963. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  27964. dispersion: HAS_DISPERSION,
  27965. iridescence: HAS_IRIDESCENCE,
  27966. iridescenceMap: HAS_IRIDESCENCEMAP,
  27967. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  27968. sheen: HAS_SHEEN,
  27969. sheenColorMap: HAS_SHEEN_COLORMAP,
  27970. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  27971. specularMap: HAS_SPECULARMAP,
  27972. specularColorMap: HAS_SPECULAR_COLORMAP,
  27973. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  27974. transmission: HAS_TRANSMISSION,
  27975. transmissionMap: HAS_TRANSMISSIONMAP,
  27976. thicknessMap: HAS_THICKNESSMAP,
  27977. gradientMap: HAS_GRADIENTMAP,
  27978. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  27979. alphaMap: HAS_ALPHAMAP,
  27980. alphaTest: HAS_ALPHATEST,
  27981. alphaHash: HAS_ALPHAHASH,
  27982. combine: material.combine,
  27983. //
  27984. mapUv: HAS_MAP && getChannel( material.map.channel ),
  27985. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  27986. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  27987. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  27988. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  27989. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  27990. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  27991. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  27992. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  27993. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  27994. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  27995. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  27996. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  27997. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  27998. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  27999. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  28000. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  28001. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  28002. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  28003. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  28004. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  28005. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  28006. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  28007. //
  28008. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  28009. vertexColors: material.vertexColors,
  28010. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  28011. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  28012. fog: !! fog,
  28013. useFog: material.fog === true,
  28014. fogExp2: ( !! fog && fog.isFogExp2 ),
  28015. flatShading: material.flatShading === true,
  28016. sizeAttenuation: material.sizeAttenuation === true,
  28017. logarithmicDepthBuffer: logarithmicDepthBuffer,
  28018. reverseDepthBuffer: reverseDepthBuffer,
  28019. skinning: object.isSkinnedMesh === true,
  28020. morphTargets: geometry.morphAttributes.position !== undefined,
  28021. morphNormals: geometry.morphAttributes.normal !== undefined,
  28022. morphColors: geometry.morphAttributes.color !== undefined,
  28023. morphTargetsCount: morphTargetsCount,
  28024. morphTextureStride: morphTextureStride,
  28025. numDirLights: lights.directional.length,
  28026. numPointLights: lights.point.length,
  28027. numSpotLights: lights.spot.length,
  28028. numSpotLightMaps: lights.spotLightMap.length,
  28029. numRectAreaLights: lights.rectArea.length,
  28030. numHemiLights: lights.hemi.length,
  28031. numDirLightShadows: lights.directionalShadowMap.length,
  28032. numPointLightShadows: lights.pointShadowMap.length,
  28033. numSpotLightShadows: lights.spotShadowMap.length,
  28034. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  28035. numLightProbes: lights.numLightProbes,
  28036. numClippingPlanes: clipping.numPlanes,
  28037. numClipIntersection: clipping.numIntersection,
  28038. dithering: material.dithering,
  28039. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  28040. shadowMapType: renderer.shadowMap.type,
  28041. toneMapping: toneMapping,
  28042. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  28043. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  28044. premultipliedAlpha: material.premultipliedAlpha,
  28045. doubleSided: material.side === DoubleSide,
  28046. flipSided: material.side === BackSide,
  28047. useDepthPacking: material.depthPacking >= 0,
  28048. depthPacking: material.depthPacking || 0,
  28049. index0AttributeName: material.index0AttributeName,
  28050. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  28051. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  28052. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  28053. customProgramCacheKey: material.customProgramCacheKey()
  28054. };
  28055. // the usage of getChannel() determines the active texture channels for this shader
  28056. parameters.vertexUv1s = _activeChannels.has( 1 );
  28057. parameters.vertexUv2s = _activeChannels.has( 2 );
  28058. parameters.vertexUv3s = _activeChannels.has( 3 );
  28059. _activeChannels.clear();
  28060. return parameters;
  28061. }
  28062. function getProgramCacheKey( parameters ) {
  28063. const array = [];
  28064. if ( parameters.shaderID ) {
  28065. array.push( parameters.shaderID );
  28066. } else {
  28067. array.push( parameters.customVertexShaderID );
  28068. array.push( parameters.customFragmentShaderID );
  28069. }
  28070. if ( parameters.defines !== undefined ) {
  28071. for ( const name in parameters.defines ) {
  28072. array.push( name );
  28073. array.push( parameters.defines[ name ] );
  28074. }
  28075. }
  28076. if ( parameters.isRawShaderMaterial === false ) {
  28077. getProgramCacheKeyParameters( array, parameters );
  28078. getProgramCacheKeyBooleans( array, parameters );
  28079. array.push( renderer.outputColorSpace );
  28080. }
  28081. array.push( parameters.customProgramCacheKey );
  28082. return array.join();
  28083. }
  28084. function getProgramCacheKeyParameters( array, parameters ) {
  28085. array.push( parameters.precision );
  28086. array.push( parameters.outputColorSpace );
  28087. array.push( parameters.envMapMode );
  28088. array.push( parameters.envMapCubeUVHeight );
  28089. array.push( parameters.mapUv );
  28090. array.push( parameters.alphaMapUv );
  28091. array.push( parameters.lightMapUv );
  28092. array.push( parameters.aoMapUv );
  28093. array.push( parameters.bumpMapUv );
  28094. array.push( parameters.normalMapUv );
  28095. array.push( parameters.displacementMapUv );
  28096. array.push( parameters.emissiveMapUv );
  28097. array.push( parameters.metalnessMapUv );
  28098. array.push( parameters.roughnessMapUv );
  28099. array.push( parameters.anisotropyMapUv );
  28100. array.push( parameters.clearcoatMapUv );
  28101. array.push( parameters.clearcoatNormalMapUv );
  28102. array.push( parameters.clearcoatRoughnessMapUv );
  28103. array.push( parameters.iridescenceMapUv );
  28104. array.push( parameters.iridescenceThicknessMapUv );
  28105. array.push( parameters.sheenColorMapUv );
  28106. array.push( parameters.sheenRoughnessMapUv );
  28107. array.push( parameters.specularMapUv );
  28108. array.push( parameters.specularColorMapUv );
  28109. array.push( parameters.specularIntensityMapUv );
  28110. array.push( parameters.transmissionMapUv );
  28111. array.push( parameters.thicknessMapUv );
  28112. array.push( parameters.combine );
  28113. array.push( parameters.fogExp2 );
  28114. array.push( parameters.sizeAttenuation );
  28115. array.push( parameters.morphTargetsCount );
  28116. array.push( parameters.morphAttributeCount );
  28117. array.push( parameters.numDirLights );
  28118. array.push( parameters.numPointLights );
  28119. array.push( parameters.numSpotLights );
  28120. array.push( parameters.numSpotLightMaps );
  28121. array.push( parameters.numHemiLights );
  28122. array.push( parameters.numRectAreaLights );
  28123. array.push( parameters.numDirLightShadows );
  28124. array.push( parameters.numPointLightShadows );
  28125. array.push( parameters.numSpotLightShadows );
  28126. array.push( parameters.numSpotLightShadowsWithMaps );
  28127. array.push( parameters.numLightProbes );
  28128. array.push( parameters.shadowMapType );
  28129. array.push( parameters.toneMapping );
  28130. array.push( parameters.numClippingPlanes );
  28131. array.push( parameters.numClipIntersection );
  28132. array.push( parameters.depthPacking );
  28133. }
  28134. function getProgramCacheKeyBooleans( array, parameters ) {
  28135. _programLayers.disableAll();
  28136. if ( parameters.supportsVertexTextures )
  28137. _programLayers.enable( 0 );
  28138. if ( parameters.instancing )
  28139. _programLayers.enable( 1 );
  28140. if ( parameters.instancingColor )
  28141. _programLayers.enable( 2 );
  28142. if ( parameters.instancingMorph )
  28143. _programLayers.enable( 3 );
  28144. if ( parameters.matcap )
  28145. _programLayers.enable( 4 );
  28146. if ( parameters.envMap )
  28147. _programLayers.enable( 5 );
  28148. if ( parameters.normalMapObjectSpace )
  28149. _programLayers.enable( 6 );
  28150. if ( parameters.normalMapTangentSpace )
  28151. _programLayers.enable( 7 );
  28152. if ( parameters.clearcoat )
  28153. _programLayers.enable( 8 );
  28154. if ( parameters.iridescence )
  28155. _programLayers.enable( 9 );
  28156. if ( parameters.alphaTest )
  28157. _programLayers.enable( 10 );
  28158. if ( parameters.vertexColors )
  28159. _programLayers.enable( 11 );
  28160. if ( parameters.vertexAlphas )
  28161. _programLayers.enable( 12 );
  28162. if ( parameters.vertexUv1s )
  28163. _programLayers.enable( 13 );
  28164. if ( parameters.vertexUv2s )
  28165. _programLayers.enable( 14 );
  28166. if ( parameters.vertexUv3s )
  28167. _programLayers.enable( 15 );
  28168. if ( parameters.vertexTangents )
  28169. _programLayers.enable( 16 );
  28170. if ( parameters.anisotropy )
  28171. _programLayers.enable( 17 );
  28172. if ( parameters.alphaHash )
  28173. _programLayers.enable( 18 );
  28174. if ( parameters.batching )
  28175. _programLayers.enable( 19 );
  28176. if ( parameters.dispersion )
  28177. _programLayers.enable( 20 );
  28178. if ( parameters.batchingColor )
  28179. _programLayers.enable( 21 );
  28180. array.push( _programLayers.mask );
  28181. _programLayers.disableAll();
  28182. if ( parameters.fog )
  28183. _programLayers.enable( 0 );
  28184. if ( parameters.useFog )
  28185. _programLayers.enable( 1 );
  28186. if ( parameters.flatShading )
  28187. _programLayers.enable( 2 );
  28188. if ( parameters.logarithmicDepthBuffer )
  28189. _programLayers.enable( 3 );
  28190. if ( parameters.reverseDepthBuffer )
  28191. _programLayers.enable( 4 );
  28192. if ( parameters.skinning )
  28193. _programLayers.enable( 5 );
  28194. if ( parameters.morphTargets )
  28195. _programLayers.enable( 6 );
  28196. if ( parameters.morphNormals )
  28197. _programLayers.enable( 7 );
  28198. if ( parameters.morphColors )
  28199. _programLayers.enable( 8 );
  28200. if ( parameters.premultipliedAlpha )
  28201. _programLayers.enable( 9 );
  28202. if ( parameters.shadowMapEnabled )
  28203. _programLayers.enable( 10 );
  28204. if ( parameters.doubleSided )
  28205. _programLayers.enable( 11 );
  28206. if ( parameters.flipSided )
  28207. _programLayers.enable( 12 );
  28208. if ( parameters.useDepthPacking )
  28209. _programLayers.enable( 13 );
  28210. if ( parameters.dithering )
  28211. _programLayers.enable( 14 );
  28212. if ( parameters.transmission )
  28213. _programLayers.enable( 15 );
  28214. if ( parameters.sheen )
  28215. _programLayers.enable( 16 );
  28216. if ( parameters.opaque )
  28217. _programLayers.enable( 17 );
  28218. if ( parameters.pointsUvs )
  28219. _programLayers.enable( 18 );
  28220. if ( parameters.decodeVideoTexture )
  28221. _programLayers.enable( 19 );
  28222. if ( parameters.decodeVideoTextureEmissive )
  28223. _programLayers.enable( 20 );
  28224. if ( parameters.alphaToCoverage )
  28225. _programLayers.enable( 21 );
  28226. array.push( _programLayers.mask );
  28227. }
  28228. function getUniforms( material ) {
  28229. const shaderID = shaderIDs[ material.type ];
  28230. let uniforms;
  28231. if ( shaderID ) {
  28232. const shader = ShaderLib[ shaderID ];
  28233. uniforms = UniformsUtils.clone( shader.uniforms );
  28234. } else {
  28235. uniforms = material.uniforms;
  28236. }
  28237. return uniforms;
  28238. }
  28239. function acquireProgram( parameters, cacheKey ) {
  28240. let program;
  28241. // Check if code has been already compiled
  28242. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  28243. const preexistingProgram = programs[ p ];
  28244. if ( preexistingProgram.cacheKey === cacheKey ) {
  28245. program = preexistingProgram;
  28246. ++ program.usedTimes;
  28247. break;
  28248. }
  28249. }
  28250. if ( program === undefined ) {
  28251. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  28252. programs.push( program );
  28253. }
  28254. return program;
  28255. }
  28256. function releaseProgram( program ) {
  28257. if ( -- program.usedTimes === 0 ) {
  28258. // Remove from unordered set
  28259. const i = programs.indexOf( program );
  28260. programs[ i ] = programs[ programs.length - 1 ];
  28261. programs.pop();
  28262. // Free WebGL resources
  28263. program.destroy();
  28264. }
  28265. }
  28266. function releaseShaderCache( material ) {
  28267. _customShaders.remove( material );
  28268. }
  28269. function dispose() {
  28270. _customShaders.dispose();
  28271. }
  28272. return {
  28273. getParameters: getParameters,
  28274. getProgramCacheKey: getProgramCacheKey,
  28275. getUniforms: getUniforms,
  28276. acquireProgram: acquireProgram,
  28277. releaseProgram: releaseProgram,
  28278. releaseShaderCache: releaseShaderCache,
  28279. // Exposed for resource monitoring & error feedback via renderer.info:
  28280. programs: programs,
  28281. dispose: dispose
  28282. };
  28283. }
  28284. function WebGLProperties() {
  28285. let properties = new WeakMap();
  28286. function has( object ) {
  28287. return properties.has( object );
  28288. }
  28289. function get( object ) {
  28290. let map = properties.get( object );
  28291. if ( map === undefined ) {
  28292. map = {};
  28293. properties.set( object, map );
  28294. }
  28295. return map;
  28296. }
  28297. function remove( object ) {
  28298. properties.delete( object );
  28299. }
  28300. function update( object, key, value ) {
  28301. properties.get( object )[ key ] = value;
  28302. }
  28303. function dispose() {
  28304. properties = new WeakMap();
  28305. }
  28306. return {
  28307. has: has,
  28308. get: get,
  28309. remove: remove,
  28310. update: update,
  28311. dispose: dispose
  28312. };
  28313. }
  28314. function painterSortStable( a, b ) {
  28315. if ( a.groupOrder !== b.groupOrder ) {
  28316. return a.groupOrder - b.groupOrder;
  28317. } else if ( a.renderOrder !== b.renderOrder ) {
  28318. return a.renderOrder - b.renderOrder;
  28319. } else if ( a.material.id !== b.material.id ) {
  28320. return a.material.id - b.material.id;
  28321. } else if ( a.z !== b.z ) {
  28322. return a.z - b.z;
  28323. } else {
  28324. return a.id - b.id;
  28325. }
  28326. }
  28327. function reversePainterSortStable( a, b ) {
  28328. if ( a.groupOrder !== b.groupOrder ) {
  28329. return a.groupOrder - b.groupOrder;
  28330. } else if ( a.renderOrder !== b.renderOrder ) {
  28331. return a.renderOrder - b.renderOrder;
  28332. } else if ( a.z !== b.z ) {
  28333. return b.z - a.z;
  28334. } else {
  28335. return a.id - b.id;
  28336. }
  28337. }
  28338. function WebGLRenderList() {
  28339. const renderItems = [];
  28340. let renderItemsIndex = 0;
  28341. const opaque = [];
  28342. const transmissive = [];
  28343. const transparent = [];
  28344. function init() {
  28345. renderItemsIndex = 0;
  28346. opaque.length = 0;
  28347. transmissive.length = 0;
  28348. transparent.length = 0;
  28349. }
  28350. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  28351. let renderItem = renderItems[ renderItemsIndex ];
  28352. if ( renderItem === undefined ) {
  28353. renderItem = {
  28354. id: object.id,
  28355. object: object,
  28356. geometry: geometry,
  28357. material: material,
  28358. groupOrder: groupOrder,
  28359. renderOrder: object.renderOrder,
  28360. z: z,
  28361. group: group
  28362. };
  28363. renderItems[ renderItemsIndex ] = renderItem;
  28364. } else {
  28365. renderItem.id = object.id;
  28366. renderItem.object = object;
  28367. renderItem.geometry = geometry;
  28368. renderItem.material = material;
  28369. renderItem.groupOrder = groupOrder;
  28370. renderItem.renderOrder = object.renderOrder;
  28371. renderItem.z = z;
  28372. renderItem.group = group;
  28373. }
  28374. renderItemsIndex ++;
  28375. return renderItem;
  28376. }
  28377. function push( object, geometry, material, groupOrder, z, group ) {
  28378. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  28379. if ( material.transmission > 0.0 ) {
  28380. transmissive.push( renderItem );
  28381. } else if ( material.transparent === true ) {
  28382. transparent.push( renderItem );
  28383. } else {
  28384. opaque.push( renderItem );
  28385. }
  28386. }
  28387. function unshift( object, geometry, material, groupOrder, z, group ) {
  28388. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  28389. if ( material.transmission > 0.0 ) {
  28390. transmissive.unshift( renderItem );
  28391. } else if ( material.transparent === true ) {
  28392. transparent.unshift( renderItem );
  28393. } else {
  28394. opaque.unshift( renderItem );
  28395. }
  28396. }
  28397. function sort( customOpaqueSort, customTransparentSort ) {
  28398. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  28399. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  28400. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  28401. }
  28402. function finish() {
  28403. // Clear references from inactive renderItems in the list
  28404. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  28405. const renderItem = renderItems[ i ];
  28406. if ( renderItem.id === null ) break;
  28407. renderItem.id = null;
  28408. renderItem.object = null;
  28409. renderItem.geometry = null;
  28410. renderItem.material = null;
  28411. renderItem.group = null;
  28412. }
  28413. }
  28414. return {
  28415. opaque: opaque,
  28416. transmissive: transmissive,
  28417. transparent: transparent,
  28418. init: init,
  28419. push: push,
  28420. unshift: unshift,
  28421. finish: finish,
  28422. sort: sort
  28423. };
  28424. }
  28425. function WebGLRenderLists() {
  28426. let lists = new WeakMap();
  28427. function get( scene, renderCallDepth ) {
  28428. const listArray = lists.get( scene );
  28429. let list;
  28430. if ( listArray === undefined ) {
  28431. list = new WebGLRenderList();
  28432. lists.set( scene, [ list ] );
  28433. } else {
  28434. if ( renderCallDepth >= listArray.length ) {
  28435. list = new WebGLRenderList();
  28436. listArray.push( list );
  28437. } else {
  28438. list = listArray[ renderCallDepth ];
  28439. }
  28440. }
  28441. return list;
  28442. }
  28443. function dispose() {
  28444. lists = new WeakMap();
  28445. }
  28446. return {
  28447. get: get,
  28448. dispose: dispose
  28449. };
  28450. }
  28451. function UniformsCache() {
  28452. const lights = {};
  28453. return {
  28454. get: function ( light ) {
  28455. if ( lights[ light.id ] !== undefined ) {
  28456. return lights[ light.id ];
  28457. }
  28458. let uniforms;
  28459. switch ( light.type ) {
  28460. case 'DirectionalLight':
  28461. uniforms = {
  28462. direction: new Vector3(),
  28463. color: new Color()
  28464. };
  28465. break;
  28466. case 'SpotLight':
  28467. uniforms = {
  28468. position: new Vector3(),
  28469. direction: new Vector3(),
  28470. color: new Color(),
  28471. distance: 0,
  28472. coneCos: 0,
  28473. penumbraCos: 0,
  28474. decay: 0
  28475. };
  28476. break;
  28477. case 'PointLight':
  28478. uniforms = {
  28479. position: new Vector3(),
  28480. color: new Color(),
  28481. distance: 0,
  28482. decay: 0
  28483. };
  28484. break;
  28485. case 'HemisphereLight':
  28486. uniforms = {
  28487. direction: new Vector3(),
  28488. skyColor: new Color(),
  28489. groundColor: new Color()
  28490. };
  28491. break;
  28492. case 'RectAreaLight':
  28493. uniforms = {
  28494. color: new Color(),
  28495. position: new Vector3(),
  28496. halfWidth: new Vector3(),
  28497. halfHeight: new Vector3()
  28498. };
  28499. break;
  28500. }
  28501. lights[ light.id ] = uniforms;
  28502. return uniforms;
  28503. }
  28504. };
  28505. }
  28506. function ShadowUniformsCache() {
  28507. const lights = {};
  28508. return {
  28509. get: function ( light ) {
  28510. if ( lights[ light.id ] !== undefined ) {
  28511. return lights[ light.id ];
  28512. }
  28513. let uniforms;
  28514. switch ( light.type ) {
  28515. case 'DirectionalLight':
  28516. uniforms = {
  28517. shadowIntensity: 1,
  28518. shadowBias: 0,
  28519. shadowNormalBias: 0,
  28520. shadowRadius: 1,
  28521. shadowMapSize: new Vector2()
  28522. };
  28523. break;
  28524. case 'SpotLight':
  28525. uniforms = {
  28526. shadowIntensity: 1,
  28527. shadowBias: 0,
  28528. shadowNormalBias: 0,
  28529. shadowRadius: 1,
  28530. shadowMapSize: new Vector2()
  28531. };
  28532. break;
  28533. case 'PointLight':
  28534. uniforms = {
  28535. shadowIntensity: 1,
  28536. shadowBias: 0,
  28537. shadowNormalBias: 0,
  28538. shadowRadius: 1,
  28539. shadowMapSize: new Vector2(),
  28540. shadowCameraNear: 1,
  28541. shadowCameraFar: 1000
  28542. };
  28543. break;
  28544. // TODO (abelnation): set RectAreaLight shadow uniforms
  28545. }
  28546. lights[ light.id ] = uniforms;
  28547. return uniforms;
  28548. }
  28549. };
  28550. }
  28551. let nextVersion = 0;
  28552. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  28553. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  28554. }
  28555. function WebGLLights( extensions ) {
  28556. const cache = new UniformsCache();
  28557. const shadowCache = ShadowUniformsCache();
  28558. const state = {
  28559. version: 0,
  28560. hash: {
  28561. directionalLength: -1,
  28562. pointLength: -1,
  28563. spotLength: -1,
  28564. rectAreaLength: -1,
  28565. hemiLength: -1,
  28566. numDirectionalShadows: -1,
  28567. numPointShadows: -1,
  28568. numSpotShadows: -1,
  28569. numSpotMaps: -1,
  28570. numLightProbes: -1
  28571. },
  28572. ambient: [ 0, 0, 0 ],
  28573. probe: [],
  28574. directional: [],
  28575. directionalShadow: [],
  28576. directionalShadowMap: [],
  28577. directionalShadowMatrix: [],
  28578. spot: [],
  28579. spotLightMap: [],
  28580. spotShadow: [],
  28581. spotShadowMap: [],
  28582. spotLightMatrix: [],
  28583. rectArea: [],
  28584. rectAreaLTC1: null,
  28585. rectAreaLTC2: null,
  28586. point: [],
  28587. pointShadow: [],
  28588. pointShadowMap: [],
  28589. pointShadowMatrix: [],
  28590. hemi: [],
  28591. numSpotLightShadowsWithMaps: 0,
  28592. numLightProbes: 0
  28593. };
  28594. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  28595. const vector3 = new Vector3();
  28596. const matrix4 = new Matrix4();
  28597. const matrix42 = new Matrix4();
  28598. function setup( lights ) {
  28599. let r = 0, g = 0, b = 0;
  28600. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  28601. let directionalLength = 0;
  28602. let pointLength = 0;
  28603. let spotLength = 0;
  28604. let rectAreaLength = 0;
  28605. let hemiLength = 0;
  28606. let numDirectionalShadows = 0;
  28607. let numPointShadows = 0;
  28608. let numSpotShadows = 0;
  28609. let numSpotMaps = 0;
  28610. let numSpotShadowsWithMaps = 0;
  28611. let numLightProbes = 0;
  28612. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  28613. lights.sort( shadowCastingAndTexturingLightsFirst );
  28614. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  28615. const light = lights[ i ];
  28616. const color = light.color;
  28617. const intensity = light.intensity;
  28618. const distance = light.distance;
  28619. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  28620. if ( light.isAmbientLight ) {
  28621. r += color.r * intensity;
  28622. g += color.g * intensity;
  28623. b += color.b * intensity;
  28624. } else if ( light.isLightProbe ) {
  28625. for ( let j = 0; j < 9; j ++ ) {
  28626. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  28627. }
  28628. numLightProbes ++;
  28629. } else if ( light.isDirectionalLight ) {
  28630. const uniforms = cache.get( light );
  28631. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  28632. if ( light.castShadow ) {
  28633. const shadow = light.shadow;
  28634. const shadowUniforms = shadowCache.get( light );
  28635. shadowUniforms.shadowIntensity = shadow.intensity;
  28636. shadowUniforms.shadowBias = shadow.bias;
  28637. shadowUniforms.shadowNormalBias = shadow.normalBias;
  28638. shadowUniforms.shadowRadius = shadow.radius;
  28639. shadowUniforms.shadowMapSize = shadow.mapSize;
  28640. state.directionalShadow[ directionalLength ] = shadowUniforms;
  28641. state.directionalShadowMap[ directionalLength ] = shadowMap;
  28642. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  28643. numDirectionalShadows ++;
  28644. }
  28645. state.directional[ directionalLength ] = uniforms;
  28646. directionalLength ++;
  28647. } else if ( light.isSpotLight ) {
  28648. const uniforms = cache.get( light );
  28649. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  28650. uniforms.color.copy( color ).multiplyScalar( intensity );
  28651. uniforms.distance = distance;
  28652. uniforms.coneCos = Math.cos( light.angle );
  28653. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  28654. uniforms.decay = light.decay;
  28655. state.spot[ spotLength ] = uniforms;
  28656. const shadow = light.shadow;
  28657. if ( light.map ) {
  28658. state.spotLightMap[ numSpotMaps ] = light.map;
  28659. numSpotMaps ++;
  28660. // make sure the lightMatrix is up to date
  28661. // TODO : do it if required only
  28662. shadow.updateMatrices( light );
  28663. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  28664. }
  28665. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  28666. if ( light.castShadow ) {
  28667. const shadowUniforms = shadowCache.get( light );
  28668. shadowUniforms.shadowIntensity = shadow.intensity;
  28669. shadowUniforms.shadowBias = shadow.bias;
  28670. shadowUniforms.shadowNormalBias = shadow.normalBias;
  28671. shadowUniforms.shadowRadius = shadow.radius;
  28672. shadowUniforms.shadowMapSize = shadow.mapSize;
  28673. state.spotShadow[ spotLength ] = shadowUniforms;
  28674. state.spotShadowMap[ spotLength ] = shadowMap;
  28675. numSpotShadows ++;
  28676. }
  28677. spotLength ++;
  28678. } else if ( light.isRectAreaLight ) {
  28679. const uniforms = cache.get( light );
  28680. uniforms.color.copy( color ).multiplyScalar( intensity );
  28681. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  28682. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  28683. state.rectArea[ rectAreaLength ] = uniforms;
  28684. rectAreaLength ++;
  28685. } else if ( light.isPointLight ) {
  28686. const uniforms = cache.get( light );
  28687. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  28688. uniforms.distance = light.distance;
  28689. uniforms.decay = light.decay;
  28690. if ( light.castShadow ) {
  28691. const shadow = light.shadow;
  28692. const shadowUniforms = shadowCache.get( light );
  28693. shadowUniforms.shadowIntensity = shadow.intensity;
  28694. shadowUniforms.shadowBias = shadow.bias;
  28695. shadowUniforms.shadowNormalBias = shadow.normalBias;
  28696. shadowUniforms.shadowRadius = shadow.radius;
  28697. shadowUniforms.shadowMapSize = shadow.mapSize;
  28698. shadowUniforms.shadowCameraNear = shadow.camera.near;
  28699. shadowUniforms.shadowCameraFar = shadow.camera.far;
  28700. state.pointShadow[ pointLength ] = shadowUniforms;
  28701. state.pointShadowMap[ pointLength ] = shadowMap;
  28702. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  28703. numPointShadows ++;
  28704. }
  28705. state.point[ pointLength ] = uniforms;
  28706. pointLength ++;
  28707. } else if ( light.isHemisphereLight ) {
  28708. const uniforms = cache.get( light );
  28709. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  28710. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  28711. state.hemi[ hemiLength ] = uniforms;
  28712. hemiLength ++;
  28713. }
  28714. }
  28715. if ( rectAreaLength > 0 ) {
  28716. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  28717. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  28718. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  28719. } else {
  28720. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  28721. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  28722. }
  28723. }
  28724. state.ambient[ 0 ] = r;
  28725. state.ambient[ 1 ] = g;
  28726. state.ambient[ 2 ] = b;
  28727. const hash = state.hash;
  28728. if ( hash.directionalLength !== directionalLength ||
  28729. hash.pointLength !== pointLength ||
  28730. hash.spotLength !== spotLength ||
  28731. hash.rectAreaLength !== rectAreaLength ||
  28732. hash.hemiLength !== hemiLength ||
  28733. hash.numDirectionalShadows !== numDirectionalShadows ||
  28734. hash.numPointShadows !== numPointShadows ||
  28735. hash.numSpotShadows !== numSpotShadows ||
  28736. hash.numSpotMaps !== numSpotMaps ||
  28737. hash.numLightProbes !== numLightProbes ) {
  28738. state.directional.length = directionalLength;
  28739. state.spot.length = spotLength;
  28740. state.rectArea.length = rectAreaLength;
  28741. state.point.length = pointLength;
  28742. state.hemi.length = hemiLength;
  28743. state.directionalShadow.length = numDirectionalShadows;
  28744. state.directionalShadowMap.length = numDirectionalShadows;
  28745. state.pointShadow.length = numPointShadows;
  28746. state.pointShadowMap.length = numPointShadows;
  28747. state.spotShadow.length = numSpotShadows;
  28748. state.spotShadowMap.length = numSpotShadows;
  28749. state.directionalShadowMatrix.length = numDirectionalShadows;
  28750. state.pointShadowMatrix.length = numPointShadows;
  28751. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  28752. state.spotLightMap.length = numSpotMaps;
  28753. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  28754. state.numLightProbes = numLightProbes;
  28755. hash.directionalLength = directionalLength;
  28756. hash.pointLength = pointLength;
  28757. hash.spotLength = spotLength;
  28758. hash.rectAreaLength = rectAreaLength;
  28759. hash.hemiLength = hemiLength;
  28760. hash.numDirectionalShadows = numDirectionalShadows;
  28761. hash.numPointShadows = numPointShadows;
  28762. hash.numSpotShadows = numSpotShadows;
  28763. hash.numSpotMaps = numSpotMaps;
  28764. hash.numLightProbes = numLightProbes;
  28765. state.version = nextVersion ++;
  28766. }
  28767. }
  28768. function setupView( lights, camera ) {
  28769. let directionalLength = 0;
  28770. let pointLength = 0;
  28771. let spotLength = 0;
  28772. let rectAreaLength = 0;
  28773. let hemiLength = 0;
  28774. const viewMatrix = camera.matrixWorldInverse;
  28775. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  28776. const light = lights[ i ];
  28777. if ( light.isDirectionalLight ) {
  28778. const uniforms = state.directional[ directionalLength ];
  28779. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  28780. vector3.setFromMatrixPosition( light.target.matrixWorld );
  28781. uniforms.direction.sub( vector3 );
  28782. uniforms.direction.transformDirection( viewMatrix );
  28783. directionalLength ++;
  28784. } else if ( light.isSpotLight ) {
  28785. const uniforms = state.spot[ spotLength ];
  28786. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  28787. uniforms.position.applyMatrix4( viewMatrix );
  28788. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  28789. vector3.setFromMatrixPosition( light.target.matrixWorld );
  28790. uniforms.direction.sub( vector3 );
  28791. uniforms.direction.transformDirection( viewMatrix );
  28792. spotLength ++;
  28793. } else if ( light.isRectAreaLight ) {
  28794. const uniforms = state.rectArea[ rectAreaLength ];
  28795. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  28796. uniforms.position.applyMatrix4( viewMatrix );
  28797. // extract local rotation of light to derive width/height half vectors
  28798. matrix42.identity();
  28799. matrix4.copy( light.matrixWorld );
  28800. matrix4.premultiply( viewMatrix );
  28801. matrix42.extractRotation( matrix4 );
  28802. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  28803. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  28804. uniforms.halfWidth.applyMatrix4( matrix42 );
  28805. uniforms.halfHeight.applyMatrix4( matrix42 );
  28806. rectAreaLength ++;
  28807. } else if ( light.isPointLight ) {
  28808. const uniforms = state.point[ pointLength ];
  28809. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  28810. uniforms.position.applyMatrix4( viewMatrix );
  28811. pointLength ++;
  28812. } else if ( light.isHemisphereLight ) {
  28813. const uniforms = state.hemi[ hemiLength ];
  28814. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  28815. uniforms.direction.transformDirection( viewMatrix );
  28816. hemiLength ++;
  28817. }
  28818. }
  28819. }
  28820. return {
  28821. setup: setup,
  28822. setupView: setupView,
  28823. state: state
  28824. };
  28825. }
  28826. function WebGLRenderState( extensions ) {
  28827. const lights = new WebGLLights( extensions );
  28828. const lightsArray = [];
  28829. const shadowsArray = [];
  28830. function init( camera ) {
  28831. state.camera = camera;
  28832. lightsArray.length = 0;
  28833. shadowsArray.length = 0;
  28834. }
  28835. function pushLight( light ) {
  28836. lightsArray.push( light );
  28837. }
  28838. function pushShadow( shadowLight ) {
  28839. shadowsArray.push( shadowLight );
  28840. }
  28841. function setupLights() {
  28842. lights.setup( lightsArray );
  28843. }
  28844. function setupLightsView( camera ) {
  28845. lights.setupView( lightsArray, camera );
  28846. }
  28847. const state = {
  28848. lightsArray: lightsArray,
  28849. shadowsArray: shadowsArray,
  28850. camera: null,
  28851. lights: lights,
  28852. transmissionRenderTarget: {}
  28853. };
  28854. return {
  28855. init: init,
  28856. state: state,
  28857. setupLights: setupLights,
  28858. setupLightsView: setupLightsView,
  28859. pushLight: pushLight,
  28860. pushShadow: pushShadow
  28861. };
  28862. }
  28863. function WebGLRenderStates( extensions ) {
  28864. let renderStates = new WeakMap();
  28865. function get( scene, renderCallDepth = 0 ) {
  28866. const renderStateArray = renderStates.get( scene );
  28867. let renderState;
  28868. if ( renderStateArray === undefined ) {
  28869. renderState = new WebGLRenderState( extensions );
  28870. renderStates.set( scene, [ renderState ] );
  28871. } else {
  28872. if ( renderCallDepth >= renderStateArray.length ) {
  28873. renderState = new WebGLRenderState( extensions );
  28874. renderStateArray.push( renderState );
  28875. } else {
  28876. renderState = renderStateArray[ renderCallDepth ];
  28877. }
  28878. }
  28879. return renderState;
  28880. }
  28881. function dispose() {
  28882. renderStates = new WeakMap();
  28883. }
  28884. return {
  28885. get: get,
  28886. dispose: dispose
  28887. };
  28888. }
  28889. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  28890. 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}";
  28891. function WebGLShadowMap( renderer, objects, capabilities ) {
  28892. let _frustum = new Frustum();
  28893. const _shadowMapSize = new Vector2(),
  28894. _viewportSize = new Vector2(),
  28895. _viewport = new Vector4(),
  28896. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  28897. _distanceMaterial = new MeshDistanceMaterial(),
  28898. _materialCache = {},
  28899. _maxTextureSize = capabilities.maxTextureSize;
  28900. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  28901. const shadowMaterialVertical = new ShaderMaterial( {
  28902. defines: {
  28903. VSM_SAMPLES: 8
  28904. },
  28905. uniforms: {
  28906. shadow_pass: { value: null },
  28907. resolution: { value: new Vector2() },
  28908. radius: { value: 4.0 }
  28909. },
  28910. vertexShader: vertex,
  28911. fragmentShader: fragment
  28912. } );
  28913. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  28914. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  28915. const fullScreenTri = new BufferGeometry();
  28916. fullScreenTri.setAttribute(
  28917. 'position',
  28918. new BufferAttribute(
  28919. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  28920. 3
  28921. )
  28922. );
  28923. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  28924. const scope = this;
  28925. this.enabled = false;
  28926. this.autoUpdate = true;
  28927. this.needsUpdate = false;
  28928. this.type = PCFShadowMap;
  28929. let _previousType = this.type;
  28930. this.render = function ( lights, scene, camera ) {
  28931. if ( scope.enabled === false ) return;
  28932. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  28933. if ( lights.length === 0 ) return;
  28934. const currentRenderTarget = renderer.getRenderTarget();
  28935. const activeCubeFace = renderer.getActiveCubeFace();
  28936. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  28937. const _state = renderer.state;
  28938. // Set GL state for depth map.
  28939. _state.setBlending( NoBlending );
  28940. _state.buffers.color.setClear( 1, 1, 1, 1 );
  28941. _state.buffers.depth.setTest( true );
  28942. _state.setScissorTest( false );
  28943. // check for shadow map type changes
  28944. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  28945. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  28946. // render depth map
  28947. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  28948. const light = lights[ i ];
  28949. const shadow = light.shadow;
  28950. if ( shadow === undefined ) {
  28951. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  28952. continue;
  28953. }
  28954. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  28955. _shadowMapSize.copy( shadow.mapSize );
  28956. const shadowFrameExtents = shadow.getFrameExtents();
  28957. _shadowMapSize.multiply( shadowFrameExtents );
  28958. _viewportSize.copy( shadow.mapSize );
  28959. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  28960. if ( _shadowMapSize.x > _maxTextureSize ) {
  28961. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  28962. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  28963. shadow.mapSize.x = _viewportSize.x;
  28964. }
  28965. if ( _shadowMapSize.y > _maxTextureSize ) {
  28966. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  28967. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  28968. shadow.mapSize.y = _viewportSize.y;
  28969. }
  28970. }
  28971. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  28972. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  28973. if ( shadow.map !== null ) {
  28974. shadow.map.dispose();
  28975. }
  28976. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  28977. shadow.map.texture.name = light.name + '.shadowMap';
  28978. shadow.camera.updateProjectionMatrix();
  28979. }
  28980. renderer.setRenderTarget( shadow.map );
  28981. renderer.clear();
  28982. const viewportCount = shadow.getViewportCount();
  28983. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  28984. const viewport = shadow.getViewport( vp );
  28985. _viewport.set(
  28986. _viewportSize.x * viewport.x,
  28987. _viewportSize.y * viewport.y,
  28988. _viewportSize.x * viewport.z,
  28989. _viewportSize.y * viewport.w
  28990. );
  28991. _state.viewport( _viewport );
  28992. shadow.updateMatrices( light, vp );
  28993. _frustum = shadow.getFrustum();
  28994. renderObject( scene, camera, shadow.camera, light, this.type );
  28995. }
  28996. // do blur pass for VSM
  28997. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  28998. VSMPass( shadow, camera );
  28999. }
  29000. shadow.needsUpdate = false;
  29001. }
  29002. _previousType = this.type;
  29003. scope.needsUpdate = false;
  29004. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  29005. };
  29006. function VSMPass( shadow, camera ) {
  29007. const geometry = objects.update( fullScreenMesh );
  29008. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  29009. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  29010. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  29011. shadowMaterialVertical.needsUpdate = true;
  29012. shadowMaterialHorizontal.needsUpdate = true;
  29013. }
  29014. if ( shadow.mapPass === null ) {
  29015. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  29016. }
  29017. // vertical pass
  29018. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  29019. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  29020. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  29021. renderer.setRenderTarget( shadow.mapPass );
  29022. renderer.clear();
  29023. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  29024. // horizontal pass
  29025. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  29026. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  29027. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  29028. renderer.setRenderTarget( shadow.map );
  29029. renderer.clear();
  29030. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  29031. }
  29032. function getDepthMaterial( object, material, light, type ) {
  29033. let result = null;
  29034. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  29035. if ( customMaterial !== undefined ) {
  29036. result = customMaterial;
  29037. } else {
  29038. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  29039. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  29040. ( material.displacementMap && material.displacementScale !== 0 ) ||
  29041. ( material.alphaMap && material.alphaTest > 0 ) ||
  29042. ( material.map && material.alphaTest > 0 ) ) {
  29043. // in this case we need a unique material instance reflecting the
  29044. // appropriate state
  29045. const keyA = result.uuid, keyB = material.uuid;
  29046. let materialsForVariant = _materialCache[ keyA ];
  29047. if ( materialsForVariant === undefined ) {
  29048. materialsForVariant = {};
  29049. _materialCache[ keyA ] = materialsForVariant;
  29050. }
  29051. let cachedMaterial = materialsForVariant[ keyB ];
  29052. if ( cachedMaterial === undefined ) {
  29053. cachedMaterial = result.clone();
  29054. materialsForVariant[ keyB ] = cachedMaterial;
  29055. material.addEventListener( 'dispose', onMaterialDispose );
  29056. }
  29057. result = cachedMaterial;
  29058. }
  29059. }
  29060. result.visible = material.visible;
  29061. result.wireframe = material.wireframe;
  29062. if ( type === VSMShadowMap ) {
  29063. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  29064. } else {
  29065. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  29066. }
  29067. result.alphaMap = material.alphaMap;
  29068. result.alphaTest = material.alphaTest;
  29069. result.map = material.map;
  29070. result.clipShadows = material.clipShadows;
  29071. result.clippingPlanes = material.clippingPlanes;
  29072. result.clipIntersection = material.clipIntersection;
  29073. result.displacementMap = material.displacementMap;
  29074. result.displacementScale = material.displacementScale;
  29075. result.displacementBias = material.displacementBias;
  29076. result.wireframeLinewidth = material.wireframeLinewidth;
  29077. result.linewidth = material.linewidth;
  29078. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  29079. const materialProperties = renderer.properties.get( result );
  29080. materialProperties.light = light;
  29081. }
  29082. return result;
  29083. }
  29084. function renderObject( object, camera, shadowCamera, light, type ) {
  29085. if ( object.visible === false ) return;
  29086. const visible = object.layers.test( camera.layers );
  29087. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  29088. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  29089. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  29090. const geometry = objects.update( object );
  29091. const material = object.material;
  29092. if ( Array.isArray( material ) ) {
  29093. const groups = geometry.groups;
  29094. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  29095. const group = groups[ k ];
  29096. const groupMaterial = material[ group.materialIndex ];
  29097. if ( groupMaterial && groupMaterial.visible ) {
  29098. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  29099. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  29100. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  29101. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  29102. }
  29103. }
  29104. } else if ( material.visible ) {
  29105. const depthMaterial = getDepthMaterial( object, material, light, type );
  29106. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  29107. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  29108. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  29109. }
  29110. }
  29111. }
  29112. const children = object.children;
  29113. for ( let i = 0, l = children.length; i < l; i ++ ) {
  29114. renderObject( children[ i ], camera, shadowCamera, light, type );
  29115. }
  29116. }
  29117. function onMaterialDispose( event ) {
  29118. const material = event.target;
  29119. material.removeEventListener( 'dispose', onMaterialDispose );
  29120. // make sure to remove the unique distance/depth materials used for shadow map rendering
  29121. for ( const id in _materialCache ) {
  29122. const cache = _materialCache[ id ];
  29123. const uuid = event.target.uuid;
  29124. if ( uuid in cache ) {
  29125. const shadowMaterial = cache[ uuid ];
  29126. shadowMaterial.dispose();
  29127. delete cache[ uuid ];
  29128. }
  29129. }
  29130. }
  29131. }
  29132. const reversedFuncs = {
  29133. [ NeverDepth ]: AlwaysDepth,
  29134. [ LessDepth ]: GreaterDepth,
  29135. [ EqualDepth ]: NotEqualDepth,
  29136. [ LessEqualDepth ]: GreaterEqualDepth,
  29137. [ AlwaysDepth ]: NeverDepth,
  29138. [ GreaterDepth ]: LessDepth,
  29139. [ NotEqualDepth ]: EqualDepth,
  29140. [ GreaterEqualDepth ]: LessEqualDepth,
  29141. };
  29142. function WebGLState( gl, extensions ) {
  29143. function ColorBuffer() {
  29144. let locked = false;
  29145. const color = new Vector4();
  29146. let currentColorMask = null;
  29147. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  29148. return {
  29149. setMask: function ( colorMask ) {
  29150. if ( currentColorMask !== colorMask && ! locked ) {
  29151. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  29152. currentColorMask = colorMask;
  29153. }
  29154. },
  29155. setLocked: function ( lock ) {
  29156. locked = lock;
  29157. },
  29158. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  29159. if ( premultipliedAlpha === true ) {
  29160. r *= a; g *= a; b *= a;
  29161. }
  29162. color.set( r, g, b, a );
  29163. if ( currentColorClear.equals( color ) === false ) {
  29164. gl.clearColor( r, g, b, a );
  29165. currentColorClear.copy( color );
  29166. }
  29167. },
  29168. reset: function () {
  29169. locked = false;
  29170. currentColorMask = null;
  29171. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  29172. }
  29173. };
  29174. }
  29175. function DepthBuffer() {
  29176. let locked = false;
  29177. let reversed = false;
  29178. let currentDepthMask = null;
  29179. let currentDepthFunc = null;
  29180. let currentDepthClear = null;
  29181. return {
  29182. setReversed: function ( value ) {
  29183. if ( reversed !== value ) {
  29184. const ext = extensions.get( 'EXT_clip_control' );
  29185. if ( reversed ) {
  29186. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  29187. } else {
  29188. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  29189. }
  29190. const oldDepth = currentDepthClear;
  29191. currentDepthClear = null;
  29192. this.setClear( oldDepth );
  29193. }
  29194. reversed = value;
  29195. },
  29196. getReversed: function () {
  29197. return reversed;
  29198. },
  29199. setTest: function ( depthTest ) {
  29200. if ( depthTest ) {
  29201. enable( gl.DEPTH_TEST );
  29202. } else {
  29203. disable( gl.DEPTH_TEST );
  29204. }
  29205. },
  29206. setMask: function ( depthMask ) {
  29207. if ( currentDepthMask !== depthMask && ! locked ) {
  29208. gl.depthMask( depthMask );
  29209. currentDepthMask = depthMask;
  29210. }
  29211. },
  29212. setFunc: function ( depthFunc ) {
  29213. if ( reversed ) depthFunc = reversedFuncs[ depthFunc ];
  29214. if ( currentDepthFunc !== depthFunc ) {
  29215. switch ( depthFunc ) {
  29216. case NeverDepth:
  29217. gl.depthFunc( gl.NEVER );
  29218. break;
  29219. case AlwaysDepth:
  29220. gl.depthFunc( gl.ALWAYS );
  29221. break;
  29222. case LessDepth:
  29223. gl.depthFunc( gl.LESS );
  29224. break;
  29225. case LessEqualDepth:
  29226. gl.depthFunc( gl.LEQUAL );
  29227. break;
  29228. case EqualDepth:
  29229. gl.depthFunc( gl.EQUAL );
  29230. break;
  29231. case GreaterEqualDepth:
  29232. gl.depthFunc( gl.GEQUAL );
  29233. break;
  29234. case GreaterDepth:
  29235. gl.depthFunc( gl.GREATER );
  29236. break;
  29237. case NotEqualDepth:
  29238. gl.depthFunc( gl.NOTEQUAL );
  29239. break;
  29240. default:
  29241. gl.depthFunc( gl.LEQUAL );
  29242. }
  29243. currentDepthFunc = depthFunc;
  29244. }
  29245. },
  29246. setLocked: function ( lock ) {
  29247. locked = lock;
  29248. },
  29249. setClear: function ( depth ) {
  29250. if ( currentDepthClear !== depth ) {
  29251. if ( reversed ) {
  29252. depth = 1 - depth;
  29253. }
  29254. gl.clearDepth( depth );
  29255. currentDepthClear = depth;
  29256. }
  29257. },
  29258. reset: function () {
  29259. locked = false;
  29260. currentDepthMask = null;
  29261. currentDepthFunc = null;
  29262. currentDepthClear = null;
  29263. reversed = false;
  29264. }
  29265. };
  29266. }
  29267. function StencilBuffer() {
  29268. let locked = false;
  29269. let currentStencilMask = null;
  29270. let currentStencilFunc = null;
  29271. let currentStencilRef = null;
  29272. let currentStencilFuncMask = null;
  29273. let currentStencilFail = null;
  29274. let currentStencilZFail = null;
  29275. let currentStencilZPass = null;
  29276. let currentStencilClear = null;
  29277. return {
  29278. setTest: function ( stencilTest ) {
  29279. if ( ! locked ) {
  29280. if ( stencilTest ) {
  29281. enable( gl.STENCIL_TEST );
  29282. } else {
  29283. disable( gl.STENCIL_TEST );
  29284. }
  29285. }
  29286. },
  29287. setMask: function ( stencilMask ) {
  29288. if ( currentStencilMask !== stencilMask && ! locked ) {
  29289. gl.stencilMask( stencilMask );
  29290. currentStencilMask = stencilMask;
  29291. }
  29292. },
  29293. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  29294. if ( currentStencilFunc !== stencilFunc ||
  29295. currentStencilRef !== stencilRef ||
  29296. currentStencilFuncMask !== stencilMask ) {
  29297. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  29298. currentStencilFunc = stencilFunc;
  29299. currentStencilRef = stencilRef;
  29300. currentStencilFuncMask = stencilMask;
  29301. }
  29302. },
  29303. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  29304. if ( currentStencilFail !== stencilFail ||
  29305. currentStencilZFail !== stencilZFail ||
  29306. currentStencilZPass !== stencilZPass ) {
  29307. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  29308. currentStencilFail = stencilFail;
  29309. currentStencilZFail = stencilZFail;
  29310. currentStencilZPass = stencilZPass;
  29311. }
  29312. },
  29313. setLocked: function ( lock ) {
  29314. locked = lock;
  29315. },
  29316. setClear: function ( stencil ) {
  29317. if ( currentStencilClear !== stencil ) {
  29318. gl.clearStencil( stencil );
  29319. currentStencilClear = stencil;
  29320. }
  29321. },
  29322. reset: function () {
  29323. locked = false;
  29324. currentStencilMask = null;
  29325. currentStencilFunc = null;
  29326. currentStencilRef = null;
  29327. currentStencilFuncMask = null;
  29328. currentStencilFail = null;
  29329. currentStencilZFail = null;
  29330. currentStencilZPass = null;
  29331. currentStencilClear = null;
  29332. }
  29333. };
  29334. }
  29335. //
  29336. const colorBuffer = new ColorBuffer();
  29337. const depthBuffer = new DepthBuffer();
  29338. const stencilBuffer = new StencilBuffer();
  29339. const uboBindings = new WeakMap();
  29340. const uboProgramMap = new WeakMap();
  29341. let enabledCapabilities = {};
  29342. let currentBoundFramebuffers = {};
  29343. let currentDrawbuffers = new WeakMap();
  29344. let defaultDrawbuffers = [];
  29345. let currentProgram = null;
  29346. let currentBlendingEnabled = false;
  29347. let currentBlending = null;
  29348. let currentBlendEquation = null;
  29349. let currentBlendSrc = null;
  29350. let currentBlendDst = null;
  29351. let currentBlendEquationAlpha = null;
  29352. let currentBlendSrcAlpha = null;
  29353. let currentBlendDstAlpha = null;
  29354. let currentBlendColor = new Color( 0, 0, 0 );
  29355. let currentBlendAlpha = 0;
  29356. let currentPremultipledAlpha = false;
  29357. let currentFlipSided = null;
  29358. let currentCullFace = null;
  29359. let currentLineWidth = null;
  29360. let currentPolygonOffsetFactor = null;
  29361. let currentPolygonOffsetUnits = null;
  29362. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  29363. let lineWidthAvailable = false;
  29364. let version = 0;
  29365. const glVersion = gl.getParameter( gl.VERSION );
  29366. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  29367. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  29368. lineWidthAvailable = ( version >= 1.0 );
  29369. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  29370. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  29371. lineWidthAvailable = ( version >= 2.0 );
  29372. }
  29373. let currentTextureSlot = null;
  29374. let currentBoundTextures = {};
  29375. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  29376. const viewportParam = gl.getParameter( gl.VIEWPORT );
  29377. const currentScissor = new Vector4().fromArray( scissorParam );
  29378. const currentViewport = new Vector4().fromArray( viewportParam );
  29379. function createTexture( type, target, count, dimensions ) {
  29380. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  29381. const texture = gl.createTexture();
  29382. gl.bindTexture( type, texture );
  29383. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  29384. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  29385. for ( let i = 0; i < count; i ++ ) {
  29386. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  29387. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  29388. } else {
  29389. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  29390. }
  29391. }
  29392. return texture;
  29393. }
  29394. const emptyTextures = {};
  29395. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  29396. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  29397. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  29398. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  29399. // init
  29400. colorBuffer.setClear( 0, 0, 0, 1 );
  29401. depthBuffer.setClear( 1 );
  29402. stencilBuffer.setClear( 0 );
  29403. enable( gl.DEPTH_TEST );
  29404. depthBuffer.setFunc( LessEqualDepth );
  29405. setFlipSided( false );
  29406. setCullFace( CullFaceBack );
  29407. enable( gl.CULL_FACE );
  29408. setBlending( NoBlending );
  29409. //
  29410. function enable( id ) {
  29411. if ( enabledCapabilities[ id ] !== true ) {
  29412. gl.enable( id );
  29413. enabledCapabilities[ id ] = true;
  29414. }
  29415. }
  29416. function disable( id ) {
  29417. if ( enabledCapabilities[ id ] !== false ) {
  29418. gl.disable( id );
  29419. enabledCapabilities[ id ] = false;
  29420. }
  29421. }
  29422. function bindFramebuffer( target, framebuffer ) {
  29423. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  29424. gl.bindFramebuffer( target, framebuffer );
  29425. currentBoundFramebuffers[ target ] = framebuffer;
  29426. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  29427. if ( target === gl.DRAW_FRAMEBUFFER ) {
  29428. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  29429. }
  29430. if ( target === gl.FRAMEBUFFER ) {
  29431. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  29432. }
  29433. return true;
  29434. }
  29435. return false;
  29436. }
  29437. function drawBuffers( renderTarget, framebuffer ) {
  29438. let drawBuffers = defaultDrawbuffers;
  29439. let needsUpdate = false;
  29440. if ( renderTarget ) {
  29441. drawBuffers = currentDrawbuffers.get( framebuffer );
  29442. if ( drawBuffers === undefined ) {
  29443. drawBuffers = [];
  29444. currentDrawbuffers.set( framebuffer, drawBuffers );
  29445. }
  29446. const textures = renderTarget.textures;
  29447. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  29448. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  29449. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  29450. }
  29451. drawBuffers.length = textures.length;
  29452. needsUpdate = true;
  29453. }
  29454. } else {
  29455. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  29456. drawBuffers[ 0 ] = gl.BACK;
  29457. needsUpdate = true;
  29458. }
  29459. }
  29460. if ( needsUpdate ) {
  29461. gl.drawBuffers( drawBuffers );
  29462. }
  29463. }
  29464. function useProgram( program ) {
  29465. if ( currentProgram !== program ) {
  29466. gl.useProgram( program );
  29467. currentProgram = program;
  29468. return true;
  29469. }
  29470. return false;
  29471. }
  29472. const equationToGL = {
  29473. [ AddEquation ]: gl.FUNC_ADD,
  29474. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  29475. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  29476. };
  29477. equationToGL[ MinEquation ] = gl.MIN;
  29478. equationToGL[ MaxEquation ] = gl.MAX;
  29479. const factorToGL = {
  29480. [ ZeroFactor ]: gl.ZERO,
  29481. [ OneFactor ]: gl.ONE,
  29482. [ SrcColorFactor ]: gl.SRC_COLOR,
  29483. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  29484. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  29485. [ DstColorFactor ]: gl.DST_COLOR,
  29486. [ DstAlphaFactor ]: gl.DST_ALPHA,
  29487. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  29488. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  29489. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  29490. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  29491. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  29492. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  29493. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  29494. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  29495. };
  29496. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  29497. if ( blending === NoBlending ) {
  29498. if ( currentBlendingEnabled === true ) {
  29499. disable( gl.BLEND );
  29500. currentBlendingEnabled = false;
  29501. }
  29502. return;
  29503. }
  29504. if ( currentBlendingEnabled === false ) {
  29505. enable( gl.BLEND );
  29506. currentBlendingEnabled = true;
  29507. }
  29508. if ( blending !== CustomBlending ) {
  29509. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  29510. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  29511. gl.blendEquation( gl.FUNC_ADD );
  29512. currentBlendEquation = AddEquation;
  29513. currentBlendEquationAlpha = AddEquation;
  29514. }
  29515. if ( premultipliedAlpha ) {
  29516. switch ( blending ) {
  29517. case NormalBlending:
  29518. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  29519. break;
  29520. case AdditiveBlending:
  29521. gl.blendFunc( gl.ONE, gl.ONE );
  29522. break;
  29523. case SubtractiveBlending:
  29524. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  29525. break;
  29526. case MultiplyBlending:
  29527. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  29528. break;
  29529. default:
  29530. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  29531. break;
  29532. }
  29533. } else {
  29534. switch ( blending ) {
  29535. case NormalBlending:
  29536. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  29537. break;
  29538. case AdditiveBlending:
  29539. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  29540. break;
  29541. case SubtractiveBlending:
  29542. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  29543. break;
  29544. case MultiplyBlending:
  29545. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  29546. break;
  29547. default:
  29548. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  29549. break;
  29550. }
  29551. }
  29552. currentBlendSrc = null;
  29553. currentBlendDst = null;
  29554. currentBlendSrcAlpha = null;
  29555. currentBlendDstAlpha = null;
  29556. currentBlendColor.set( 0, 0, 0 );
  29557. currentBlendAlpha = 0;
  29558. currentBlending = blending;
  29559. currentPremultipledAlpha = premultipliedAlpha;
  29560. }
  29561. return;
  29562. }
  29563. // custom blending
  29564. blendEquationAlpha = blendEquationAlpha || blendEquation;
  29565. blendSrcAlpha = blendSrcAlpha || blendSrc;
  29566. blendDstAlpha = blendDstAlpha || blendDst;
  29567. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  29568. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  29569. currentBlendEquation = blendEquation;
  29570. currentBlendEquationAlpha = blendEquationAlpha;
  29571. }
  29572. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  29573. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  29574. currentBlendSrc = blendSrc;
  29575. currentBlendDst = blendDst;
  29576. currentBlendSrcAlpha = blendSrcAlpha;
  29577. currentBlendDstAlpha = blendDstAlpha;
  29578. }
  29579. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  29580. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  29581. currentBlendColor.copy( blendColor );
  29582. currentBlendAlpha = blendAlpha;
  29583. }
  29584. currentBlending = blending;
  29585. currentPremultipledAlpha = false;
  29586. }
  29587. function setMaterial( material, frontFaceCW ) {
  29588. material.side === DoubleSide
  29589. ? disable( gl.CULL_FACE )
  29590. : enable( gl.CULL_FACE );
  29591. let flipSided = ( material.side === BackSide );
  29592. if ( frontFaceCW ) flipSided = ! flipSided;
  29593. setFlipSided( flipSided );
  29594. ( material.blending === NormalBlending && material.transparent === false )
  29595. ? setBlending( NoBlending )
  29596. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  29597. depthBuffer.setFunc( material.depthFunc );
  29598. depthBuffer.setTest( material.depthTest );
  29599. depthBuffer.setMask( material.depthWrite );
  29600. colorBuffer.setMask( material.colorWrite );
  29601. const stencilWrite = material.stencilWrite;
  29602. stencilBuffer.setTest( stencilWrite );
  29603. if ( stencilWrite ) {
  29604. stencilBuffer.setMask( material.stencilWriteMask );
  29605. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  29606. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  29607. }
  29608. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  29609. material.alphaToCoverage === true
  29610. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  29611. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  29612. }
  29613. //
  29614. function setFlipSided( flipSided ) {
  29615. if ( currentFlipSided !== flipSided ) {
  29616. if ( flipSided ) {
  29617. gl.frontFace( gl.CW );
  29618. } else {
  29619. gl.frontFace( gl.CCW );
  29620. }
  29621. currentFlipSided = flipSided;
  29622. }
  29623. }
  29624. function setCullFace( cullFace ) {
  29625. if ( cullFace !== CullFaceNone ) {
  29626. enable( gl.CULL_FACE );
  29627. if ( cullFace !== currentCullFace ) {
  29628. if ( cullFace === CullFaceBack ) {
  29629. gl.cullFace( gl.BACK );
  29630. } else if ( cullFace === CullFaceFront ) {
  29631. gl.cullFace( gl.FRONT );
  29632. } else {
  29633. gl.cullFace( gl.FRONT_AND_BACK );
  29634. }
  29635. }
  29636. } else {
  29637. disable( gl.CULL_FACE );
  29638. }
  29639. currentCullFace = cullFace;
  29640. }
  29641. function setLineWidth( width ) {
  29642. if ( width !== currentLineWidth ) {
  29643. if ( lineWidthAvailable ) gl.lineWidth( width );
  29644. currentLineWidth = width;
  29645. }
  29646. }
  29647. function setPolygonOffset( polygonOffset, factor, units ) {
  29648. if ( polygonOffset ) {
  29649. enable( gl.POLYGON_OFFSET_FILL );
  29650. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  29651. gl.polygonOffset( factor, units );
  29652. currentPolygonOffsetFactor = factor;
  29653. currentPolygonOffsetUnits = units;
  29654. }
  29655. } else {
  29656. disable( gl.POLYGON_OFFSET_FILL );
  29657. }
  29658. }
  29659. function setScissorTest( scissorTest ) {
  29660. if ( scissorTest ) {
  29661. enable( gl.SCISSOR_TEST );
  29662. } else {
  29663. disable( gl.SCISSOR_TEST );
  29664. }
  29665. }
  29666. // texture
  29667. function activeTexture( webglSlot ) {
  29668. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  29669. if ( currentTextureSlot !== webglSlot ) {
  29670. gl.activeTexture( webglSlot );
  29671. currentTextureSlot = webglSlot;
  29672. }
  29673. }
  29674. function bindTexture( webglType, webglTexture, webglSlot ) {
  29675. if ( webglSlot === undefined ) {
  29676. if ( currentTextureSlot === null ) {
  29677. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  29678. } else {
  29679. webglSlot = currentTextureSlot;
  29680. }
  29681. }
  29682. let boundTexture = currentBoundTextures[ webglSlot ];
  29683. if ( boundTexture === undefined ) {
  29684. boundTexture = { type: undefined, texture: undefined };
  29685. currentBoundTextures[ webglSlot ] = boundTexture;
  29686. }
  29687. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  29688. if ( currentTextureSlot !== webglSlot ) {
  29689. gl.activeTexture( webglSlot );
  29690. currentTextureSlot = webglSlot;
  29691. }
  29692. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  29693. boundTexture.type = webglType;
  29694. boundTexture.texture = webglTexture;
  29695. }
  29696. }
  29697. function unbindTexture() {
  29698. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  29699. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  29700. gl.bindTexture( boundTexture.type, null );
  29701. boundTexture.type = undefined;
  29702. boundTexture.texture = undefined;
  29703. }
  29704. }
  29705. function compressedTexImage2D() {
  29706. try {
  29707. gl.compressedTexImage2D( ...arguments );
  29708. } catch ( error ) {
  29709. console.error( 'THREE.WebGLState:', error );
  29710. }
  29711. }
  29712. function compressedTexImage3D() {
  29713. try {
  29714. gl.compressedTexImage3D( ...arguments );
  29715. } catch ( error ) {
  29716. console.error( 'THREE.WebGLState:', error );
  29717. }
  29718. }
  29719. function texSubImage2D() {
  29720. try {
  29721. gl.texSubImage2D( ...arguments );
  29722. } catch ( error ) {
  29723. console.error( 'THREE.WebGLState:', error );
  29724. }
  29725. }
  29726. function texSubImage3D() {
  29727. try {
  29728. gl.texSubImage3D( ...arguments );
  29729. } catch ( error ) {
  29730. console.error( 'THREE.WebGLState:', error );
  29731. }
  29732. }
  29733. function compressedTexSubImage2D() {
  29734. try {
  29735. gl.compressedTexSubImage2D( ...arguments );
  29736. } catch ( error ) {
  29737. console.error( 'THREE.WebGLState:', error );
  29738. }
  29739. }
  29740. function compressedTexSubImage3D() {
  29741. try {
  29742. gl.compressedTexSubImage3D( ...arguments );
  29743. } catch ( error ) {
  29744. console.error( 'THREE.WebGLState:', error );
  29745. }
  29746. }
  29747. function texStorage2D() {
  29748. try {
  29749. gl.texStorage2D( ...arguments );
  29750. } catch ( error ) {
  29751. console.error( 'THREE.WebGLState:', error );
  29752. }
  29753. }
  29754. function texStorage3D() {
  29755. try {
  29756. gl.texStorage3D( ...arguments );
  29757. } catch ( error ) {
  29758. console.error( 'THREE.WebGLState:', error );
  29759. }
  29760. }
  29761. function texImage2D() {
  29762. try {
  29763. gl.texImage2D( ...arguments );
  29764. } catch ( error ) {
  29765. console.error( 'THREE.WebGLState:', error );
  29766. }
  29767. }
  29768. function texImage3D() {
  29769. try {
  29770. gl.texImage3D( ...arguments );
  29771. } catch ( error ) {
  29772. console.error( 'THREE.WebGLState:', error );
  29773. }
  29774. }
  29775. //
  29776. function scissor( scissor ) {
  29777. if ( currentScissor.equals( scissor ) === false ) {
  29778. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  29779. currentScissor.copy( scissor );
  29780. }
  29781. }
  29782. function viewport( viewport ) {
  29783. if ( currentViewport.equals( viewport ) === false ) {
  29784. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  29785. currentViewport.copy( viewport );
  29786. }
  29787. }
  29788. function updateUBOMapping( uniformsGroup, program ) {
  29789. let mapping = uboProgramMap.get( program );
  29790. if ( mapping === undefined ) {
  29791. mapping = new WeakMap();
  29792. uboProgramMap.set( program, mapping );
  29793. }
  29794. let blockIndex = mapping.get( uniformsGroup );
  29795. if ( blockIndex === undefined ) {
  29796. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  29797. mapping.set( uniformsGroup, blockIndex );
  29798. }
  29799. }
  29800. function uniformBlockBinding( uniformsGroup, program ) {
  29801. const mapping = uboProgramMap.get( program );
  29802. const blockIndex = mapping.get( uniformsGroup );
  29803. if ( uboBindings.get( program ) !== blockIndex ) {
  29804. // bind shader specific block index to global block point
  29805. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  29806. uboBindings.set( program, blockIndex );
  29807. }
  29808. }
  29809. //
  29810. function reset() {
  29811. // reset state
  29812. gl.disable( gl.BLEND );
  29813. gl.disable( gl.CULL_FACE );
  29814. gl.disable( gl.DEPTH_TEST );
  29815. gl.disable( gl.POLYGON_OFFSET_FILL );
  29816. gl.disable( gl.SCISSOR_TEST );
  29817. gl.disable( gl.STENCIL_TEST );
  29818. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  29819. gl.blendEquation( gl.FUNC_ADD );
  29820. gl.blendFunc( gl.ONE, gl.ZERO );
  29821. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  29822. gl.blendColor( 0, 0, 0, 0 );
  29823. gl.colorMask( true, true, true, true );
  29824. gl.clearColor( 0, 0, 0, 0 );
  29825. gl.depthMask( true );
  29826. gl.depthFunc( gl.LESS );
  29827. depthBuffer.setReversed( false );
  29828. gl.clearDepth( 1 );
  29829. gl.stencilMask( 0xffffffff );
  29830. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  29831. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  29832. gl.clearStencil( 0 );
  29833. gl.cullFace( gl.BACK );
  29834. gl.frontFace( gl.CCW );
  29835. gl.polygonOffset( 0, 0 );
  29836. gl.activeTexture( gl.TEXTURE0 );
  29837. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  29838. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  29839. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  29840. gl.useProgram( null );
  29841. gl.lineWidth( 1 );
  29842. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  29843. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  29844. // reset internals
  29845. enabledCapabilities = {};
  29846. currentTextureSlot = null;
  29847. currentBoundTextures = {};
  29848. currentBoundFramebuffers = {};
  29849. currentDrawbuffers = new WeakMap();
  29850. defaultDrawbuffers = [];
  29851. currentProgram = null;
  29852. currentBlendingEnabled = false;
  29853. currentBlending = null;
  29854. currentBlendEquation = null;
  29855. currentBlendSrc = null;
  29856. currentBlendDst = null;
  29857. currentBlendEquationAlpha = null;
  29858. currentBlendSrcAlpha = null;
  29859. currentBlendDstAlpha = null;
  29860. currentBlendColor = new Color( 0, 0, 0 );
  29861. currentBlendAlpha = 0;
  29862. currentPremultipledAlpha = false;
  29863. currentFlipSided = null;
  29864. currentCullFace = null;
  29865. currentLineWidth = null;
  29866. currentPolygonOffsetFactor = null;
  29867. currentPolygonOffsetUnits = null;
  29868. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  29869. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  29870. colorBuffer.reset();
  29871. depthBuffer.reset();
  29872. stencilBuffer.reset();
  29873. }
  29874. return {
  29875. buffers: {
  29876. color: colorBuffer,
  29877. depth: depthBuffer,
  29878. stencil: stencilBuffer
  29879. },
  29880. enable: enable,
  29881. disable: disable,
  29882. bindFramebuffer: bindFramebuffer,
  29883. drawBuffers: drawBuffers,
  29884. useProgram: useProgram,
  29885. setBlending: setBlending,
  29886. setMaterial: setMaterial,
  29887. setFlipSided: setFlipSided,
  29888. setCullFace: setCullFace,
  29889. setLineWidth: setLineWidth,
  29890. setPolygonOffset: setPolygonOffset,
  29891. setScissorTest: setScissorTest,
  29892. activeTexture: activeTexture,
  29893. bindTexture: bindTexture,
  29894. unbindTexture: unbindTexture,
  29895. compressedTexImage2D: compressedTexImage2D,
  29896. compressedTexImage3D: compressedTexImage3D,
  29897. texImage2D: texImage2D,
  29898. texImage3D: texImage3D,
  29899. updateUBOMapping: updateUBOMapping,
  29900. uniformBlockBinding: uniformBlockBinding,
  29901. texStorage2D: texStorage2D,
  29902. texStorage3D: texStorage3D,
  29903. texSubImage2D: texSubImage2D,
  29904. texSubImage3D: texSubImage3D,
  29905. compressedTexSubImage2D: compressedTexSubImage2D,
  29906. compressedTexSubImage3D: compressedTexSubImage3D,
  29907. scissor: scissor,
  29908. viewport: viewport,
  29909. reset: reset
  29910. };
  29911. }
  29912. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  29913. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  29914. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  29915. const _imageDimensions = new Vector2();
  29916. const _videoTextures = new WeakMap();
  29917. let _canvas;
  29918. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  29919. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  29920. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  29921. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  29922. let useOffscreenCanvas = false;
  29923. try {
  29924. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  29925. // eslint-disable-next-line compat/compat
  29926. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  29927. } catch ( err ) {
  29928. // Ignore any errors
  29929. }
  29930. function createCanvas( width, height ) {
  29931. // Use OffscreenCanvas when available. Specially needed in web workers
  29932. return useOffscreenCanvas ?
  29933. // eslint-disable-next-line compat/compat
  29934. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  29935. }
  29936. function resizeImage( image, needsNewCanvas, maxSize ) {
  29937. let scale = 1;
  29938. const dimensions = getDimensions( image );
  29939. // handle case if texture exceeds max size
  29940. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  29941. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  29942. }
  29943. // only perform resize if necessary
  29944. if ( scale < 1 ) {
  29945. // only perform resize for certain image types
  29946. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  29947. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  29948. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  29949. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  29950. const width = Math.floor( scale * dimensions.width );
  29951. const height = Math.floor( scale * dimensions.height );
  29952. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  29953. // cube textures can't reuse the same canvas
  29954. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  29955. canvas.width = width;
  29956. canvas.height = height;
  29957. const context = canvas.getContext( '2d' );
  29958. context.drawImage( image, 0, 0, width, height );
  29959. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  29960. return canvas;
  29961. } else {
  29962. if ( 'data' in image ) {
  29963. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  29964. }
  29965. return image;
  29966. }
  29967. }
  29968. return image;
  29969. }
  29970. function textureNeedsGenerateMipmaps( texture ) {
  29971. return texture.generateMipmaps;
  29972. }
  29973. function generateMipmap( target ) {
  29974. _gl.generateMipmap( target );
  29975. }
  29976. function getTargetType( texture ) {
  29977. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  29978. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  29979. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  29980. return _gl.TEXTURE_2D;
  29981. }
  29982. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  29983. if ( internalFormatName !== null ) {
  29984. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  29985. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  29986. }
  29987. let internalFormat = glFormat;
  29988. if ( glFormat === _gl.RED ) {
  29989. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  29990. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  29991. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  29992. }
  29993. if ( glFormat === _gl.RED_INTEGER ) {
  29994. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  29995. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  29996. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  29997. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  29998. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  29999. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  30000. }
  30001. if ( glFormat === _gl.RG ) {
  30002. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  30003. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  30004. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  30005. }
  30006. if ( glFormat === _gl.RG_INTEGER ) {
  30007. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  30008. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  30009. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  30010. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  30011. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  30012. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  30013. }
  30014. if ( glFormat === _gl.RGB_INTEGER ) {
  30015. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  30016. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  30017. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  30018. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  30019. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  30020. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  30021. }
  30022. if ( glFormat === _gl.RGBA_INTEGER ) {
  30023. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  30024. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  30025. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  30026. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  30027. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  30028. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  30029. }
  30030. if ( glFormat === _gl.RGB ) {
  30031. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  30032. }
  30033. if ( glFormat === _gl.RGBA ) {
  30034. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  30035. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  30036. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  30037. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  30038. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  30039. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  30040. }
  30041. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  30042. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  30043. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  30044. extensions.get( 'EXT_color_buffer_float' );
  30045. }
  30046. return internalFormat;
  30047. }
  30048. function getInternalDepthFormat( useStencil, depthType ) {
  30049. let glInternalFormat;
  30050. if ( useStencil ) {
  30051. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  30052. glInternalFormat = _gl.DEPTH24_STENCIL8;
  30053. } else if ( depthType === FloatType ) {
  30054. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  30055. } else if ( depthType === UnsignedShortType ) {
  30056. glInternalFormat = _gl.DEPTH24_STENCIL8;
  30057. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  30058. }
  30059. } else {
  30060. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  30061. glInternalFormat = _gl.DEPTH_COMPONENT24;
  30062. } else if ( depthType === FloatType ) {
  30063. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  30064. } else if ( depthType === UnsignedShortType ) {
  30065. glInternalFormat = _gl.DEPTH_COMPONENT16;
  30066. }
  30067. }
  30068. return glInternalFormat;
  30069. }
  30070. function getMipLevels( texture, image ) {
  30071. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  30072. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  30073. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  30074. // user-defined mipmaps
  30075. return texture.mipmaps.length;
  30076. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  30077. return image.mipmaps.length;
  30078. } else {
  30079. // texture without mipmaps (only base level)
  30080. return 1;
  30081. }
  30082. }
  30083. //
  30084. function onTextureDispose( event ) {
  30085. const texture = event.target;
  30086. texture.removeEventListener( 'dispose', onTextureDispose );
  30087. deallocateTexture( texture );
  30088. if ( texture.isVideoTexture ) {
  30089. _videoTextures.delete( texture );
  30090. }
  30091. }
  30092. function onRenderTargetDispose( event ) {
  30093. const renderTarget = event.target;
  30094. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  30095. deallocateRenderTarget( renderTarget );
  30096. }
  30097. //
  30098. function deallocateTexture( texture ) {
  30099. const textureProperties = properties.get( texture );
  30100. if ( textureProperties.__webglInit === undefined ) return;
  30101. // check if it's necessary to remove the WebGLTexture object
  30102. const source = texture.source;
  30103. const webglTextures = _sources.get( source );
  30104. if ( webglTextures ) {
  30105. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  30106. webglTexture.usedTimes --;
  30107. // the WebGLTexture object is not used anymore, remove it
  30108. if ( webglTexture.usedTimes === 0 ) {
  30109. deleteTexture( texture );
  30110. }
  30111. // remove the weak map entry if no WebGLTexture uses the source anymore
  30112. if ( Object.keys( webglTextures ).length === 0 ) {
  30113. _sources.delete( source );
  30114. }
  30115. }
  30116. properties.remove( texture );
  30117. }
  30118. function deleteTexture( texture ) {
  30119. const textureProperties = properties.get( texture );
  30120. _gl.deleteTexture( textureProperties.__webglTexture );
  30121. const source = texture.source;
  30122. const webglTextures = _sources.get( source );
  30123. delete webglTextures[ textureProperties.__cacheKey ];
  30124. info.memory.textures --;
  30125. }
  30126. function deallocateRenderTarget( renderTarget ) {
  30127. const renderTargetProperties = properties.get( renderTarget );
  30128. if ( renderTarget.depthTexture ) {
  30129. renderTarget.depthTexture.dispose();
  30130. properties.remove( renderTarget.depthTexture );
  30131. }
  30132. if ( renderTarget.isWebGLCubeRenderTarget ) {
  30133. for ( let i = 0; i < 6; i ++ ) {
  30134. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  30135. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  30136. } else {
  30137. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  30138. }
  30139. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  30140. }
  30141. } else {
  30142. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  30143. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  30144. } else {
  30145. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  30146. }
  30147. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  30148. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  30149. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  30150. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  30151. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  30152. }
  30153. }
  30154. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  30155. }
  30156. const textures = renderTarget.textures;
  30157. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  30158. const attachmentProperties = properties.get( textures[ i ] );
  30159. if ( attachmentProperties.__webglTexture ) {
  30160. _gl.deleteTexture( attachmentProperties.__webglTexture );
  30161. info.memory.textures --;
  30162. }
  30163. properties.remove( textures[ i ] );
  30164. }
  30165. properties.remove( renderTarget );
  30166. }
  30167. //
  30168. let textureUnits = 0;
  30169. function resetTextureUnits() {
  30170. textureUnits = 0;
  30171. }
  30172. function allocateTextureUnit() {
  30173. const textureUnit = textureUnits;
  30174. if ( textureUnit >= capabilities.maxTextures ) {
  30175. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  30176. }
  30177. textureUnits += 1;
  30178. return textureUnit;
  30179. }
  30180. function getTextureCacheKey( texture ) {
  30181. const array = [];
  30182. array.push( texture.wrapS );
  30183. array.push( texture.wrapT );
  30184. array.push( texture.wrapR || 0 );
  30185. array.push( texture.magFilter );
  30186. array.push( texture.minFilter );
  30187. array.push( texture.anisotropy );
  30188. array.push( texture.internalFormat );
  30189. array.push( texture.format );
  30190. array.push( texture.type );
  30191. array.push( texture.generateMipmaps );
  30192. array.push( texture.premultiplyAlpha );
  30193. array.push( texture.flipY );
  30194. array.push( texture.unpackAlignment );
  30195. array.push( texture.colorSpace );
  30196. return array.join();
  30197. }
  30198. //
  30199. function setTexture2D( texture, slot ) {
  30200. const textureProperties = properties.get( texture );
  30201. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  30202. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  30203. const image = texture.image;
  30204. if ( image === null ) {
  30205. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  30206. } else if ( image.complete === false ) {
  30207. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  30208. } else {
  30209. uploadTexture( textureProperties, texture, slot );
  30210. return;
  30211. }
  30212. }
  30213. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  30214. }
  30215. function setTexture2DArray( texture, slot ) {
  30216. const textureProperties = properties.get( texture );
  30217. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  30218. uploadTexture( textureProperties, texture, slot );
  30219. return;
  30220. }
  30221. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  30222. }
  30223. function setTexture3D( texture, slot ) {
  30224. const textureProperties = properties.get( texture );
  30225. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  30226. uploadTexture( textureProperties, texture, slot );
  30227. return;
  30228. }
  30229. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  30230. }
  30231. function setTextureCube( texture, slot ) {
  30232. const textureProperties = properties.get( texture );
  30233. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  30234. uploadCubeTexture( textureProperties, texture, slot );
  30235. return;
  30236. }
  30237. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  30238. }
  30239. const wrappingToGL = {
  30240. [ RepeatWrapping ]: _gl.REPEAT,
  30241. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  30242. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  30243. };
  30244. const filterToGL = {
  30245. [ NearestFilter ]: _gl.NEAREST,
  30246. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  30247. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  30248. [ LinearFilter ]: _gl.LINEAR,
  30249. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  30250. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  30251. };
  30252. const compareToGL = {
  30253. [ NeverCompare ]: _gl.NEVER,
  30254. [ AlwaysCompare ]: _gl.ALWAYS,
  30255. [ LessCompare ]: _gl.LESS,
  30256. [ LessEqualCompare ]: _gl.LEQUAL,
  30257. [ EqualCompare ]: _gl.EQUAL,
  30258. [ GreaterEqualCompare ]: _gl.GEQUAL,
  30259. [ GreaterCompare ]: _gl.GREATER,
  30260. [ NotEqualCompare ]: _gl.NOTEQUAL
  30261. };
  30262. function setTextureParameters( textureType, texture ) {
  30263. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  30264. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30265. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  30266. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  30267. }
  30268. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  30269. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  30270. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  30271. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  30272. }
  30273. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  30274. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  30275. if ( texture.compareFunction ) {
  30276. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  30277. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  30278. }
  30279. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  30280. if ( texture.magFilter === NearestFilter ) return;
  30281. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  30282. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  30283. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  30284. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  30285. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  30286. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  30287. }
  30288. }
  30289. }
  30290. function initTexture( textureProperties, texture ) {
  30291. let forceUpload = false;
  30292. if ( textureProperties.__webglInit === undefined ) {
  30293. textureProperties.__webglInit = true;
  30294. texture.addEventListener( 'dispose', onTextureDispose );
  30295. }
  30296. // create Source <-> WebGLTextures mapping if necessary
  30297. const source = texture.source;
  30298. let webglTextures = _sources.get( source );
  30299. if ( webglTextures === undefined ) {
  30300. webglTextures = {};
  30301. _sources.set( source, webglTextures );
  30302. }
  30303. // check if there is already a WebGLTexture object for the given texture parameters
  30304. const textureCacheKey = getTextureCacheKey( texture );
  30305. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  30306. // if not, create a new instance of WebGLTexture
  30307. if ( webglTextures[ textureCacheKey ] === undefined ) {
  30308. // create new entry
  30309. webglTextures[ textureCacheKey ] = {
  30310. texture: _gl.createTexture(),
  30311. usedTimes: 0
  30312. };
  30313. info.memory.textures ++;
  30314. // when a new instance of WebGLTexture was created, a texture upload is required
  30315. // even if the image contents are identical
  30316. forceUpload = true;
  30317. }
  30318. webglTextures[ textureCacheKey ].usedTimes ++;
  30319. // every time the texture cache key changes, it's necessary to check if an instance of
  30320. // WebGLTexture can be deleted in order to avoid a memory leak.
  30321. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  30322. if ( webglTexture !== undefined ) {
  30323. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  30324. if ( webglTexture.usedTimes === 0 ) {
  30325. deleteTexture( texture );
  30326. }
  30327. }
  30328. // store references to cache key and WebGLTexture object
  30329. textureProperties.__cacheKey = textureCacheKey;
  30330. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  30331. }
  30332. return forceUpload;
  30333. }
  30334. function uploadTexture( textureProperties, texture, slot ) {
  30335. let textureType = _gl.TEXTURE_2D;
  30336. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  30337. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  30338. const forceUpload = initTexture( textureProperties, texture );
  30339. const source = texture.source;
  30340. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  30341. const sourceProperties = properties.get( source );
  30342. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  30343. state.activeTexture( _gl.TEXTURE0 + slot );
  30344. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  30345. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  30346. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  30347. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  30348. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  30349. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  30350. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  30351. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  30352. image = verifyColorSpace( texture, image );
  30353. const glFormat = utils.convert( texture.format, texture.colorSpace );
  30354. const glType = utils.convert( texture.type );
  30355. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  30356. setTextureParameters( textureType, texture );
  30357. let mipmap;
  30358. const mipmaps = texture.mipmaps;
  30359. const useTexStorage = ( texture.isVideoTexture !== true );
  30360. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  30361. const dataReady = source.dataReady;
  30362. const levels = getMipLevels( texture, image );
  30363. if ( texture.isDepthTexture ) {
  30364. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  30365. //
  30366. if ( allocateMemory ) {
  30367. if ( useTexStorage ) {
  30368. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  30369. } else {
  30370. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  30371. }
  30372. }
  30373. } else if ( texture.isDataTexture ) {
  30374. // use manually created mipmaps if available
  30375. // if there are no manual mipmaps
  30376. // set 0 level mipmap and then use GL to generate other mipmap levels
  30377. if ( mipmaps.length > 0 ) {
  30378. if ( useTexStorage && allocateMemory ) {
  30379. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  30380. }
  30381. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  30382. mipmap = mipmaps[ i ];
  30383. if ( useTexStorage ) {
  30384. if ( dataReady ) {
  30385. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  30386. }
  30387. } else {
  30388. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  30389. }
  30390. }
  30391. texture.generateMipmaps = false;
  30392. } else {
  30393. if ( useTexStorage ) {
  30394. if ( allocateMemory ) {
  30395. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  30396. }
  30397. if ( dataReady ) {
  30398. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  30399. }
  30400. } else {
  30401. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  30402. }
  30403. }
  30404. } else if ( texture.isCompressedTexture ) {
  30405. if ( texture.isCompressedArrayTexture ) {
  30406. if ( useTexStorage && allocateMemory ) {
  30407. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  30408. }
  30409. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  30410. mipmap = mipmaps[ i ];
  30411. if ( texture.format !== RGBAFormat ) {
  30412. if ( glFormat !== null ) {
  30413. if ( useTexStorage ) {
  30414. if ( dataReady ) {
  30415. if ( texture.layerUpdates.size > 0 ) {
  30416. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  30417. for ( const layerIndex of texture.layerUpdates ) {
  30418. const layerData = mipmap.data.subarray(
  30419. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  30420. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  30421. );
  30422. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  30423. }
  30424. texture.clearLayerUpdates();
  30425. } else {
  30426. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  30427. }
  30428. }
  30429. } else {
  30430. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  30431. }
  30432. } else {
  30433. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  30434. }
  30435. } else {
  30436. if ( useTexStorage ) {
  30437. if ( dataReady ) {
  30438. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  30439. }
  30440. } else {
  30441. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  30442. }
  30443. }
  30444. }
  30445. } else {
  30446. if ( useTexStorage && allocateMemory ) {
  30447. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  30448. }
  30449. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  30450. mipmap = mipmaps[ i ];
  30451. if ( texture.format !== RGBAFormat ) {
  30452. if ( glFormat !== null ) {
  30453. if ( useTexStorage ) {
  30454. if ( dataReady ) {
  30455. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  30456. }
  30457. } else {
  30458. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  30459. }
  30460. } else {
  30461. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  30462. }
  30463. } else {
  30464. if ( useTexStorage ) {
  30465. if ( dataReady ) {
  30466. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  30467. }
  30468. } else {
  30469. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  30470. }
  30471. }
  30472. }
  30473. }
  30474. } else if ( texture.isDataArrayTexture ) {
  30475. if ( useTexStorage ) {
  30476. if ( allocateMemory ) {
  30477. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  30478. }
  30479. if ( dataReady ) {
  30480. if ( texture.layerUpdates.size > 0 ) {
  30481. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  30482. for ( const layerIndex of texture.layerUpdates ) {
  30483. const layerData = image.data.subarray(
  30484. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  30485. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  30486. );
  30487. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  30488. }
  30489. texture.clearLayerUpdates();
  30490. } else {
  30491. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  30492. }
  30493. }
  30494. } else {
  30495. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  30496. }
  30497. } else if ( texture.isData3DTexture ) {
  30498. if ( useTexStorage ) {
  30499. if ( allocateMemory ) {
  30500. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  30501. }
  30502. if ( dataReady ) {
  30503. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  30504. }
  30505. } else {
  30506. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  30507. }
  30508. } else if ( texture.isFramebufferTexture ) {
  30509. if ( allocateMemory ) {
  30510. if ( useTexStorage ) {
  30511. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  30512. } else {
  30513. let width = image.width, height = image.height;
  30514. for ( let i = 0; i < levels; i ++ ) {
  30515. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  30516. width >>= 1;
  30517. height >>= 1;
  30518. }
  30519. }
  30520. }
  30521. } else {
  30522. // regular Texture (image, video, canvas)
  30523. // use manually created mipmaps if available
  30524. // if there are no manual mipmaps
  30525. // set 0 level mipmap and then use GL to generate other mipmap levels
  30526. if ( mipmaps.length > 0 ) {
  30527. if ( useTexStorage && allocateMemory ) {
  30528. const dimensions = getDimensions( mipmaps[ 0 ] );
  30529. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  30530. }
  30531. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  30532. mipmap = mipmaps[ i ];
  30533. if ( useTexStorage ) {
  30534. if ( dataReady ) {
  30535. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  30536. }
  30537. } else {
  30538. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  30539. }
  30540. }
  30541. texture.generateMipmaps = false;
  30542. } else {
  30543. if ( useTexStorage ) {
  30544. if ( allocateMemory ) {
  30545. const dimensions = getDimensions( image );
  30546. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  30547. }
  30548. if ( dataReady ) {
  30549. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  30550. }
  30551. } else {
  30552. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  30553. }
  30554. }
  30555. }
  30556. if ( textureNeedsGenerateMipmaps( texture ) ) {
  30557. generateMipmap( textureType );
  30558. }
  30559. sourceProperties.__version = source.version;
  30560. if ( texture.onUpdate ) texture.onUpdate( texture );
  30561. }
  30562. textureProperties.__version = texture.version;
  30563. }
  30564. function uploadCubeTexture( textureProperties, texture, slot ) {
  30565. if ( texture.image.length !== 6 ) return;
  30566. const forceUpload = initTexture( textureProperties, texture );
  30567. const source = texture.source;
  30568. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  30569. const sourceProperties = properties.get( source );
  30570. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  30571. state.activeTexture( _gl.TEXTURE0 + slot );
  30572. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  30573. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  30574. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  30575. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  30576. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  30577. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  30578. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  30579. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  30580. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  30581. const cubeImage = [];
  30582. for ( let i = 0; i < 6; i ++ ) {
  30583. if ( ! isCompressed && ! isDataTexture ) {
  30584. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  30585. } else {
  30586. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  30587. }
  30588. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  30589. }
  30590. const image = cubeImage[ 0 ],
  30591. glFormat = utils.convert( texture.format, texture.colorSpace ),
  30592. glType = utils.convert( texture.type ),
  30593. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  30594. const useTexStorage = ( texture.isVideoTexture !== true );
  30595. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  30596. const dataReady = source.dataReady;
  30597. let levels = getMipLevels( texture, image );
  30598. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  30599. let mipmaps;
  30600. if ( isCompressed ) {
  30601. if ( useTexStorage && allocateMemory ) {
  30602. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  30603. }
  30604. for ( let i = 0; i < 6; i ++ ) {
  30605. mipmaps = cubeImage[ i ].mipmaps;
  30606. for ( let j = 0; j < mipmaps.length; j ++ ) {
  30607. const mipmap = mipmaps[ j ];
  30608. if ( texture.format !== RGBAFormat ) {
  30609. if ( glFormat !== null ) {
  30610. if ( useTexStorage ) {
  30611. if ( dataReady ) {
  30612. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  30613. }
  30614. } else {
  30615. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  30616. }
  30617. } else {
  30618. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  30619. }
  30620. } else {
  30621. if ( useTexStorage ) {
  30622. if ( dataReady ) {
  30623. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  30624. }
  30625. } else {
  30626. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  30627. }
  30628. }
  30629. }
  30630. }
  30631. } else {
  30632. mipmaps = texture.mipmaps;
  30633. if ( useTexStorage && allocateMemory ) {
  30634. // TODO: Uniformly handle mipmap definitions
  30635. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  30636. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  30637. if ( mipmaps.length > 0 ) levels ++;
  30638. const dimensions = getDimensions( cubeImage[ 0 ] );
  30639. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  30640. }
  30641. for ( let i = 0; i < 6; i ++ ) {
  30642. if ( isDataTexture ) {
  30643. if ( useTexStorage ) {
  30644. if ( dataReady ) {
  30645. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  30646. }
  30647. } else {
  30648. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  30649. }
  30650. for ( let j = 0; j < mipmaps.length; j ++ ) {
  30651. const mipmap = mipmaps[ j ];
  30652. const mipmapImage = mipmap.image[ i ].image;
  30653. if ( useTexStorage ) {
  30654. if ( dataReady ) {
  30655. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  30656. }
  30657. } else {
  30658. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  30659. }
  30660. }
  30661. } else {
  30662. if ( useTexStorage ) {
  30663. if ( dataReady ) {
  30664. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  30665. }
  30666. } else {
  30667. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  30668. }
  30669. for ( let j = 0; j < mipmaps.length; j ++ ) {
  30670. const mipmap = mipmaps[ j ];
  30671. if ( useTexStorage ) {
  30672. if ( dataReady ) {
  30673. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  30674. }
  30675. } else {
  30676. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  30677. }
  30678. }
  30679. }
  30680. }
  30681. }
  30682. if ( textureNeedsGenerateMipmaps( texture ) ) {
  30683. // We assume images for cube map have the same size.
  30684. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  30685. }
  30686. sourceProperties.__version = source.version;
  30687. if ( texture.onUpdate ) texture.onUpdate( texture );
  30688. }
  30689. textureProperties.__version = texture.version;
  30690. }
  30691. // Render targets
  30692. // Setup storage for target texture and bind it to correct framebuffer
  30693. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  30694. const glFormat = utils.convert( texture.format, texture.colorSpace );
  30695. const glType = utils.convert( texture.type );
  30696. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  30697. const renderTargetProperties = properties.get( renderTarget );
  30698. const textureProperties = properties.get( texture );
  30699. textureProperties.__renderTarget = renderTarget;
  30700. if ( ! renderTargetProperties.__hasExternalTextures ) {
  30701. const width = Math.max( 1, renderTarget.width >> level );
  30702. const height = Math.max( 1, renderTarget.height >> level );
  30703. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  30704. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  30705. } else {
  30706. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  30707. }
  30708. }
  30709. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  30710. if ( useMultisampledRTT( renderTarget ) ) {
  30711. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  30712. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  30713. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  30714. }
  30715. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  30716. }
  30717. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  30718. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  30719. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  30720. if ( renderTarget.depthBuffer ) {
  30721. // retrieve the depth attachment types
  30722. const depthTexture = renderTarget.depthTexture;
  30723. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  30724. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  30725. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  30726. // set up the attachment
  30727. const samples = getRenderTargetSamples( renderTarget );
  30728. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  30729. if ( isUseMultisampledRTT ) {
  30730. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  30731. } else if ( isMultisample ) {
  30732. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  30733. } else {
  30734. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  30735. }
  30736. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  30737. } else {
  30738. const textures = renderTarget.textures;
  30739. for ( let i = 0; i < textures.length; i ++ ) {
  30740. const texture = textures[ i ];
  30741. const glFormat = utils.convert( texture.format, texture.colorSpace );
  30742. const glType = utils.convert( texture.type );
  30743. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  30744. const samples = getRenderTargetSamples( renderTarget );
  30745. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  30746. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  30747. } else if ( useMultisampledRTT( renderTarget ) ) {
  30748. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  30749. } else {
  30750. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  30751. }
  30752. }
  30753. }
  30754. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  30755. }
  30756. // Setup resources for a Depth Texture for a FBO (needs an extension)
  30757. function setupDepthTexture( framebuffer, renderTarget ) {
  30758. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  30759. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  30760. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  30761. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  30762. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  30763. }
  30764. const textureProperties = properties.get( renderTarget.depthTexture );
  30765. textureProperties.__renderTarget = renderTarget;
  30766. // upload an empty depth texture with framebuffer size
  30767. if ( ! textureProperties.__webglTexture ||
  30768. renderTarget.depthTexture.image.width !== renderTarget.width ||
  30769. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  30770. renderTarget.depthTexture.image.width = renderTarget.width;
  30771. renderTarget.depthTexture.image.height = renderTarget.height;
  30772. renderTarget.depthTexture.needsUpdate = true;
  30773. }
  30774. setTexture2D( renderTarget.depthTexture, 0 );
  30775. const webglDepthTexture = textureProperties.__webglTexture;
  30776. const samples = getRenderTargetSamples( renderTarget );
  30777. if ( renderTarget.depthTexture.format === DepthFormat ) {
  30778. if ( useMultisampledRTT( renderTarget ) ) {
  30779. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  30780. } else {
  30781. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  30782. }
  30783. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  30784. if ( useMultisampledRTT( renderTarget ) ) {
  30785. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  30786. } else {
  30787. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  30788. }
  30789. } else {
  30790. throw new Error( 'Unknown depthTexture format' );
  30791. }
  30792. }
  30793. // Setup GL resources for a non-texture depth buffer
  30794. function setupDepthRenderbuffer( renderTarget ) {
  30795. const renderTargetProperties = properties.get( renderTarget );
  30796. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  30797. // if the bound depth texture has changed
  30798. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  30799. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  30800. const depthTexture = renderTarget.depthTexture;
  30801. if ( renderTargetProperties.__depthDisposeCallback ) {
  30802. renderTargetProperties.__depthDisposeCallback();
  30803. }
  30804. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  30805. if ( depthTexture ) {
  30806. const disposeEvent = () => {
  30807. delete renderTargetProperties.__boundDepthTexture;
  30808. delete renderTargetProperties.__depthDisposeCallback;
  30809. depthTexture.removeEventListener( 'dispose', disposeEvent );
  30810. };
  30811. depthTexture.addEventListener( 'dispose', disposeEvent );
  30812. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  30813. }
  30814. renderTargetProperties.__boundDepthTexture = depthTexture;
  30815. }
  30816. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  30817. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  30818. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  30819. } else {
  30820. if ( isCube ) {
  30821. renderTargetProperties.__webglDepthbuffer = [];
  30822. for ( let i = 0; i < 6; i ++ ) {
  30823. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  30824. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  30825. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  30826. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  30827. } else {
  30828. // attach buffer if it's been created already
  30829. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  30830. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  30831. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  30832. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  30833. }
  30834. }
  30835. } else {
  30836. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  30837. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  30838. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  30839. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  30840. } else {
  30841. // attach buffer if it's been created already
  30842. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  30843. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  30844. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  30845. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  30846. }
  30847. }
  30848. }
  30849. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  30850. }
  30851. // rebind framebuffer with external textures
  30852. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  30853. const renderTargetProperties = properties.get( renderTarget );
  30854. if ( colorTexture !== undefined ) {
  30855. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  30856. }
  30857. if ( depthTexture !== undefined ) {
  30858. setupDepthRenderbuffer( renderTarget );
  30859. }
  30860. }
  30861. // Set up GL resources for the render target
  30862. function setupRenderTarget( renderTarget ) {
  30863. const texture = renderTarget.texture;
  30864. const renderTargetProperties = properties.get( renderTarget );
  30865. const textureProperties = properties.get( texture );
  30866. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  30867. const textures = renderTarget.textures;
  30868. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  30869. const isMultipleRenderTargets = ( textures.length > 1 );
  30870. if ( ! isMultipleRenderTargets ) {
  30871. if ( textureProperties.__webglTexture === undefined ) {
  30872. textureProperties.__webglTexture = _gl.createTexture();
  30873. }
  30874. textureProperties.__version = texture.version;
  30875. info.memory.textures ++;
  30876. }
  30877. // Setup framebuffer
  30878. if ( isCube ) {
  30879. renderTargetProperties.__webglFramebuffer = [];
  30880. for ( let i = 0; i < 6; i ++ ) {
  30881. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  30882. renderTargetProperties.__webglFramebuffer[ i ] = [];
  30883. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  30884. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  30885. }
  30886. } else {
  30887. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  30888. }
  30889. }
  30890. } else {
  30891. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  30892. renderTargetProperties.__webglFramebuffer = [];
  30893. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  30894. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  30895. }
  30896. } else {
  30897. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  30898. }
  30899. if ( isMultipleRenderTargets ) {
  30900. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  30901. const attachmentProperties = properties.get( textures[ i ] );
  30902. if ( attachmentProperties.__webglTexture === undefined ) {
  30903. attachmentProperties.__webglTexture = _gl.createTexture();
  30904. info.memory.textures ++;
  30905. }
  30906. }
  30907. }
  30908. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  30909. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  30910. renderTargetProperties.__webglColorRenderbuffer = [];
  30911. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  30912. for ( let i = 0; i < textures.length; i ++ ) {
  30913. const texture = textures[ i ];
  30914. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  30915. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  30916. const glFormat = utils.convert( texture.format, texture.colorSpace );
  30917. const glType = utils.convert( texture.type );
  30918. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  30919. const samples = getRenderTargetSamples( renderTarget );
  30920. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  30921. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  30922. }
  30923. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  30924. if ( renderTarget.depthBuffer ) {
  30925. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  30926. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  30927. }
  30928. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  30929. }
  30930. }
  30931. // Setup color buffer
  30932. if ( isCube ) {
  30933. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  30934. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  30935. for ( let i = 0; i < 6; i ++ ) {
  30936. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  30937. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  30938. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  30939. }
  30940. } else {
  30941. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  30942. }
  30943. }
  30944. if ( textureNeedsGenerateMipmaps( texture ) ) {
  30945. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  30946. }
  30947. state.unbindTexture();
  30948. } else if ( isMultipleRenderTargets ) {
  30949. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  30950. const attachment = textures[ i ];
  30951. const attachmentProperties = properties.get( attachment );
  30952. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  30953. setTextureParameters( _gl.TEXTURE_2D, attachment );
  30954. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  30955. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  30956. generateMipmap( _gl.TEXTURE_2D );
  30957. }
  30958. }
  30959. state.unbindTexture();
  30960. } else {
  30961. let glTextureType = _gl.TEXTURE_2D;
  30962. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  30963. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  30964. }
  30965. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  30966. setTextureParameters( glTextureType, texture );
  30967. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  30968. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  30969. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  30970. }
  30971. } else {
  30972. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  30973. }
  30974. if ( textureNeedsGenerateMipmaps( texture ) ) {
  30975. generateMipmap( glTextureType );
  30976. }
  30977. state.unbindTexture();
  30978. }
  30979. // Setup depth and stencil buffers
  30980. if ( renderTarget.depthBuffer ) {
  30981. setupDepthRenderbuffer( renderTarget );
  30982. }
  30983. }
  30984. function updateRenderTargetMipmap( renderTarget ) {
  30985. const textures = renderTarget.textures;
  30986. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  30987. const texture = textures[ i ];
  30988. if ( textureNeedsGenerateMipmaps( texture ) ) {
  30989. const targetType = getTargetType( renderTarget );
  30990. const webglTexture = properties.get( texture ).__webglTexture;
  30991. state.bindTexture( targetType, webglTexture );
  30992. generateMipmap( targetType );
  30993. state.unbindTexture();
  30994. }
  30995. }
  30996. }
  30997. const invalidationArrayRead = [];
  30998. const invalidationArrayDraw = [];
  30999. function updateMultisampleRenderTarget( renderTarget ) {
  31000. if ( renderTarget.samples > 0 ) {
  31001. if ( useMultisampledRTT( renderTarget ) === false ) {
  31002. const textures = renderTarget.textures;
  31003. const width = renderTarget.width;
  31004. const height = renderTarget.height;
  31005. let mask = _gl.COLOR_BUFFER_BIT;
  31006. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  31007. const renderTargetProperties = properties.get( renderTarget );
  31008. const isMultipleRenderTargets = ( textures.length > 1 );
  31009. // If MRT we need to remove FBO attachments
  31010. if ( isMultipleRenderTargets ) {
  31011. for ( let i = 0; i < textures.length; i ++ ) {
  31012. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  31013. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  31014. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  31015. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  31016. }
  31017. }
  31018. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  31019. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  31020. for ( let i = 0; i < textures.length; i ++ ) {
  31021. if ( renderTarget.resolveDepthBuffer ) {
  31022. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  31023. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  31024. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  31025. }
  31026. if ( isMultipleRenderTargets ) {
  31027. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  31028. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  31029. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  31030. }
  31031. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  31032. if ( supportsInvalidateFramebuffer === true ) {
  31033. invalidationArrayRead.length = 0;
  31034. invalidationArrayDraw.length = 0;
  31035. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  31036. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  31037. invalidationArrayRead.push( depthStyle );
  31038. invalidationArrayDraw.push( depthStyle );
  31039. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  31040. }
  31041. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  31042. }
  31043. }
  31044. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  31045. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  31046. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  31047. if ( isMultipleRenderTargets ) {
  31048. for ( let i = 0; i < textures.length; i ++ ) {
  31049. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  31050. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  31051. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  31052. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  31053. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  31054. }
  31055. }
  31056. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  31057. } else {
  31058. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  31059. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  31060. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  31061. }
  31062. }
  31063. }
  31064. }
  31065. function getRenderTargetSamples( renderTarget ) {
  31066. return Math.min( capabilities.maxSamples, renderTarget.samples );
  31067. }
  31068. function useMultisampledRTT( renderTarget ) {
  31069. const renderTargetProperties = properties.get( renderTarget );
  31070. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  31071. }
  31072. function updateVideoTexture( texture ) {
  31073. const frame = info.render.frame;
  31074. // Check the last frame we updated the VideoTexture
  31075. if ( _videoTextures.get( texture ) !== frame ) {
  31076. _videoTextures.set( texture, frame );
  31077. texture.update();
  31078. }
  31079. }
  31080. function verifyColorSpace( texture, image ) {
  31081. const colorSpace = texture.colorSpace;
  31082. const format = texture.format;
  31083. const type = texture.type;
  31084. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  31085. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  31086. // sRGB
  31087. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  31088. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  31089. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  31090. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  31091. }
  31092. } else {
  31093. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  31094. }
  31095. }
  31096. return image;
  31097. }
  31098. function getDimensions( image ) {
  31099. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  31100. // if intrinsic data are not available, fallback to width/height
  31101. _imageDimensions.width = image.naturalWidth || image.width;
  31102. _imageDimensions.height = image.naturalHeight || image.height;
  31103. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  31104. _imageDimensions.width = image.displayWidth;
  31105. _imageDimensions.height = image.displayHeight;
  31106. } else {
  31107. _imageDimensions.width = image.width;
  31108. _imageDimensions.height = image.height;
  31109. }
  31110. return _imageDimensions;
  31111. }
  31112. //
  31113. this.allocateTextureUnit = allocateTextureUnit;
  31114. this.resetTextureUnits = resetTextureUnits;
  31115. this.setTexture2D = setTexture2D;
  31116. this.setTexture2DArray = setTexture2DArray;
  31117. this.setTexture3D = setTexture3D;
  31118. this.setTextureCube = setTextureCube;
  31119. this.rebindTextures = rebindTextures;
  31120. this.setupRenderTarget = setupRenderTarget;
  31121. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  31122. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  31123. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  31124. this.setupFrameBufferTexture = setupFrameBufferTexture;
  31125. this.useMultisampledRTT = useMultisampledRTT;
  31126. }
  31127. function WebGLUtils( gl, extensions ) {
  31128. function convert( p, colorSpace = NoColorSpace ) {
  31129. let extension;
  31130. const transfer = ColorManagement.getTransfer( colorSpace );
  31131. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  31132. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  31133. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  31134. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  31135. if ( p === ByteType ) return gl.BYTE;
  31136. if ( p === ShortType ) return gl.SHORT;
  31137. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  31138. if ( p === IntType ) return gl.INT;
  31139. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  31140. if ( p === FloatType ) return gl.FLOAT;
  31141. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  31142. if ( p === AlphaFormat ) return gl.ALPHA;
  31143. if ( p === RGBFormat ) return gl.RGB;
  31144. if ( p === RGBAFormat ) return gl.RGBA;
  31145. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  31146. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  31147. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  31148. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  31149. // WebGL2 formats.
  31150. if ( p === RedFormat ) return gl.RED;
  31151. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  31152. if ( p === RGFormat ) return gl.RG;
  31153. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  31154. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  31155. // S3TC
  31156. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  31157. if ( transfer === SRGBTransfer ) {
  31158. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  31159. if ( extension !== null ) {
  31160. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  31161. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  31162. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  31163. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  31164. } else {
  31165. return null;
  31166. }
  31167. } else {
  31168. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  31169. if ( extension !== null ) {
  31170. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  31171. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  31172. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  31173. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  31174. } else {
  31175. return null;
  31176. }
  31177. }
  31178. }
  31179. // PVRTC
  31180. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  31181. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  31182. if ( extension !== null ) {
  31183. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  31184. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  31185. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  31186. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  31187. } else {
  31188. return null;
  31189. }
  31190. }
  31191. // ETC
  31192. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  31193. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  31194. if ( extension !== null ) {
  31195. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  31196. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  31197. } else {
  31198. return null;
  31199. }
  31200. }
  31201. // ASTC
  31202. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  31203. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  31204. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  31205. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  31206. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  31207. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  31208. if ( extension !== null ) {
  31209. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  31210. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  31211. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  31212. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  31213. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  31214. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  31215. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  31216. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  31217. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  31218. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  31219. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  31220. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  31221. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  31222. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  31223. } else {
  31224. return null;
  31225. }
  31226. }
  31227. // BPTC
  31228. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  31229. extension = extensions.get( 'EXT_texture_compression_bptc' );
  31230. if ( extension !== null ) {
  31231. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  31232. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  31233. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  31234. } else {
  31235. return null;
  31236. }
  31237. }
  31238. // RGTC
  31239. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  31240. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  31241. if ( extension !== null ) {
  31242. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  31243. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  31244. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  31245. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  31246. } else {
  31247. return null;
  31248. }
  31249. }
  31250. //
  31251. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  31252. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  31253. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  31254. }
  31255. return { convert: convert };
  31256. }
  31257. const _occlusion_vertex = `
  31258. void main() {
  31259. gl_Position = vec4( position, 1.0 );
  31260. }`;
  31261. const _occlusion_fragment = `
  31262. uniform sampler2DArray depthColor;
  31263. uniform float depthWidth;
  31264. uniform float depthHeight;
  31265. void main() {
  31266. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  31267. if ( coord.x >= 1.0 ) {
  31268. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  31269. } else {
  31270. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  31271. }
  31272. }`;
  31273. class WebXRDepthSensing {
  31274. constructor() {
  31275. this.texture = null;
  31276. this.mesh = null;
  31277. this.depthNear = 0;
  31278. this.depthFar = 0;
  31279. }
  31280. init( renderer, depthData, renderState ) {
  31281. if ( this.texture === null ) {
  31282. const texture = new Texture();
  31283. const texProps = renderer.properties.get( texture );
  31284. texProps.__webglTexture = depthData.texture;
  31285. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  31286. this.depthNear = depthData.depthNear;
  31287. this.depthFar = depthData.depthFar;
  31288. }
  31289. this.texture = texture;
  31290. }
  31291. }
  31292. getMesh( cameraXR ) {
  31293. if ( this.texture !== null ) {
  31294. if ( this.mesh === null ) {
  31295. const viewport = cameraXR.cameras[ 0 ].viewport;
  31296. const material = new ShaderMaterial( {
  31297. vertexShader: _occlusion_vertex,
  31298. fragmentShader: _occlusion_fragment,
  31299. uniforms: {
  31300. depthColor: { value: this.texture },
  31301. depthWidth: { value: viewport.z },
  31302. depthHeight: { value: viewport.w }
  31303. }
  31304. } );
  31305. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  31306. }
  31307. }
  31308. return this.mesh;
  31309. }
  31310. reset() {
  31311. this.texture = null;
  31312. this.mesh = null;
  31313. }
  31314. getDepthTexture() {
  31315. return this.texture;
  31316. }
  31317. }
  31318. class WebXRManager extends EventDispatcher {
  31319. constructor( renderer, gl ) {
  31320. super();
  31321. const scope = this;
  31322. let session = null;
  31323. let framebufferScaleFactor = 1.0;
  31324. let referenceSpace = null;
  31325. let referenceSpaceType = 'local-floor';
  31326. // Set default foveation to maximum.
  31327. let foveation = 1.0;
  31328. let customReferenceSpace = null;
  31329. let pose = null;
  31330. let glBinding = null;
  31331. let glProjLayer = null;
  31332. let glBaseLayer = null;
  31333. let xrFrame = null;
  31334. const depthSensing = new WebXRDepthSensing();
  31335. const attributes = gl.getContextAttributes();
  31336. let initialRenderTarget = null;
  31337. let newRenderTarget = null;
  31338. const controllers = [];
  31339. const controllerInputSources = [];
  31340. const currentSize = new Vector2();
  31341. let currentPixelRatio = null;
  31342. //
  31343. const cameraL = new PerspectiveCamera();
  31344. cameraL.viewport = new Vector4();
  31345. const cameraR = new PerspectiveCamera();
  31346. cameraR.viewport = new Vector4();
  31347. const cameras = [ cameraL, cameraR ];
  31348. const cameraXR = new ArrayCamera();
  31349. let _currentDepthNear = null;
  31350. let _currentDepthFar = null;
  31351. //
  31352. this.cameraAutoUpdate = true;
  31353. this.enabled = false;
  31354. this.isPresenting = false;
  31355. this.getController = function ( index ) {
  31356. let controller = controllers[ index ];
  31357. if ( controller === undefined ) {
  31358. controller = new WebXRController();
  31359. controllers[ index ] = controller;
  31360. }
  31361. return controller.getTargetRaySpace();
  31362. };
  31363. this.getControllerGrip = function ( index ) {
  31364. let controller = controllers[ index ];
  31365. if ( controller === undefined ) {
  31366. controller = new WebXRController();
  31367. controllers[ index ] = controller;
  31368. }
  31369. return controller.getGripSpace();
  31370. };
  31371. this.getHand = function ( index ) {
  31372. let controller = controllers[ index ];
  31373. if ( controller === undefined ) {
  31374. controller = new WebXRController();
  31375. controllers[ index ] = controller;
  31376. }
  31377. return controller.getHandSpace();
  31378. };
  31379. //
  31380. function onSessionEvent( event ) {
  31381. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  31382. if ( controllerIndex === -1 ) {
  31383. return;
  31384. }
  31385. const controller = controllers[ controllerIndex ];
  31386. if ( controller !== undefined ) {
  31387. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  31388. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  31389. }
  31390. }
  31391. function onSessionEnd() {
  31392. session.removeEventListener( 'select', onSessionEvent );
  31393. session.removeEventListener( 'selectstart', onSessionEvent );
  31394. session.removeEventListener( 'selectend', onSessionEvent );
  31395. session.removeEventListener( 'squeeze', onSessionEvent );
  31396. session.removeEventListener( 'squeezestart', onSessionEvent );
  31397. session.removeEventListener( 'squeezeend', onSessionEvent );
  31398. session.removeEventListener( 'end', onSessionEnd );
  31399. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  31400. for ( let i = 0; i < controllers.length; i ++ ) {
  31401. const inputSource = controllerInputSources[ i ];
  31402. if ( inputSource === null ) continue;
  31403. controllerInputSources[ i ] = null;
  31404. controllers[ i ].disconnect( inputSource );
  31405. }
  31406. _currentDepthNear = null;
  31407. _currentDepthFar = null;
  31408. depthSensing.reset();
  31409. // restore framebuffer/rendering state
  31410. renderer.setRenderTarget( initialRenderTarget );
  31411. glBaseLayer = null;
  31412. glProjLayer = null;
  31413. glBinding = null;
  31414. session = null;
  31415. newRenderTarget = null;
  31416. //
  31417. animation.stop();
  31418. scope.isPresenting = false;
  31419. renderer.setPixelRatio( currentPixelRatio );
  31420. renderer.setSize( currentSize.width, currentSize.height, false );
  31421. scope.dispatchEvent( { type: 'sessionend' } );
  31422. }
  31423. this.setFramebufferScaleFactor = function ( value ) {
  31424. framebufferScaleFactor = value;
  31425. if ( scope.isPresenting === true ) {
  31426. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  31427. }
  31428. };
  31429. this.setReferenceSpaceType = function ( value ) {
  31430. referenceSpaceType = value;
  31431. if ( scope.isPresenting === true ) {
  31432. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  31433. }
  31434. };
  31435. this.getReferenceSpace = function () {
  31436. return customReferenceSpace || referenceSpace;
  31437. };
  31438. this.setReferenceSpace = function ( space ) {
  31439. customReferenceSpace = space;
  31440. };
  31441. this.getBaseLayer = function () {
  31442. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  31443. };
  31444. this.getBinding = function () {
  31445. return glBinding;
  31446. };
  31447. this.getFrame = function () {
  31448. return xrFrame;
  31449. };
  31450. this.getSession = function () {
  31451. return session;
  31452. };
  31453. this.setSession = async function ( value ) {
  31454. session = value;
  31455. if ( session !== null ) {
  31456. initialRenderTarget = renderer.getRenderTarget();
  31457. session.addEventListener( 'select', onSessionEvent );
  31458. session.addEventListener( 'selectstart', onSessionEvent );
  31459. session.addEventListener( 'selectend', onSessionEvent );
  31460. session.addEventListener( 'squeeze', onSessionEvent );
  31461. session.addEventListener( 'squeezestart', onSessionEvent );
  31462. session.addEventListener( 'squeezeend', onSessionEvent );
  31463. session.addEventListener( 'end', onSessionEnd );
  31464. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  31465. if ( attributes.xrCompatible !== true ) {
  31466. await gl.makeXRCompatible();
  31467. }
  31468. currentPixelRatio = renderer.getPixelRatio();
  31469. renderer.getSize( currentSize );
  31470. // Check that the browser implements the necessary APIs to use an
  31471. // XRProjectionLayer rather than an XRWebGLLayer
  31472. const useLayers = typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype;
  31473. if ( ! useLayers ) {
  31474. const layerInit = {
  31475. antialias: attributes.antialias,
  31476. alpha: true,
  31477. depth: attributes.depth,
  31478. stencil: attributes.stencil,
  31479. framebufferScaleFactor: framebufferScaleFactor
  31480. };
  31481. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  31482. session.updateRenderState( { baseLayer: glBaseLayer } );
  31483. renderer.setPixelRatio( 1 );
  31484. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  31485. newRenderTarget = new WebGLRenderTarget(
  31486. glBaseLayer.framebufferWidth,
  31487. glBaseLayer.framebufferHeight,
  31488. {
  31489. format: RGBAFormat,
  31490. type: UnsignedByteType,
  31491. colorSpace: renderer.outputColorSpace,
  31492. stencilBuffer: attributes.stencil
  31493. }
  31494. );
  31495. } else {
  31496. let depthFormat = null;
  31497. let depthType = null;
  31498. let glDepthFormat = null;
  31499. if ( attributes.depth ) {
  31500. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  31501. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  31502. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  31503. }
  31504. const projectionlayerInit = {
  31505. colorFormat: gl.RGBA8,
  31506. depthFormat: glDepthFormat,
  31507. scaleFactor: framebufferScaleFactor
  31508. };
  31509. glBinding = new XRWebGLBinding( session, gl );
  31510. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  31511. session.updateRenderState( { layers: [ glProjLayer ] } );
  31512. renderer.setPixelRatio( 1 );
  31513. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  31514. newRenderTarget = new WebGLRenderTarget(
  31515. glProjLayer.textureWidth,
  31516. glProjLayer.textureHeight,
  31517. {
  31518. format: RGBAFormat,
  31519. type: UnsignedByteType,
  31520. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  31521. stencilBuffer: attributes.stencil,
  31522. colorSpace: renderer.outputColorSpace,
  31523. samples: attributes.antialias ? 4 : 0,
  31524. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false )
  31525. } );
  31526. }
  31527. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  31528. this.setFoveation( foveation );
  31529. customReferenceSpace = null;
  31530. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  31531. animation.setContext( session );
  31532. animation.start();
  31533. scope.isPresenting = true;
  31534. scope.dispatchEvent( { type: 'sessionstart' } );
  31535. }
  31536. };
  31537. this.getEnvironmentBlendMode = function () {
  31538. if ( session !== null ) {
  31539. return session.environmentBlendMode;
  31540. }
  31541. };
  31542. this.getDepthTexture = function () {
  31543. return depthSensing.getDepthTexture();
  31544. };
  31545. function onInputSourcesChange( event ) {
  31546. // Notify disconnected
  31547. for ( let i = 0; i < event.removed.length; i ++ ) {
  31548. const inputSource = event.removed[ i ];
  31549. const index = controllerInputSources.indexOf( inputSource );
  31550. if ( index >= 0 ) {
  31551. controllerInputSources[ index ] = null;
  31552. controllers[ index ].disconnect( inputSource );
  31553. }
  31554. }
  31555. // Notify connected
  31556. for ( let i = 0; i < event.added.length; i ++ ) {
  31557. const inputSource = event.added[ i ];
  31558. let controllerIndex = controllerInputSources.indexOf( inputSource );
  31559. if ( controllerIndex === -1 ) {
  31560. // Assign input source a controller that currently has no input source
  31561. for ( let i = 0; i < controllers.length; i ++ ) {
  31562. if ( i >= controllerInputSources.length ) {
  31563. controllerInputSources.push( inputSource );
  31564. controllerIndex = i;
  31565. break;
  31566. } else if ( controllerInputSources[ i ] === null ) {
  31567. controllerInputSources[ i ] = inputSource;
  31568. controllerIndex = i;
  31569. break;
  31570. }
  31571. }
  31572. // If all controllers do currently receive input we ignore new ones
  31573. if ( controllerIndex === -1 ) break;
  31574. }
  31575. const controller = controllers[ controllerIndex ];
  31576. if ( controller ) {
  31577. controller.connect( inputSource );
  31578. }
  31579. }
  31580. }
  31581. //
  31582. const cameraLPos = new Vector3();
  31583. const cameraRPos = new Vector3();
  31584. /**
  31585. * Assumes 2 cameras that are parallel and share an X-axis, and that
  31586. * the cameras' projection and world matrices have already been set.
  31587. * And that near and far planes are identical for both cameras.
  31588. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  31589. *
  31590. * @param {ArrayCamera} camera - The camera to update.
  31591. * @param {PerspectiveCamera} cameraL - The left camera.
  31592. * @param {PerspectiveCamera} cameraR - The right camera.
  31593. */
  31594. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  31595. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  31596. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  31597. const ipd = cameraLPos.distanceTo( cameraRPos );
  31598. const projL = cameraL.projectionMatrix.elements;
  31599. const projR = cameraR.projectionMatrix.elements;
  31600. // VR systems will have identical far and near planes, and
  31601. // most likely identical top and bottom frustum extents.
  31602. // Use the left camera for these values.
  31603. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  31604. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  31605. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  31606. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  31607. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  31608. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  31609. const left = near * leftFov;
  31610. const right = near * rightFov;
  31611. // Calculate the new camera's position offset from the
  31612. // left camera. xOffset should be roughly half `ipd`.
  31613. const zOffset = ipd / ( - leftFov + rightFov );
  31614. const xOffset = zOffset * - leftFov;
  31615. // TODO: Better way to apply this offset?
  31616. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  31617. camera.translateX( xOffset );
  31618. camera.translateZ( zOffset );
  31619. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  31620. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  31621. // Check if the projection uses an infinite far plane.
  31622. if ( projL[ 10 ] === -1 ) {
  31623. // Use the projection matrix from the left eye.
  31624. // The camera offset is sufficient to include the view volumes
  31625. // of both eyes (assuming symmetric projections).
  31626. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  31627. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  31628. } else {
  31629. // Find the union of the frustum values of the cameras and scale
  31630. // the values so that the near plane's position does not change in world space,
  31631. // although must now be relative to the new union camera.
  31632. const near2 = near + zOffset;
  31633. const far2 = far + zOffset;
  31634. const left2 = left - xOffset;
  31635. const right2 = right + ( ipd - xOffset );
  31636. const top2 = topFov * far / far2 * near2;
  31637. const bottom2 = bottomFov * far / far2 * near2;
  31638. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  31639. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  31640. }
  31641. }
  31642. function updateCamera( camera, parent ) {
  31643. if ( parent === null ) {
  31644. camera.matrixWorld.copy( camera.matrix );
  31645. } else {
  31646. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  31647. }
  31648. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  31649. }
  31650. this.updateCamera = function ( camera ) {
  31651. if ( session === null ) return;
  31652. let depthNear = camera.near;
  31653. let depthFar = camera.far;
  31654. if ( depthSensing.texture !== null ) {
  31655. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  31656. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  31657. }
  31658. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  31659. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  31660. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  31661. // Note that the new renderState won't apply until the next frame. See #18320
  31662. session.updateRenderState( {
  31663. depthNear: cameraXR.near,
  31664. depthFar: cameraXR.far
  31665. } );
  31666. _currentDepthNear = cameraXR.near;
  31667. _currentDepthFar = cameraXR.far;
  31668. }
  31669. cameraL.layers.mask = camera.layers.mask | 0b010;
  31670. cameraR.layers.mask = camera.layers.mask | 0b100;
  31671. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  31672. const parent = camera.parent;
  31673. const cameras = cameraXR.cameras;
  31674. updateCamera( cameraXR, parent );
  31675. for ( let i = 0; i < cameras.length; i ++ ) {
  31676. updateCamera( cameras[ i ], parent );
  31677. }
  31678. // update projection matrix for proper view frustum culling
  31679. if ( cameras.length === 2 ) {
  31680. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  31681. } else {
  31682. // assume single camera setup (AR)
  31683. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  31684. }
  31685. // update user camera and its children
  31686. updateUserCamera( camera, cameraXR, parent );
  31687. };
  31688. function updateUserCamera( camera, cameraXR, parent ) {
  31689. if ( parent === null ) {
  31690. camera.matrix.copy( cameraXR.matrixWorld );
  31691. } else {
  31692. camera.matrix.copy( parent.matrixWorld );
  31693. camera.matrix.invert();
  31694. camera.matrix.multiply( cameraXR.matrixWorld );
  31695. }
  31696. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  31697. camera.updateMatrixWorld( true );
  31698. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  31699. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  31700. if ( camera.isPerspectiveCamera ) {
  31701. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  31702. camera.zoom = 1;
  31703. }
  31704. }
  31705. this.getCamera = function () {
  31706. return cameraXR;
  31707. };
  31708. this.getFoveation = function () {
  31709. if ( glProjLayer === null && glBaseLayer === null ) {
  31710. return undefined;
  31711. }
  31712. return foveation;
  31713. };
  31714. this.setFoveation = function ( value ) {
  31715. // 0 = no foveation = full resolution
  31716. // 1 = maximum foveation = the edges render at lower resolution
  31717. foveation = value;
  31718. if ( glProjLayer !== null ) {
  31719. glProjLayer.fixedFoveation = value;
  31720. }
  31721. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  31722. glBaseLayer.fixedFoveation = value;
  31723. }
  31724. };
  31725. this.hasDepthSensing = function () {
  31726. return depthSensing.texture !== null;
  31727. };
  31728. this.getDepthSensingMesh = function () {
  31729. return depthSensing.getMesh( cameraXR );
  31730. };
  31731. // Animation Loop
  31732. let onAnimationFrameCallback = null;
  31733. function onAnimationFrame( time, frame ) {
  31734. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  31735. xrFrame = frame;
  31736. if ( pose !== null ) {
  31737. const views = pose.views;
  31738. if ( glBaseLayer !== null ) {
  31739. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  31740. renderer.setRenderTarget( newRenderTarget );
  31741. }
  31742. let cameraXRNeedsUpdate = false;
  31743. // check if it's necessary to rebuild cameraXR's camera list
  31744. if ( views.length !== cameraXR.cameras.length ) {
  31745. cameraXR.cameras.length = 0;
  31746. cameraXRNeedsUpdate = true;
  31747. }
  31748. for ( let i = 0; i < views.length; i ++ ) {
  31749. const view = views[ i ];
  31750. let viewport = null;
  31751. if ( glBaseLayer !== null ) {
  31752. viewport = glBaseLayer.getViewport( view );
  31753. } else {
  31754. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  31755. viewport = glSubImage.viewport;
  31756. // For side-by-side projection, we only produce a single texture for both eyes.
  31757. if ( i === 0 ) {
  31758. renderer.setRenderTargetTextures(
  31759. newRenderTarget,
  31760. glSubImage.colorTexture,
  31761. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  31762. renderer.setRenderTarget( newRenderTarget );
  31763. }
  31764. }
  31765. let camera = cameras[ i ];
  31766. if ( camera === undefined ) {
  31767. camera = new PerspectiveCamera();
  31768. camera.layers.enable( i );
  31769. camera.viewport = new Vector4();
  31770. cameras[ i ] = camera;
  31771. }
  31772. camera.matrix.fromArray( view.transform.matrix );
  31773. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  31774. camera.projectionMatrix.fromArray( view.projectionMatrix );
  31775. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  31776. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  31777. if ( i === 0 ) {
  31778. cameraXR.matrix.copy( camera.matrix );
  31779. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  31780. }
  31781. if ( cameraXRNeedsUpdate === true ) {
  31782. cameraXR.cameras.push( camera );
  31783. }
  31784. }
  31785. //
  31786. const enabledFeatures = session.enabledFeatures;
  31787. const gpuDepthSensingEnabled = enabledFeatures &&
  31788. enabledFeatures.includes( 'depth-sensing' ) &&
  31789. session.depthUsage == 'gpu-optimized';
  31790. if ( gpuDepthSensingEnabled && glBinding ) {
  31791. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  31792. if ( depthData && depthData.isValid && depthData.texture ) {
  31793. depthSensing.init( renderer, depthData, session.renderState );
  31794. }
  31795. }
  31796. }
  31797. //
  31798. for ( let i = 0; i < controllers.length; i ++ ) {
  31799. const inputSource = controllerInputSources[ i ];
  31800. const controller = controllers[ i ];
  31801. if ( inputSource !== null && controller !== undefined ) {
  31802. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  31803. }
  31804. }
  31805. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  31806. if ( frame.detectedPlanes ) {
  31807. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  31808. }
  31809. xrFrame = null;
  31810. }
  31811. const animation = new WebGLAnimation();
  31812. animation.setAnimationLoop( onAnimationFrame );
  31813. this.setAnimationLoop = function ( callback ) {
  31814. onAnimationFrameCallback = callback;
  31815. };
  31816. this.dispose = function () {};
  31817. }
  31818. }
  31819. const _e1 = /*@__PURE__*/ new Euler();
  31820. const _m1 = /*@__PURE__*/ new Matrix4();
  31821. function WebGLMaterials( renderer, properties ) {
  31822. function refreshTransformUniform( map, uniform ) {
  31823. if ( map.matrixAutoUpdate === true ) {
  31824. map.updateMatrix();
  31825. }
  31826. uniform.value.copy( map.matrix );
  31827. }
  31828. function refreshFogUniforms( uniforms, fog ) {
  31829. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  31830. if ( fog.isFog ) {
  31831. uniforms.fogNear.value = fog.near;
  31832. uniforms.fogFar.value = fog.far;
  31833. } else if ( fog.isFogExp2 ) {
  31834. uniforms.fogDensity.value = fog.density;
  31835. }
  31836. }
  31837. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  31838. if ( material.isMeshBasicMaterial ) {
  31839. refreshUniformsCommon( uniforms, material );
  31840. } else if ( material.isMeshLambertMaterial ) {
  31841. refreshUniformsCommon( uniforms, material );
  31842. } else if ( material.isMeshToonMaterial ) {
  31843. refreshUniformsCommon( uniforms, material );
  31844. refreshUniformsToon( uniforms, material );
  31845. } else if ( material.isMeshPhongMaterial ) {
  31846. refreshUniformsCommon( uniforms, material );
  31847. refreshUniformsPhong( uniforms, material );
  31848. } else if ( material.isMeshStandardMaterial ) {
  31849. refreshUniformsCommon( uniforms, material );
  31850. refreshUniformsStandard( uniforms, material );
  31851. if ( material.isMeshPhysicalMaterial ) {
  31852. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  31853. }
  31854. } else if ( material.isMeshMatcapMaterial ) {
  31855. refreshUniformsCommon( uniforms, material );
  31856. refreshUniformsMatcap( uniforms, material );
  31857. } else if ( material.isMeshDepthMaterial ) {
  31858. refreshUniformsCommon( uniforms, material );
  31859. } else if ( material.isMeshDistanceMaterial ) {
  31860. refreshUniformsCommon( uniforms, material );
  31861. refreshUniformsDistance( uniforms, material );
  31862. } else if ( material.isMeshNormalMaterial ) {
  31863. refreshUniformsCommon( uniforms, material );
  31864. } else if ( material.isLineBasicMaterial ) {
  31865. refreshUniformsLine( uniforms, material );
  31866. if ( material.isLineDashedMaterial ) {
  31867. refreshUniformsDash( uniforms, material );
  31868. }
  31869. } else if ( material.isPointsMaterial ) {
  31870. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  31871. } else if ( material.isSpriteMaterial ) {
  31872. refreshUniformsSprites( uniforms, material );
  31873. } else if ( material.isShadowMaterial ) {
  31874. uniforms.color.value.copy( material.color );
  31875. uniforms.opacity.value = material.opacity;
  31876. } else if ( material.isShaderMaterial ) {
  31877. material.uniformsNeedUpdate = false; // #15581
  31878. }
  31879. }
  31880. function refreshUniformsCommon( uniforms, material ) {
  31881. uniforms.opacity.value = material.opacity;
  31882. if ( material.color ) {
  31883. uniforms.diffuse.value.copy( material.color );
  31884. }
  31885. if ( material.emissive ) {
  31886. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  31887. }
  31888. if ( material.map ) {
  31889. uniforms.map.value = material.map;
  31890. refreshTransformUniform( material.map, uniforms.mapTransform );
  31891. }
  31892. if ( material.alphaMap ) {
  31893. uniforms.alphaMap.value = material.alphaMap;
  31894. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  31895. }
  31896. if ( material.bumpMap ) {
  31897. uniforms.bumpMap.value = material.bumpMap;
  31898. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  31899. uniforms.bumpScale.value = material.bumpScale;
  31900. if ( material.side === BackSide ) {
  31901. uniforms.bumpScale.value *= -1;
  31902. }
  31903. }
  31904. if ( material.normalMap ) {
  31905. uniforms.normalMap.value = material.normalMap;
  31906. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  31907. uniforms.normalScale.value.copy( material.normalScale );
  31908. if ( material.side === BackSide ) {
  31909. uniforms.normalScale.value.negate();
  31910. }
  31911. }
  31912. if ( material.displacementMap ) {
  31913. uniforms.displacementMap.value = material.displacementMap;
  31914. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  31915. uniforms.displacementScale.value = material.displacementScale;
  31916. uniforms.displacementBias.value = material.displacementBias;
  31917. }
  31918. if ( material.emissiveMap ) {
  31919. uniforms.emissiveMap.value = material.emissiveMap;
  31920. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  31921. }
  31922. if ( material.specularMap ) {
  31923. uniforms.specularMap.value = material.specularMap;
  31924. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  31925. }
  31926. if ( material.alphaTest > 0 ) {
  31927. uniforms.alphaTest.value = material.alphaTest;
  31928. }
  31929. const materialProperties = properties.get( material );
  31930. const envMap = materialProperties.envMap;
  31931. const envMapRotation = materialProperties.envMapRotation;
  31932. if ( envMap ) {
  31933. uniforms.envMap.value = envMap;
  31934. _e1.copy( envMapRotation );
  31935. // accommodate left-handed frame
  31936. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  31937. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  31938. // environment maps which are not cube render targets or PMREMs follow a different convention
  31939. _e1.y *= -1;
  31940. _e1.z *= -1;
  31941. }
  31942. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  31943. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  31944. uniforms.reflectivity.value = material.reflectivity;
  31945. uniforms.ior.value = material.ior;
  31946. uniforms.refractionRatio.value = material.refractionRatio;
  31947. }
  31948. if ( material.lightMap ) {
  31949. uniforms.lightMap.value = material.lightMap;
  31950. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  31951. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  31952. }
  31953. if ( material.aoMap ) {
  31954. uniforms.aoMap.value = material.aoMap;
  31955. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  31956. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  31957. }
  31958. }
  31959. function refreshUniformsLine( uniforms, material ) {
  31960. uniforms.diffuse.value.copy( material.color );
  31961. uniforms.opacity.value = material.opacity;
  31962. if ( material.map ) {
  31963. uniforms.map.value = material.map;
  31964. refreshTransformUniform( material.map, uniforms.mapTransform );
  31965. }
  31966. }
  31967. function refreshUniformsDash( uniforms, material ) {
  31968. uniforms.dashSize.value = material.dashSize;
  31969. uniforms.totalSize.value = material.dashSize + material.gapSize;
  31970. uniforms.scale.value = material.scale;
  31971. }
  31972. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  31973. uniforms.diffuse.value.copy( material.color );
  31974. uniforms.opacity.value = material.opacity;
  31975. uniforms.size.value = material.size * pixelRatio;
  31976. uniforms.scale.value = height * 0.5;
  31977. if ( material.map ) {
  31978. uniforms.map.value = material.map;
  31979. refreshTransformUniform( material.map, uniforms.uvTransform );
  31980. }
  31981. if ( material.alphaMap ) {
  31982. uniforms.alphaMap.value = material.alphaMap;
  31983. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  31984. }
  31985. if ( material.alphaTest > 0 ) {
  31986. uniforms.alphaTest.value = material.alphaTest;
  31987. }
  31988. }
  31989. function refreshUniformsSprites( uniforms, material ) {
  31990. uniforms.diffuse.value.copy( material.color );
  31991. uniforms.opacity.value = material.opacity;
  31992. uniforms.rotation.value = material.rotation;
  31993. if ( material.map ) {
  31994. uniforms.map.value = material.map;
  31995. refreshTransformUniform( material.map, uniforms.mapTransform );
  31996. }
  31997. if ( material.alphaMap ) {
  31998. uniforms.alphaMap.value = material.alphaMap;
  31999. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  32000. }
  32001. if ( material.alphaTest > 0 ) {
  32002. uniforms.alphaTest.value = material.alphaTest;
  32003. }
  32004. }
  32005. function refreshUniformsPhong( uniforms, material ) {
  32006. uniforms.specular.value.copy( material.specular );
  32007. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  32008. }
  32009. function refreshUniformsToon( uniforms, material ) {
  32010. if ( material.gradientMap ) {
  32011. uniforms.gradientMap.value = material.gradientMap;
  32012. }
  32013. }
  32014. function refreshUniformsStandard( uniforms, material ) {
  32015. uniforms.metalness.value = material.metalness;
  32016. if ( material.metalnessMap ) {
  32017. uniforms.metalnessMap.value = material.metalnessMap;
  32018. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  32019. }
  32020. uniforms.roughness.value = material.roughness;
  32021. if ( material.roughnessMap ) {
  32022. uniforms.roughnessMap.value = material.roughnessMap;
  32023. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  32024. }
  32025. if ( material.envMap ) {
  32026. //uniforms.envMap.value = material.envMap; // part of uniforms common
  32027. uniforms.envMapIntensity.value = material.envMapIntensity;
  32028. }
  32029. }
  32030. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  32031. uniforms.ior.value = material.ior; // also part of uniforms common
  32032. if ( material.sheen > 0 ) {
  32033. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  32034. uniforms.sheenRoughness.value = material.sheenRoughness;
  32035. if ( material.sheenColorMap ) {
  32036. uniforms.sheenColorMap.value = material.sheenColorMap;
  32037. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  32038. }
  32039. if ( material.sheenRoughnessMap ) {
  32040. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  32041. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  32042. }
  32043. }
  32044. if ( material.clearcoat > 0 ) {
  32045. uniforms.clearcoat.value = material.clearcoat;
  32046. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  32047. if ( material.clearcoatMap ) {
  32048. uniforms.clearcoatMap.value = material.clearcoatMap;
  32049. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  32050. }
  32051. if ( material.clearcoatRoughnessMap ) {
  32052. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  32053. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  32054. }
  32055. if ( material.clearcoatNormalMap ) {
  32056. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  32057. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  32058. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  32059. if ( material.side === BackSide ) {
  32060. uniforms.clearcoatNormalScale.value.negate();
  32061. }
  32062. }
  32063. }
  32064. if ( material.dispersion > 0 ) {
  32065. uniforms.dispersion.value = material.dispersion;
  32066. }
  32067. if ( material.iridescence > 0 ) {
  32068. uniforms.iridescence.value = material.iridescence;
  32069. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  32070. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  32071. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  32072. if ( material.iridescenceMap ) {
  32073. uniforms.iridescenceMap.value = material.iridescenceMap;
  32074. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  32075. }
  32076. if ( material.iridescenceThicknessMap ) {
  32077. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  32078. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  32079. }
  32080. }
  32081. if ( material.transmission > 0 ) {
  32082. uniforms.transmission.value = material.transmission;
  32083. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  32084. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  32085. if ( material.transmissionMap ) {
  32086. uniforms.transmissionMap.value = material.transmissionMap;
  32087. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  32088. }
  32089. uniforms.thickness.value = material.thickness;
  32090. if ( material.thicknessMap ) {
  32091. uniforms.thicknessMap.value = material.thicknessMap;
  32092. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  32093. }
  32094. uniforms.attenuationDistance.value = material.attenuationDistance;
  32095. uniforms.attenuationColor.value.copy( material.attenuationColor );
  32096. }
  32097. if ( material.anisotropy > 0 ) {
  32098. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  32099. if ( material.anisotropyMap ) {
  32100. uniforms.anisotropyMap.value = material.anisotropyMap;
  32101. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  32102. }
  32103. }
  32104. uniforms.specularIntensity.value = material.specularIntensity;
  32105. uniforms.specularColor.value.copy( material.specularColor );
  32106. if ( material.specularColorMap ) {
  32107. uniforms.specularColorMap.value = material.specularColorMap;
  32108. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  32109. }
  32110. if ( material.specularIntensityMap ) {
  32111. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  32112. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  32113. }
  32114. }
  32115. function refreshUniformsMatcap( uniforms, material ) {
  32116. if ( material.matcap ) {
  32117. uniforms.matcap.value = material.matcap;
  32118. }
  32119. }
  32120. function refreshUniformsDistance( uniforms, material ) {
  32121. const light = properties.get( material ).light;
  32122. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  32123. uniforms.nearDistance.value = light.shadow.camera.near;
  32124. uniforms.farDistance.value = light.shadow.camera.far;
  32125. }
  32126. return {
  32127. refreshFogUniforms: refreshFogUniforms,
  32128. refreshMaterialUniforms: refreshMaterialUniforms
  32129. };
  32130. }
  32131. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  32132. let buffers = {};
  32133. let updateList = {};
  32134. let allocatedBindingPoints = [];
  32135. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  32136. function bind( uniformsGroup, program ) {
  32137. const webglProgram = program.program;
  32138. state.uniformBlockBinding( uniformsGroup, webglProgram );
  32139. }
  32140. function update( uniformsGroup, program ) {
  32141. let buffer = buffers[ uniformsGroup.id ];
  32142. if ( buffer === undefined ) {
  32143. prepareUniformsGroup( uniformsGroup );
  32144. buffer = createBuffer( uniformsGroup );
  32145. buffers[ uniformsGroup.id ] = buffer;
  32146. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  32147. }
  32148. // ensure to update the binding points/block indices mapping for this program
  32149. const webglProgram = program.program;
  32150. state.updateUBOMapping( uniformsGroup, webglProgram );
  32151. // update UBO once per frame
  32152. const frame = info.render.frame;
  32153. if ( updateList[ uniformsGroup.id ] !== frame ) {
  32154. updateBufferData( uniformsGroup );
  32155. updateList[ uniformsGroup.id ] = frame;
  32156. }
  32157. }
  32158. function createBuffer( uniformsGroup ) {
  32159. // the setup of an UBO is independent of a particular shader program but global
  32160. const bindingPointIndex = allocateBindingPointIndex();
  32161. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  32162. const buffer = gl.createBuffer();
  32163. const size = uniformsGroup.__size;
  32164. const usage = uniformsGroup.usage;
  32165. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  32166. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  32167. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  32168. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  32169. return buffer;
  32170. }
  32171. function allocateBindingPointIndex() {
  32172. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  32173. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  32174. allocatedBindingPoints.push( i );
  32175. return i;
  32176. }
  32177. }
  32178. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  32179. return 0;
  32180. }
  32181. function updateBufferData( uniformsGroup ) {
  32182. const buffer = buffers[ uniformsGroup.id ];
  32183. const uniforms = uniformsGroup.uniforms;
  32184. const cache = uniformsGroup.__cache;
  32185. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  32186. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  32187. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  32188. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  32189. const uniform = uniformArray[ j ];
  32190. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  32191. const offset = uniform.__offset;
  32192. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  32193. let arrayOffset = 0;
  32194. for ( let k = 0; k < values.length; k ++ ) {
  32195. const value = values[ k ];
  32196. const info = getUniformSize( value );
  32197. // TODO add integer and struct support
  32198. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  32199. uniform.__data[ 0 ] = value;
  32200. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  32201. } else if ( value.isMatrix3 ) {
  32202. // manually converting 3x3 to 3x4
  32203. uniform.__data[ 0 ] = value.elements[ 0 ];
  32204. uniform.__data[ 1 ] = value.elements[ 1 ];
  32205. uniform.__data[ 2 ] = value.elements[ 2 ];
  32206. uniform.__data[ 3 ] = 0;
  32207. uniform.__data[ 4 ] = value.elements[ 3 ];
  32208. uniform.__data[ 5 ] = value.elements[ 4 ];
  32209. uniform.__data[ 6 ] = value.elements[ 5 ];
  32210. uniform.__data[ 7 ] = 0;
  32211. uniform.__data[ 8 ] = value.elements[ 6 ];
  32212. uniform.__data[ 9 ] = value.elements[ 7 ];
  32213. uniform.__data[ 10 ] = value.elements[ 8 ];
  32214. uniform.__data[ 11 ] = 0;
  32215. } else {
  32216. value.toArray( uniform.__data, arrayOffset );
  32217. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  32218. }
  32219. }
  32220. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  32221. }
  32222. }
  32223. }
  32224. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  32225. }
  32226. function hasUniformChanged( uniform, index, indexArray, cache ) {
  32227. const value = uniform.value;
  32228. const indexString = index + '_' + indexArray;
  32229. if ( cache[ indexString ] === undefined ) {
  32230. // cache entry does not exist so far
  32231. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  32232. cache[ indexString ] = value;
  32233. } else {
  32234. cache[ indexString ] = value.clone();
  32235. }
  32236. return true;
  32237. } else {
  32238. const cachedObject = cache[ indexString ];
  32239. // compare current value with cached entry
  32240. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  32241. if ( cachedObject !== value ) {
  32242. cache[ indexString ] = value;
  32243. return true;
  32244. }
  32245. } else {
  32246. if ( cachedObject.equals( value ) === false ) {
  32247. cachedObject.copy( value );
  32248. return true;
  32249. }
  32250. }
  32251. }
  32252. return false;
  32253. }
  32254. function prepareUniformsGroup( uniformsGroup ) {
  32255. // determine total buffer size according to the STD140 layout
  32256. // Hint: STD140 is the only supported layout in WebGL 2
  32257. const uniforms = uniformsGroup.uniforms;
  32258. let offset = 0; // global buffer offset in bytes
  32259. const chunkSize = 16; // size of a chunk in bytes
  32260. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  32261. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  32262. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  32263. const uniform = uniformArray[ j ];
  32264. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  32265. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  32266. const value = values[ k ];
  32267. const info = getUniformSize( value );
  32268. const chunkOffset = offset % chunkSize; // offset in the current chunk
  32269. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  32270. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  32271. offset += chunkPadding;
  32272. // Check for chunk overflow
  32273. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  32274. // Add padding and adjust offset
  32275. offset += ( chunkSize - chunkStart );
  32276. }
  32277. // the following two properties will be used for partial buffer updates
  32278. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  32279. uniform.__offset = offset;
  32280. // Update the global offset
  32281. offset += info.storage;
  32282. }
  32283. }
  32284. }
  32285. // ensure correct final padding
  32286. const chunkOffset = offset % chunkSize;
  32287. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  32288. //
  32289. uniformsGroup.__size = offset;
  32290. uniformsGroup.__cache = {};
  32291. return this;
  32292. }
  32293. function getUniformSize( value ) {
  32294. const info = {
  32295. boundary: 0, // bytes
  32296. storage: 0 // bytes
  32297. };
  32298. // determine sizes according to STD140
  32299. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  32300. // float/int/bool
  32301. info.boundary = 4;
  32302. info.storage = 4;
  32303. } else if ( value.isVector2 ) {
  32304. // vec2
  32305. info.boundary = 8;
  32306. info.storage = 8;
  32307. } else if ( value.isVector3 || value.isColor ) {
  32308. // vec3
  32309. info.boundary = 16;
  32310. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  32311. } else if ( value.isVector4 ) {
  32312. // vec4
  32313. info.boundary = 16;
  32314. info.storage = 16;
  32315. } else if ( value.isMatrix3 ) {
  32316. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  32317. info.boundary = 48;
  32318. info.storage = 48;
  32319. } else if ( value.isMatrix4 ) {
  32320. // mat4
  32321. info.boundary = 64;
  32322. info.storage = 64;
  32323. } else if ( value.isTexture ) {
  32324. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  32325. } else {
  32326. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  32327. }
  32328. return info;
  32329. }
  32330. function onUniformsGroupsDispose( event ) {
  32331. const uniformsGroup = event.target;
  32332. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  32333. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  32334. allocatedBindingPoints.splice( index, 1 );
  32335. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  32336. delete buffers[ uniformsGroup.id ];
  32337. delete updateList[ uniformsGroup.id ];
  32338. }
  32339. function dispose() {
  32340. for ( const id in buffers ) {
  32341. gl.deleteBuffer( buffers[ id ] );
  32342. }
  32343. allocatedBindingPoints = [];
  32344. buffers = {};
  32345. updateList = {};
  32346. }
  32347. return {
  32348. bind: bind,
  32349. update: update,
  32350. dispose: dispose
  32351. };
  32352. }
  32353. class WebGLRenderer {
  32354. constructor( parameters = {} ) {
  32355. const {
  32356. canvas = createCanvasElement(),
  32357. context = null,
  32358. depth = true,
  32359. stencil = false,
  32360. alpha = false,
  32361. antialias = false,
  32362. premultipliedAlpha = true,
  32363. preserveDrawingBuffer = false,
  32364. powerPreference = 'default',
  32365. failIfMajorPerformanceCaveat = false,
  32366. reverseDepthBuffer = false,
  32367. } = parameters;
  32368. this.isWebGLRenderer = true;
  32369. let _alpha;
  32370. if ( context !== null ) {
  32371. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  32372. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  32373. }
  32374. _alpha = context.getContextAttributes().alpha;
  32375. } else {
  32376. _alpha = alpha;
  32377. }
  32378. const uintClearColor = new Uint32Array( 4 );
  32379. const intClearColor = new Int32Array( 4 );
  32380. let currentRenderList = null;
  32381. let currentRenderState = null;
  32382. // render() can be called from within a callback triggered by another render.
  32383. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  32384. const renderListStack = [];
  32385. const renderStateStack = [];
  32386. // public properties
  32387. this.domElement = canvas;
  32388. // Debug configuration container
  32389. this.debug = {
  32390. /**
  32391. * Enables error checking and reporting when shader programs are being compiled
  32392. * @type {boolean}
  32393. */
  32394. checkShaderErrors: true,
  32395. /**
  32396. * Callback for custom error reporting.
  32397. * @type {?Function}
  32398. */
  32399. onShaderError: null
  32400. };
  32401. // clearing
  32402. this.autoClear = true;
  32403. this.autoClearColor = true;
  32404. this.autoClearDepth = true;
  32405. this.autoClearStencil = true;
  32406. // scene graph
  32407. this.sortObjects = true;
  32408. // user-defined clipping
  32409. this.clippingPlanes = [];
  32410. this.localClippingEnabled = false;
  32411. // physically based shading
  32412. this._outputColorSpace = SRGBColorSpace;
  32413. // tone mapping
  32414. this.toneMapping = NoToneMapping;
  32415. this.toneMappingExposure = 1.0;
  32416. // internal properties
  32417. const _this = this;
  32418. let _isContextLost = false;
  32419. // internal state cache
  32420. let _currentActiveCubeFace = 0;
  32421. let _currentActiveMipmapLevel = 0;
  32422. let _currentRenderTarget = null;
  32423. let _currentMaterialId = -1;
  32424. let _currentCamera = null;
  32425. const _currentViewport = new Vector4();
  32426. const _currentScissor = new Vector4();
  32427. let _currentScissorTest = null;
  32428. const _currentClearColor = new Color( 0x000000 );
  32429. let _currentClearAlpha = 0;
  32430. //
  32431. let _width = canvas.width;
  32432. let _height = canvas.height;
  32433. let _pixelRatio = 1;
  32434. let _opaqueSort = null;
  32435. let _transparentSort = null;
  32436. const _viewport = new Vector4( 0, 0, _width, _height );
  32437. const _scissor = new Vector4( 0, 0, _width, _height );
  32438. let _scissorTest = false;
  32439. // frustum
  32440. const _frustum = new Frustum();
  32441. // clipping
  32442. let _clippingEnabled = false;
  32443. let _localClippingEnabled = false;
  32444. // transmission render target scale
  32445. this.transmissionResolutionScale = 1.0;
  32446. // camera matrices cache
  32447. const _currentProjectionMatrix = new Matrix4();
  32448. const _projScreenMatrix = new Matrix4();
  32449. const _vector3 = new Vector3();
  32450. const _vector4 = new Vector4();
  32451. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  32452. let _renderBackground = false;
  32453. function getTargetPixelRatio() {
  32454. return _currentRenderTarget === null ? _pixelRatio : 1;
  32455. }
  32456. // initialize
  32457. let _gl = context;
  32458. function getContext( contextName, contextAttributes ) {
  32459. return canvas.getContext( contextName, contextAttributes );
  32460. }
  32461. try {
  32462. const contextAttributes = {
  32463. alpha: true,
  32464. depth,
  32465. stencil,
  32466. antialias,
  32467. premultipliedAlpha,
  32468. preserveDrawingBuffer,
  32469. powerPreference,
  32470. failIfMajorPerformanceCaveat,
  32471. };
  32472. // OffscreenCanvas does not have setAttribute, see #22811
  32473. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  32474. // event listeners must be registered before WebGL context is created, see #12753
  32475. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  32476. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  32477. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  32478. if ( _gl === null ) {
  32479. const contextName = 'webgl2';
  32480. _gl = getContext( contextName, contextAttributes );
  32481. if ( _gl === null ) {
  32482. if ( getContext( contextName ) ) {
  32483. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  32484. } else {
  32485. throw new Error( 'Error creating WebGL context.' );
  32486. }
  32487. }
  32488. }
  32489. } catch ( error ) {
  32490. console.error( 'THREE.WebGLRenderer: ' + error.message );
  32491. throw error;
  32492. }
  32493. let extensions, capabilities, state, info;
  32494. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  32495. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  32496. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  32497. let utils, bindingStates, uniformsGroups;
  32498. function initGLContext() {
  32499. extensions = new WebGLExtensions( _gl );
  32500. extensions.init();
  32501. utils = new WebGLUtils( _gl, extensions );
  32502. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  32503. state = new WebGLState( _gl, extensions );
  32504. if ( capabilities.reverseDepthBuffer && reverseDepthBuffer ) {
  32505. state.buffers.depth.setReversed( true );
  32506. }
  32507. info = new WebGLInfo( _gl );
  32508. properties = new WebGLProperties();
  32509. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  32510. cubemaps = new WebGLCubeMaps( _this );
  32511. cubeuvmaps = new WebGLCubeUVMaps( _this );
  32512. attributes = new WebGLAttributes( _gl );
  32513. bindingStates = new WebGLBindingStates( _gl, attributes );
  32514. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  32515. objects = new WebGLObjects( _gl, geometries, attributes, info );
  32516. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  32517. clipping = new WebGLClipping( properties );
  32518. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  32519. materials = new WebGLMaterials( _this, properties );
  32520. renderLists = new WebGLRenderLists();
  32521. renderStates = new WebGLRenderStates( extensions );
  32522. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  32523. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  32524. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  32525. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  32526. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  32527. info.programs = programCache.programs;
  32528. _this.capabilities = capabilities;
  32529. _this.extensions = extensions;
  32530. _this.properties = properties;
  32531. _this.renderLists = renderLists;
  32532. _this.shadowMap = shadowMap;
  32533. _this.state = state;
  32534. _this.info = info;
  32535. }
  32536. initGLContext();
  32537. // xr
  32538. const xr = new WebXRManager( _this, _gl );
  32539. this.xr = xr;
  32540. // API
  32541. this.getContext = function () {
  32542. return _gl;
  32543. };
  32544. this.getContextAttributes = function () {
  32545. return _gl.getContextAttributes();
  32546. };
  32547. this.forceContextLoss = function () {
  32548. const extension = extensions.get( 'WEBGL_lose_context' );
  32549. if ( extension ) extension.loseContext();
  32550. };
  32551. this.forceContextRestore = function () {
  32552. const extension = extensions.get( 'WEBGL_lose_context' );
  32553. if ( extension ) extension.restoreContext();
  32554. };
  32555. this.getPixelRatio = function () {
  32556. return _pixelRatio;
  32557. };
  32558. this.setPixelRatio = function ( value ) {
  32559. if ( value === undefined ) return;
  32560. _pixelRatio = value;
  32561. this.setSize( _width, _height, false );
  32562. };
  32563. this.getSize = function ( target ) {
  32564. return target.set( _width, _height );
  32565. };
  32566. this.setSize = function ( width, height, updateStyle = true ) {
  32567. if ( xr.isPresenting ) {
  32568. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  32569. return;
  32570. }
  32571. _width = width;
  32572. _height = height;
  32573. canvas.width = Math.floor( width * _pixelRatio );
  32574. canvas.height = Math.floor( height * _pixelRatio );
  32575. if ( updateStyle === true ) {
  32576. canvas.style.width = width + 'px';
  32577. canvas.style.height = height + 'px';
  32578. }
  32579. this.setViewport( 0, 0, width, height );
  32580. };
  32581. this.getDrawingBufferSize = function ( target ) {
  32582. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  32583. };
  32584. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  32585. _width = width;
  32586. _height = height;
  32587. _pixelRatio = pixelRatio;
  32588. canvas.width = Math.floor( width * pixelRatio );
  32589. canvas.height = Math.floor( height * pixelRatio );
  32590. this.setViewport( 0, 0, width, height );
  32591. };
  32592. this.getCurrentViewport = function ( target ) {
  32593. return target.copy( _currentViewport );
  32594. };
  32595. this.getViewport = function ( target ) {
  32596. return target.copy( _viewport );
  32597. };
  32598. this.setViewport = function ( x, y, width, height ) {
  32599. if ( x.isVector4 ) {
  32600. _viewport.set( x.x, x.y, x.z, x.w );
  32601. } else {
  32602. _viewport.set( x, y, width, height );
  32603. }
  32604. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  32605. };
  32606. this.getScissor = function ( target ) {
  32607. return target.copy( _scissor );
  32608. };
  32609. this.setScissor = function ( x, y, width, height ) {
  32610. if ( x.isVector4 ) {
  32611. _scissor.set( x.x, x.y, x.z, x.w );
  32612. } else {
  32613. _scissor.set( x, y, width, height );
  32614. }
  32615. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  32616. };
  32617. this.getScissorTest = function () {
  32618. return _scissorTest;
  32619. };
  32620. this.setScissorTest = function ( boolean ) {
  32621. state.setScissorTest( _scissorTest = boolean );
  32622. };
  32623. this.setOpaqueSort = function ( method ) {
  32624. _opaqueSort = method;
  32625. };
  32626. this.setTransparentSort = function ( method ) {
  32627. _transparentSort = method;
  32628. };
  32629. // Clearing
  32630. this.getClearColor = function ( target ) {
  32631. return target.copy( background.getClearColor() );
  32632. };
  32633. this.setClearColor = function () {
  32634. background.setClearColor( ...arguments );
  32635. };
  32636. this.getClearAlpha = function () {
  32637. return background.getClearAlpha();
  32638. };
  32639. this.setClearAlpha = function () {
  32640. background.setClearAlpha( ...arguments );
  32641. };
  32642. this.clear = function ( color = true, depth = true, stencil = true ) {
  32643. let bits = 0;
  32644. if ( color ) {
  32645. // check if we're trying to clear an integer target
  32646. let isIntegerFormat = false;
  32647. if ( _currentRenderTarget !== null ) {
  32648. const targetFormat = _currentRenderTarget.texture.format;
  32649. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  32650. targetFormat === RGIntegerFormat ||
  32651. targetFormat === RedIntegerFormat;
  32652. }
  32653. // use the appropriate clear functions to clear the target if it's a signed
  32654. // or unsigned integer target
  32655. if ( isIntegerFormat ) {
  32656. const targetType = _currentRenderTarget.texture.type;
  32657. const isUnsignedType = targetType === UnsignedByteType ||
  32658. targetType === UnsignedIntType ||
  32659. targetType === UnsignedShortType ||
  32660. targetType === UnsignedInt248Type ||
  32661. targetType === UnsignedShort4444Type ||
  32662. targetType === UnsignedShort5551Type;
  32663. const clearColor = background.getClearColor();
  32664. const a = background.getClearAlpha();
  32665. const r = clearColor.r;
  32666. const g = clearColor.g;
  32667. const b = clearColor.b;
  32668. if ( isUnsignedType ) {
  32669. uintClearColor[ 0 ] = r;
  32670. uintClearColor[ 1 ] = g;
  32671. uintClearColor[ 2 ] = b;
  32672. uintClearColor[ 3 ] = a;
  32673. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  32674. } else {
  32675. intClearColor[ 0 ] = r;
  32676. intClearColor[ 1 ] = g;
  32677. intClearColor[ 2 ] = b;
  32678. intClearColor[ 3 ] = a;
  32679. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  32680. }
  32681. } else {
  32682. bits |= _gl.COLOR_BUFFER_BIT;
  32683. }
  32684. }
  32685. if ( depth ) {
  32686. bits |= _gl.DEPTH_BUFFER_BIT;
  32687. }
  32688. if ( stencil ) {
  32689. bits |= _gl.STENCIL_BUFFER_BIT;
  32690. this.state.buffers.stencil.setMask( 0xffffffff );
  32691. }
  32692. _gl.clear( bits );
  32693. };
  32694. this.clearColor = function () {
  32695. this.clear( true, false, false );
  32696. };
  32697. this.clearDepth = function () {
  32698. this.clear( false, true, false );
  32699. };
  32700. this.clearStencil = function () {
  32701. this.clear( false, false, true );
  32702. };
  32703. //
  32704. this.dispose = function () {
  32705. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  32706. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  32707. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  32708. background.dispose();
  32709. renderLists.dispose();
  32710. renderStates.dispose();
  32711. properties.dispose();
  32712. cubemaps.dispose();
  32713. cubeuvmaps.dispose();
  32714. objects.dispose();
  32715. bindingStates.dispose();
  32716. uniformsGroups.dispose();
  32717. programCache.dispose();
  32718. xr.dispose();
  32719. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  32720. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  32721. animation.stop();
  32722. };
  32723. // Events
  32724. function onContextLost( event ) {
  32725. event.preventDefault();
  32726. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  32727. _isContextLost = true;
  32728. }
  32729. function onContextRestore( /* event */ ) {
  32730. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  32731. _isContextLost = false;
  32732. const infoAutoReset = info.autoReset;
  32733. const shadowMapEnabled = shadowMap.enabled;
  32734. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  32735. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  32736. const shadowMapType = shadowMap.type;
  32737. initGLContext();
  32738. info.autoReset = infoAutoReset;
  32739. shadowMap.enabled = shadowMapEnabled;
  32740. shadowMap.autoUpdate = shadowMapAutoUpdate;
  32741. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  32742. shadowMap.type = shadowMapType;
  32743. }
  32744. function onContextCreationError( event ) {
  32745. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  32746. }
  32747. function onMaterialDispose( event ) {
  32748. const material = event.target;
  32749. material.removeEventListener( 'dispose', onMaterialDispose );
  32750. deallocateMaterial( material );
  32751. }
  32752. // Buffer deallocation
  32753. function deallocateMaterial( material ) {
  32754. releaseMaterialProgramReferences( material );
  32755. properties.remove( material );
  32756. }
  32757. function releaseMaterialProgramReferences( material ) {
  32758. const programs = properties.get( material ).programs;
  32759. if ( programs !== undefined ) {
  32760. programs.forEach( function ( program ) {
  32761. programCache.releaseProgram( program );
  32762. } );
  32763. if ( material.isShaderMaterial ) {
  32764. programCache.releaseShaderCache( material );
  32765. }
  32766. }
  32767. }
  32768. // Buffer rendering
  32769. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  32770. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  32771. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  32772. const program = setProgram( camera, scene, geometry, material, object );
  32773. state.setMaterial( material, frontFaceCW );
  32774. //
  32775. let index = geometry.index;
  32776. let rangeFactor = 1;
  32777. if ( material.wireframe === true ) {
  32778. index = geometries.getWireframeAttribute( geometry );
  32779. if ( index === undefined ) return;
  32780. rangeFactor = 2;
  32781. }
  32782. //
  32783. const drawRange = geometry.drawRange;
  32784. const position = geometry.attributes.position;
  32785. let drawStart = drawRange.start * rangeFactor;
  32786. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  32787. if ( group !== null ) {
  32788. drawStart = Math.max( drawStart, group.start * rangeFactor );
  32789. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  32790. }
  32791. if ( index !== null ) {
  32792. drawStart = Math.max( drawStart, 0 );
  32793. drawEnd = Math.min( drawEnd, index.count );
  32794. } else if ( position !== undefined && position !== null ) {
  32795. drawStart = Math.max( drawStart, 0 );
  32796. drawEnd = Math.min( drawEnd, position.count );
  32797. }
  32798. const drawCount = drawEnd - drawStart;
  32799. if ( drawCount < 0 || drawCount === Infinity ) return;
  32800. //
  32801. bindingStates.setup( object, material, program, geometry, index );
  32802. let attribute;
  32803. let renderer = bufferRenderer;
  32804. if ( index !== null ) {
  32805. attribute = attributes.get( index );
  32806. renderer = indexedBufferRenderer;
  32807. renderer.setIndex( attribute );
  32808. }
  32809. //
  32810. if ( object.isMesh ) {
  32811. if ( material.wireframe === true ) {
  32812. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  32813. renderer.setMode( _gl.LINES );
  32814. } else {
  32815. renderer.setMode( _gl.TRIANGLES );
  32816. }
  32817. } else if ( object.isLine ) {
  32818. let lineWidth = material.linewidth;
  32819. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  32820. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  32821. if ( object.isLineSegments ) {
  32822. renderer.setMode( _gl.LINES );
  32823. } else if ( object.isLineLoop ) {
  32824. renderer.setMode( _gl.LINE_LOOP );
  32825. } else {
  32826. renderer.setMode( _gl.LINE_STRIP );
  32827. }
  32828. } else if ( object.isPoints ) {
  32829. renderer.setMode( _gl.POINTS );
  32830. } else if ( object.isSprite ) {
  32831. renderer.setMode( _gl.TRIANGLES );
  32832. }
  32833. if ( object.isBatchedMesh ) {
  32834. if ( object._multiDrawInstances !== null ) {
  32835. // @deprecated, r174
  32836. warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  32837. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  32838. } else {
  32839. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  32840. const starts = object._multiDrawStarts;
  32841. const counts = object._multiDrawCounts;
  32842. const drawCount = object._multiDrawCount;
  32843. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  32844. const uniforms = properties.get( material ).currentProgram.getUniforms();
  32845. for ( let i = 0; i < drawCount; i ++ ) {
  32846. uniforms.setValue( _gl, '_gl_DrawID', i );
  32847. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  32848. }
  32849. } else {
  32850. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  32851. }
  32852. }
  32853. } else if ( object.isInstancedMesh ) {
  32854. renderer.renderInstances( drawStart, drawCount, object.count );
  32855. } else if ( geometry.isInstancedBufferGeometry ) {
  32856. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  32857. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  32858. renderer.renderInstances( drawStart, drawCount, instanceCount );
  32859. } else {
  32860. renderer.render( drawStart, drawCount );
  32861. }
  32862. };
  32863. // Compile
  32864. function prepareMaterial( material, scene, object ) {
  32865. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  32866. material.side = BackSide;
  32867. material.needsUpdate = true;
  32868. getProgram( material, scene, object );
  32869. material.side = FrontSide;
  32870. material.needsUpdate = true;
  32871. getProgram( material, scene, object );
  32872. material.side = DoubleSide;
  32873. } else {
  32874. getProgram( material, scene, object );
  32875. }
  32876. }
  32877. this.compile = function ( scene, camera, targetScene = null ) {
  32878. if ( targetScene === null ) targetScene = scene;
  32879. currentRenderState = renderStates.get( targetScene );
  32880. currentRenderState.init( camera );
  32881. renderStateStack.push( currentRenderState );
  32882. // gather lights from both the target scene and the new object that will be added to the scene.
  32883. targetScene.traverseVisible( function ( object ) {
  32884. if ( object.isLight && object.layers.test( camera.layers ) ) {
  32885. currentRenderState.pushLight( object );
  32886. if ( object.castShadow ) {
  32887. currentRenderState.pushShadow( object );
  32888. }
  32889. }
  32890. } );
  32891. if ( scene !== targetScene ) {
  32892. scene.traverseVisible( function ( object ) {
  32893. if ( object.isLight && object.layers.test( camera.layers ) ) {
  32894. currentRenderState.pushLight( object );
  32895. if ( object.castShadow ) {
  32896. currentRenderState.pushShadow( object );
  32897. }
  32898. }
  32899. } );
  32900. }
  32901. currentRenderState.setupLights();
  32902. // Only initialize materials in the new scene, not the targetScene.
  32903. const materials = new Set();
  32904. scene.traverse( function ( object ) {
  32905. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  32906. return;
  32907. }
  32908. const material = object.material;
  32909. if ( material ) {
  32910. if ( Array.isArray( material ) ) {
  32911. for ( let i = 0; i < material.length; i ++ ) {
  32912. const material2 = material[ i ];
  32913. prepareMaterial( material2, targetScene, object );
  32914. materials.add( material2 );
  32915. }
  32916. } else {
  32917. prepareMaterial( material, targetScene, object );
  32918. materials.add( material );
  32919. }
  32920. }
  32921. } );
  32922. renderStateStack.pop();
  32923. currentRenderState = null;
  32924. return materials;
  32925. };
  32926. // compileAsync
  32927. this.compileAsync = function ( scene, camera, targetScene = null ) {
  32928. const materials = this.compile( scene, camera, targetScene );
  32929. // Wait for all the materials in the new object to indicate that they're
  32930. // ready to be used before resolving the promise.
  32931. return new Promise( ( resolve ) => {
  32932. function checkMaterialsReady() {
  32933. materials.forEach( function ( material ) {
  32934. const materialProperties = properties.get( material );
  32935. const program = materialProperties.currentProgram;
  32936. if ( program.isReady() ) {
  32937. // remove any programs that report they're ready to use from the list
  32938. materials.delete( material );
  32939. }
  32940. } );
  32941. // once the list of compiling materials is empty, call the callback
  32942. if ( materials.size === 0 ) {
  32943. resolve( scene );
  32944. return;
  32945. }
  32946. // if some materials are still not ready, wait a bit and check again
  32947. setTimeout( checkMaterialsReady, 10 );
  32948. }
  32949. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  32950. // If we can check the compilation status of the materials without
  32951. // blocking then do so right away.
  32952. checkMaterialsReady();
  32953. } else {
  32954. // Otherwise start by waiting a bit to give the materials we just
  32955. // initialized a chance to finish.
  32956. setTimeout( checkMaterialsReady, 10 );
  32957. }
  32958. } );
  32959. };
  32960. // Animation Loop
  32961. let onAnimationFrameCallback = null;
  32962. function onAnimationFrame( time ) {
  32963. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  32964. }
  32965. function onXRSessionStart() {
  32966. animation.stop();
  32967. }
  32968. function onXRSessionEnd() {
  32969. animation.start();
  32970. }
  32971. const animation = new WebGLAnimation();
  32972. animation.setAnimationLoop( onAnimationFrame );
  32973. if ( typeof self !== 'undefined' ) animation.setContext( self );
  32974. this.setAnimationLoop = function ( callback ) {
  32975. onAnimationFrameCallback = callback;
  32976. xr.setAnimationLoop( callback );
  32977. ( callback === null ) ? animation.stop() : animation.start();
  32978. };
  32979. xr.addEventListener( 'sessionstart', onXRSessionStart );
  32980. xr.addEventListener( 'sessionend', onXRSessionEnd );
  32981. // Rendering
  32982. this.render = function ( scene, camera ) {
  32983. if ( camera !== undefined && camera.isCamera !== true ) {
  32984. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  32985. return;
  32986. }
  32987. if ( _isContextLost === true ) return;
  32988. // update scene graph
  32989. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  32990. // update camera matrices and frustum
  32991. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  32992. if ( xr.enabled === true && xr.isPresenting === true ) {
  32993. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  32994. camera = xr.getCamera(); // use XR camera for rendering
  32995. }
  32996. //
  32997. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  32998. currentRenderState = renderStates.get( scene, renderStateStack.length );
  32999. currentRenderState.init( camera );
  33000. renderStateStack.push( currentRenderState );
  33001. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33002. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  33003. _localClippingEnabled = this.localClippingEnabled;
  33004. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  33005. currentRenderList = renderLists.get( scene, renderListStack.length );
  33006. currentRenderList.init();
  33007. renderListStack.push( currentRenderList );
  33008. if ( xr.enabled === true && xr.isPresenting === true ) {
  33009. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  33010. if ( depthSensingMesh !== null ) {
  33011. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  33012. }
  33013. }
  33014. projectObject( scene, camera, 0, _this.sortObjects );
  33015. currentRenderList.finish();
  33016. if ( _this.sortObjects === true ) {
  33017. currentRenderList.sort( _opaqueSort, _transparentSort );
  33018. }
  33019. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  33020. if ( _renderBackground ) {
  33021. background.addToRenderList( currentRenderList, scene );
  33022. }
  33023. //
  33024. this.info.render.frame ++;
  33025. if ( _clippingEnabled === true ) clipping.beginShadows();
  33026. const shadowsArray = currentRenderState.state.shadowsArray;
  33027. shadowMap.render( shadowsArray, scene, camera );
  33028. if ( _clippingEnabled === true ) clipping.endShadows();
  33029. //
  33030. if ( this.info.autoReset === true ) this.info.reset();
  33031. // render scene
  33032. const opaqueObjects = currentRenderList.opaque;
  33033. const transmissiveObjects = currentRenderList.transmissive;
  33034. currentRenderState.setupLights();
  33035. if ( camera.isArrayCamera ) {
  33036. const cameras = camera.cameras;
  33037. if ( transmissiveObjects.length > 0 ) {
  33038. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  33039. const camera2 = cameras[ i ];
  33040. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  33041. }
  33042. }
  33043. if ( _renderBackground ) background.render( scene );
  33044. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  33045. const camera2 = cameras[ i ];
  33046. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  33047. }
  33048. } else {
  33049. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  33050. if ( _renderBackground ) background.render( scene );
  33051. renderScene( currentRenderList, scene, camera );
  33052. }
  33053. //
  33054. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  33055. // resolve multisample renderbuffers to a single-sample texture if necessary
  33056. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  33057. // Generate mipmap if we're using any kind of mipmap filtering
  33058. textures.updateRenderTargetMipmap( _currentRenderTarget );
  33059. }
  33060. //
  33061. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  33062. // _gl.finish();
  33063. bindingStates.resetDefaultState();
  33064. _currentMaterialId = -1;
  33065. _currentCamera = null;
  33066. renderStateStack.pop();
  33067. if ( renderStateStack.length > 0 ) {
  33068. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  33069. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  33070. } else {
  33071. currentRenderState = null;
  33072. }
  33073. renderListStack.pop();
  33074. if ( renderListStack.length > 0 ) {
  33075. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  33076. } else {
  33077. currentRenderList = null;
  33078. }
  33079. };
  33080. function projectObject( object, camera, groupOrder, sortObjects ) {
  33081. if ( object.visible === false ) return;
  33082. const visible = object.layers.test( camera.layers );
  33083. if ( visible ) {
  33084. if ( object.isGroup ) {
  33085. groupOrder = object.renderOrder;
  33086. } else if ( object.isLOD ) {
  33087. if ( object.autoUpdate === true ) object.update( camera );
  33088. } else if ( object.isLight ) {
  33089. currentRenderState.pushLight( object );
  33090. if ( object.castShadow ) {
  33091. currentRenderState.pushShadow( object );
  33092. }
  33093. } else if ( object.isSprite ) {
  33094. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  33095. if ( sortObjects ) {
  33096. _vector4.setFromMatrixPosition( object.matrixWorld )
  33097. .applyMatrix4( _projScreenMatrix );
  33098. }
  33099. const geometry = objects.update( object );
  33100. const material = object.material;
  33101. if ( material.visible ) {
  33102. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  33103. }
  33104. }
  33105. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  33106. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  33107. const geometry = objects.update( object );
  33108. const material = object.material;
  33109. if ( sortObjects ) {
  33110. if ( object.boundingSphere !== undefined ) {
  33111. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  33112. _vector4.copy( object.boundingSphere.center );
  33113. } else {
  33114. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  33115. _vector4.copy( geometry.boundingSphere.center );
  33116. }
  33117. _vector4
  33118. .applyMatrix4( object.matrixWorld )
  33119. .applyMatrix4( _projScreenMatrix );
  33120. }
  33121. if ( Array.isArray( material ) ) {
  33122. const groups = geometry.groups;
  33123. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  33124. const group = groups[ i ];
  33125. const groupMaterial = material[ group.materialIndex ];
  33126. if ( groupMaterial && groupMaterial.visible ) {
  33127. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  33128. }
  33129. }
  33130. } else if ( material.visible ) {
  33131. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  33132. }
  33133. }
  33134. }
  33135. }
  33136. const children = object.children;
  33137. for ( let i = 0, l = children.length; i < l; i ++ ) {
  33138. projectObject( children[ i ], camera, groupOrder, sortObjects );
  33139. }
  33140. }
  33141. function renderScene( currentRenderList, scene, camera, viewport ) {
  33142. const opaqueObjects = currentRenderList.opaque;
  33143. const transmissiveObjects = currentRenderList.transmissive;
  33144. const transparentObjects = currentRenderList.transparent;
  33145. currentRenderState.setupLightsView( camera );
  33146. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  33147. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  33148. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  33149. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  33150. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  33151. // Ensure depth buffer writing is enabled so it can be cleared on next render
  33152. state.buffers.depth.setTest( true );
  33153. state.buffers.depth.setMask( true );
  33154. state.buffers.color.setMask( true );
  33155. state.setPolygonOffset( false );
  33156. }
  33157. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  33158. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  33159. if ( overrideMaterial !== null ) {
  33160. return;
  33161. }
  33162. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  33163. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  33164. generateMipmaps: true,
  33165. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  33166. minFilter: LinearMipmapLinearFilter,
  33167. samples: 4,
  33168. stencilBuffer: stencil,
  33169. resolveDepthBuffer: false,
  33170. resolveStencilBuffer: false,
  33171. colorSpace: ColorManagement.workingColorSpace,
  33172. } );
  33173. // debug
  33174. /*
  33175. const geometry = new PlaneGeometry();
  33176. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  33177. const mesh = new Mesh( geometry, material );
  33178. scene.add( mesh );
  33179. */
  33180. }
  33181. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  33182. const activeViewport = camera.viewport || _currentViewport;
  33183. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  33184. //
  33185. const currentRenderTarget = _this.getRenderTarget();
  33186. _this.setRenderTarget( transmissionRenderTarget );
  33187. _this.getClearColor( _currentClearColor );
  33188. _currentClearAlpha = _this.getClearAlpha();
  33189. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  33190. _this.clear();
  33191. if ( _renderBackground ) background.render( scene );
  33192. // Turn off the features which can affect the frag color for opaque objects pass.
  33193. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  33194. const currentToneMapping = _this.toneMapping;
  33195. _this.toneMapping = NoToneMapping;
  33196. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  33197. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  33198. const currentCameraViewport = camera.viewport;
  33199. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  33200. currentRenderState.setupLightsView( camera );
  33201. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  33202. renderObjects( opaqueObjects, scene, camera );
  33203. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  33204. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  33205. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  33206. let renderTargetNeedsUpdate = false;
  33207. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  33208. const renderItem = transmissiveObjects[ i ];
  33209. const object = renderItem.object;
  33210. const geometry = renderItem.geometry;
  33211. const material = renderItem.material;
  33212. const group = renderItem.group;
  33213. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  33214. const currentSide = material.side;
  33215. material.side = BackSide;
  33216. material.needsUpdate = true;
  33217. renderObject( object, scene, camera, geometry, material, group );
  33218. material.side = currentSide;
  33219. material.needsUpdate = true;
  33220. renderTargetNeedsUpdate = true;
  33221. }
  33222. }
  33223. if ( renderTargetNeedsUpdate === true ) {
  33224. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  33225. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  33226. }
  33227. }
  33228. _this.setRenderTarget( currentRenderTarget );
  33229. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  33230. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  33231. _this.toneMapping = currentToneMapping;
  33232. }
  33233. function renderObjects( renderList, scene, camera ) {
  33234. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  33235. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  33236. const renderItem = renderList[ i ];
  33237. const object = renderItem.object;
  33238. const geometry = renderItem.geometry;
  33239. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  33240. const group = renderItem.group;
  33241. if ( object.layers.test( camera.layers ) ) {
  33242. renderObject( object, scene, camera, geometry, material, group );
  33243. }
  33244. }
  33245. }
  33246. function renderObject( object, scene, camera, geometry, material, group ) {
  33247. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  33248. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  33249. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  33250. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  33251. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  33252. material.side = BackSide;
  33253. material.needsUpdate = true;
  33254. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  33255. material.side = FrontSide;
  33256. material.needsUpdate = true;
  33257. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  33258. material.side = DoubleSide;
  33259. } else {
  33260. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  33261. }
  33262. object.onAfterRender( _this, scene, camera, geometry, material, group );
  33263. }
  33264. function getProgram( material, scene, object ) {
  33265. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  33266. const materialProperties = properties.get( material );
  33267. const lights = currentRenderState.state.lights;
  33268. const shadowsArray = currentRenderState.state.shadowsArray;
  33269. const lightsStateVersion = lights.state.version;
  33270. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  33271. const programCacheKey = programCache.getProgramCacheKey( parameters );
  33272. let programs = materialProperties.programs;
  33273. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  33274. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  33275. materialProperties.fog = scene.fog;
  33276. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  33277. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  33278. if ( programs === undefined ) {
  33279. // new material
  33280. material.addEventListener( 'dispose', onMaterialDispose );
  33281. programs = new Map();
  33282. materialProperties.programs = programs;
  33283. }
  33284. let program = programs.get( programCacheKey );
  33285. if ( program !== undefined ) {
  33286. // early out if program and light state is identical
  33287. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  33288. updateCommonMaterialProperties( material, parameters );
  33289. return program;
  33290. }
  33291. } else {
  33292. parameters.uniforms = programCache.getUniforms( material );
  33293. material.onBeforeCompile( parameters, _this );
  33294. program = programCache.acquireProgram( parameters, programCacheKey );
  33295. programs.set( programCacheKey, program );
  33296. materialProperties.uniforms = parameters.uniforms;
  33297. }
  33298. const uniforms = materialProperties.uniforms;
  33299. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  33300. uniforms.clippingPlanes = clipping.uniform;
  33301. }
  33302. updateCommonMaterialProperties( material, parameters );
  33303. // store the light setup it was created for
  33304. materialProperties.needsLights = materialNeedsLights( material );
  33305. materialProperties.lightsStateVersion = lightsStateVersion;
  33306. if ( materialProperties.needsLights ) {
  33307. // wire up the material to this renderer's lighting state
  33308. uniforms.ambientLightColor.value = lights.state.ambient;
  33309. uniforms.lightProbe.value = lights.state.probe;
  33310. uniforms.directionalLights.value = lights.state.directional;
  33311. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  33312. uniforms.spotLights.value = lights.state.spot;
  33313. uniforms.spotLightShadows.value = lights.state.spotShadow;
  33314. uniforms.rectAreaLights.value = lights.state.rectArea;
  33315. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  33316. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  33317. uniforms.pointLights.value = lights.state.point;
  33318. uniforms.pointLightShadows.value = lights.state.pointShadow;
  33319. uniforms.hemisphereLights.value = lights.state.hemi;
  33320. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  33321. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  33322. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  33323. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  33324. uniforms.spotLightMap.value = lights.state.spotLightMap;
  33325. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  33326. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  33327. // TODO (abelnation): add area lights shadow info to uniforms
  33328. }
  33329. materialProperties.currentProgram = program;
  33330. materialProperties.uniformsList = null;
  33331. return program;
  33332. }
  33333. function getUniformList( materialProperties ) {
  33334. if ( materialProperties.uniformsList === null ) {
  33335. const progUniforms = materialProperties.currentProgram.getUniforms();
  33336. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  33337. }
  33338. return materialProperties.uniformsList;
  33339. }
  33340. function updateCommonMaterialProperties( material, parameters ) {
  33341. const materialProperties = properties.get( material );
  33342. materialProperties.outputColorSpace = parameters.outputColorSpace;
  33343. materialProperties.batching = parameters.batching;
  33344. materialProperties.batchingColor = parameters.batchingColor;
  33345. materialProperties.instancing = parameters.instancing;
  33346. materialProperties.instancingColor = parameters.instancingColor;
  33347. materialProperties.instancingMorph = parameters.instancingMorph;
  33348. materialProperties.skinning = parameters.skinning;
  33349. materialProperties.morphTargets = parameters.morphTargets;
  33350. materialProperties.morphNormals = parameters.morphNormals;
  33351. materialProperties.morphColors = parameters.morphColors;
  33352. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  33353. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  33354. materialProperties.numIntersection = parameters.numClipIntersection;
  33355. materialProperties.vertexAlphas = parameters.vertexAlphas;
  33356. materialProperties.vertexTangents = parameters.vertexTangents;
  33357. materialProperties.toneMapping = parameters.toneMapping;
  33358. }
  33359. function setProgram( camera, scene, geometry, material, object ) {
  33360. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  33361. textures.resetTextureUnits();
  33362. const fog = scene.fog;
  33363. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  33364. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  33365. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  33366. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  33367. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  33368. const morphTargets = !! geometry.morphAttributes.position;
  33369. const morphNormals = !! geometry.morphAttributes.normal;
  33370. const morphColors = !! geometry.morphAttributes.color;
  33371. let toneMapping = NoToneMapping;
  33372. if ( material.toneMapped ) {
  33373. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  33374. toneMapping = _this.toneMapping;
  33375. }
  33376. }
  33377. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  33378. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  33379. const materialProperties = properties.get( material );
  33380. const lights = currentRenderState.state.lights;
  33381. if ( _clippingEnabled === true ) {
  33382. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  33383. const useCache =
  33384. camera === _currentCamera &&
  33385. material.id === _currentMaterialId;
  33386. // we might want to call this function with some ClippingGroup
  33387. // object instead of the material, once it becomes feasible
  33388. // (#8465, #8379)
  33389. clipping.setState( material, camera, useCache );
  33390. }
  33391. }
  33392. //
  33393. let needsProgramChange = false;
  33394. if ( material.version === materialProperties.__version ) {
  33395. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  33396. needsProgramChange = true;
  33397. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  33398. needsProgramChange = true;
  33399. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  33400. needsProgramChange = true;
  33401. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  33402. needsProgramChange = true;
  33403. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  33404. needsProgramChange = true;
  33405. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  33406. needsProgramChange = true;
  33407. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  33408. needsProgramChange = true;
  33409. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  33410. needsProgramChange = true;
  33411. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  33412. needsProgramChange = true;
  33413. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  33414. needsProgramChange = true;
  33415. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  33416. needsProgramChange = true;
  33417. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  33418. needsProgramChange = true;
  33419. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  33420. needsProgramChange = true;
  33421. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  33422. needsProgramChange = true;
  33423. } else if ( materialProperties.envMap !== envMap ) {
  33424. needsProgramChange = true;
  33425. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  33426. needsProgramChange = true;
  33427. } else if ( materialProperties.numClippingPlanes !== undefined &&
  33428. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  33429. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  33430. needsProgramChange = true;
  33431. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  33432. needsProgramChange = true;
  33433. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  33434. needsProgramChange = true;
  33435. } else if ( materialProperties.morphTargets !== morphTargets ) {
  33436. needsProgramChange = true;
  33437. } else if ( materialProperties.morphNormals !== morphNormals ) {
  33438. needsProgramChange = true;
  33439. } else if ( materialProperties.morphColors !== morphColors ) {
  33440. needsProgramChange = true;
  33441. } else if ( materialProperties.toneMapping !== toneMapping ) {
  33442. needsProgramChange = true;
  33443. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  33444. needsProgramChange = true;
  33445. }
  33446. } else {
  33447. needsProgramChange = true;
  33448. materialProperties.__version = material.version;
  33449. }
  33450. //
  33451. let program = materialProperties.currentProgram;
  33452. if ( needsProgramChange === true ) {
  33453. program = getProgram( material, scene, object );
  33454. }
  33455. let refreshProgram = false;
  33456. let refreshMaterial = false;
  33457. let refreshLights = false;
  33458. const p_uniforms = program.getUniforms(),
  33459. m_uniforms = materialProperties.uniforms;
  33460. if ( state.useProgram( program.program ) ) {
  33461. refreshProgram = true;
  33462. refreshMaterial = true;
  33463. refreshLights = true;
  33464. }
  33465. if ( material.id !== _currentMaterialId ) {
  33466. _currentMaterialId = material.id;
  33467. refreshMaterial = true;
  33468. }
  33469. if ( refreshProgram || _currentCamera !== camera ) {
  33470. // common camera uniforms
  33471. const reverseDepthBuffer = state.buffers.depth.getReversed();
  33472. if ( reverseDepthBuffer ) {
  33473. _currentProjectionMatrix.copy( camera.projectionMatrix );
  33474. toNormalizedProjectionMatrix( _currentProjectionMatrix );
  33475. toReversedProjectionMatrix( _currentProjectionMatrix );
  33476. p_uniforms.setValue( _gl, 'projectionMatrix', _currentProjectionMatrix );
  33477. } else {
  33478. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  33479. }
  33480. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  33481. const uCamPos = p_uniforms.map.cameraPosition;
  33482. if ( uCamPos !== undefined ) {
  33483. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  33484. }
  33485. if ( capabilities.logarithmicDepthBuffer ) {
  33486. p_uniforms.setValue( _gl, 'logDepthBufFC',
  33487. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  33488. }
  33489. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  33490. if ( material.isMeshPhongMaterial ||
  33491. material.isMeshToonMaterial ||
  33492. material.isMeshLambertMaterial ||
  33493. material.isMeshBasicMaterial ||
  33494. material.isMeshStandardMaterial ||
  33495. material.isShaderMaterial ) {
  33496. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  33497. }
  33498. if ( _currentCamera !== camera ) {
  33499. _currentCamera = camera;
  33500. // lighting uniforms depend on the camera so enforce an update
  33501. // now, in case this material supports lights - or later, when
  33502. // the next material that does gets activated:
  33503. refreshMaterial = true; // set to true on material change
  33504. refreshLights = true; // remains set until update done
  33505. }
  33506. }
  33507. // skinning and morph target uniforms must be set even if material didn't change
  33508. // auto-setting of texture unit for bone and morph texture must go before other textures
  33509. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  33510. if ( object.isSkinnedMesh ) {
  33511. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  33512. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  33513. const skeleton = object.skeleton;
  33514. if ( skeleton ) {
  33515. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  33516. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  33517. }
  33518. }
  33519. if ( object.isBatchedMesh ) {
  33520. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  33521. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  33522. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  33523. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  33524. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  33525. if ( object._colorsTexture !== null ) {
  33526. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  33527. }
  33528. }
  33529. const morphAttributes = geometry.morphAttributes;
  33530. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  33531. morphtargets.update( object, geometry, program );
  33532. }
  33533. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  33534. materialProperties.receiveShadow = object.receiveShadow;
  33535. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  33536. }
  33537. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  33538. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  33539. m_uniforms.envMap.value = envMap;
  33540. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  33541. }
  33542. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  33543. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  33544. }
  33545. if ( refreshMaterial ) {
  33546. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  33547. if ( materialProperties.needsLights ) {
  33548. // the current material requires lighting info
  33549. // note: all lighting uniforms are always set correctly
  33550. // they simply reference the renderer's state for their
  33551. // values
  33552. //
  33553. // use the current material's .needsUpdate flags to set
  33554. // the GL state when required
  33555. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  33556. }
  33557. // refresh uniforms common to several materials
  33558. if ( fog && material.fog === true ) {
  33559. materials.refreshFogUniforms( m_uniforms, fog );
  33560. }
  33561. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  33562. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  33563. }
  33564. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  33565. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  33566. material.uniformsNeedUpdate = false;
  33567. }
  33568. if ( material.isSpriteMaterial ) {
  33569. p_uniforms.setValue( _gl, 'center', object.center );
  33570. }
  33571. // common matrices
  33572. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  33573. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  33574. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  33575. // UBOs
  33576. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  33577. const groups = material.uniformsGroups;
  33578. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  33579. const group = groups[ i ];
  33580. uniformsGroups.update( group, program );
  33581. uniformsGroups.bind( group, program );
  33582. }
  33583. }
  33584. return program;
  33585. }
  33586. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  33587. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  33588. uniforms.ambientLightColor.needsUpdate = value;
  33589. uniforms.lightProbe.needsUpdate = value;
  33590. uniforms.directionalLights.needsUpdate = value;
  33591. uniforms.directionalLightShadows.needsUpdate = value;
  33592. uniforms.pointLights.needsUpdate = value;
  33593. uniforms.pointLightShadows.needsUpdate = value;
  33594. uniforms.spotLights.needsUpdate = value;
  33595. uniforms.spotLightShadows.needsUpdate = value;
  33596. uniforms.rectAreaLights.needsUpdate = value;
  33597. uniforms.hemisphereLights.needsUpdate = value;
  33598. }
  33599. function materialNeedsLights( material ) {
  33600. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  33601. material.isMeshStandardMaterial || material.isShadowMaterial ||
  33602. ( material.isShaderMaterial && material.lights === true );
  33603. }
  33604. this.getActiveCubeFace = function () {
  33605. return _currentActiveCubeFace;
  33606. };
  33607. this.getActiveMipmapLevel = function () {
  33608. return _currentActiveMipmapLevel;
  33609. };
  33610. this.getRenderTarget = function () {
  33611. return _currentRenderTarget;
  33612. };
  33613. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  33614. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  33615. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  33616. const renderTargetProperties = properties.get( renderTarget );
  33617. renderTargetProperties.__hasExternalTextures = true;
  33618. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  33619. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  33620. // The multisample_render_to_texture extension doesn't work properly if there
  33621. // are midframe flushes and an external depth buffer. Disable use of the extension.
  33622. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  33623. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  33624. renderTargetProperties.__useRenderToTexture = false;
  33625. }
  33626. }
  33627. };
  33628. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  33629. const renderTargetProperties = properties.get( renderTarget );
  33630. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  33631. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  33632. };
  33633. const _scratchFrameBuffer = _gl.createFramebuffer();
  33634. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  33635. _currentRenderTarget = renderTarget;
  33636. _currentActiveCubeFace = activeCubeFace;
  33637. _currentActiveMipmapLevel = activeMipmapLevel;
  33638. let useDefaultFramebuffer = true;
  33639. let framebuffer = null;
  33640. let isCube = false;
  33641. let isRenderTarget3D = false;
  33642. if ( renderTarget ) {
  33643. const renderTargetProperties = properties.get( renderTarget );
  33644. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  33645. // We need to make sure to rebind the framebuffer.
  33646. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  33647. useDefaultFramebuffer = false;
  33648. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  33649. textures.setupRenderTarget( renderTarget );
  33650. } else if ( renderTargetProperties.__hasExternalTextures ) {
  33651. // Color and depth texture must be rebound in order for the swapchain to update.
  33652. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  33653. } else if ( renderTarget.depthBuffer ) {
  33654. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  33655. const depthTexture = renderTarget.depthTexture;
  33656. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  33657. // check if the depth texture is compatible
  33658. if (
  33659. depthTexture !== null &&
  33660. properties.has( depthTexture ) &&
  33661. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  33662. ) {
  33663. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  33664. }
  33665. // Swap the depth buffer to the currently attached one
  33666. textures.setupDepthRenderbuffer( renderTarget );
  33667. }
  33668. }
  33669. const texture = renderTarget.texture;
  33670. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  33671. isRenderTarget3D = true;
  33672. }
  33673. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  33674. if ( renderTarget.isWebGLCubeRenderTarget ) {
  33675. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  33676. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  33677. } else {
  33678. framebuffer = __webglFramebuffer[ activeCubeFace ];
  33679. }
  33680. isCube = true;
  33681. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  33682. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  33683. } else {
  33684. if ( Array.isArray( __webglFramebuffer ) ) {
  33685. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  33686. } else {
  33687. framebuffer = __webglFramebuffer;
  33688. }
  33689. }
  33690. _currentViewport.copy( renderTarget.viewport );
  33691. _currentScissor.copy( renderTarget.scissor );
  33692. _currentScissorTest = renderTarget.scissorTest;
  33693. } else {
  33694. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  33695. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  33696. _currentScissorTest = _scissorTest;
  33697. }
  33698. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  33699. // being bound that are different sizes.
  33700. if ( activeMipmapLevel !== 0 ) {
  33701. framebuffer = _scratchFrameBuffer;
  33702. }
  33703. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  33704. if ( framebufferBound && useDefaultFramebuffer ) {
  33705. state.drawBuffers( renderTarget, framebuffer );
  33706. }
  33707. state.viewport( _currentViewport );
  33708. state.scissor( _currentScissor );
  33709. state.setScissorTest( _currentScissorTest );
  33710. if ( isCube ) {
  33711. const textureProperties = properties.get( renderTarget.texture );
  33712. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  33713. } else if ( isRenderTarget3D ) {
  33714. const textureProperties = properties.get( renderTarget.texture );
  33715. const layer = activeCubeFace;
  33716. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer );
  33717. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  33718. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  33719. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  33720. const textureProperties = properties.get( renderTarget.texture );
  33721. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  33722. }
  33723. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  33724. };
  33725. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  33726. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  33727. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  33728. return;
  33729. }
  33730. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  33731. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  33732. framebuffer = framebuffer[ activeCubeFaceIndex ];
  33733. }
  33734. if ( framebuffer ) {
  33735. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  33736. try {
  33737. const texture = renderTarget.texture;
  33738. const textureFormat = texture.format;
  33739. const textureType = texture.type;
  33740. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  33741. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  33742. return;
  33743. }
  33744. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  33745. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  33746. return;
  33747. }
  33748. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  33749. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  33750. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  33751. }
  33752. } finally {
  33753. // restore framebuffer of current render target if necessary
  33754. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  33755. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  33756. }
  33757. }
  33758. };
  33759. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  33760. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  33761. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  33762. }
  33763. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  33764. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  33765. framebuffer = framebuffer[ activeCubeFaceIndex ];
  33766. }
  33767. if ( framebuffer ) {
  33768. const texture = renderTarget.texture;
  33769. const textureFormat = texture.format;
  33770. const textureType = texture.type;
  33771. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  33772. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  33773. }
  33774. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  33775. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  33776. }
  33777. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  33778. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  33779. // set the active frame buffer to the one we want to read
  33780. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  33781. const glBuffer = _gl.createBuffer();
  33782. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  33783. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  33784. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  33785. // reset the frame buffer to the currently set buffer before waiting
  33786. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  33787. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  33788. // check if the commands have finished every 8 ms
  33789. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  33790. _gl.flush();
  33791. await probeAsync( _gl, sync, 4 );
  33792. // read the data and delete the buffer
  33793. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  33794. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  33795. _gl.deleteBuffer( glBuffer );
  33796. _gl.deleteSync( sync );
  33797. return buffer;
  33798. } else {
  33799. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  33800. }
  33801. }
  33802. };
  33803. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  33804. // support previous signature with position first
  33805. if ( texture.isTexture !== true ) {
  33806. // @deprecated, r165
  33807. warnOnce( 'WebGLRenderer: copyFramebufferToTexture function signature has changed.' );
  33808. position = arguments[ 0 ] || null;
  33809. texture = arguments[ 1 ];
  33810. }
  33811. const levelScale = Math.pow( 2, - level );
  33812. const width = Math.floor( texture.image.width * levelScale );
  33813. const height = Math.floor( texture.image.height * levelScale );
  33814. const x = position !== null ? position.x : 0;
  33815. const y = position !== null ? position.y : 0;
  33816. textures.setTexture2D( texture, 0 );
  33817. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  33818. state.unbindTexture();
  33819. };
  33820. const _srcFramebuffer = _gl.createFramebuffer();
  33821. const _dstFramebuffer = _gl.createFramebuffer();
  33822. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  33823. // support previous signature with dstPosition first
  33824. if ( srcTexture.isTexture !== true ) {
  33825. // @deprecated, r165
  33826. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  33827. dstPosition = arguments[ 0 ] || null;
  33828. srcTexture = arguments[ 1 ];
  33829. dstTexture = arguments[ 2 ];
  33830. dstLevel = arguments[ 3 ] || 0;
  33831. srcRegion = null;
  33832. }
  33833. // support the previous signature with just a single dst mipmap level
  33834. if ( dstLevel === null ) {
  33835. if ( srcLevel !== 0 ) {
  33836. // @deprecated, r171
  33837. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  33838. dstLevel = srcLevel;
  33839. srcLevel = 0;
  33840. } else {
  33841. dstLevel = 0;
  33842. }
  33843. }
  33844. // gather the necessary dimensions to copy
  33845. let width, height, depth, minX, minY, minZ;
  33846. let dstX, dstY, dstZ;
  33847. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  33848. if ( srcRegion !== null ) {
  33849. width = srcRegion.max.x - srcRegion.min.x;
  33850. height = srcRegion.max.y - srcRegion.min.y;
  33851. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  33852. minX = srcRegion.min.x;
  33853. minY = srcRegion.min.y;
  33854. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  33855. } else {
  33856. const levelScale = Math.pow( 2, - srcLevel );
  33857. width = Math.floor( image.width * levelScale );
  33858. height = Math.floor( image.height * levelScale );
  33859. if ( srcTexture.isDataArrayTexture ) {
  33860. depth = image.depth;
  33861. } else if ( srcTexture.isData3DTexture ) {
  33862. depth = Math.floor( image.depth * levelScale );
  33863. } else {
  33864. depth = 1;
  33865. }
  33866. minX = 0;
  33867. minY = 0;
  33868. minZ = 0;
  33869. }
  33870. if ( dstPosition !== null ) {
  33871. dstX = dstPosition.x;
  33872. dstY = dstPosition.y;
  33873. dstZ = dstPosition.z;
  33874. } else {
  33875. dstX = 0;
  33876. dstY = 0;
  33877. dstZ = 0;
  33878. }
  33879. // Set up the destination target
  33880. const glFormat = utils.convert( dstTexture.format );
  33881. const glType = utils.convert( dstTexture.type );
  33882. let glTarget;
  33883. if ( dstTexture.isData3DTexture ) {
  33884. textures.setTexture3D( dstTexture, 0 );
  33885. glTarget = _gl.TEXTURE_3D;
  33886. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  33887. textures.setTexture2DArray( dstTexture, 0 );
  33888. glTarget = _gl.TEXTURE_2D_ARRAY;
  33889. } else {
  33890. textures.setTexture2D( dstTexture, 0 );
  33891. glTarget = _gl.TEXTURE_2D;
  33892. }
  33893. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  33894. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  33895. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  33896. // used for copying data from cpu
  33897. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  33898. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  33899. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  33900. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  33901. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  33902. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  33903. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  33904. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  33905. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  33906. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  33907. // set up the src texture
  33908. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  33909. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  33910. if ( srcTexture.isDepthTexture ) {
  33911. const srcTextureProperties = properties.get( srcTexture );
  33912. const dstTextureProperties = properties.get( dstTexture );
  33913. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  33914. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  33915. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  33916. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  33917. for ( let i = 0; i < depth; i ++ ) {
  33918. // if the source or destination are a 3d target then a layer needs to be bound
  33919. if ( isSrc3D ) {
  33920. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  33921. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  33922. }
  33923. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  33924. }
  33925. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  33926. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  33927. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  33928. // get the appropriate frame buffers
  33929. const srcTextureProperties = properties.get( srcTexture );
  33930. const dstTextureProperties = properties.get( dstTexture );
  33931. // bind the frame buffer targets
  33932. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  33933. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  33934. for ( let i = 0; i < depth; i ++ ) {
  33935. // assign the correct layers and mip maps to the frame buffers
  33936. if ( isSrc3D ) {
  33937. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  33938. } else {
  33939. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  33940. }
  33941. if ( isDst3D ) {
  33942. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  33943. } else {
  33944. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  33945. }
  33946. // copy the data using the fastest function that can achieve the copy
  33947. if ( srcLevel !== 0 ) {
  33948. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  33949. } else if ( isDst3D ) {
  33950. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  33951. } else {
  33952. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  33953. }
  33954. }
  33955. // unbind read, draw buffers
  33956. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  33957. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  33958. } else {
  33959. if ( isDst3D ) {
  33960. // copy data into the 3d texture
  33961. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  33962. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  33963. } else if ( dstTexture.isCompressedArrayTexture ) {
  33964. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  33965. } else {
  33966. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  33967. }
  33968. } else {
  33969. // copy data into the 2d texture
  33970. if ( srcTexture.isDataTexture ) {
  33971. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  33972. } else if ( srcTexture.isCompressedTexture ) {
  33973. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  33974. } else {
  33975. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  33976. }
  33977. }
  33978. }
  33979. // reset values
  33980. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  33981. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  33982. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  33983. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  33984. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  33985. // Generate mipmaps only when copying level 0
  33986. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  33987. _gl.generateMipmap( glTarget );
  33988. }
  33989. state.unbindTexture();
  33990. };
  33991. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  33992. // support previous signature with source box first
  33993. if ( srcTexture.isTexture !== true ) {
  33994. // @deprecated, r165
  33995. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  33996. srcRegion = arguments[ 0 ] || null;
  33997. dstPosition = arguments[ 1 ] || null;
  33998. srcTexture = arguments[ 2 ];
  33999. dstTexture = arguments[ 3 ];
  34000. level = arguments[ 4 ] || 0;
  34001. }
  34002. // @deprecated, r170
  34003. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.' );
  34004. return this.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  34005. };
  34006. this.initRenderTarget = function ( target ) {
  34007. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  34008. textures.setupRenderTarget( target );
  34009. }
  34010. };
  34011. this.initTexture = function ( texture ) {
  34012. if ( texture.isCubeTexture ) {
  34013. textures.setTextureCube( texture, 0 );
  34014. } else if ( texture.isData3DTexture ) {
  34015. textures.setTexture3D( texture, 0 );
  34016. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  34017. textures.setTexture2DArray( texture, 0 );
  34018. } else {
  34019. textures.setTexture2D( texture, 0 );
  34020. }
  34021. state.unbindTexture();
  34022. };
  34023. this.resetState = function () {
  34024. _currentActiveCubeFace = 0;
  34025. _currentActiveMipmapLevel = 0;
  34026. _currentRenderTarget = null;
  34027. state.reset();
  34028. bindingStates.reset();
  34029. };
  34030. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  34031. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  34032. }
  34033. }
  34034. get coordinateSystem() {
  34035. return WebGLCoordinateSystem;
  34036. }
  34037. get outputColorSpace() {
  34038. return this._outputColorSpace;
  34039. }
  34040. set outputColorSpace( colorSpace ) {
  34041. this._outputColorSpace = colorSpace;
  34042. const gl = this.getContext();
  34043. gl.drawingBufferColorspace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  34044. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  34045. }
  34046. }
  34047. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  34048. exports.AddEquation = AddEquation;
  34049. exports.AddOperation = AddOperation;
  34050. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  34051. exports.AdditiveBlending = AdditiveBlending;
  34052. exports.AgXToneMapping = AgXToneMapping;
  34053. exports.AlphaFormat = AlphaFormat;
  34054. exports.AlwaysCompare = AlwaysCompare;
  34055. exports.AlwaysDepth = AlwaysDepth;
  34056. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  34057. exports.AmbientLight = AmbientLight;
  34058. exports.AnimationAction = AnimationAction;
  34059. exports.AnimationClip = AnimationClip;
  34060. exports.AnimationLoader = AnimationLoader;
  34061. exports.AnimationMixer = AnimationMixer;
  34062. exports.AnimationObjectGroup = AnimationObjectGroup;
  34063. exports.AnimationUtils = AnimationUtils;
  34064. exports.ArcCurve = ArcCurve;
  34065. exports.ArrayCamera = ArrayCamera;
  34066. exports.ArrowHelper = ArrowHelper;
  34067. exports.AttachedBindMode = AttachedBindMode;
  34068. exports.Audio = Audio;
  34069. exports.AudioAnalyser = AudioAnalyser;
  34070. exports.AudioContext = AudioContext;
  34071. exports.AudioListener = AudioListener;
  34072. exports.AudioLoader = AudioLoader;
  34073. exports.AxesHelper = AxesHelper;
  34074. exports.BackSide = BackSide;
  34075. exports.BasicDepthPacking = BasicDepthPacking;
  34076. exports.BasicShadowMap = BasicShadowMap;
  34077. exports.BatchedMesh = BatchedMesh;
  34078. exports.Bone = Bone;
  34079. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  34080. exports.Box2 = Box2;
  34081. exports.Box3 = Box3;
  34082. exports.Box3Helper = Box3Helper;
  34083. exports.BoxGeometry = BoxGeometry;
  34084. exports.BoxHelper = BoxHelper;
  34085. exports.BufferAttribute = BufferAttribute;
  34086. exports.BufferGeometry = BufferGeometry;
  34087. exports.BufferGeometryLoader = BufferGeometryLoader;
  34088. exports.ByteType = ByteType;
  34089. exports.Cache = Cache;
  34090. exports.Camera = Camera;
  34091. exports.CameraHelper = CameraHelper;
  34092. exports.CanvasTexture = CanvasTexture;
  34093. exports.CapsuleGeometry = CapsuleGeometry;
  34094. exports.CatmullRomCurve3 = CatmullRomCurve3;
  34095. exports.CineonToneMapping = CineonToneMapping;
  34096. exports.CircleGeometry = CircleGeometry;
  34097. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  34098. exports.Clock = Clock;
  34099. exports.Color = Color;
  34100. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  34101. exports.ColorManagement = ColorManagement;
  34102. exports.CompressedArrayTexture = CompressedArrayTexture;
  34103. exports.CompressedCubeTexture = CompressedCubeTexture;
  34104. exports.CompressedTexture = CompressedTexture;
  34105. exports.CompressedTextureLoader = CompressedTextureLoader;
  34106. exports.ConeGeometry = ConeGeometry;
  34107. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  34108. exports.ConstantColorFactor = ConstantColorFactor;
  34109. exports.Controls = Controls;
  34110. exports.CubeCamera = CubeCamera;
  34111. exports.CubeReflectionMapping = CubeReflectionMapping;
  34112. exports.CubeRefractionMapping = CubeRefractionMapping;
  34113. exports.CubeTexture = CubeTexture;
  34114. exports.CubeTextureLoader = CubeTextureLoader;
  34115. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  34116. exports.CubicBezierCurve = CubicBezierCurve;
  34117. exports.CubicBezierCurve3 = CubicBezierCurve3;
  34118. exports.CubicInterpolant = CubicInterpolant;
  34119. exports.CullFaceBack = CullFaceBack;
  34120. exports.CullFaceFront = CullFaceFront;
  34121. exports.CullFaceFrontBack = CullFaceFrontBack;
  34122. exports.CullFaceNone = CullFaceNone;
  34123. exports.Curve = Curve;
  34124. exports.CurvePath = CurvePath;
  34125. exports.CustomBlending = CustomBlending;
  34126. exports.CustomToneMapping = CustomToneMapping;
  34127. exports.CylinderGeometry = CylinderGeometry;
  34128. exports.Cylindrical = Cylindrical;
  34129. exports.Data3DTexture = Data3DTexture;
  34130. exports.DataArrayTexture = DataArrayTexture;
  34131. exports.DataTexture = DataTexture;
  34132. exports.DataTextureLoader = DataTextureLoader;
  34133. exports.DataUtils = DataUtils;
  34134. exports.DecrementStencilOp = DecrementStencilOp;
  34135. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  34136. exports.DefaultLoadingManager = DefaultLoadingManager;
  34137. exports.DepthFormat = DepthFormat;
  34138. exports.DepthStencilFormat = DepthStencilFormat;
  34139. exports.DepthTexture = DepthTexture;
  34140. exports.DetachedBindMode = DetachedBindMode;
  34141. exports.DirectionalLight = DirectionalLight;
  34142. exports.DirectionalLightHelper = DirectionalLightHelper;
  34143. exports.DiscreteInterpolant = DiscreteInterpolant;
  34144. exports.DodecahedronGeometry = DodecahedronGeometry;
  34145. exports.DoubleSide = DoubleSide;
  34146. exports.DstAlphaFactor = DstAlphaFactor;
  34147. exports.DstColorFactor = DstColorFactor;
  34148. exports.DynamicCopyUsage = DynamicCopyUsage;
  34149. exports.DynamicDrawUsage = DynamicDrawUsage;
  34150. exports.DynamicReadUsage = DynamicReadUsage;
  34151. exports.EdgesGeometry = EdgesGeometry;
  34152. exports.EllipseCurve = EllipseCurve;
  34153. exports.EqualCompare = EqualCompare;
  34154. exports.EqualDepth = EqualDepth;
  34155. exports.EqualStencilFunc = EqualStencilFunc;
  34156. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  34157. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  34158. exports.Euler = Euler;
  34159. exports.EventDispatcher = EventDispatcher;
  34160. exports.ExtrudeGeometry = ExtrudeGeometry;
  34161. exports.FileLoader = FileLoader;
  34162. exports.Float16BufferAttribute = Float16BufferAttribute;
  34163. exports.Float32BufferAttribute = Float32BufferAttribute;
  34164. exports.FloatType = FloatType;
  34165. exports.Fog = Fog;
  34166. exports.FogExp2 = FogExp2;
  34167. exports.FramebufferTexture = FramebufferTexture;
  34168. exports.FrontSide = FrontSide;
  34169. exports.Frustum = Frustum;
  34170. exports.GLBufferAttribute = GLBufferAttribute;
  34171. exports.GLSL1 = GLSL1;
  34172. exports.GLSL3 = GLSL3;
  34173. exports.GreaterCompare = GreaterCompare;
  34174. exports.GreaterDepth = GreaterDepth;
  34175. exports.GreaterEqualCompare = GreaterEqualCompare;
  34176. exports.GreaterEqualDepth = GreaterEqualDepth;
  34177. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  34178. exports.GreaterStencilFunc = GreaterStencilFunc;
  34179. exports.GridHelper = GridHelper;
  34180. exports.Group = Group;
  34181. exports.HalfFloatType = HalfFloatType;
  34182. exports.HemisphereLight = HemisphereLight;
  34183. exports.HemisphereLightHelper = HemisphereLightHelper;
  34184. exports.IcosahedronGeometry = IcosahedronGeometry;
  34185. exports.ImageBitmapLoader = ImageBitmapLoader;
  34186. exports.ImageLoader = ImageLoader;
  34187. exports.ImageUtils = ImageUtils;
  34188. exports.IncrementStencilOp = IncrementStencilOp;
  34189. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  34190. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  34191. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  34192. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  34193. exports.InstancedMesh = InstancedMesh;
  34194. exports.Int16BufferAttribute = Int16BufferAttribute;
  34195. exports.Int32BufferAttribute = Int32BufferAttribute;
  34196. exports.Int8BufferAttribute = Int8BufferAttribute;
  34197. exports.IntType = IntType;
  34198. exports.InterleavedBuffer = InterleavedBuffer;
  34199. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  34200. exports.Interpolant = Interpolant;
  34201. exports.InterpolateDiscrete = InterpolateDiscrete;
  34202. exports.InterpolateLinear = InterpolateLinear;
  34203. exports.InterpolateSmooth = InterpolateSmooth;
  34204. exports.InvertStencilOp = InvertStencilOp;
  34205. exports.KeepStencilOp = KeepStencilOp;
  34206. exports.KeyframeTrack = KeyframeTrack;
  34207. exports.LOD = LOD;
  34208. exports.LatheGeometry = LatheGeometry;
  34209. exports.Layers = Layers;
  34210. exports.LessCompare = LessCompare;
  34211. exports.LessDepth = LessDepth;
  34212. exports.LessEqualCompare = LessEqualCompare;
  34213. exports.LessEqualDepth = LessEqualDepth;
  34214. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  34215. exports.LessStencilFunc = LessStencilFunc;
  34216. exports.Light = Light;
  34217. exports.LightProbe = LightProbe;
  34218. exports.Line = Line;
  34219. exports.Line3 = Line3;
  34220. exports.LineBasicMaterial = LineBasicMaterial;
  34221. exports.LineCurve = LineCurve;
  34222. exports.LineCurve3 = LineCurve3;
  34223. exports.LineDashedMaterial = LineDashedMaterial;
  34224. exports.LineLoop = LineLoop;
  34225. exports.LineSegments = LineSegments;
  34226. exports.LinearFilter = LinearFilter;
  34227. exports.LinearInterpolant = LinearInterpolant;
  34228. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  34229. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  34230. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  34231. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  34232. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  34233. exports.LinearToneMapping = LinearToneMapping;
  34234. exports.LinearTransfer = LinearTransfer;
  34235. exports.Loader = Loader;
  34236. exports.LoaderUtils = LoaderUtils;
  34237. exports.LoadingManager = LoadingManager;
  34238. exports.LoopOnce = LoopOnce;
  34239. exports.LoopPingPong = LoopPingPong;
  34240. exports.LoopRepeat = LoopRepeat;
  34241. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  34242. exports.LuminanceFormat = LuminanceFormat;
  34243. exports.MOUSE = MOUSE;
  34244. exports.Material = Material;
  34245. exports.MaterialLoader = MaterialLoader;
  34246. exports.MathUtils = MathUtils;
  34247. exports.Matrix2 = Matrix2;
  34248. exports.Matrix3 = Matrix3;
  34249. exports.Matrix4 = Matrix4;
  34250. exports.MaxEquation = MaxEquation;
  34251. exports.Mesh = Mesh;
  34252. exports.MeshBasicMaterial = MeshBasicMaterial;
  34253. exports.MeshDepthMaterial = MeshDepthMaterial;
  34254. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  34255. exports.MeshLambertMaterial = MeshLambertMaterial;
  34256. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  34257. exports.MeshNormalMaterial = MeshNormalMaterial;
  34258. exports.MeshPhongMaterial = MeshPhongMaterial;
  34259. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  34260. exports.MeshStandardMaterial = MeshStandardMaterial;
  34261. exports.MeshToonMaterial = MeshToonMaterial;
  34262. exports.MinEquation = MinEquation;
  34263. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  34264. exports.MixOperation = MixOperation;
  34265. exports.MultiplyBlending = MultiplyBlending;
  34266. exports.MultiplyOperation = MultiplyOperation;
  34267. exports.NearestFilter = NearestFilter;
  34268. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  34269. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  34270. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  34271. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  34272. exports.NeutralToneMapping = NeutralToneMapping;
  34273. exports.NeverCompare = NeverCompare;
  34274. exports.NeverDepth = NeverDepth;
  34275. exports.NeverStencilFunc = NeverStencilFunc;
  34276. exports.NoBlending = NoBlending;
  34277. exports.NoColorSpace = NoColorSpace;
  34278. exports.NoToneMapping = NoToneMapping;
  34279. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  34280. exports.NormalBlending = NormalBlending;
  34281. exports.NotEqualCompare = NotEqualCompare;
  34282. exports.NotEqualDepth = NotEqualDepth;
  34283. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  34284. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  34285. exports.Object3D = Object3D;
  34286. exports.ObjectLoader = ObjectLoader;
  34287. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  34288. exports.OctahedronGeometry = OctahedronGeometry;
  34289. exports.OneFactor = OneFactor;
  34290. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  34291. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  34292. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  34293. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  34294. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  34295. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  34296. exports.OrthographicCamera = OrthographicCamera;
  34297. exports.PCFShadowMap = PCFShadowMap;
  34298. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  34299. exports.PMREMGenerator = PMREMGenerator;
  34300. exports.Path = Path;
  34301. exports.PerspectiveCamera = PerspectiveCamera;
  34302. exports.Plane = Plane;
  34303. exports.PlaneGeometry = PlaneGeometry;
  34304. exports.PlaneHelper = PlaneHelper;
  34305. exports.PointLight = PointLight;
  34306. exports.PointLightHelper = PointLightHelper;
  34307. exports.Points = Points;
  34308. exports.PointsMaterial = PointsMaterial;
  34309. exports.PolarGridHelper = PolarGridHelper;
  34310. exports.PolyhedronGeometry = PolyhedronGeometry;
  34311. exports.PositionalAudio = PositionalAudio;
  34312. exports.PropertyBinding = PropertyBinding;
  34313. exports.PropertyMixer = PropertyMixer;
  34314. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  34315. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  34316. exports.Quaternion = Quaternion;
  34317. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  34318. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  34319. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  34320. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  34321. exports.REVISION = REVISION;
  34322. exports.RGBADepthPacking = RGBADepthPacking;
  34323. exports.RGBAFormat = RGBAFormat;
  34324. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  34325. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  34326. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  34327. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  34328. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  34329. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  34330. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  34331. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  34332. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  34333. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  34334. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  34335. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  34336. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  34337. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  34338. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  34339. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  34340. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  34341. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  34342. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  34343. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  34344. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  34345. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  34346. exports.RGBDepthPacking = RGBDepthPacking;
  34347. exports.RGBFormat = RGBFormat;
  34348. exports.RGBIntegerFormat = RGBIntegerFormat;
  34349. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  34350. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  34351. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  34352. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  34353. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  34354. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  34355. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  34356. exports.RGDepthPacking = RGDepthPacking;
  34357. exports.RGFormat = RGFormat;
  34358. exports.RGIntegerFormat = RGIntegerFormat;
  34359. exports.RawShaderMaterial = RawShaderMaterial;
  34360. exports.Ray = Ray;
  34361. exports.Raycaster = Raycaster;
  34362. exports.RectAreaLight = RectAreaLight;
  34363. exports.RedFormat = RedFormat;
  34364. exports.RedIntegerFormat = RedIntegerFormat;
  34365. exports.ReinhardToneMapping = ReinhardToneMapping;
  34366. exports.RenderTarget = RenderTarget;
  34367. exports.RenderTarget3D = RenderTarget3D;
  34368. exports.RenderTargetArray = RenderTargetArray;
  34369. exports.RepeatWrapping = RepeatWrapping;
  34370. exports.ReplaceStencilOp = ReplaceStencilOp;
  34371. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  34372. exports.RingGeometry = RingGeometry;
  34373. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  34374. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  34375. exports.SRGBColorSpace = SRGBColorSpace;
  34376. exports.SRGBTransfer = SRGBTransfer;
  34377. exports.Scene = Scene;
  34378. exports.ShaderChunk = ShaderChunk;
  34379. exports.ShaderLib = ShaderLib;
  34380. exports.ShaderMaterial = ShaderMaterial;
  34381. exports.ShadowMaterial = ShadowMaterial;
  34382. exports.Shape = Shape;
  34383. exports.ShapeGeometry = ShapeGeometry;
  34384. exports.ShapePath = ShapePath;
  34385. exports.ShapeUtils = ShapeUtils;
  34386. exports.ShortType = ShortType;
  34387. exports.Skeleton = Skeleton;
  34388. exports.SkeletonHelper = SkeletonHelper;
  34389. exports.SkinnedMesh = SkinnedMesh;
  34390. exports.Source = Source;
  34391. exports.Sphere = Sphere;
  34392. exports.SphereGeometry = SphereGeometry;
  34393. exports.Spherical = Spherical;
  34394. exports.SphericalHarmonics3 = SphericalHarmonics3;
  34395. exports.SplineCurve = SplineCurve;
  34396. exports.SpotLight = SpotLight;
  34397. exports.SpotLightHelper = SpotLightHelper;
  34398. exports.Sprite = Sprite;
  34399. exports.SpriteMaterial = SpriteMaterial;
  34400. exports.SrcAlphaFactor = SrcAlphaFactor;
  34401. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  34402. exports.SrcColorFactor = SrcColorFactor;
  34403. exports.StaticCopyUsage = StaticCopyUsage;
  34404. exports.StaticDrawUsage = StaticDrawUsage;
  34405. exports.StaticReadUsage = StaticReadUsage;
  34406. exports.StereoCamera = StereoCamera;
  34407. exports.StreamCopyUsage = StreamCopyUsage;
  34408. exports.StreamDrawUsage = StreamDrawUsage;
  34409. exports.StreamReadUsage = StreamReadUsage;
  34410. exports.StringKeyframeTrack = StringKeyframeTrack;
  34411. exports.SubtractEquation = SubtractEquation;
  34412. exports.SubtractiveBlending = SubtractiveBlending;
  34413. exports.TOUCH = TOUCH;
  34414. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  34415. exports.TetrahedronGeometry = TetrahedronGeometry;
  34416. exports.Texture = Texture;
  34417. exports.TextureLoader = TextureLoader;
  34418. exports.TextureUtils = TextureUtils;
  34419. exports.TimestampQuery = TimestampQuery;
  34420. exports.TorusGeometry = TorusGeometry;
  34421. exports.TorusKnotGeometry = TorusKnotGeometry;
  34422. exports.Triangle = Triangle;
  34423. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  34424. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  34425. exports.TrianglesDrawMode = TrianglesDrawMode;
  34426. exports.TubeGeometry = TubeGeometry;
  34427. exports.UVMapping = UVMapping;
  34428. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  34429. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  34430. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  34431. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  34432. exports.Uniform = Uniform;
  34433. exports.UniformsGroup = UniformsGroup;
  34434. exports.UniformsLib = UniformsLib;
  34435. exports.UniformsUtils = UniformsUtils;
  34436. exports.UnsignedByteType = UnsignedByteType;
  34437. exports.UnsignedInt248Type = UnsignedInt248Type;
  34438. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  34439. exports.UnsignedIntType = UnsignedIntType;
  34440. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  34441. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  34442. exports.UnsignedShortType = UnsignedShortType;
  34443. exports.VSMShadowMap = VSMShadowMap;
  34444. exports.Vector2 = Vector2;
  34445. exports.Vector3 = Vector3;
  34446. exports.Vector4 = Vector4;
  34447. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  34448. exports.VideoFrameTexture = VideoFrameTexture;
  34449. exports.VideoTexture = VideoTexture;
  34450. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  34451. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  34452. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  34453. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  34454. exports.WebGLRenderTarget = WebGLRenderTarget;
  34455. exports.WebGLRenderer = WebGLRenderer;
  34456. exports.WebGLUtils = WebGLUtils;
  34457. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  34458. exports.WebXRController = WebXRController;
  34459. exports.WireframeGeometry = WireframeGeometry;
  34460. exports.WrapAroundEnding = WrapAroundEnding;
  34461. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  34462. exports.ZeroFactor = ZeroFactor;
  34463. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  34464. exports.ZeroStencilOp = ZeroStencilOp;
  34465. exports.createCanvasElement = createCanvasElement;
粤ICP备19079148号